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 );
476 char buf[MAX_PATH+1];
478 DIR *opendir( char *path )
481 int len = strlen(path);
484 WIN32_FIND_DATA data;
486 if (len+3 >= sizeof(tmp))
494 h = FindFirstFile( tmp, &data );
496 if ( h == INVALID_HANDLE_VALUE )
499 d = ber_memalloc( sizeof(DIR) );
503 d->data.d_name = d->buf;
505 strcpy(d->data.d_name, data.cFileName);
508 struct dirent *readdir(DIR *dir)
510 WIN32_FIND_DATA data;
515 if (!FindNextFile(dir->dir, &data))
517 strcpy(dir->data.d_name, data.cFileName);
521 void closedir(DIR *dir)
529 * Memory Reverse Search
532 lutil_memrchr(const void *b, int c, size_t n)
535 const unsigned char *s, *bb = b, cc = c;
537 for ( s = bb + n; s > bb; ) {
548 lutil_atoix( int *v, const char *s, int x )
556 i = strtol( s, &next, x );
557 if ( next == s || next[ 0 ] != '\0' ) {
561 if ( (long)(int)i != i ) {
571 lutil_atoux( unsigned *v, const char *s, int x )
579 /* strtoul() has an odd interface */
580 if ( s[ 0 ] == '-' ) {
584 u = strtoul( s, &next, x );
585 if ( next == s || next[ 0 ] != '\0' ) {
589 if ( (unsigned long)(unsigned)u != u ) {
599 lutil_atolx( long *v, const char *s, int x )
607 l = strtol( s, &next, x );
608 if ( next == s || next[ 0 ] != '\0' ) {
618 lutil_atoulx( unsigned long *v, const char *s, int x )
626 /* strtoul() has an odd interface */
627 if ( s[ 0 ] == '-' ) {
631 ul = strtoul( s, &next, x );
632 if ( next == s || next[ 0 ] != '\0' ) {
641 /* Multiply an integer by 100000000 and add new */
642 typedef struct lutil_int_decnum {
649 #define FACTOR1 (100000000&0xffff)
650 #define FACTOR2 (100000000>>16)
653 scale( int new, lutil_int_decnum *prev, unsigned char *tmp )
656 unsigned char *in = prev->buf+prev->beg;
658 unsigned char *out = tmp + prev->bufsiz - prev->len;
660 memset( tmp, 0, prev->bufsiz );
662 for ( i = prev->len-1; i>=0; i-- ) {
663 part = in[i] * FACTOR1;
664 for ( j = i; part; j-- ) {
666 out[j] = part & 0xff;
669 part = in[i] * FACTOR2;
670 for ( j = i-2; part; j-- ) {
672 out[j] = part & 0xff;
681 out = tmp + prev->bufsiz;
690 if ( prev->len < i ) {
691 prev->beg = prev->bufsiz - i;
694 AC_MEMCPY( prev->buf+prev->beg, tmp+prev->beg, prev->len );
697 /* Convert unlimited length decimal or hex string to binary.
698 * Output buffer must be provided, bv_len must indicate buffer size
699 * Hex input can be "0x1234" or "'1234'H"
701 * Temporarily modifies the input string.
703 * Note: High bit of binary form is always the sign bit. If the number
704 * is supposed to be positive but has the high bit set, a zero byte
705 * is prepended. It is assumed that this has already been handled on
709 lutil_str2bin( struct berval *in, struct berval *out, void *ctx )
711 char *pin, *pout, ctmp;
713 int i, chunk, len, rc = 0, hex = 0;
714 if ( !out || !out->bv_val || out->bv_len < in->bv_len )
718 /* Leading "0x" for hex input */
719 if ( in->bv_len > 2 && in->bv_val[0] == '0' &&
720 ( in->bv_val[1] == 'x' || in->bv_val[1] == 'X' ) )
722 len = in->bv_len - 2;
723 pin = in->bv_val + 2;
725 } else if ( in->bv_len > 3 && in->bv_val[0] == '\'' &&
726 in->bv_val[in->bv_len-2] == '\'' &&
727 in->bv_val[in->bv_len-1] == 'H' )
729 len = in->bv_len - 3;
730 pin = in->bv_val + 1;
734 #define HEXMAX (2 * sizeof(long))
736 /* Convert a longword at a time, but handle leading
739 chunk = len % HEXMAX;
748 l = strtoul( pin, &end, 16 );
752 ochunk = (chunk + 1)/2;
753 for ( i = ochunk - 1; i >= 0; i-- ) {
762 out->bv_len = pout - out->bv_val;
765 char tmpbuf[64], *tmp;
766 lutil_int_decnum num;
772 num.buf = (unsigned char *)out->bv_val;
773 num.bufsiz = out->bv_len;
774 num.beg = num.bufsiz-1;
776 if ( pin[0] == '-' ) {
782 #define DECMAX 8 /* 8 digits at a time */
784 /* tmp must be at least as large as outbuf */
785 if ( out->bv_len > sizeof(tmpbuf)) {
786 tmp = ber_memalloc_x( out->bv_len, ctx );
790 chunk = len & (DECMAX-1);
798 l = strtol( pin, &end, 10 );
804 scale( l, &num, (unsigned char *)tmp );
809 /* Negate the result */
813 ptr = num.buf+num.beg;
816 for ( i=0; i<num.len; i++ )
819 /* add 1, with carry - overflow handled below */
820 while ( i-- && ! (ptr[i] = (ptr[i] + 1) & 0xff )) ;
822 /* Prepend sign byte if wrong sign bit */
823 if (( num.buf[num.beg] ^ neg ) & 0x80 ) {
826 num.buf[num.beg] = neg;
829 AC_MEMCPY( num.buf, num.buf+num.beg, num.len );
830 out->bv_len = num.len;
832 if ( tmp != tmpbuf ) {
833 ber_memfree_x( tmp, ctx );
839 static char time_unit[] = "dhms";
841 /* Used to parse and unparse time intervals, not timestamps */
851 scale[] = { 86400, 3600, 60, 1 };
855 for ( s = (char *)in; s[ 0 ] != '\0'; ) {
859 /* strtoul() has an odd interface */
860 if ( s[ 0 ] == '-' ) {
864 u = strtoul( s, &next, 10 );
869 if ( next[ 0 ] == '\0' ) {
875 what = strchr( time_unit, next[ 0 ] );
876 if ( what == NULL ) {
880 if ( what - time_unit <= sofar ) {
884 sofar = what - time_unit;
885 t += u * scale[ sofar ];
901 unsigned long v[ 4 ];
905 v[ 1 ] = (t%86400)/3600;
906 v[ 2 ] = (t%3600)/60;
909 for ( i = 0; i < 4; i++ ) {
910 if ( v[i] > 0 || ( i == 3 && ptr == buf ) ) {
911 len = snprintf( ptr, buflen, "%lu%c", v[ i ], time_unit[ i ] );
912 if ( len < 0 || (unsigned)len >= buflen ) {
924 * formatted print to string
926 * - if return code < 0, the error code returned by vsnprintf(3) is returned
928 * - if return code > 0, the buffer was not long enough;
929 * - if next is not NULL, *next will be set to buf + bufsize - 1
930 * - if len is not NULL, *len will contain the required buffer length
932 * - if return code == 0, the buffer was long enough;
933 * - if next is not NULL, *next will point to the end of the string printed so far
934 * - if len is not NULL, *len will contain the length of the string printed so far
937 lutil_snprintf( char *buf, ber_len_t bufsize, char **next, ber_len_t *len, LDAP_CONST char *fmt, ... )
942 assert( buf != NULL );
943 assert( bufsize > 0 );
944 assert( fmt != NULL );
947 ret = vsnprintf( buf, bufsize, fmt, ap );
958 if ( (unsigned) ret >= bufsize ) {
960 *next = &buf[ bufsize - 1 ];