2 /* This work is part of OpenLDAP Software <http://www.openldap.org/>.
4 * Copyright 1998-2007 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];
84 size_t lutil_gentime( char *s, size_t smax, const struct tm *tm )
88 /* We've been compiling in ASCII so far, but we want EBCDIC now since
89 * strftime only understands EBCDIC input.
91 #pragma convlit(suspend)
93 ret = strftime( s, smax, "%Y%m%d%H%M%SZ", tm );
95 #pragma convlit(resume)
102 size_t lutil_localtime( char *s, size_t smax, const struct tm *tm, long delta )
107 if ( smax < 16 ) { /* YYYYmmddHHMMSSZ */
112 /* We've been compiling in ASCII so far, but we want EBCDIC now since
113 * strftime only understands EBCDIC input.
115 #pragma convlit(suspend)
117 ret = strftime( s, smax, "%Y%m%d%H%M%SZ", tm );
119 #pragma convlit(resume)
122 if ( delta == 0 || ret == 0 ) {
126 if ( smax < 20 ) { /* YYYYmmddHHMMSS+HHMM */
140 snprintf( p, smax - 15, "%02ld%02ld", delta / 3600,
141 ( delta % 3600 ) / 60 );
146 int lutil_tm2time( struct lutil_tm *tm, struct lutil_timet *tt )
148 static int moffset[12] = {
154 tt->tt_usec = tm->tm_usec;
156 /* special case 0000/01/01+00:00:00 is returned as zero */
157 if ( tm->tm_year == -1900 && tm->tm_mon == 0 && tm->tm_mday == 1 &&
158 tm->tm_hour == 0 && tm->tm_min == 0 && tm->tm_sec == 0 ) {
164 /* tm->tm_year is years since 1900 */
165 /* calculate days from years since 1970 (epoch) */
166 tt->tt_sec = tm->tm_year - 70;
169 /* count leap days in preceding years */
170 tt->tt_sec += ((tm->tm_year -69) >> 2);
172 /* calculate days from months */
173 tt->tt_sec += moffset[tm->tm_mon];
175 /* add in this year's leap day, if any */
176 if (((tm->tm_year & 3) == 0) && (tm->tm_mon > 1)) {
180 /* add in days in this month */
181 tt->tt_sec += (tm->tm_mday - 1);
183 /* this function can handle a range of about 17408 years... */
184 /* 86400 seconds in a day, divided by 128 = 675 */
187 /* move high 7 bits into tt_gsec */
188 tt->tt_gsec = tt->tt_sec >> 25;
189 tt->tt_sec -= tt->tt_gsec << 25;
194 /* convert to minutes */
198 /* convert to seconds */
202 /* add remaining seconds */
210 int lutil_parsetime( char *atm, struct lutil_tm *tm )
216 /* Is the stamp reasonably long? */
217 for (i=0; isdigit((unsigned char) atm[i]); i++);
218 if (i < sizeof("00000101000000")-1)
222 * parse the time into a struct tm
224 /* 4 digit year to year - 1900 */
225 tm->tm_year = *ptr++ - '0';
226 tm->tm_year *= 10; tm->tm_year += *ptr++ - '0';
227 tm->tm_year *= 10; tm->tm_year += *ptr++ - '0';
228 tm->tm_year *= 10; tm->tm_year += *ptr++ - '0';
230 /* month 01-12 to 0-11 */
231 tm->tm_mon = *ptr++ - '0';
232 tm->tm_mon *=10; tm->tm_mon += *ptr++ - '0';
233 if (tm->tm_mon < 1 || tm->tm_mon > 12) break;
236 /* day of month 01-31 */
237 tm->tm_mday = *ptr++ - '0';
238 tm->tm_mday *=10; tm->tm_mday += *ptr++ - '0';
239 if (tm->tm_mday < 1 || tm->tm_mday > 31) break;
242 tm->tm_hour = *ptr++ - '0';
243 tm->tm_hour *=10; tm->tm_hour += *ptr++ - '0';
244 if (tm->tm_hour < 0 || tm->tm_hour > 23) break;
247 tm->tm_min = *ptr++ - '0';
248 tm->tm_min *=10; tm->tm_min += *ptr++ - '0';
249 if (tm->tm_min < 0 || tm->tm_min > 59) break;
252 tm->tm_sec = *ptr++ - '0';
253 tm->tm_sec *=10; tm->tm_sec += *ptr++ - '0';
254 if (tm->tm_sec < 0 || tm->tm_sec > 61) break;
256 /* Fractions of seconds */
259 for (i = 0, fracs = 0; isdigit((unsigned char) *ptr); ) {
260 i*=10; i+= *ptr++ - '0';
265 for (i = fracs; i<6; i++)
271 if (*ptr != 'Z') break;
278 /* return a broken out time, with microseconds
279 * Must be mutex-protected.
282 /* Windows SYSTEMTIME only has 10 millisecond resolution, so we
283 * also need to use a high resolution timer to get microseconds.
284 * This is pretty clunky.
287 lutil_gettime( struct lutil_tm *tm )
289 static LARGE_INTEGER cFreq;
290 static LARGE_INTEGER prevCount;
296 GetSystemTime( &st );
297 QueryPerformanceCounter( &count );
299 /* We assume Windows has at least a vague idea of
300 * when a second begins. So we align our microsecond count
301 * with the Windows millisecond count using this offset.
302 * We retain the submillisecond portion of our own count.
304 if ( !cFreq.QuadPart ) {
307 QueryPerformanceFrequency( &cFreq );
309 t = count.QuadPart * 1000000;
313 offset = ( usec - st.wMilliseconds ) * 1000;
316 /* It shouldn't ever go backwards, but multiple CPUs might
317 * be able to hit in the same tick.
319 if ( count.QuadPart <= prevCount.QuadPart ) {
328 /* convert to microseconds */
329 count.QuadPart *= 1000000;
330 count.QuadPart /= cFreq.QuadPart;
331 count.QuadPart -= offset;
333 tm->tm_usec = count.QuadPart % 1000000;
335 /* any difference larger than microseconds is
336 * already reflected in st
339 tm->tm_sec = st.wSecond;
340 tm->tm_min = st.wMinute;
341 tm->tm_hour = st.wHour;
342 tm->tm_mday = st.wDay;
343 tm->tm_mon = st.wMonth - 1;
344 tm->tm_year = st.wYear - 1900;
348 lutil_gettime( struct lutil_tm *ltm )
351 static struct timeval prevTv;
360 gettimeofday( &tv, NULL );
363 if ( tv.tv_sec < prevTv.tv_sec
364 || ( tv.tv_sec == prevTv.tv_sec && tv.tv_usec == prevTv.tv_usec )) {
374 tm = gmtime_r( &t, &tm_buf );
379 ltm->tm_sec = tm->tm_sec;
380 ltm->tm_min = tm->tm_min;
381 ltm->tm_hour = tm->tm_hour;
382 ltm->tm_mday = tm->tm_mday;
383 ltm->tm_mon = tm->tm_mon;
384 ltm->tm_year = tm->tm_year;
385 ltm->tm_usec = tv.tv_usec;
389 /* strcopy is like strcpy except it returns a pointer to the trailing NUL of
390 * the result string. This allows fast construction of catenated strings
391 * without the overhead of strlen/strcat.
402 while ((*a++ = *b++)) ;
406 /* strncopy is like strcpy except it returns a pointer to the trailing NUL of
407 * the result string. This allows fast construction of catenated strings
408 * without the overhead of strlen/strcat.
417 if (!a || !b || n == 0)
420 while ((*a++ = *b++) && n-- > 0) ;
425 int mkstemp( char * template )
428 return open ( mktemp ( template ), O_RDWR|O_CREAT|O_EXCL, 0600 );
443 char buf[MAX_PATH+1];
445 DIR *opendir( char *path )
448 int len = strlen(path);
451 WIN32_FIND_DATA data;
453 if (len+3 >= sizeof(tmp))
461 h = FindFirstFile( tmp, &data );
463 if ( h == INVALID_HANDLE_VALUE )
466 d = ber_memalloc( sizeof(DIR) );
470 d->data.d_name = d->buf;
472 strcpy(d->data.d_name, data.cFileName);
475 struct dirent *readdir(DIR *dir)
477 WIN32_FIND_DATA data;
482 if (!FindNextFile(dir->dir, &data))
484 strcpy(dir->data.d_name, data.cFileName);
488 void closedir(DIR *dir)
496 * Memory Reverse Search
499 lutil_memrchr(const void *b, int c, size_t n)
502 const unsigned char *s, *bb = b, cc = c;
504 for ( s = bb + n; s > bb; ) {
515 lutil_atoix( int *v, const char *s, int x )
523 i = strtol( s, &next, x );
524 if ( next == s || next[ 0 ] != '\0' ) {
528 if ( (long)(int)i != i ) {
538 lutil_atoux( unsigned *v, const char *s, int x )
546 /* strtoul() has an odd interface */
547 if ( s[ 0 ] == '-' ) {
551 u = strtoul( s, &next, x );
552 if ( next == s || next[ 0 ] != '\0' ) {
556 if ( (unsigned long)(unsigned)u != u ) {
566 lutil_atolx( long *v, const char *s, int x )
574 l = strtol( s, &next, x );
575 if ( next == s || next[ 0 ] != '\0' ) {
585 lutil_atoulx( unsigned long *v, const char *s, int x )
593 /* strtoul() has an odd interface */
594 if ( s[ 0 ] == '-' ) {
598 ul = strtoul( s, &next, x );
599 if ( next == s || next[ 0 ] != '\0' ) {
608 /* Multiply an integer by 100000000 and add new */
609 typedef struct lutil_int_decnum {
616 #define FACTOR1 (100000000&0xffff)
617 #define FACTOR2 (100000000>>16)
620 scale( int new, lutil_int_decnum *prev, unsigned char *tmp )
623 unsigned char *in = prev->buf+prev->beg;
625 unsigned char *out = tmp + prev->bufsiz - prev->len;
627 memset( tmp, 0, prev->bufsiz );
629 for ( i = prev->len-1; i>=0; i-- ) {
630 part = in[i] * FACTOR1;
631 for ( j = i; part; j-- ) {
633 out[j] = part & 0xff;
636 part = in[i] * FACTOR2;
637 for ( j = i-2; part; j-- ) {
639 out[j] = part & 0xff;
648 out = tmp + prev->bufsiz;
657 if ( prev->len < i ) {
658 prev->beg = prev->bufsiz - i;
661 AC_MEMCPY( prev->buf+prev->beg, tmp+prev->beg, prev->len );
664 /* Convert unlimited length decimal or hex string to binary.
665 * Output buffer must be provided, bv_len must indicate buffer size
666 * Hex input can be "0x1234" or "'1234'H"
668 * Temporarily modifies the input string.
670 * Note: High bit of binary form is always the sign bit. If the number
671 * is supposed to be positive but has the high bit set, a zero byte
672 * is prepended. It is assumed that this has already been handled on
676 lutil_str2bin( struct berval *in, struct berval *out, void *ctx )
678 char *pin, *pout, ctmp;
681 int i, chunk, len, rc = 0, hex = 0;
682 if ( !out || !out->bv_val || out->bv_len < in->bv_len )
686 /* Leading "0x" for hex input */
687 if ( in->bv_len > 2 && in->bv_val[0] == '0' &&
688 ( in->bv_val[1] == 'x' || in->bv_val[1] == 'X' ) )
690 len = in->bv_len - 2;
691 pin = in->bv_val + 2;
693 } else if ( in->bv_len > 3 && in->bv_val[0] == '\'' &&
694 in->bv_val[in->bv_len-2] == '\'' &&
695 in->bv_val[in->bv_len-1] == 'H' )
697 len = in->bv_len - 3;
698 pin = in->bv_val + 1;
702 #define HEXMAX (2 * sizeof(long))
703 /* Convert a longword at a time, but handle leading
706 chunk = len & (HEXMAX-1);
714 l = strtol( pin, &end, 16 );
720 for ( i = chunk; i>=0; i-- ) {
725 pout += sizeof(long);
729 out->bv_len = pout + len - out->bv_val;
732 char tmpbuf[64], *tmp;
733 lutil_int_decnum num;
738 num.buf = (unsigned char *)out->bv_val;
739 num.bufsiz = out->bv_len;
740 num.beg = num.bufsiz-1;
742 if ( pin[0] == '-' ) {
748 #define DECMAX 8 /* 8 digits at a time */
750 /* tmp must be at least as large as outbuf */
751 if ( out->bv_len > sizeof(tmpbuf)) {
752 tmp = ber_memalloc_x( out->bv_len, ctx );
756 chunk = len & (DECMAX-1);
764 l = strtol( pin, &end, 10 );
770 scale( l, &num, (unsigned char *)tmp );
775 /* Negate the result */
779 ptr = num.buf+num.beg;
782 for ( i=0; i<num.len; i++ )
785 /* add 1, with carry - overflow handled below */
786 while ( i-- && ! (ptr[i] = (ptr[i] + 1) & 0xff )) ;
788 /* Prepend sign byte if wrong sign bit */
789 if (( num.buf[num.beg] ^ neg ) & 0x80 ) {
792 num.buf[num.beg] = neg;
795 AC_MEMCPY( num.buf, num.buf+num.beg, num.len );
796 out->bv_len = num.len;
798 if ( tmp != tmpbuf ) {
799 ber_memfree_x( tmp, ctx );
805 static char time_unit[] = "dhms";
807 /* Used to parse and unparse time intervals, not timestamps */
817 scale[] = { 86400, 3600, 60, 1 };
821 for ( s = (char *)in; s[ 0 ] != '\0'; ) {
825 /* strtoul() has an odd interface */
826 if ( s[ 0 ] == '-' ) {
830 u = strtoul( s, &next, 10 );
835 if ( next[ 0 ] == '\0' ) {
841 what = strchr( time_unit, next[ 0 ] );
842 if ( what == NULL ) {
846 if ( what - time_unit <= sofar ) {
850 sofar = what - time_unit;
851 t += u * scale[ sofar ];
867 unsigned long v[ 4 ];
871 v[ 1 ] = (t%86400)/3600;
872 v[ 2 ] = (t%3600)/60;
875 for ( i = 0; i < 4; i++ ) {
876 if ( v[i] > 0 || ( i == 3 && ptr == buf ) ) {
877 len = snprintf( ptr, buflen, "%lu%c", v[ i ], time_unit[ i ] );
878 if ( len < 0 || (unsigned)len >= buflen ) {
890 * formatted print to string
892 * - if return code < 0, the error code returned by vsnprintf(3) is returned
894 * - if return code > 0, the buffer was not long enough;
895 * - if next is not NULL, *next will be set to buf + bufsize - 1
896 * - if len is not NULL, *len will contain the required buffer length
898 * - if return code == 0, the buffer was long enough;
899 * - if next is not NULL, *next will point to the end of the string printed so far
900 * - if len is not NULL, *len will contain the length of the string printed so far
903 lutil_snprintf( char *buf, ber_len_t bufsize, char **next, ber_len_t *len, LDAP_CONST char *fmt, ... )
908 assert( buf != NULL );
909 assert( bufsize > 0 );
910 assert( fmt != NULL );
913 ret = vsnprintf( buf, bufsize, fmt, ap );
924 if ( ret >= bufsize ) {
926 *next = &buf[ bufsize - 1 ];