2 /* This work is part of OpenLDAP Software <http://www.openldap.org/>.
4 * Copyright 1998-2009 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 /* return a broken out time, with microseconds
286 * Must be mutex-protected.
289 /* Windows SYSTEMTIME only has 10 millisecond resolution, so we
290 * also need to use a high resolution timer to get microseconds.
291 * This is pretty clunky.
294 lutil_gettime( struct lutil_tm *tm )
296 static LARGE_INTEGER cFreq;
297 static LARGE_INTEGER prevCount;
303 GetSystemTime( &st );
304 QueryPerformanceCounter( &count );
306 /* It shouldn't ever go backwards, but multiple CPUs might
307 * be able to hit in the same tick.
309 if ( count.QuadPart <= prevCount.QuadPart ) {
316 /* We assume Windows has at least a vague idea of
317 * when a second begins. So we align our microsecond count
318 * with the Windows millisecond count using this offset.
319 * We retain the submillisecond portion of our own count.
321 * Note - this also assumes that the relationship between
322 * the PerformanceCouunter and SystemTime stays constant;
323 * that assumption breaks if the SystemTime is adjusted by
324 * an external action.
326 if ( !cFreq.QuadPart ) {
329 QueryPerformanceFrequency( &cFreq );
331 /* just get sub-second portion of counter */
332 t = count.QuadPart % cFreq.QuadPart;
334 /* convert to microseconds */
336 usec = t / cFreq.QuadPart;
338 offset = usec - st.wMilliseconds * 1000;
343 /* convert to microseconds */
344 count.QuadPart %= cFreq.QuadPart;
345 count.QuadPart *= 1000000;
346 count.QuadPart /= cFreq.QuadPart;
347 count.QuadPart -= offset;
349 tm->tm_usec = count.QuadPart % 1000000;
350 if ( tm->tm_usec < 0 )
351 tm->tm_usec += 1000000;
353 /* any difference larger than microseconds is
354 * already reflected in st
357 tm->tm_sec = st.wSecond;
358 tm->tm_min = st.wMinute;
359 tm->tm_hour = st.wHour;
360 tm->tm_mday = st.wDay;
361 tm->tm_mon = st.wMonth - 1;
362 tm->tm_year = st.wYear - 1900;
366 lutil_gettime( struct lutil_tm *ltm )
369 static struct timeval prevTv;
378 gettimeofday( &tv, NULL );
381 if ( tv.tv_sec < prevTv.tv_sec
382 || ( tv.tv_sec == prevTv.tv_sec && tv.tv_usec == prevTv.tv_usec )) {
392 tm = gmtime_r( &t, &tm_buf );
397 ltm->tm_sec = tm->tm_sec;
398 ltm->tm_min = tm->tm_min;
399 ltm->tm_hour = tm->tm_hour;
400 ltm->tm_mday = tm->tm_mday;
401 ltm->tm_mon = tm->tm_mon;
402 ltm->tm_year = tm->tm_year;
403 ltm->tm_usec = tv.tv_usec;
407 /* strcopy is like strcpy except it returns a pointer to the trailing NUL of
408 * the result string. This allows fast construction of catenated strings
409 * without the overhead of strlen/strcat.
420 while ((*a++ = *b++)) ;
424 /* strncopy is like strcpy except it returns a pointer to the trailing NUL of
425 * the result string. This allows fast construction of catenated strings
426 * without the overhead of strlen/strcat.
435 if (!a || !b || n == 0)
438 while ((*a++ = *b++) && n-- > 0) ;
442 /* memcopy is like memcpy except it returns a pointer to the byte past
443 * the end of the result buffer, set to NULL. This allows fast construction
444 * of catenated buffers. Provided for API consistency with lutil_str*copy().
458 int mkstemp( char * template )
461 return open ( mktemp ( template ), O_RDWR|O_CREAT|O_EXCL, 0600 );
469 /* Equivalent of MS CRT's _dosmaperr().
470 * @param lastError[in] Result of GetLastError().
472 static errno_t win2errno(DWORD lastError)
477 } WIN2ERRNO_TABLE[] = {
478 { ERROR_SUCCESS, 0 },
479 { ERROR_FILE_NOT_FOUND, ENOENT },
480 { ERROR_PATH_NOT_FOUND, ENOENT },
481 { ERROR_TOO_MANY_OPEN_FILES, EMFILE },
482 { ERROR_ACCESS_DENIED, EACCES },
483 { ERROR_INVALID_HANDLE, EBADF },
484 { ERROR_NOT_ENOUGH_MEMORY, ENOMEM },
485 { ERROR_LOCK_VIOLATION, EACCES },
486 { ERROR_FILE_EXISTS, EEXIST },
487 { ERROR_INVALID_PARAMETER, EINVAL },
488 { ERROR_FILENAME_EXCED_RANGE, ENAMETOOLONG },
490 const unsigned int WIN2ERRNO_TABLE_SIZE = sizeof(WIN2ERRNO_TABLE) /
491 sizeof(WIN2ERRNO_TABLE[0]);
492 const errno_t DEFAULT_ERRNO_ERROR = -1;
495 for (i = 0; i < WIN2ERRNO_TABLE_SIZE; ++i) {
496 if (WIN2ERRNO_TABLE[i].windows_code == lastError) {
497 return WIN2ERRNO_TABLE[i].errno_code;
500 return DEFAULT_ERRNO_ERROR;
510 char buf[MAX_PATH+1];
512 DIR *opendir( char *path )
515 int len = strlen(path);
518 WIN32_FIND_DATA data;
520 if (len+3 >= sizeof(tmp)) {
521 errno = ENAMETOOLONG;
530 h = FindFirstFile( tmp, &data );
532 if ( h == INVALID_HANDLE_VALUE ) {
533 errno = win2errno( GetLastError());
537 d = ber_memalloc( sizeof(DIR) );
541 d->data.d_name = d->buf;
543 strcpy(d->data.d_name, data.cFileName);
546 struct dirent *readdir(DIR *dir)
548 WIN32_FIND_DATA data;
553 if (!FindNextFile(dir->dir, &data))
555 strcpy(dir->data.d_name, data.cFileName);
559 int closedir(DIR *dir)
567 * Memory Reverse Search
570 lutil_memrchr(const void *b, int c, size_t n)
573 const unsigned char *s, *bb = b, cc = c;
575 for ( s = bb + n; s > bb; ) {
586 lutil_atoix( int *v, const char *s, int x )
594 i = strtol( s, &next, x );
595 if ( next == s || next[ 0 ] != '\0' ) {
599 if ( (long)(int)i != i ) {
609 lutil_atoux( unsigned *v, const char *s, int x )
617 /* strtoul() has an odd interface */
618 if ( s[ 0 ] == '-' ) {
622 u = strtoul( s, &next, x );
623 if ( next == s || next[ 0 ] != '\0' ) {
627 if ( (unsigned long)(unsigned)u != u ) {
637 lutil_atolx( long *v, const char *s, int x )
645 l = strtol( s, &next, x );
646 if ( next == s || next[ 0 ] != '\0' ) {
656 lutil_atoulx( unsigned long *v, const char *s, int x )
664 /* strtoul() has an odd interface */
665 if ( s[ 0 ] == '-' ) {
669 ul = strtoul( s, &next, x );
670 if ( next == s || next[ 0 ] != '\0' ) {
679 /* Multiply an integer by 100000000 and add new */
680 typedef struct lutil_int_decnum {
687 #define FACTOR1 (100000000&0xffff)
688 #define FACTOR2 (100000000>>16)
691 scale( int new, lutil_int_decnum *prev, unsigned char *tmp )
694 unsigned char *in = prev->buf+prev->beg;
696 unsigned char *out = tmp + prev->bufsiz - prev->len;
698 memset( tmp, 0, prev->bufsiz );
700 for ( i = prev->len-1; i>=0; i-- ) {
701 part = in[i] * FACTOR1;
702 for ( j = i; part; j-- ) {
704 out[j] = part & 0xff;
707 part = in[i] * FACTOR2;
708 for ( j = i-2; part; j-- ) {
710 out[j] = part & 0xff;
719 out = tmp + prev->bufsiz;
728 if ( prev->len < i ) {
729 prev->beg = prev->bufsiz - i;
732 AC_MEMCPY( prev->buf+prev->beg, tmp+prev->beg, prev->len );
735 /* Convert unlimited length decimal or hex string to binary.
736 * Output buffer must be provided, bv_len must indicate buffer size
737 * Hex input can be "0x1234" or "'1234'H"
739 * Temporarily modifies the input string.
741 * Note: High bit of binary form is always the sign bit. If the number
742 * is supposed to be positive but has the high bit set, a zero byte
743 * is prepended. It is assumed that this has already been handled on
747 lutil_str2bin( struct berval *in, struct berval *out, void *ctx )
749 char *pin, *pout, ctmp;
751 int i, chunk, len, rc = 0, hex = 0;
752 if ( !out || !out->bv_val || out->bv_len < in->bv_len )
756 /* Leading "0x" for hex input */
757 if ( in->bv_len > 2 && in->bv_val[0] == '0' &&
758 ( in->bv_val[1] == 'x' || in->bv_val[1] == 'X' ) )
760 len = in->bv_len - 2;
761 pin = in->bv_val + 2;
763 } else if ( in->bv_len > 3 && in->bv_val[0] == '\'' &&
764 in->bv_val[in->bv_len-2] == '\'' &&
765 in->bv_val[in->bv_len-1] == 'H' )
767 len = in->bv_len - 3;
768 pin = in->bv_val + 1;
772 #define HEXMAX (2 * sizeof(long))
774 /* Convert a longword at a time, but handle leading
777 chunk = len % HEXMAX;
786 l = strtoul( pin, &end, 16 );
790 ochunk = (chunk + 1)/2;
791 for ( i = ochunk - 1; i >= 0; i-- ) {
800 out->bv_len = pout - out->bv_val;
803 char tmpbuf[64], *tmp;
804 lutil_int_decnum num;
810 num.buf = (unsigned char *)out->bv_val;
811 num.bufsiz = out->bv_len;
812 num.beg = num.bufsiz-1;
814 if ( pin[0] == '-' ) {
820 #define DECMAX 8 /* 8 digits at a time */
822 /* tmp must be at least as large as outbuf */
823 if ( out->bv_len > sizeof(tmpbuf)) {
824 tmp = ber_memalloc_x( out->bv_len, ctx );
828 chunk = len & (DECMAX-1);
836 l = strtol( pin, &end, 10 );
842 scale( l, &num, (unsigned char *)tmp );
847 /* Negate the result */
851 ptr = num.buf+num.beg;
854 for ( i=0; i<num.len; i++ )
857 /* add 1, with carry - overflow handled below */
858 while ( i-- && ! (ptr[i] = (ptr[i] + 1) & 0xff )) ;
860 /* Prepend sign byte if wrong sign bit */
861 if (( num.buf[num.beg] ^ neg ) & 0x80 ) {
864 num.buf[num.beg] = neg;
867 AC_MEMCPY( num.buf, num.buf+num.beg, num.len );
868 out->bv_len = num.len;
870 if ( tmp != tmpbuf ) {
871 ber_memfree_x( tmp, ctx );
877 static char time_unit[] = "dhms";
879 /* Used to parse and unparse time intervals, not timestamps */
889 scale[] = { 86400, 3600, 60, 1 };
893 for ( s = (char *)in; s[ 0 ] != '\0'; ) {
897 /* strtoul() has an odd interface */
898 if ( s[ 0 ] == '-' ) {
902 u = strtoul( s, &next, 10 );
907 if ( next[ 0 ] == '\0' ) {
913 what = strchr( time_unit, next[ 0 ] );
914 if ( what == NULL ) {
918 if ( what - time_unit <= sofar ) {
922 sofar = what - time_unit;
923 t += u * scale[ sofar ];
939 unsigned long v[ 4 ];
943 v[ 1 ] = (t%86400)/3600;
944 v[ 2 ] = (t%3600)/60;
947 for ( i = 0; i < 4; i++ ) {
948 if ( v[i] > 0 || ( i == 3 && ptr == buf ) ) {
949 len = snprintf( ptr, buflen, "%lu%c", v[ i ], time_unit[ i ] );
950 if ( len < 0 || (unsigned)len >= buflen ) {
962 * formatted print to string
964 * - if return code < 0, the error code returned by vsnprintf(3) is returned
966 * - if return code > 0, the buffer was not long enough;
967 * - if next is not NULL, *next will be set to buf + bufsize - 1
968 * - if len is not NULL, *len will contain the required buffer length
970 * - if return code == 0, the buffer was long enough;
971 * - if next is not NULL, *next will point to the end of the string printed so far
972 * - if len is not NULL, *len will contain the length of the string printed so far
975 lutil_snprintf( char *buf, ber_len_t bufsize, char **next, ber_len_t *len, LDAP_CONST char *fmt, ... )
980 assert( buf != NULL );
981 assert( bufsize > 0 );
982 assert( fmt != NULL );
985 ret = vsnprintf( buf, bufsize, fmt, ap );
996 if ( (unsigned) ret >= bufsize ) {
998 *next = &buf[ bufsize - 1 ];
1005 *next = &buf[ ret ];