2 /* This work is part of OpenLDAP Software <http://www.openldap.org/>.
4 * Copyright 1998-2010 The OpenLDAP Foundation.
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted only as authorized by the OpenLDAP
11 * A copy of this license is available in the file LICENSE in the
12 * top-level directory of the distribution or, alternatively, at
13 * <http://www.OpenLDAP.org/license.html>.
19 #include <ac/stdlib.h>
20 #include <ac/stdarg.h>
21 #include <ac/string.h>
23 #include <ac/unistd.h>
37 #include "ldap_defaults.h"
46 /* Some Windows versions accept both forward and backslashes in
47 * directory paths, but we always use backslashes when generating
50 void lutil_slashpath( char *path )
55 while (( c=strchr( p, '/' ))) {
62 char* lutil_progname( const char* name, int argc, char *argv[] )
73 for (i=0; i<argc; i++) __etoa(argv[i]);
77 LUTIL_SLASHPATH( argv[0] );
78 progname = strrchr ( argv[0], *LDAP_DIRSEP );
79 progname = progname ? &progname[1] : argv[0];
82 size_t len = strlen( progname );
83 if ( len > 4 && strcasecmp( &progname[len - 4], ".exe" ) == 0 )
84 progname[len - 4] = '\0';
91 size_t lutil_gentime( char *s, size_t smax, const struct tm *tm )
95 /* We've been compiling in ASCII so far, but we want EBCDIC now since
96 * strftime only understands EBCDIC input.
98 #pragma convlit(suspend)
100 ret = strftime( s, smax, "%Y%m%d%H%M%SZ", tm );
102 #pragma convlit(resume)
109 size_t lutil_localtime( char *s, size_t smax, const struct tm *tm, long delta )
114 if ( smax < 16 ) { /* YYYYmmddHHMMSSZ */
119 /* We've been compiling in ASCII so far, but we want EBCDIC now since
120 * strftime only understands EBCDIC input.
122 #pragma convlit(suspend)
124 ret = strftime( s, smax, "%Y%m%d%H%M%SZ", tm );
126 #pragma convlit(resume)
129 if ( delta == 0 || ret == 0 ) {
133 if ( smax < 20 ) { /* YYYYmmddHHMMSS+HHMM */
147 snprintf( p, smax - 15, "%02ld%02ld", delta / 3600,
148 ( delta % 3600 ) / 60 );
153 int lutil_tm2time( struct lutil_tm *tm, struct lutil_timet *tt )
155 static int moffset[12] = {
161 tt->tt_usec = tm->tm_usec;
163 /* special case 0000/01/01+00:00:00 is returned as zero */
164 if ( tm->tm_year == -1900 && tm->tm_mon == 0 && tm->tm_mday == 1 &&
165 tm->tm_hour == 0 && tm->tm_min == 0 && tm->tm_sec == 0 ) {
171 /* tm->tm_year is years since 1900 */
172 /* calculate days from years since 1970 (epoch) */
173 tt->tt_sec = tm->tm_year - 70;
176 /* count leap days in preceding years */
177 tt->tt_sec += ((tm->tm_year -69) >> 2);
179 /* calculate days from months */
180 tt->tt_sec += moffset[tm->tm_mon];
182 /* add in this year's leap day, if any */
183 if (((tm->tm_year & 3) == 0) && (tm->tm_mon > 1)) {
187 /* add in days in this month */
188 tt->tt_sec += (tm->tm_mday - 1);
190 /* this function can handle a range of about 17408 years... */
191 /* 86400 seconds in a day, divided by 128 = 675 */
194 /* move high 7 bits into tt_gsec */
195 tt->tt_gsec = tt->tt_sec >> 25;
196 tt->tt_sec -= tt->tt_gsec << 25;
201 /* convert to minutes */
205 /* convert to seconds */
209 /* add remaining seconds */
217 int lutil_parsetime( char *atm, struct lutil_tm *tm )
223 /* Is the stamp reasonably long? */
224 for (i=0; isdigit((unsigned char) atm[i]); i++);
225 if (i < sizeof("00000101000000")-1)
229 * parse the time into a struct tm
231 /* 4 digit year to year - 1900 */
232 tm->tm_year = *ptr++ - '0';
233 tm->tm_year *= 10; tm->tm_year += *ptr++ - '0';
234 tm->tm_year *= 10; tm->tm_year += *ptr++ - '0';
235 tm->tm_year *= 10; tm->tm_year += *ptr++ - '0';
237 /* month 01-12 to 0-11 */
238 tm->tm_mon = *ptr++ - '0';
239 tm->tm_mon *=10; tm->tm_mon += *ptr++ - '0';
240 if (tm->tm_mon < 1 || tm->tm_mon > 12) break;
243 /* day of month 01-31 */
244 tm->tm_mday = *ptr++ - '0';
245 tm->tm_mday *=10; tm->tm_mday += *ptr++ - '0';
246 if (tm->tm_mday < 1 || tm->tm_mday > 31) break;
249 tm->tm_hour = *ptr++ - '0';
250 tm->tm_hour *=10; tm->tm_hour += *ptr++ - '0';
251 if (tm->tm_hour < 0 || tm->tm_hour > 23) break;
254 tm->tm_min = *ptr++ - '0';
255 tm->tm_min *=10; tm->tm_min += *ptr++ - '0';
256 if (tm->tm_min < 0 || tm->tm_min > 59) break;
259 tm->tm_sec = *ptr++ - '0';
260 tm->tm_sec *=10; tm->tm_sec += *ptr++ - '0';
261 if (tm->tm_sec < 0 || tm->tm_sec > 61) break;
263 /* Fractions of seconds */
266 for (i = 0, fracs = 0; isdigit((unsigned char) *ptr); ) {
267 i*=10; i+= *ptr++ - '0';
272 for (i = fracs; i<6; i++)
278 if (*ptr != 'Z') break;
285 /* strcopy is like strcpy except it returns a pointer to the trailing NUL of
286 * the result string. This allows fast construction of catenated strings
287 * without the overhead of strlen/strcat.
298 while ((*a++ = *b++)) ;
302 /* strncopy is like strcpy except it returns a pointer to the trailing NUL of
303 * the result string. This allows fast construction of catenated strings
304 * without the overhead of strlen/strcat.
313 if (!a || !b || n == 0)
316 while ((*a++ = *b++) && n-- > 0) ;
320 /* memcopy is like memcpy except it returns a pointer to the byte past
321 * the end of the result buffer, set to NULL. This allows fast construction
322 * of catenated buffers. Provided for API consistency with lutil_str*copy().
336 int mkstemp( char * template )
339 return open ( mktemp ( template ), O_RDWR|O_CREAT|O_EXCL, 0600 );
347 /* Equivalent of MS CRT's _dosmaperr().
348 * @param lastError[in] Result of GetLastError().
350 static errno_t win2errno(DWORD lastError)
355 } WIN2ERRNO_TABLE[] = {
356 { ERROR_SUCCESS, 0 },
357 { ERROR_FILE_NOT_FOUND, ENOENT },
358 { ERROR_PATH_NOT_FOUND, ENOENT },
359 { ERROR_TOO_MANY_OPEN_FILES, EMFILE },
360 { ERROR_ACCESS_DENIED, EACCES },
361 { ERROR_INVALID_HANDLE, EBADF },
362 { ERROR_NOT_ENOUGH_MEMORY, ENOMEM },
363 { ERROR_LOCK_VIOLATION, EACCES },
364 { ERROR_FILE_EXISTS, EEXIST },
365 { ERROR_INVALID_PARAMETER, EINVAL },
366 { ERROR_FILENAME_EXCED_RANGE, ENAMETOOLONG },
368 const unsigned int WIN2ERRNO_TABLE_SIZE = sizeof(WIN2ERRNO_TABLE) /
369 sizeof(WIN2ERRNO_TABLE[0]);
370 const errno_t DEFAULT_ERRNO_ERROR = -1;
373 for (i = 0; i < WIN2ERRNO_TABLE_SIZE; ++i) {
374 if (WIN2ERRNO_TABLE[i].windows_code == lastError) {
375 return WIN2ERRNO_TABLE[i].errno_code;
378 return DEFAULT_ERRNO_ERROR;
388 char buf[MAX_PATH+1];
390 DIR *opendir( char *path )
393 int len = strlen(path);
396 WIN32_FIND_DATA data;
398 if (len+3 >= sizeof(tmp)) {
399 errno = ENAMETOOLONG;
408 h = FindFirstFile( tmp, &data );
410 if ( h == INVALID_HANDLE_VALUE ) {
411 errno = win2errno( GetLastError());
415 d = ber_memalloc( sizeof(DIR) );
419 d->data.d_name = d->buf;
421 strcpy(d->data.d_name, data.cFileName);
424 struct dirent *readdir(DIR *dir)
426 WIN32_FIND_DATA data;
431 if (!FindNextFile(dir->dir, &data))
433 strcpy(dir->data.d_name, data.cFileName);
437 int closedir(DIR *dir)
445 * Memory Reverse Search
448 (lutil_memrchr)(const void *b, int c, size_t n)
451 const unsigned char *s, *bb = b, cc = c;
453 for ( s = bb + n; s > bb; ) {
464 lutil_atoix( int *v, const char *s, int x )
472 i = strtol( s, &next, x );
473 if ( next == s || next[ 0 ] != '\0' ) {
477 if ( (long)(int)i != i ) {
487 lutil_atoux( unsigned *v, const char *s, int x )
495 /* strtoul() has an odd interface */
496 if ( s[ 0 ] == '-' ) {
500 u = strtoul( s, &next, x );
501 if ( next == s || next[ 0 ] != '\0' ) {
505 if ( (unsigned long)(unsigned)u != u ) {
515 lutil_atolx( long *v, const char *s, int x )
523 l = strtol( s, &next, x );
524 if ( next == s || next[ 0 ] != '\0' ) {
534 lutil_atoulx( unsigned long *v, const char *s, int x )
542 /* strtoul() has an odd interface */
543 if ( s[ 0 ] == '-' ) {
547 ul = strtoul( s, &next, x );
548 if ( next == s || next[ 0 ] != '\0' ) {
557 /* Multiply an integer by 100000000 and add new */
558 typedef struct lutil_int_decnum {
565 #define FACTOR1 (100000000&0xffff)
566 #define FACTOR2 (100000000>>16)
569 scale( int new, lutil_int_decnum *prev, unsigned char *tmp )
572 unsigned char *in = prev->buf+prev->beg;
574 unsigned char *out = tmp + prev->bufsiz - prev->len;
576 memset( tmp, 0, prev->bufsiz );
578 for ( i = prev->len-1; i>=0; i-- ) {
579 part = in[i] * FACTOR1;
580 for ( j = i; part; j-- ) {
582 out[j] = part & 0xff;
585 part = in[i] * FACTOR2;
586 for ( j = i-2; part; j-- ) {
588 out[j] = part & 0xff;
597 out = tmp + prev->bufsiz;
606 if ( prev->len < i ) {
607 prev->beg = prev->bufsiz - i;
610 AC_MEMCPY( prev->buf+prev->beg, tmp+prev->beg, prev->len );
613 /* Convert unlimited length decimal or hex string to binary.
614 * Output buffer must be provided, bv_len must indicate buffer size
615 * Hex input can be "0x1234" or "'1234'H"
617 * Temporarily modifies the input string.
619 * Note: High bit of binary form is always the sign bit. If the number
620 * is supposed to be positive but has the high bit set, a zero byte
621 * is prepended. It is assumed that this has already been handled on
625 lutil_str2bin( struct berval *in, struct berval *out, void *ctx )
627 char *pin, *pout, ctmp;
629 int i, chunk, len, rc = 0, hex = 0;
630 if ( !out || !out->bv_val || out->bv_len < in->bv_len )
634 /* Leading "0x" for hex input */
635 if ( in->bv_len > 2 && in->bv_val[0] == '0' &&
636 ( in->bv_val[1] == 'x' || in->bv_val[1] == 'X' ) )
638 len = in->bv_len - 2;
639 pin = in->bv_val + 2;
641 } else if ( in->bv_len > 3 && in->bv_val[0] == '\'' &&
642 in->bv_val[in->bv_len-2] == '\'' &&
643 in->bv_val[in->bv_len-1] == 'H' )
645 len = in->bv_len - 3;
646 pin = in->bv_val + 1;
650 #define HEXMAX (2 * sizeof(long))
652 /* Convert a longword at a time, but handle leading
655 chunk = len % HEXMAX;
664 l = strtoul( pin, &end, 16 );
668 ochunk = (chunk + 1)/2;
669 for ( i = ochunk - 1; i >= 0; i-- ) {
678 out->bv_len = pout - out->bv_val;
681 char tmpbuf[64], *tmp;
682 lutil_int_decnum num;
688 num.buf = (unsigned char *)out->bv_val;
689 num.bufsiz = out->bv_len;
690 num.beg = num.bufsiz-1;
692 if ( pin[0] == '-' ) {
698 #define DECMAX 8 /* 8 digits at a time */
700 /* tmp must be at least as large as outbuf */
701 if ( out->bv_len > sizeof(tmpbuf)) {
702 tmp = ber_memalloc_x( out->bv_len, ctx );
706 chunk = len & (DECMAX-1);
714 l = strtol( pin, &end, 10 );
720 scale( l, &num, (unsigned char *)tmp );
725 /* Negate the result */
729 ptr = num.buf+num.beg;
732 for ( i=0; i<num.len; i++ )
735 /* add 1, with carry - overflow handled below */
736 while ( i-- && ! (ptr[i] = (ptr[i] + 1) & 0xff )) ;
738 /* Prepend sign byte if wrong sign bit */
739 if (( num.buf[num.beg] ^ neg ) & 0x80 ) {
742 num.buf[num.beg] = neg;
745 AC_MEMCPY( num.buf, num.buf+num.beg, num.len );
746 out->bv_len = num.len;
748 if ( tmp != tmpbuf ) {
749 ber_memfree_x( tmp, ctx );
755 static char time_unit[] = "dhms";
757 /* Used to parse and unparse time intervals, not timestamps */
767 scale[] = { 86400, 3600, 60, 1 };
771 for ( s = (char *)in; s[ 0 ] != '\0'; ) {
775 /* strtoul() has an odd interface */
776 if ( s[ 0 ] == '-' ) {
780 u = strtoul( s, &next, 10 );
785 if ( next[ 0 ] == '\0' ) {
791 what = strchr( time_unit, next[ 0 ] );
792 if ( what == NULL ) {
796 if ( what - time_unit <= sofar ) {
800 sofar = what - time_unit;
801 t += u * scale[ sofar ];
817 unsigned long v[ 4 ];
821 v[ 1 ] = (t%86400)/3600;
822 v[ 2 ] = (t%3600)/60;
825 for ( i = 0; i < 4; i++ ) {
826 if ( v[i] > 0 || ( i == 3 && ptr == buf ) ) {
827 len = snprintf( ptr, buflen, "%lu%c", v[ i ], time_unit[ i ] );
828 if ( len < 0 || (unsigned)len >= buflen ) {
840 * formatted print to string
842 * - if return code < 0, the error code returned by vsnprintf(3) is returned
844 * - if return code > 0, the buffer was not long enough;
845 * - if next is not NULL, *next will be set to buf + bufsize - 1
846 * - if len is not NULL, *len will contain the required buffer length
848 * - if return code == 0, the buffer was long enough;
849 * - if next is not NULL, *next will point to the end of the string printed so far
850 * - if len is not NULL, *len will contain the length of the string printed so far
853 lutil_snprintf( char *buf, ber_len_t bufsize, char **next, ber_len_t *len, LDAP_CONST char *fmt, ... )
858 assert( buf != NULL );
859 assert( bufsize > 0 );
860 assert( fmt != NULL );
863 ret = vsnprintf( buf, bufsize, fmt, ap );
874 if ( (unsigned) ret >= bufsize ) {
876 *next = &buf[ bufsize - 1 ];