2 /* This work is part of OpenLDAP Software <http://www.openldap.org/>.
4 * Copyright 1998-2008 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 /* We assume Windows has at least a vague idea of
307 * when a second begins. So we align our microsecond count
308 * with the Windows millisecond count using this offset.
309 * We retain the submillisecond portion of our own count.
311 if ( !cFreq.QuadPart ) {
314 QueryPerformanceFrequency( &cFreq );
316 t = count.QuadPart * 1000000;
320 offset = ( usec - st.wMilliseconds ) * 1000;
323 /* It shouldn't ever go backwards, but multiple CPUs might
324 * be able to hit in the same tick.
326 if ( count.QuadPart <= prevCount.QuadPart ) {
335 /* convert to microseconds */
336 count.QuadPart *= 1000000;
337 count.QuadPart /= cFreq.QuadPart;
338 count.QuadPart -= offset;
340 tm->tm_usec = count.QuadPart % 1000000;
342 /* any difference larger than microseconds is
343 * already reflected in st
346 tm->tm_sec = st.wSecond;
347 tm->tm_min = st.wMinute;
348 tm->tm_hour = st.wHour;
349 tm->tm_mday = st.wDay;
350 tm->tm_mon = st.wMonth - 1;
351 tm->tm_year = st.wYear - 1900;
355 lutil_gettime( struct lutil_tm *ltm )
358 static struct timeval prevTv;
367 gettimeofday( &tv, NULL );
370 if ( tv.tv_sec < prevTv.tv_sec
371 || ( tv.tv_sec == prevTv.tv_sec && tv.tv_usec == prevTv.tv_usec )) {
381 tm = gmtime_r( &t, &tm_buf );
386 ltm->tm_sec = tm->tm_sec;
387 ltm->tm_min = tm->tm_min;
388 ltm->tm_hour = tm->tm_hour;
389 ltm->tm_mday = tm->tm_mday;
390 ltm->tm_mon = tm->tm_mon;
391 ltm->tm_year = tm->tm_year;
392 ltm->tm_usec = tv.tv_usec;
396 /* strcopy is like strcpy except it returns a pointer to the trailing NUL of
397 * the result string. This allows fast construction of catenated strings
398 * without the overhead of strlen/strcat.
409 while ((*a++ = *b++)) ;
413 /* strncopy is like strcpy except it returns a pointer to the trailing NUL of
414 * the result string. This allows fast construction of catenated strings
415 * without the overhead of strlen/strcat.
424 if (!a || !b || n == 0)
427 while ((*a++ = *b++) && n-- > 0) ;
432 int mkstemp( char * template )
435 return open ( mktemp ( template ), O_RDWR|O_CREAT|O_EXCL, 0600 );
450 char buf[MAX_PATH+1];
452 DIR *opendir( char *path )
455 int len = strlen(path);
458 WIN32_FIND_DATA data;
460 if (len+3 >= sizeof(tmp))
468 h = FindFirstFile( tmp, &data );
470 if ( h == INVALID_HANDLE_VALUE )
473 d = ber_memalloc( sizeof(DIR) );
477 d->data.d_name = d->buf;
479 strcpy(d->data.d_name, data.cFileName);
482 struct dirent *readdir(DIR *dir)
484 WIN32_FIND_DATA data;
489 if (!FindNextFile(dir->dir, &data))
491 strcpy(dir->data.d_name, data.cFileName);
495 void closedir(DIR *dir)
503 * Memory Reverse Search
506 lutil_memrchr(const void *b, int c, size_t n)
509 const unsigned char *s, *bb = b, cc = c;
511 for ( s = bb + n; s > bb; ) {
522 lutil_atoix( int *v, const char *s, int x )
530 i = strtol( s, &next, x );
531 if ( next == s || next[ 0 ] != '\0' ) {
535 if ( (long)(int)i != i ) {
545 lutil_atoux( unsigned *v, const char *s, int x )
553 /* strtoul() has an odd interface */
554 if ( s[ 0 ] == '-' ) {
558 u = strtoul( s, &next, x );
559 if ( next == s || next[ 0 ] != '\0' ) {
563 if ( (unsigned long)(unsigned)u != u ) {
573 lutil_atolx( long *v, const char *s, int x )
581 l = strtol( s, &next, x );
582 if ( next == s || next[ 0 ] != '\0' ) {
592 lutil_atoulx( unsigned long *v, const char *s, int x )
600 /* strtoul() has an odd interface */
601 if ( s[ 0 ] == '-' ) {
605 ul = strtoul( s, &next, x );
606 if ( next == s || next[ 0 ] != '\0' ) {
615 /* Multiply an integer by 100000000 and add new */
616 typedef struct lutil_int_decnum {
623 #define FACTOR1 (100000000&0xffff)
624 #define FACTOR2 (100000000>>16)
627 scale( int new, lutil_int_decnum *prev, unsigned char *tmp )
630 unsigned char *in = prev->buf+prev->beg;
632 unsigned char *out = tmp + prev->bufsiz - prev->len;
634 memset( tmp, 0, prev->bufsiz );
636 for ( i = prev->len-1; i>=0; i-- ) {
637 part = in[i] * FACTOR1;
638 for ( j = i; part; j-- ) {
640 out[j] = part & 0xff;
643 part = in[i] * FACTOR2;
644 for ( j = i-2; part; j-- ) {
646 out[j] = part & 0xff;
655 out = tmp + prev->bufsiz;
664 if ( prev->len < i ) {
665 prev->beg = prev->bufsiz - i;
668 AC_MEMCPY( prev->buf+prev->beg, tmp+prev->beg, prev->len );
671 /* Convert unlimited length decimal or hex string to binary.
672 * Output buffer must be provided, bv_len must indicate buffer size
673 * Hex input can be "0x1234" or "'1234'H"
675 * Temporarily modifies the input string.
677 * Note: High bit of binary form is always the sign bit. If the number
678 * is supposed to be positive but has the high bit set, a zero byte
679 * is prepended. It is assumed that this has already been handled on
683 lutil_str2bin( struct berval *in, struct berval *out, void *ctx )
685 char *pin, *pout, ctmp;
688 int i, chunk, len, rc = 0, hex = 0;
689 if ( !out || !out->bv_val || out->bv_len < in->bv_len )
693 /* Leading "0x" for hex input */
694 if ( in->bv_len > 2 && in->bv_val[0] == '0' &&
695 ( in->bv_val[1] == 'x' || in->bv_val[1] == 'X' ) )
697 len = in->bv_len - 2;
698 pin = in->bv_val + 2;
700 } else if ( in->bv_len > 3 && in->bv_val[0] == '\'' &&
701 in->bv_val[in->bv_len-2] == '\'' &&
702 in->bv_val[in->bv_len-1] == 'H' )
704 len = in->bv_len - 3;
705 pin = in->bv_val + 1;
709 #define HEXMAX (2 * sizeof(long))
710 /* Convert a longword at a time, but handle leading
713 chunk = len & (HEXMAX-1);
721 l = strtol( pin, &end, 16 );
727 for ( i = chunk; i>=0; i-- ) {
732 pout += sizeof(long);
736 out->bv_len = pout + len - out->bv_val;
739 char tmpbuf[64], *tmp;
740 lutil_int_decnum num;
745 num.buf = (unsigned char *)out->bv_val;
746 num.bufsiz = out->bv_len;
747 num.beg = num.bufsiz-1;
749 if ( pin[0] == '-' ) {
755 #define DECMAX 8 /* 8 digits at a time */
757 /* tmp must be at least as large as outbuf */
758 if ( out->bv_len > sizeof(tmpbuf)) {
759 tmp = ber_memalloc_x( out->bv_len, ctx );
763 chunk = len & (DECMAX-1);
771 l = strtol( pin, &end, 10 );
777 scale( l, &num, (unsigned char *)tmp );
782 /* Negate the result */
786 ptr = num.buf+num.beg;
789 for ( i=0; i<num.len; i++ )
792 /* add 1, with carry - overflow handled below */
793 while ( i-- && ! (ptr[i] = (ptr[i] + 1) & 0xff )) ;
795 /* Prepend sign byte if wrong sign bit */
796 if (( num.buf[num.beg] ^ neg ) & 0x80 ) {
799 num.buf[num.beg] = neg;
802 AC_MEMCPY( num.buf, num.buf+num.beg, num.len );
803 out->bv_len = num.len;
805 if ( tmp != tmpbuf ) {
806 ber_memfree_x( tmp, ctx );
812 static char time_unit[] = "dhms";
814 /* Used to parse and unparse time intervals, not timestamps */
824 scale[] = { 86400, 3600, 60, 1 };
828 for ( s = (char *)in; s[ 0 ] != '\0'; ) {
832 /* strtoul() has an odd interface */
833 if ( s[ 0 ] == '-' ) {
837 u = strtoul( s, &next, 10 );
842 if ( next[ 0 ] == '\0' ) {
848 what = strchr( time_unit, next[ 0 ] );
849 if ( what == NULL ) {
853 if ( what - time_unit <= sofar ) {
857 sofar = what - time_unit;
858 t += u * scale[ sofar ];
874 unsigned long v[ 4 ];
878 v[ 1 ] = (t%86400)/3600;
879 v[ 2 ] = (t%3600)/60;
882 for ( i = 0; i < 4; i++ ) {
883 if ( v[i] > 0 || ( i == 3 && ptr == buf ) ) {
884 len = snprintf( ptr, buflen, "%lu%c", v[ i ], time_unit[ i ] );
885 if ( len < 0 || (unsigned)len >= buflen ) {
897 * formatted print to string
899 * - if return code < 0, the error code returned by vsnprintf(3) is returned
901 * - if return code > 0, the buffer was not long enough;
902 * - if next is not NULL, *next will be set to buf + bufsize - 1
903 * - if len is not NULL, *len will contain the required buffer length
905 * - if return code == 0, the buffer was long enough;
906 * - if next is not NULL, *next will point to the end of the string printed so far
907 * - if len is not NULL, *len will contain the length of the string printed so far
910 lutil_snprintf( char *buf, ber_len_t bufsize, char **next, ber_len_t *len, LDAP_CONST char *fmt, ... )
915 assert( buf != NULL );
916 assert( bufsize > 0 );
917 assert( fmt != NULL );
920 ret = vsnprintf( buf, bufsize, fmt, ap );
931 if ( ret >= bufsize ) {
933 *next = &buf[ bufsize - 1 ];