2 /* This work is part of OpenLDAP Software <http://www.openldap.org/>.
4 * Copyright 1998-2016 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>.
20 #include <ac/stdlib.h>
21 #include <ac/stdarg.h>
22 #include <ac/string.h>
24 #include <ac/unistd.h>
38 #include "ldap_defaults.h"
47 /* Some Windows versions accept both forward and backslashes in
48 * directory paths, but we always use backslashes when generating
51 void lutil_slashpath( char *path )
56 while (( c=strchr( p, '/' ))) {
63 char* lutil_progname( const char* name, int argc, char *argv[] )
74 for (i=0; i<argc; i++) __etoa(argv[i]);
78 LUTIL_SLASHPATH( argv[0] );
79 progname = strrchr ( argv[0], *LDAP_DIRSEP );
80 progname = progname ? &progname[1] : argv[0];
83 size_t len = strlen( progname );
84 if ( len > 4 && strcasecmp( &progname[len - 4], ".exe" ) == 0 )
85 progname[len - 4] = '\0';
92 size_t lutil_gentime( char *s, size_t smax, const struct tm *tm )
96 /* We've been compiling in ASCII so far, but we want EBCDIC now since
97 * strftime only understands EBCDIC input.
99 #pragma convlit(suspend)
101 ret = strftime( s, smax, "%Y%m%d%H%M%SZ", tm );
103 #pragma convlit(resume)
110 size_t lutil_localtime( char *s, size_t smax, const struct tm *tm, long delta )
115 if ( smax < 16 ) { /* YYYYmmddHHMMSSZ */
120 /* We've been compiling in ASCII so far, but we want EBCDIC now since
121 * strftime only understands EBCDIC input.
123 #pragma convlit(suspend)
125 ret = strftime( s, smax, "%Y%m%d%H%M%SZ", tm );
127 #pragma convlit(resume)
130 if ( delta == 0 || ret == 0 ) {
134 if ( smax < 20 ) { /* YYYYmmddHHMMSS+HHMM */
148 snprintf( p, smax - 15, "%02ld%02ld", delta / 3600,
149 ( delta % 3600 ) / 60 );
154 int lutil_tm2time( struct lutil_tm *tm, struct lutil_timet *tt )
156 static int moffset[12] = {
162 tt->tt_usec = tm->tm_usec;
164 /* special case 0000/01/01+00:00:00 is returned as zero */
165 if ( tm->tm_year == -1900 && tm->tm_mon == 0 && tm->tm_mday == 1 &&
166 tm->tm_hour == 0 && tm->tm_min == 0 && tm->tm_sec == 0 ) {
172 /* tm->tm_year is years since 1900 */
173 /* calculate days from years since 1970 (epoch) */
174 tt->tt_sec = tm->tm_year - 70;
177 /* count leap days in preceding years */
178 tt->tt_sec += ((tm->tm_year -69) >> 2);
180 /* calculate days from months */
181 tt->tt_sec += moffset[tm->tm_mon];
183 /* add in this year's leap day, if any */
184 if (((tm->tm_year & 3) == 0) && (tm->tm_mon > 1)) {
188 /* add in days in this month */
189 tt->tt_sec += (tm->tm_mday - 1);
191 /* this function can handle a range of about 17408 years... */
192 /* 86400 seconds in a day, divided by 128 = 675 */
195 /* move high 7 bits into tt_gsec */
196 tt->tt_gsec = tt->tt_sec >> 25;
197 tt->tt_sec -= tt->tt_gsec << 25;
202 /* convert to minutes */
206 /* convert to seconds */
210 /* add remaining seconds */
218 int lutil_parsetime( char *atm, struct lutil_tm *tm )
224 /* Is the stamp reasonably long? */
225 for (i=0; isdigit((unsigned char) atm[i]); i++);
226 if (i < sizeof("00000101000000")-1)
230 * parse the time into a struct tm
232 /* 4 digit year to year - 1900 */
233 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';
236 tm->tm_year *= 10; tm->tm_year += *ptr++ - '0';
238 /* month 01-12 to 0-11 */
239 tm->tm_mon = *ptr++ - '0';
240 tm->tm_mon *=10; tm->tm_mon += *ptr++ - '0';
241 if (tm->tm_mon < 1 || tm->tm_mon > 12) break;
244 /* day of month 01-31 */
245 tm->tm_mday = *ptr++ - '0';
246 tm->tm_mday *=10; tm->tm_mday += *ptr++ - '0';
247 if (tm->tm_mday < 1 || tm->tm_mday > 31) break;
250 tm->tm_hour = *ptr++ - '0';
251 tm->tm_hour *=10; tm->tm_hour += *ptr++ - '0';
252 if (tm->tm_hour < 0 || tm->tm_hour > 23) break;
255 tm->tm_min = *ptr++ - '0';
256 tm->tm_min *=10; tm->tm_min += *ptr++ - '0';
257 if (tm->tm_min < 0 || tm->tm_min > 59) break;
260 tm->tm_sec = *ptr++ - '0';
261 tm->tm_sec *=10; tm->tm_sec += *ptr++ - '0';
262 if (tm->tm_sec < 0 || tm->tm_sec > 61) break;
264 /* Fractions of seconds */
267 for (i = 0, fracs = 0; isdigit((unsigned char) *ptr); ) {
268 i*=10; i+= *ptr++ - '0';
273 for (i = fracs; i<6; i++)
279 if (*ptr != 'Z') break;
286 /* strcopy is like strcpy except it returns a pointer to the trailing NUL of
287 * the result string. This allows fast construction of catenated strings
288 * without the overhead of strlen/strcat.
299 while ((*a++ = *b++)) ;
303 /* strncopy is like strcpy except it returns a pointer to the trailing NUL of
304 * the result string. This allows fast construction of catenated strings
305 * without the overhead of strlen/strcat.
314 if (!a || !b || n == 0)
317 while ((*a++ = *b++) && n-- > 0) ;
321 /* memcopy is like memcpy except it returns a pointer to the byte past
322 * the end of the result buffer, set to NULL. This allows fast construction
323 * of catenated buffers. Provided for API consistency with lutil_str*copy().
337 int mkstemp( char * template )
340 return open ( mktemp ( template ), O_RDWR|O_CREAT|O_EXCL, 0600 );
348 /* Equivalent of MS CRT's _dosmaperr().
349 * @param lastError[in] Result of GetLastError().
351 static errno_t win2errno(DWORD lastError)
356 } WIN2ERRNO_TABLE[] = {
357 { ERROR_SUCCESS, 0 },
358 { ERROR_FILE_NOT_FOUND, ENOENT },
359 { ERROR_PATH_NOT_FOUND, ENOENT },
360 { ERROR_TOO_MANY_OPEN_FILES, EMFILE },
361 { ERROR_ACCESS_DENIED, EACCES },
362 { ERROR_INVALID_HANDLE, EBADF },
363 { ERROR_NOT_ENOUGH_MEMORY, ENOMEM },
364 { ERROR_LOCK_VIOLATION, EACCES },
365 { ERROR_FILE_EXISTS, EEXIST },
366 { ERROR_INVALID_PARAMETER, EINVAL },
367 { ERROR_FILENAME_EXCED_RANGE, ENAMETOOLONG },
369 const unsigned int WIN2ERRNO_TABLE_SIZE = sizeof(WIN2ERRNO_TABLE) /
370 sizeof(WIN2ERRNO_TABLE[0]);
371 const errno_t DEFAULT_ERRNO_ERROR = -1;
374 for (i = 0; i < WIN2ERRNO_TABLE_SIZE; ++i) {
375 if (WIN2ERRNO_TABLE[i].windows_code == lastError) {
376 return WIN2ERRNO_TABLE[i].errno_code;
379 return DEFAULT_ERRNO_ERROR;
389 char buf[MAX_PATH+1];
391 DIR *opendir( char *path )
394 int len = strlen(path);
397 WIN32_FIND_DATA data;
399 if (len+3 >= sizeof(tmp)) {
400 errno = ENAMETOOLONG;
409 h = FindFirstFile( tmp, &data );
411 if ( h == INVALID_HANDLE_VALUE ) {
412 errno = win2errno( GetLastError());
416 d = ber_memalloc( sizeof(DIR) );
420 d->data.d_name = d->buf;
422 strcpy(d->data.d_name, data.cFileName);
425 struct dirent *readdir(DIR *dir)
427 WIN32_FIND_DATA data;
432 if (!FindNextFile(dir->dir, &data))
434 strcpy(dir->data.d_name, data.cFileName);
438 int closedir(DIR *dir)
440 (void) FindClose(dir->dir);
447 * Memory Reverse Search
450 (lutil_memrchr)(const void *b, int c, size_t n)
453 const unsigned char *s, *bb = b, cc = c;
455 for ( s = bb + n; s > bb; ) {
466 lutil_atoix( int *v, const char *s, int x )
474 i = strtol( s, &next, x );
475 if ( next == s || next[ 0 ] != '\0' ) {
479 if ( (long)(int)i != i ) {
489 lutil_atoux( unsigned *v, const char *s, int x )
497 /* strtoul() has an odd interface */
498 if ( s[ 0 ] == '-' ) {
502 u = strtoul( s, &next, x );
503 if ( next == s || next[ 0 ] != '\0' ) {
507 if ( (unsigned long)(unsigned)u != u ) {
517 lutil_atolx( long *v, const char *s, int x )
526 if ( isspace( s[ 0 ] ) ) {
531 l = strtol( s, &next, x );
533 if ( next == s || next[ 0 ] != '\0' ) {
537 if ( ( l == LONG_MIN || l == LONG_MAX ) && save_errno != 0 ) {
547 lutil_atoulx( unsigned long *v, const char *s, int x )
556 /* strtoul() has an odd interface */
557 if ( s[ 0 ] == '-' || isspace( s[ 0 ] ) ) {
562 ul = strtoul( s, &next, x );
564 if ( next == s || next[ 0 ] != '\0' ) {
568 if ( ( ul == 0 || ul == ULONG_MAX ) && save_errno != 0 ) {
577 #ifdef HAVE_LONG_LONG
578 #if defined(HAVE_STRTOLL) || defined(HAVE_STRTOQ)
580 lutil_atollx( long long *v, const char *s, int x )
589 if ( isspace( s[ 0 ] ) ) {
595 ll = strtoll( s, &next, x );
596 #else /* HAVE_STRTOQ */
597 ll = (unsigned long long)strtoq( s, &next, x );
598 #endif /* HAVE_STRTOQ */
600 if ( next == s || next[ 0 ] != '\0' ) {
604 /* LLONG_MIN, LLONG_MAX are C99 only */
605 #if defined (LLONG_MIN) && defined(LLONG_MAX)
606 if ( ( ll == LLONG_MIN || ll == LLONG_MAX ) && save_errno != 0 ) {
609 #endif /* LLONG_MIN && LLONG_MAX */
615 #endif /* HAVE_STRTOLL || HAVE_STRTOQ */
617 #if defined(HAVE_STRTOULL) || defined(HAVE_STRTOUQ)
619 lutil_atoullx( unsigned long long *v, const char *s, int x )
622 unsigned long long ull;
628 /* strtoull() has an odd interface */
629 if ( s[ 0 ] == '-' || isspace( s[ 0 ] ) ) {
635 ull = strtoull( s, &next, x );
636 #else /* HAVE_STRTOUQ */
637 ull = (unsigned long long)strtouq( s, &next, x );
638 #endif /* HAVE_STRTOUQ */
640 if ( next == s || next[ 0 ] != '\0' ) {
644 /* ULLONG_MAX is C99 only */
645 #if defined(ULLONG_MAX)
646 if ( ( ull == 0 || ull == ULLONG_MAX ) && save_errno != 0 ) {
649 #endif /* ULLONG_MAX */
655 #endif /* HAVE_STRTOULL || HAVE_STRTOUQ */
656 #endif /* HAVE_LONG_LONG */
658 /* Multiply an integer by 100000000 and add new */
659 typedef struct lutil_int_decnum {
666 #define FACTOR1 (100000000&0xffff)
667 #define FACTOR2 (100000000>>16)
670 scale( int new, lutil_int_decnum *prev, unsigned char *tmp )
673 unsigned char *in = prev->buf+prev->beg;
675 unsigned char *out = tmp + prev->bufsiz - prev->len;
677 memset( tmp, 0, prev->bufsiz );
679 for ( i = prev->len-1; i>=0; i-- ) {
680 part = in[i] * FACTOR1;
681 for ( j = i; part; j-- ) {
683 out[j] = part & 0xff;
686 part = in[i] * FACTOR2;
687 for ( j = i-2; part; j-- ) {
689 out[j] = part & 0xff;
698 out = tmp + prev->bufsiz;
707 if ( prev->len < i ) {
708 prev->beg = prev->bufsiz - i;
711 AC_MEMCPY( prev->buf+prev->beg, tmp+prev->beg, prev->len );
714 /* Convert unlimited length decimal or hex string to binary.
715 * Output buffer must be provided, bv_len must indicate buffer size
716 * Hex input can be "0x1234" or "'1234'H"
718 * Note: High bit of binary form is always the sign bit. If the number
719 * is supposed to be positive but has the high bit set, a zero byte
720 * is prepended. It is assumed that this has already been handled on
724 lutil_str2bin( struct berval *in, struct berval *out, void *ctx )
728 int i, chunk, len, rc = 0, hex = 0;
729 if ( !out || !out->bv_val || out->bv_len < in->bv_len )
733 /* Leading "0x" for hex input */
734 if ( in->bv_len > 2 && in->bv_val[0] == '0' &&
735 ( in->bv_val[1] == 'x' || in->bv_val[1] == 'X' ) )
737 len = in->bv_len - 2;
738 pin = in->bv_val + 2;
740 } else if ( in->bv_len > 3 && in->bv_val[0] == '\'' &&
741 in->bv_val[in->bv_len-2] == '\'' &&
742 in->bv_val[in->bv_len-1] == 'H' )
744 len = in->bv_len - 3;
745 pin = in->bv_val + 1;
749 #define HEXMAX (2 * sizeof(long))
753 /* Convert a longword at a time, but handle leading
756 chunk = len % HEXMAX;
762 memcpy( tbuf, pin, chunk );
765 l = strtoul( tbuf, &end, 16 );
768 ochunk = (chunk + 1)/2;
769 for ( i = ochunk - 1; i >= 0; i-- ) {
778 out->bv_len = pout - out->bv_val;
781 #define DECMAX 8 /* 8 digits at a time */
782 char tmpbuf[64], *tmp;
783 lutil_int_decnum num;
790 num.buf = (unsigned char *)out->bv_val;
791 num.bufsiz = out->bv_len;
792 num.beg = num.bufsiz-1;
794 if ( pin[0] == '-' ) {
800 /* tmp must be at least as large as outbuf */
801 if ( out->bv_len > sizeof(tmpbuf)) {
802 tmp = ber_memalloc_x( out->bv_len, ctx );
806 chunk = len & (DECMAX-1);
811 memcpy( tbuf, pin, chunk );
814 l = strtol( tbuf, &end, 10 );
819 scale( l, &num, (unsigned char *)tmp );
824 /* Negate the result */
828 ptr = num.buf+num.beg;
831 for ( i=0; i<num.len; i++ )
834 /* add 1, with carry - overflow handled below */
835 while ( i-- && ! (ptr[i] = (ptr[i] + 1) & 0xff )) ;
837 /* Prepend sign byte if wrong sign bit */
838 if (( num.buf[num.beg] ^ neg ) & 0x80 ) {
841 num.buf[num.beg] = neg;
844 AC_MEMCPY( num.buf, num.buf+num.beg, num.len );
845 out->bv_len = num.len;
847 if ( tmp != tmpbuf ) {
848 ber_memfree_x( tmp, ctx );
854 static char time_unit[] = "dhms";
856 /* Used to parse and unparse time intervals, not timestamps */
866 scale[] = { 86400, 3600, 60, 1 };
870 for ( s = (char *)in; s[ 0 ] != '\0'; ) {
874 /* strtoul() has an odd interface */
875 if ( s[ 0 ] == '-' ) {
879 u = strtoul( s, &next, 10 );
884 if ( next[ 0 ] == '\0' ) {
890 what = strchr( time_unit, next[ 0 ] );
891 if ( what == NULL ) {
895 if ( what - time_unit <= sofar ) {
899 sofar = what - time_unit;
900 t += u * scale[ sofar ];
916 unsigned long v[ 4 ];
920 v[ 1 ] = (t%86400)/3600;
921 v[ 2 ] = (t%3600)/60;
924 for ( i = 0; i < 4; i++ ) {
925 if ( v[i] > 0 || ( i == 3 && ptr == buf ) ) {
926 len = snprintf( ptr, buflen, "%lu%c", v[ i ], time_unit[ i ] );
927 if ( len < 0 || (unsigned)len >= buflen ) {
939 * formatted print to string
941 * - if return code < 0, the error code returned by vsnprintf(3) is returned
943 * - if return code > 0, the buffer was not long enough;
944 * - if next is not NULL, *next will be set to buf + bufsize - 1
945 * - if len is not NULL, *len will contain the required buffer length
947 * - if return code == 0, the buffer was long enough;
948 * - if next is not NULL, *next will point to the end of the string printed so far
949 * - if len is not NULL, *len will contain the length of the string printed so far
952 lutil_snprintf( char *buf, ber_len_t bufsize, char **next, ber_len_t *len, LDAP_CONST char *fmt, ... )
957 assert( buf != NULL );
958 assert( bufsize > 0 );
959 assert( fmt != NULL );
962 ret = vsnprintf( buf, bufsize, fmt, ap );
973 if ( (unsigned) ret >= bufsize ) {
975 *next = &buf[ bufsize - 1 ];