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/string.h>
22 #include <ac/unistd.h>
36 #include "ldap_defaults.h"
44 /* Some Windows versions accept both forward and backslashes in
45 * directory paths, but we always use backslashes when generating
48 void lutil_slashpath( char *path )
53 while (( c=strchr( p, '/' ))) {
60 char* lutil_progname( const char* name, int argc, char *argv[] )
71 for (i=0; i<argc; i++) __etoa(argv[i]);
75 LUTIL_SLASHPATH( argv[0] );
76 progname = strrchr ( argv[0], *LDAP_DIRSEP );
77 progname = progname ? &progname[1] : argv[0];
82 size_t lutil_gentime( char *s, size_t smax, const struct tm *tm )
86 /* We've been compiling in ASCII so far, but we want EBCDIC now since
87 * strftime only understands EBCDIC input.
89 #pragma convlit(suspend)
91 ret = strftime( s, smax, "%Y%m%d%H%M%SZ", tm );
93 #pragma convlit(resume)
100 size_t lutil_localtime( char *s, size_t smax, const struct tm *tm, long delta )
105 if ( smax < 16 ) { /* YYYYmmddHHMMSSZ */
110 /* We've been compiling in ASCII so far, but we want EBCDIC now since
111 * strftime only understands EBCDIC input.
113 #pragma convlit(suspend)
115 ret = strftime( s, smax, "%Y%m%d%H%M%SZ", tm );
117 #pragma convlit(resume)
120 if ( delta == 0 || ret == 0 ) {
124 if ( smax < 20 ) { /* YYYYmmddHHMMSS+HHMM */
138 snprintf( p, smax - 15, "%02ld%02ld", delta / 3600,
139 ( delta % 3600 ) / 60 );
144 int lutil_tm2time( struct lutil_tm *tm, struct lutil_timet *tt )
146 static int moffset[12] = {
152 tt->tt_usec = tm->tm_usec;
154 /* special case 0000/01/01+00:00:00 is returned as zero */
155 if ( tm->tm_year == -1900 && tm->tm_mon == 0 && tm->tm_mday == 1 &&
156 tm->tm_hour == 0 && tm->tm_min == 0 && tm->tm_sec == 0 ) {
162 /* tm->tm_year is years since 1900 */
163 /* calculate days from years since 1970 (epoch) */
164 tt->tt_sec = tm->tm_year - 70;
167 /* count leap days in preceding years */
168 tt->tt_sec += ((tm->tm_year -69) >> 2);
170 /* calculate days from months */
171 tt->tt_sec += moffset[tm->tm_mon];
173 /* add in this year's leap day, if any */
174 if (((tm->tm_year & 3) == 0) && (tm->tm_mon > 1)) {
178 /* add in days in this month */
179 tt->tt_sec += (tm->tm_mday - 1);
181 /* this function can handle a range of about 17408 years... */
182 /* 86400 seconds in a day, divided by 128 = 675 */
185 /* move high 7 bits into tt_gsec */
186 tt->tt_gsec = tt->tt_sec >> 25;
187 tt->tt_sec -= tt->tt_gsec << 25;
192 /* convert to minutes */
196 /* convert to seconds */
200 /* add remaining seconds */
208 int lutil_parsetime( char *atm, struct lutil_tm *tm )
214 /* Is the stamp reasonably long? */
215 for (i=0; isdigit((unsigned char) atm[i]); i++);
216 if (i < sizeof("00000101000000")-1)
220 * parse the time into a struct tm
222 /* 4 digit year to year - 1900 */
223 tm->tm_year = *ptr++ - '0';
224 tm->tm_year *= 10; tm->tm_year += *ptr++ - '0';
225 tm->tm_year *= 10; tm->tm_year += *ptr++ - '0';
226 tm->tm_year *= 10; tm->tm_year += *ptr++ - '0';
228 /* month 01-12 to 0-11 */
229 tm->tm_mon = *ptr++ - '0';
230 tm->tm_mon *=10; tm->tm_mon += *ptr++ - '0';
231 if (tm->tm_mon < 1 || tm->tm_mon > 12) break;
234 /* day of month 01-31 */
235 tm->tm_mday = *ptr++ - '0';
236 tm->tm_mday *=10; tm->tm_mday += *ptr++ - '0';
237 if (tm->tm_mday < 1 || tm->tm_mday > 31) break;
240 tm->tm_hour = *ptr++ - '0';
241 tm->tm_hour *=10; tm->tm_hour += *ptr++ - '0';
242 if (tm->tm_hour < 0 || tm->tm_hour > 23) break;
245 tm->tm_min = *ptr++ - '0';
246 tm->tm_min *=10; tm->tm_min += *ptr++ - '0';
247 if (tm->tm_min < 0 || tm->tm_min > 59) break;
250 tm->tm_sec = *ptr++ - '0';
251 tm->tm_sec *=10; tm->tm_sec += *ptr++ - '0';
252 if (tm->tm_sec < 0 || tm->tm_sec > 61) break;
254 /* Fractions of seconds */
257 for (i = 0, fracs = 0; isdigit((unsigned char) *ptr); ) {
258 i*=10; i+= *ptr++ - '0';
263 for (i = fracs; i<6; i++)
269 if (*ptr != 'Z') break;
276 /* return a broken out time, with microseconds
277 * Must be mutex-protected.
280 /* Windows SYSTEMTIME only has 10 millisecond resolution, so we
281 * also need to use a high resolution timer to get microseconds.
282 * This is pretty clunky.
285 lutil_gettime( struct lutil_tm *tm )
287 static LARGE_INTEGER cFreq;
288 static LARGE_INTEGER prevCount;
294 GetSystemTime( &st );
295 QueryPerformanceCounter( &count );
297 /* We assume Windows has at least a vague idea of
298 * when a second begins. So we align our microsecond count
299 * with the Windows millisecond count using this offset.
300 * We retain the submillisecond portion of our own count.
302 if ( !cFreq.QuadPart ) {
305 QueryPerformanceFrequency( &cFreq );
307 t = count.QuadPart * 1000000;
311 offset = ( usec - st.wMilliseconds ) * 1000;
314 /* It shouldn't ever go backwards, but multiple CPUs might
315 * be able to hit in the same tick.
317 if ( count.QuadPart <= prevCount.QuadPart ) {
326 /* convert to microseconds */
327 count.QuadPart *= 1000000;
328 count.QuadPart /= cFreq.QuadPart;
329 count.QuadPart -= offset;
331 tm->tm_usec = count.QuadPart % 1000000;
333 /* any difference larger than microseconds is
334 * already reflected in st
337 tm->tm_sec = st.wSecond;
338 tm->tm_min = st.wMinute;
339 tm->tm_hour = st.wHour;
340 tm->tm_mday = st.wDay;
341 tm->tm_mon = st.wMonth - 1;
342 tm->tm_year = st.wYear - 1900;
346 lutil_gettime( struct lutil_tm *ltm )
349 static struct timeval prevTv;
358 gettimeofday( &tv, NULL );
361 if ( tv.tv_sec < prevTv.tv_sec
362 || ( tv.tv_sec == prevTv.tv_sec && tv.tv_usec == prevTv.tv_usec )) {
372 tm = gmtime_r( &t, &tm_buf );
377 ltm->tm_sec = tm->tm_sec;
378 ltm->tm_min = tm->tm_min;
379 ltm->tm_hour = tm->tm_hour;
380 ltm->tm_mday = tm->tm_mday;
381 ltm->tm_mon = tm->tm_mon;
382 ltm->tm_year = tm->tm_year;
383 ltm->tm_usec = tv.tv_usec;
387 /* strcopy is like strcpy except it returns a pointer to the trailing NUL of
388 * the result string. This allows fast construction of catenated strings
389 * without the overhead of strlen/strcat.
400 while ((*a++ = *b++)) ;
404 /* strncopy is like strcpy except it returns a pointer to the trailing NUL of
405 * the result string. This allows fast construction of catenated strings
406 * without the overhead of strlen/strcat.
415 if (!a || !b || n == 0)
418 while ((*a++ = *b++) && n-- > 0) ;
423 int mkstemp( char * template )
426 return open ( mktemp ( template ), O_RDWR|O_CREAT|O_EXCL, 0600 );
441 char buf[MAX_PATH+1];
443 DIR *opendir( char *path )
446 int len = strlen(path);
449 WIN32_FIND_DATA data;
451 if (len+3 >= sizeof(tmp))
459 h = FindFirstFile( tmp, &data );
461 if ( h == INVALID_HANDLE_VALUE )
464 d = ber_memalloc( sizeof(DIR) );
468 d->data.d_name = d->buf;
470 strcpy(d->data.d_name, data.cFileName);
473 struct dirent *readdir(DIR *dir)
475 WIN32_FIND_DATA data;
480 if (!FindNextFile(dir->dir, &data))
482 strcpy(dir->data.d_name, data.cFileName);
486 void closedir(DIR *dir)
494 * Memory Reverse Search
497 lutil_memrchr(const void *b, int c, size_t n)
500 const unsigned char *s, *bb = b, cc = c;
502 for ( s = bb + n; s > bb; ) {
513 lutil_atoix( int *v, const char *s, int x )
521 i = strtol( s, &next, x );
522 if ( next == s || next[ 0 ] != '\0' ) {
526 if ( (long)(int)i != i ) {
536 lutil_atoux( unsigned *v, const char *s, int x )
544 /* strtoul() has an odd interface */
545 if ( s[ 0 ] == '-' ) {
549 u = strtoul( s, &next, x );
550 if ( next == s || next[ 0 ] != '\0' ) {
554 if ( (unsigned long)(unsigned)u != u ) {
564 lutil_atolx( long *v, const char *s, int x )
572 l = strtol( s, &next, x );
573 if ( next == s || next[ 0 ] != '\0' ) {
583 lutil_atoulx( unsigned long *v, const char *s, int x )
591 /* strtoul() has an odd interface */
592 if ( s[ 0 ] == '-' ) {
596 ul = strtoul( s, &next, x );
597 if ( next == s || next[ 0 ] != '\0' ) {
606 /* Multiply an integer by 100000000 and add new */
607 typedef struct lutil_int_decnum {
614 #define FACTOR1 (100000000&0xffff)
615 #define FACTOR2 (100000000>>16)
618 scale( int new, lutil_int_decnum *prev, unsigned char *tmp )
621 unsigned char *in = prev->buf+prev->beg;
623 unsigned char *out = tmp + prev->bufsiz - prev->len;
625 memset( tmp, 0, prev->bufsiz );
627 for ( i = prev->len-1; i>=0; i-- ) {
628 part = in[i] * FACTOR1;
629 for ( j = i; part; j-- ) {
631 out[j] = part & 0xff;
634 part = in[i] * FACTOR2;
635 for ( j = i-2; part; j-- ) {
637 out[j] = part & 0xff;
643 out = tmp + prev->bufsiz;
644 for ( i = -1; new ; i-- ) {
649 prev->beg = prev->bufsiz + i;
651 AC_MEMCPY( prev->buf+prev->beg, tmp+prev->beg, prev->len );
654 /* Convert unlimited length decimal or hex string to binary.
655 * Output buffer must be provided, bv_len must indicate buffer size
656 * Hex input can be "0x1234" or "'1234'H"
658 * Note: High bit of binary form is always the sign bit. If the number
659 * is supposed to be positive but has the high bit set, a zero byte
660 * is prepended. It is assumed that this has already been handled on
664 lutil_str2bin( struct berval *in, struct berval *out )
666 char *pin, *pout, ctmp;
669 int i, chunk, len, rc = 0, hex = 0;
670 if ( !out || !out->bv_val || out->bv_len < in->bv_len )
674 /* Leading "0x" for hex input */
675 if ( in->bv_len > 2 && in->bv_val[0] == '0' &&
676 ( in->bv_val[1] == 'x' || in->bv_val[1] == 'X' ) )
678 len = in->bv_len - 2;
679 pin = in->bv_val + 2;
681 } else if ( in->bv_len > 3 && in->bv_val[0] == '\'' &&
682 in->bv_val[in->bv_len-2] == '\'' &&
683 in->bv_val[in->bv_len-1] == 'H' )
685 len = in->bv_len - 3;
686 pin = in->bv_val + 1;
690 #define HEXMAX (2 * sizeof(long))
691 /* Convert a longword at a time, but handle leading
694 chunk = len & (HEXMAX-1);
702 l = strtol( pin, &end, 16 );
708 for ( i = chunk; i>=0; i-- ) {
713 pout += sizeof(long);
717 out->bv_len = pout + len - out->bv_val;
720 char tmpbuf[64], *tmp;
721 lutil_int_decnum num;
726 num.buf = (unsigned char *)out->bv_val;
727 num.bufsiz = out->bv_len;
728 num.beg = num.bufsiz-1;
730 if ( pin[0] == '-' ) {
736 #define DECMAX 8 /* 8 digits at a time */
738 if ( len > sizeof(tmpbuf)) {
739 tmp = ber_memalloc( len );
743 chunk = len & (DECMAX-1);
751 l = strtol( pin, &end, 10 );
757 scale( l, &num, (unsigned char *)tmp );
762 /* Negate the result */
767 ptr = num.buf+num.beg;
770 for ( i=0; i<num.len; i++ )
773 /* Add 1, with carry */
776 for ( ; i>=0; i-- ) {
783 /* If we overflowed and there's still room,
784 * set an explicit sign byte
786 if ( !( ptr[0] & 0x80 ) && num.beg ) {
789 num.buf[num.beg] = 0x80;
791 } else if (( num.buf[num.beg] & 0x80 ) && num.beg ) {
792 /* positive int with high bit set, prepend 0 */
795 num.buf[num.beg] = 0;
798 AC_MEMCPY( num.buf, num.buf+num.beg, num.len );
799 out->bv_len = num.len;
801 if ( tmp != tmpbuf ) {
808 static char time_unit[] = "dhms";
810 /* Used to parse and unparse time intervals, not timestamps */
820 scale[] = { 86400, 3600, 60, 1 };
824 for ( s = (char *)in; s[ 0 ] != '\0'; ) {
828 /* strtoul() has an odd interface */
829 if ( s[ 0 ] == '-' ) {
833 u = strtoul( s, &next, 10 );
838 if ( next[ 0 ] == '\0' ) {
844 what = strchr( time_unit, next[ 0 ] );
845 if ( what == NULL ) {
849 if ( what - time_unit <= sofar ) {
853 sofar = what - time_unit;
854 t += u * scale[ sofar ];
870 unsigned long v[ 4 ];
874 v[ 1 ] = (t%86400)/3600;
875 v[ 2 ] = (t%3600)/60;
878 for ( i = 0; i < 4; i++ ) {
879 if ( v[i] > 0 || ( i == 3 && ptr == buf ) ) {
880 len = snprintf( ptr, buflen, "%lu%c", v[ i ], time_unit[ i ] );
881 if ( len < 0 || (unsigned)len >= buflen ) {