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"
45 /* Some Windows versions accept both forward and backslashes in
46 * directory paths, but we always use backslashes when generating
49 void lutil_slashpath( char *path )
54 while (( c=strchr( p, '/' ))) {
61 char* lutil_progname( const char* name, int argc, char *argv[] )
72 for (i=0; i<argc; i++) __etoa(argv[i]);
76 LUTIL_SLASHPATH( argv[0] );
77 progname = strrchr ( argv[0], *LDAP_DIRSEP );
78 progname = progname ? &progname[1] : argv[0];
83 size_t lutil_gentime( char *s, size_t smax, const struct tm *tm )
87 /* We've been compiling in ASCII so far, but we want EBCDIC now since
88 * strftime only understands EBCDIC input.
90 #pragma convlit(suspend)
92 ret = strftime( s, smax, "%Y%m%d%H%M%SZ", tm );
94 #pragma convlit(resume)
101 size_t lutil_localtime( char *s, size_t smax, const struct tm *tm, long delta )
106 if ( smax < 16 ) { /* YYYYmmddHHMMSSZ */
111 /* We've been compiling in ASCII so far, but we want EBCDIC now since
112 * strftime only understands EBCDIC input.
114 #pragma convlit(suspend)
116 ret = strftime( s, smax, "%Y%m%d%H%M%SZ", tm );
118 #pragma convlit(resume)
121 if ( delta == 0 || ret == 0 ) {
125 if ( smax < 20 ) { /* YYYYmmddHHMMSS+HHMM */
139 snprintf( p, smax - 15, "%02ld%02ld", delta / 3600,
140 ( delta % 3600 ) / 60 );
145 int lutil_tm2time( struct lutil_tm *tm, struct lutil_timet *tt )
147 static int moffset[12] = {
153 tt->tt_usec = tm->tm_usec;
155 /* special case 0000/01/01+00:00:00 is returned as zero */
156 if ( tm->tm_year == -1900 && tm->tm_mon == 0 && tm->tm_mday == 1 &&
157 tm->tm_hour == 0 && tm->tm_min == 0 && tm->tm_sec == 0 ) {
163 /* tm->tm_year is years since 1900 */
164 /* calculate days from years since 1970 (epoch) */
165 tt->tt_sec = tm->tm_year - 70;
168 /* count leap days in preceding years */
169 tt->tt_sec += ((tm->tm_year -69) >> 2);
171 /* calculate days from months */
172 tt->tt_sec += moffset[tm->tm_mon];
174 /* add in this year's leap day, if any */
175 if (((tm->tm_year & 3) == 0) && (tm->tm_mon > 1)) {
179 /* add in days in this month */
180 tt->tt_sec += (tm->tm_mday - 1);
182 /* this function can handle a range of about 17408 years... */
183 /* 86400 seconds in a day, divided by 128 = 675 */
186 /* move high 7 bits into tt_gsec */
187 tt->tt_gsec = tt->tt_sec >> 25;
188 tt->tt_sec -= tt->tt_gsec << 25;
193 /* convert to minutes */
197 /* convert to seconds */
201 /* add remaining seconds */
209 int lutil_parsetime( char *atm, struct lutil_tm *tm )
215 /* Is the stamp reasonably long? */
216 for (i=0; isdigit((unsigned char) atm[i]); i++);
217 if (i < sizeof("00000101000000")-1)
221 * parse the time into a struct tm
223 /* 4 digit year to year - 1900 */
224 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';
227 tm->tm_year *= 10; tm->tm_year += *ptr++ - '0';
229 /* month 01-12 to 0-11 */
230 tm->tm_mon = *ptr++ - '0';
231 tm->tm_mon *=10; tm->tm_mon += *ptr++ - '0';
232 if (tm->tm_mon < 1 || tm->tm_mon > 12) break;
235 /* day of month 01-31 */
236 tm->tm_mday = *ptr++ - '0';
237 tm->tm_mday *=10; tm->tm_mday += *ptr++ - '0';
238 if (tm->tm_mday < 1 || tm->tm_mday > 31) break;
241 tm->tm_hour = *ptr++ - '0';
242 tm->tm_hour *=10; tm->tm_hour += *ptr++ - '0';
243 if (tm->tm_hour < 0 || tm->tm_hour > 23) break;
246 tm->tm_min = *ptr++ - '0';
247 tm->tm_min *=10; tm->tm_min += *ptr++ - '0';
248 if (tm->tm_min < 0 || tm->tm_min > 59) break;
251 tm->tm_sec = *ptr++ - '0';
252 tm->tm_sec *=10; tm->tm_sec += *ptr++ - '0';
253 if (tm->tm_sec < 0 || tm->tm_sec > 61) break;
255 /* Fractions of seconds */
258 for (i = 0, fracs = 0; isdigit((unsigned char) *ptr); ) {
259 i*=10; i+= *ptr++ - '0';
264 for (i = fracs; i<6; i++)
270 if (*ptr != 'Z') break;
277 /* return a broken out time, with microseconds
278 * Must be mutex-protected.
281 /* Windows SYSTEMTIME only has 10 millisecond resolution, so we
282 * also need to use a high resolution timer to get microseconds.
283 * This is pretty clunky.
286 lutil_gettime( struct lutil_tm *tm )
288 static LARGE_INTEGER cFreq;
289 static LARGE_INTEGER prevCount;
295 GetSystemTime( &st );
296 QueryPerformanceCounter( &count );
298 /* We assume Windows has at least a vague idea of
299 * when a second begins. So we align our microsecond count
300 * with the Windows millisecond count using this offset.
301 * We retain the submillisecond portion of our own count.
303 if ( !cFreq.QuadPart ) {
306 QueryPerformanceFrequency( &cFreq );
308 t = count.QuadPart * 1000000;
312 offset = ( usec - st.wMilliseconds ) * 1000;
315 /* It shouldn't ever go backwards, but multiple CPUs might
316 * be able to hit in the same tick.
318 if ( count.QuadPart <= prevCount.QuadPart ) {
327 /* convert to microseconds */
328 count.QuadPart *= 1000000;
329 count.QuadPart /= cFreq.QuadPart;
330 count.QuadPart -= offset;
332 tm->tm_usec = count.QuadPart % 1000000;
334 /* any difference larger than microseconds is
335 * already reflected in st
338 tm->tm_sec = st.wSecond;
339 tm->tm_min = st.wMinute;
340 tm->tm_hour = st.wHour;
341 tm->tm_mday = st.wDay;
342 tm->tm_mon = st.wMonth - 1;
343 tm->tm_year = st.wYear - 1900;
347 lutil_gettime( struct lutil_tm *ltm )
350 static struct timeval prevTv;
359 gettimeofday( &tv, NULL );
362 if ( tv.tv_sec < prevTv.tv_sec
363 || ( tv.tv_sec == prevTv.tv_sec && tv.tv_usec == prevTv.tv_usec )) {
373 tm = gmtime_r( &t, &tm_buf );
378 ltm->tm_sec = tm->tm_sec;
379 ltm->tm_min = tm->tm_min;
380 ltm->tm_hour = tm->tm_hour;
381 ltm->tm_mday = tm->tm_mday;
382 ltm->tm_mon = tm->tm_mon;
383 ltm->tm_year = tm->tm_year;
384 ltm->tm_usec = tv.tv_usec;
388 /* strcopy is like strcpy except it returns a pointer to the trailing NUL of
389 * the result string. This allows fast construction of catenated strings
390 * without the overhead of strlen/strcat.
401 while ((*a++ = *b++)) ;
405 /* strncopy is like strcpy except it returns a pointer to the trailing NUL of
406 * the result string. This allows fast construction of catenated strings
407 * without the overhead of strlen/strcat.
416 if (!a || !b || n == 0)
419 while ((*a++ = *b++) && n-- > 0) ;
424 int mkstemp( char * template )
427 return open ( mktemp ( template ), O_RDWR|O_CREAT|O_EXCL, 0600 );
442 char buf[MAX_PATH+1];
444 DIR *opendir( char *path )
447 int len = strlen(path);
450 WIN32_FIND_DATA data;
452 if (len+3 >= sizeof(tmp))
460 h = FindFirstFile( tmp, &data );
462 if ( h == INVALID_HANDLE_VALUE )
465 d = ber_memalloc( sizeof(DIR) );
469 d->data.d_name = d->buf;
471 strcpy(d->data.d_name, data.cFileName);
474 struct dirent *readdir(DIR *dir)
476 WIN32_FIND_DATA data;
481 if (!FindNextFile(dir->dir, &data))
483 strcpy(dir->data.d_name, data.cFileName);
487 void closedir(DIR *dir)
495 * Memory Reverse Search
498 lutil_memrchr(const void *b, int c, size_t n)
501 const unsigned char *s, *bb = b, cc = c;
503 for ( s = bb + n; s > bb; ) {
514 lutil_atoix( int *v, const char *s, int x )
522 i = strtol( s, &next, x );
523 if ( next == s || next[ 0 ] != '\0' ) {
527 if ( (long)(int)i != i ) {
537 lutil_atoux( unsigned *v, const char *s, int x )
545 /* strtoul() has an odd interface */
546 if ( s[ 0 ] == '-' ) {
550 u = strtoul( s, &next, x );
551 if ( next == s || next[ 0 ] != '\0' ) {
555 if ( (unsigned long)(unsigned)u != u ) {
565 lutil_atolx( long *v, const char *s, int x )
573 l = strtol( s, &next, x );
574 if ( next == s || next[ 0 ] != '\0' ) {
584 lutil_atoulx( unsigned long *v, const char *s, int x )
592 /* strtoul() has an odd interface */
593 if ( s[ 0 ] == '-' ) {
597 ul = strtoul( s, &next, x );
598 if ( next == s || next[ 0 ] != '\0' ) {
607 /* Multiply an integer by 100000000 and add new */
608 typedef struct lutil_int_decnum {
615 #define FACTOR1 (100000000&0xffff)
616 #define FACTOR2 (100000000>>16)
619 scale( int new, lutil_int_decnum *prev, unsigned char *tmp )
622 unsigned char *in = prev->buf+prev->beg;
624 unsigned char *out = tmp + prev->bufsiz - prev->len;
626 memset( tmp, 0, prev->bufsiz );
628 for ( i = prev->len-1; i>=0; i-- ) {
629 part = in[i] * FACTOR1;
630 for ( j = i; part; j-- ) {
632 out[j] = part & 0xff;
635 part = in[i] * FACTOR2;
636 for ( j = i-2; part; j-- ) {
638 out[j] = part & 0xff;
647 out = tmp + prev->bufsiz;
656 if ( prev->len < i ) {
657 prev->beg = prev->bufsiz - i;
660 AC_MEMCPY( prev->buf+prev->beg, tmp+prev->beg, prev->len );
663 /* Convert unlimited length decimal or hex string to binary.
664 * Output buffer must be provided, bv_len must indicate buffer size
665 * Hex input can be "0x1234" or "'1234'H"
667 * Temporarily modifies the input string.
669 * Note: High bit of binary form is always the sign bit. If the number
670 * is supposed to be positive but has the high bit set, a zero byte
671 * is prepended. It is assumed that this has already been handled on
675 lutil_str2bin( struct berval *in, struct berval *out, void *ctx )
677 char *pin, *pout, ctmp;
680 int i, chunk, len, rc = 0, hex = 0;
681 if ( !out || !out->bv_val || out->bv_len < in->bv_len )
685 /* Leading "0x" for hex input */
686 if ( in->bv_len > 2 && in->bv_val[0] == '0' &&
687 ( in->bv_val[1] == 'x' || in->bv_val[1] == 'X' ) )
689 len = in->bv_len - 2;
690 pin = in->bv_val + 2;
692 } else if ( in->bv_len > 3 && in->bv_val[0] == '\'' &&
693 in->bv_val[in->bv_len-2] == '\'' &&
694 in->bv_val[in->bv_len-1] == 'H' )
696 len = in->bv_len - 3;
697 pin = in->bv_val + 1;
701 #define HEXMAX (2 * sizeof(long))
702 /* Convert a longword at a time, but handle leading
705 chunk = len & (HEXMAX-1);
713 l = strtol( pin, &end, 16 );
719 for ( i = chunk; i>=0; i-- ) {
724 pout += sizeof(long);
728 out->bv_len = pout + len - out->bv_val;
731 char tmpbuf[64], *tmp;
732 lutil_int_decnum num;
737 num.buf = (unsigned char *)out->bv_val;
738 num.bufsiz = out->bv_len;
739 num.beg = num.bufsiz-1;
741 if ( pin[0] == '-' ) {
747 #define DECMAX 8 /* 8 digits at a time */
749 /* tmp must be at least as large as outbuf */
750 if ( out->bv_len > sizeof(tmpbuf)) {
751 tmp = ber_memalloc_x( out->bv_len, ctx );
755 chunk = len & (DECMAX-1);
763 l = strtol( pin, &end, 10 );
769 scale( l, &num, (unsigned char *)tmp );
774 /* Negate the result */
778 ptr = num.buf+num.beg;
781 for ( i=0; i<num.len; i++ )
784 /* add 1, with carry - overflow handled below */
785 while ( i-- && ! (ptr[i] = (ptr[i] + 1) & 0xff )) ;
787 /* Prepend sign byte if wrong sign bit */
788 if (( num.buf[num.beg] ^ neg ) & 0x80 ) {
791 num.buf[num.beg] = neg;
794 AC_MEMCPY( num.buf, num.buf+num.beg, num.len );
795 out->bv_len = num.len;
797 if ( tmp != tmpbuf ) {
798 ber_memfree_x( tmp, ctx );
804 static char time_unit[] = "dhms";
806 /* Used to parse and unparse time intervals, not timestamps */
816 scale[] = { 86400, 3600, 60, 1 };
820 for ( s = (char *)in; s[ 0 ] != '\0'; ) {
824 /* strtoul() has an odd interface */
825 if ( s[ 0 ] == '-' ) {
829 u = strtoul( s, &next, 10 );
834 if ( next[ 0 ] == '\0' ) {
840 what = strchr( time_unit, next[ 0 ] );
841 if ( what == NULL ) {
845 if ( what - time_unit <= sofar ) {
849 sofar = what - time_unit;
850 t += u * scale[ sofar ];
866 unsigned long v[ 4 ];
870 v[ 1 ] = (t%86400)/3600;
871 v[ 2 ] = (t%3600)/60;
874 for ( i = 0; i < 4; i++ ) {
875 if ( v[i] > 0 || ( i == 3 && ptr == buf ) ) {
876 len = snprintf( ptr, buflen, "%lu%c", v[ i ], time_unit[ i ] );
877 if ( len < 0 || (unsigned)len >= buflen ) {