]> git.sur5r.net Git - openldap/blob - libraries/liblutil/utils.c
Update copyright for next release
[openldap] / libraries / liblutil / utils.c
1 /* $OpenLDAP$ */
2 /* This work is part of OpenLDAP Software <http://www.openldap.org/>.
3  *
4  * Copyright 1998-2009 The OpenLDAP Foundation.
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted only as authorized by the OpenLDAP
9  * Public License.
10  *
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>.
14  */
15
16 #include "portable.h"
17
18 #include <stdio.h>
19 #include <ac/stdlib.h>
20 #include <ac/stdarg.h>
21 #include <ac/string.h>
22 #include <ac/ctype.h>
23 #include <ac/unistd.h>
24 #include <ac/time.h>
25 #include <ac/errno.h>
26 #ifdef HAVE_IO_H
27 #include <io.h>
28 #endif
29 #ifdef HAVE_FCNTL_H
30 #include <fcntl.h>
31 #endif
32 #ifdef _WIN32
33 #include <windows.h>
34 #endif
35
36 #include "lutil.h"
37 #include "ldap_defaults.h"
38 #include "ldap_pvt.h"
39 #include "lber_pvt.h"
40
41 #ifdef HAVE_EBCDIC
42 int _trans_argv = 1;
43 #endif
44
45 #ifdef _WIN32
46 /* Some Windows versions accept both forward and backslashes in
47  * directory paths, but we always use backslashes when generating
48  * and parsing...
49  */
50 void lutil_slashpath( char *path )
51 {
52         char *c, *p;
53
54         p = path;
55         while (( c=strchr( p, '/' ))) {
56                 *c++ = '\\';
57                 p = c;
58         }
59 }
60 #endif
61
62 char* lutil_progname( const char* name, int argc, char *argv[] )
63 {
64         char *progname;
65
66         if(argc == 0) {
67                 return (char *)name;
68         }
69
70 #ifdef HAVE_EBCDIC
71         if (_trans_argv) {
72                 int i;
73                 for (i=0; i<argc; i++) __etoa(argv[i]);
74                 _trans_argv = 0;
75         }
76 #endif
77         LUTIL_SLASHPATH( argv[0] );
78         progname = strrchr ( argv[0], *LDAP_DIRSEP );
79         progname = progname ? &progname[1] : argv[0];
80 #ifdef _WIN32
81         {
82                 size_t len = strlen( progname );
83                 if ( len > 4 && strcasecmp( &progname[len - 4], ".exe" ) == 0 )
84                         progname[len - 4] = '\0';
85         }
86 #endif
87         return progname;
88 }
89
90 #if 0
91 size_t lutil_gentime( char *s, size_t smax, const struct tm *tm )
92 {
93         size_t ret;
94 #ifdef HAVE_EBCDIC
95 /* We've been compiling in ASCII so far, but we want EBCDIC now since
96  * strftime only understands EBCDIC input.
97  */
98 #pragma convlit(suspend)
99 #endif
100         ret = strftime( s, smax, "%Y%m%d%H%M%SZ", tm );
101 #ifdef HAVE_EBCDIC
102 #pragma convlit(resume)
103         __etoa( s );
104 #endif
105         return ret;
106 }
107 #endif
108
109 size_t lutil_localtime( char *s, size_t smax, const struct tm *tm, long delta )
110 {
111         size_t  ret;
112         char    *p;
113
114         if ( smax < 16 ) {      /* YYYYmmddHHMMSSZ */
115                 return 0;
116         }
117
118 #ifdef HAVE_EBCDIC
119 /* We've been compiling in ASCII so far, but we want EBCDIC now since
120  * strftime only understands EBCDIC input.
121  */
122 #pragma convlit(suspend)
123 #endif
124         ret = strftime( s, smax, "%Y%m%d%H%M%SZ", tm );
125 #ifdef HAVE_EBCDIC
126 #pragma convlit(resume)
127         __etoa( s );
128 #endif
129         if ( delta == 0 || ret == 0 ) {
130                 return ret;
131         }
132
133         if ( smax < 20 ) {      /* YYYYmmddHHMMSS+HHMM */
134                 return 0;
135         }
136
137         p = s + 14;
138
139         if ( delta < 0 ) {
140                 p[ 0 ] = '-';
141                 delta = -delta;
142         } else {
143                 p[ 0 ] = '+';
144         }
145         p++;
146
147         snprintf( p, smax - 15, "%02ld%02ld", delta / 3600,
148                         ( delta % 3600 ) / 60 );
149
150         return ret + 5;
151 }
152
153 int lutil_tm2time( struct lutil_tm *tm, struct lutil_timet *tt )
154 {
155         static int moffset[12] = {
156                 0, 31, 59, 90, 120,
157                 151, 181, 212, 243,
158                 273, 304, 334 }; 
159         int sec;
160
161         tt->tt_usec = tm->tm_usec;
162
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 ) {
166                 tt->tt_sec = 0;
167                 tt->tt_gsec = 0;
168                 return 0;
169         }
170
171         /* tm->tm_year is years since 1900 */
172         /* calculate days from years since 1970 (epoch) */ 
173         tt->tt_sec = tm->tm_year - 70; 
174         tt->tt_sec *= 365L; 
175
176         /* count leap days in preceding years */ 
177         tt->tt_sec += ((tm->tm_year -69) >> 2); 
178
179         /* calculate days from months */ 
180         tt->tt_sec += moffset[tm->tm_mon]; 
181
182         /* add in this year's leap day, if any */ 
183         if (((tm->tm_year & 3) == 0) && (tm->tm_mon > 1)) { 
184                 tt->tt_sec ++; 
185         } 
186
187         /* add in days in this month */ 
188         tt->tt_sec += (tm->tm_mday - 1); 
189
190         /* this function can handle a range of about 17408 years... */
191         /* 86400 seconds in a day, divided by 128 = 675 */
192         tt->tt_sec *= 675;
193
194         /* move high 7 bits into tt_gsec */
195         tt->tt_gsec = tt->tt_sec >> 25;
196         tt->tt_sec -= tt->tt_gsec << 25;
197
198         /* get hours */ 
199         sec = tm->tm_hour; 
200
201         /* convert to minutes */ 
202         sec *= 60L; 
203         sec += tm->tm_min; 
204
205         /* convert to seconds */ 
206         sec *= 60L; 
207         sec += tm->tm_sec; 
208         
209         /* add remaining seconds */
210         tt->tt_sec <<= 7;
211         tt->tt_sec += sec;
212
213         /* return success */
214         return 0; 
215 }
216
217 int lutil_parsetime( char *atm, struct lutil_tm *tm )
218 {
219         while (atm && tm) {
220                 char *ptr = atm;
221                 unsigned i, fracs;
222
223                 /* Is the stamp reasonably long? */
224                 for (i=0; isdigit((unsigned char) atm[i]); i++);
225                 if (i < sizeof("00000101000000")-1)
226                         break;
227
228                 /*
229                  * parse the time into a struct tm
230                  */
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';
236                 tm->tm_year -= 1900;
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;
241                 tm->tm_mon--;
242
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;
247
248                 /* Hour 00-23 */
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;
252
253                 /* Minute 00-59 */
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;
257
258                 /* Second 00-61 */
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;
262
263                 /* Fractions of seconds */
264                 if ( *ptr == '.' ) {
265                         ptr++;
266                         for (i = 0, fracs = 0; isdigit((unsigned char) *ptr); ) {
267                                 i*=10; i+= *ptr++ - '0';
268                                 fracs++;
269                         }
270                         tm->tm_usec = i;
271                         if (i) {
272                                 for (i = fracs; i<6; i++)
273                                         tm->tm_usec *= 10;
274                         }
275                 }
276
277                 /* Must be UTC */
278                 if (*ptr != 'Z') break;
279
280                 return 0;
281         }
282         return -1;
283 }
284
285 /* return a broken out time, with microseconds
286  * Must be mutex-protected.
287  */
288 #ifdef _WIN32
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.
292  */
293 void
294 lutil_gettime( struct lutil_tm *tm )
295 {
296         static LARGE_INTEGER cFreq;
297         static LARGE_INTEGER prevCount;
298         static int subs;
299         static int offset;
300         LARGE_INTEGER count;
301         SYSTEMTIME st;
302
303         GetSystemTime( &st );
304         QueryPerformanceCounter( &count );
305
306         /* It shouldn't ever go backwards, but multiple CPUs might
307          * be able to hit in the same tick.
308          */
309         if ( count.QuadPart <= prevCount.QuadPart ) {
310                 subs++;
311         } else {
312                 subs = 0;
313                 prevCount = count;
314         }
315
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.
320          *
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.
325          */
326         if ( !cFreq.QuadPart ) {
327                 long long t;
328                 int usec;
329                 QueryPerformanceFrequency( &cFreq );
330
331                 /* just get sub-second portion of counter */
332                 t = count.QuadPart % cFreq.QuadPart;
333
334                 /* convert to microseconds */
335                 t *= 1000000;
336                 usec = t / cFreq.QuadPart;
337
338                 offset = usec - st.wMilliseconds * 1000;
339         }
340
341         tm->tm_usub = subs;
342
343         /* convert to microseconds */
344         count.QuadPart %= cFreq.QuadPart;
345         count.QuadPart *= 1000000;
346         count.QuadPart /= cFreq.QuadPart;
347         count.QuadPart -= offset;
348
349         tm->tm_usec = count.QuadPart % 1000000;
350         if ( tm->tm_usec < 0 )
351                 tm->tm_usec += 1000000;
352
353         /* any difference larger than microseconds is
354          * already reflected in st
355          */
356
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;
363 }
364 #else
365 void
366 lutil_gettime( struct lutil_tm *ltm )
367 {
368         struct timeval tv;
369         static struct timeval prevTv;
370         static int subs;
371
372 #ifdef HAVE_GMTIME_R
373         struct tm tm_buf;
374 #endif
375         struct tm *tm;
376         time_t t;
377
378         gettimeofday( &tv, NULL );
379         t = tv.tv_sec;
380
381         if ( tv.tv_sec < prevTv.tv_sec
382                 || ( tv.tv_sec == prevTv.tv_sec && tv.tv_usec == prevTv.tv_usec )) {
383                 subs++;
384         } else {
385                 subs = 0;
386                 prevTv = tv;
387         }
388
389         ltm->tm_usub = subs;
390
391 #ifdef HAVE_GMTIME_R
392         tm = gmtime_r( &t, &tm_buf );
393 #else
394         tm = gmtime( &t );
395 #endif
396
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;
404 }
405 #endif
406
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.
410  */
411 char *
412 lutil_strcopy(
413         char *a,
414         const char *b
415 )
416 {
417         if (!a || !b)
418                 return a;
419         
420         while ((*a++ = *b++)) ;
421         return a-1;
422 }
423
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.
427  */
428 char *
429 lutil_strncopy(
430         char *a,
431         const char *b,
432         size_t n
433 )
434 {
435         if (!a || !b || n == 0)
436                 return a;
437         
438         while ((*a++ = *b++) && n-- > 0) ;
439         return a-1;
440 }
441
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().
445  */
446 char *
447 lutil_memcopy(
448         char *a,
449         const char *b,
450         size_t n
451 )
452 {
453         AC_MEMCPY(a, b, n);
454         return a + n;
455 }
456
457 #ifndef HAVE_MKSTEMP
458 int mkstemp( char * template )
459 {
460 #ifdef HAVE_MKTEMP
461         return open ( mktemp ( template ), O_RDWR|O_CREAT|O_EXCL, 0600 );
462 #else
463         return -1;
464 #endif
465 }
466 #endif
467
468 #ifdef _MSC_VER
469 struct dirent {
470         char *d_name;
471 };
472 typedef struct DIR {
473         HANDLE dir;
474         struct dirent data;
475         int first;
476         char buf[MAX_PATH+1];
477 } DIR;
478 DIR *opendir( char *path )
479 {
480         char tmp[32768];
481         int len = strlen(path);
482         DIR *d;
483         HANDLE h;
484         WIN32_FIND_DATA data;
485         
486         if (len+3 >= sizeof(tmp))
487                 return NULL;
488
489         strcpy(tmp, path);
490         tmp[len++] = '\\';
491         tmp[len++] = '*';
492         tmp[len] = '\0';
493
494         h = FindFirstFile( tmp, &data );
495         
496         if ( h == INVALID_HANDLE_VALUE )
497                 return NULL;
498
499         d = ber_memalloc( sizeof(DIR) );
500         if ( !d )
501                 return NULL;
502         d->dir = h;
503         d->data.d_name = d->buf;
504         d->first = 1;
505         strcpy(d->data.d_name, data.cFileName);
506         return d;
507 }
508 struct dirent *readdir(DIR *dir)
509 {
510         WIN32_FIND_DATA data;
511
512         if (dir->first) {
513                 dir->first = 0;
514         } else {
515                 if (!FindNextFile(dir->dir, &data))
516                         return NULL;
517                 strcpy(dir->data.d_name, data.cFileName);
518         }
519         return &dir->data;
520 }
521 void closedir(DIR *dir)
522 {
523         FindClose(dir->dir);
524         ber_memfree(dir);
525 }
526 #endif
527
528 /*
529  * Memory Reverse Search
530  */
531 void *
532 lutil_memrchr(const void *b, int c, size_t n)
533 {
534         if (n != 0) {
535                 const unsigned char *s, *bb = b, cc = c;
536
537                 for ( s = bb + n; s > bb; ) {
538                         if ( *--s == cc ) {
539                                 return (void *) s;
540                         }
541                 }
542         }
543
544         return NULL;
545 }
546
547 int
548 lutil_atoix( int *v, const char *s, int x )
549 {
550         char            *next;
551         long            i;
552
553         assert( s != NULL );
554         assert( v != NULL );
555
556         i = strtol( s, &next, x );
557         if ( next == s || next[ 0 ] != '\0' ) {
558                 return -1;
559         }
560
561         if ( (long)(int)i != i ) {
562                 return 1;
563         }
564
565         *v = (int)i;
566
567         return 0;
568 }
569
570 int
571 lutil_atoux( unsigned *v, const char *s, int x )
572 {
573         char            *next;
574         unsigned long   u;
575
576         assert( s != NULL );
577         assert( v != NULL );
578
579         /* strtoul() has an odd interface */
580         if ( s[ 0 ] == '-' ) {
581                 return -1;
582         }
583
584         u = strtoul( s, &next, x );
585         if ( next == s || next[ 0 ] != '\0' ) {
586                 return -1;
587         }
588
589         if ( (unsigned long)(unsigned)u != u ) {
590                 return 1;
591         }
592
593         *v = u;
594
595         return 0;
596 }
597
598 int
599 lutil_atolx( long *v, const char *s, int x )
600 {
601         char            *next;
602         long            l;
603
604         assert( s != NULL );
605         assert( v != NULL );
606
607         l = strtol( s, &next, x );
608         if ( next == s || next[ 0 ] != '\0' ) {
609                 return -1;
610         }
611
612         *v = l;
613
614         return 0;
615 }
616
617 int
618 lutil_atoulx( unsigned long *v, const char *s, int x )
619 {
620         char            *next;
621         unsigned long   ul;
622
623         assert( s != NULL );
624         assert( v != NULL );
625
626         /* strtoul() has an odd interface */
627         if ( s[ 0 ] == '-' ) {
628                 return -1;
629         }
630
631         ul = strtoul( s, &next, x );
632         if ( next == s || next[ 0 ] != '\0' ) {
633                 return -1;
634         }
635
636         *v = ul;
637
638         return 0;
639 }
640
641 /* Multiply an integer by 100000000 and add new */
642 typedef struct lutil_int_decnum {
643         unsigned char *buf;
644         int bufsiz;
645         int beg;
646         int len;
647 } lutil_int_decnum;
648
649 #define FACTOR1 (100000000&0xffff)
650 #define FACTOR2 (100000000>>16)
651
652 static void
653 scale( int new, lutil_int_decnum *prev, unsigned char *tmp )
654 {
655         int i, j;
656         unsigned char *in = prev->buf+prev->beg;
657         unsigned int part;
658         unsigned char *out = tmp + prev->bufsiz - prev->len;
659
660         memset( tmp, 0, prev->bufsiz );
661         if ( prev->len ) {
662                 for ( i = prev->len-1; i>=0; i-- ) {
663                         part = in[i] * FACTOR1;
664                         for ( j = i; part; j-- ) {
665                                 part += out[j];
666                                 out[j] = part & 0xff;
667                                 part >>= 8;
668                         }
669                         part = in[i] * FACTOR2;
670                         for ( j = i-2; part; j-- ) {
671                                 part += out[j];
672                                 out[j] = part & 0xff;
673                                 part >>= 8;
674                         }
675                 }
676                 j++;
677                 prev->beg += j;
678                 prev->len -= j;
679         }
680
681         out = tmp + prev->bufsiz;
682         i = 0;
683         do {
684                 i--;
685                 new += out[i];
686                 out[i] = new & 0xff;
687                 new >>= 8;
688         } while ( new );
689         i = -i;
690         if ( prev->len < i ) {
691                 prev->beg = prev->bufsiz - i;
692                 prev->len = i;
693         }
694         AC_MEMCPY( prev->buf+prev->beg, tmp+prev->beg, prev->len );
695 }
696
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"
700  *
701  * Temporarily modifies the input string.
702  *
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
706  * any hex input.
707  */
708 int
709 lutil_str2bin( struct berval *in, struct berval *out, void *ctx )
710 {
711         char *pin, *pout, ctmp;
712         char *end;
713         int i, chunk, len, rc = 0, hex = 0;
714         if ( !out || !out->bv_val || out->bv_len < in->bv_len )
715                 return -1;
716
717         pout = out->bv_val;
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' ) )
721         {
722                 len = in->bv_len - 2;
723                 pin = in->bv_val + 2;
724                 hex = 1;
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' )
728         {
729                 len = in->bv_len - 3;
730                 pin = in->bv_val + 1;
731                 hex = 1;
732         }
733         if ( hex ) {
734 #define HEXMAX  (2 * sizeof(long))
735                 unsigned long l;
736                 /* Convert a longword at a time, but handle leading
737                  * odd bytes first
738                  */
739                 chunk = len % HEXMAX;
740                 if ( !chunk )
741                         chunk = HEXMAX;
742
743                 while ( len ) {
744                         int ochunk;
745                         ctmp = pin[chunk];
746                         pin[chunk] = '\0';
747                         errno = 0;
748                         l = strtoul( pin, &end, 16 );
749                         pin[chunk] = ctmp;
750                         if ( errno )
751                                 return -1;
752                         ochunk = (chunk + 1)/2;
753                         for ( i = ochunk - 1; i >= 0; i-- ) {
754                                 pout[i] = l & 0xff;
755                                 l >>= 8;
756                         }
757                         pin += chunk;
758                         pout += ochunk;
759                         len -= chunk;
760                         chunk = HEXMAX;
761                 }
762                 out->bv_len = pout - out->bv_val;
763         } else {
764         /* Decimal */
765                 char tmpbuf[64], *tmp;
766                 lutil_int_decnum num;
767                 int neg = 0;
768                 long l;
769
770                 len = in->bv_len;
771                 pin = in->bv_val;
772                 num.buf = (unsigned char *)out->bv_val;
773                 num.bufsiz = out->bv_len;
774                 num.beg = num.bufsiz-1;
775                 num.len = 0;
776                 if ( pin[0] == '-' ) {
777                         neg = 0xff;
778                         len--;
779                         pin++;
780                 }
781
782 #define DECMAX  8       /* 8 digits at a time */
783
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 );
787                 } else {
788                         tmp = tmpbuf;
789                 }
790                 chunk = len & (DECMAX-1);
791                 if ( !chunk )
792                         chunk = DECMAX;
793
794                 while ( len ) {
795                         ctmp = pin[chunk];
796                         pin[chunk] = '\0';
797                         errno = 0;
798                         l = strtol( pin, &end, 10 );
799                         pin[chunk] = ctmp;
800                         if ( errno ) {
801                                 rc = -1;
802                                 goto decfail;
803                         }
804                         scale( l, &num, (unsigned char *)tmp );
805                         pin += chunk;
806                         len -= chunk;
807                         chunk = DECMAX;
808                 }
809                 /* Negate the result */
810                 if ( neg ) {
811                         unsigned char *ptr;
812
813                         ptr = num.buf+num.beg;
814
815                         /* flip all bits */
816                         for ( i=0; i<num.len; i++ )
817                                 ptr[i] ^= 0xff;
818
819                         /* add 1, with carry - overflow handled below */
820                         while ( i-- && ! (ptr[i] = (ptr[i] + 1) & 0xff )) ;
821                 }
822                 /* Prepend sign byte if wrong sign bit */
823                 if (( num.buf[num.beg] ^ neg ) & 0x80 ) {
824                         num.beg--;
825                         num.len++;
826                         num.buf[num.beg] = neg;
827                 }
828                 if ( num.beg )
829                         AC_MEMCPY( num.buf, num.buf+num.beg, num.len );
830                 out->bv_len = num.len;
831 decfail:
832                 if ( tmp != tmpbuf ) {
833                         ber_memfree_x( tmp, ctx );
834                 }
835         }
836         return rc;
837 }
838
839 static  char            time_unit[] = "dhms";
840
841 /* Used to parse and unparse time intervals, not timestamps */
842 int
843 lutil_parse_time(
844         const char      *in,
845         unsigned long   *tp )
846 {
847         unsigned long   t = 0;
848         char            *s,
849                         *next;
850         int             sofar = -1,
851                         scale[] = { 86400, 3600, 60, 1 };
852
853         *tp = 0;
854
855         for ( s = (char *)in; s[ 0 ] != '\0'; ) {
856                 unsigned long   u;
857                 char            *what;
858
859                 /* strtoul() has an odd interface */
860                 if ( s[ 0 ] == '-' ) {
861                         return -1;
862                 }
863
864                 u = strtoul( s, &next, 10 );
865                 if ( next == s ) {
866                         return -1;
867                 }
868
869                 if ( next[ 0 ] == '\0' ) {
870                         /* assume seconds */
871                         t += u;
872                         break;
873                 }
874
875                 what = strchr( time_unit, next[ 0 ] );
876                 if ( what == NULL ) {
877                         return -1;
878                 }
879
880                 if ( what - time_unit <= sofar ) {
881                         return -1;
882                 }
883
884                 sofar = what - time_unit;
885                 t += u * scale[ sofar ];
886
887                 s = &next[ 1 ];
888         }
889
890         *tp = t;
891         return 0;
892 }
893
894 int
895 lutil_unparse_time(
896         char                    *buf,
897         size_t                  buflen,
898         unsigned long           t )
899 {
900         int             len, i;
901         unsigned long   v[ 4 ];
902         char            *ptr = buf;
903
904         v[ 0 ] = t/86400;
905         v[ 1 ] = (t%86400)/3600;
906         v[ 2 ] = (t%3600)/60;
907         v[ 3 ] = t%60;
908
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 ) {
913                                 return -1;
914                         }
915                         buflen -= len;
916                         ptr += len;
917                 }
918         }
919
920         return 0;
921 }
922
923 /*
924  * formatted print to string
925  *
926  * - if return code < 0, the error code returned by vsnprintf(3) is returned
927  *
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
931  *
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 
935  */
936 int
937 lutil_snprintf( char *buf, ber_len_t bufsize, char **next, ber_len_t *len, LDAP_CONST char *fmt, ... )
938 {
939         va_list         ap;
940         int             ret;
941
942         assert( buf != NULL );
943         assert( bufsize > 0 );
944         assert( fmt != NULL );
945
946         va_start( ap, fmt );
947         ret = vsnprintf( buf, bufsize, fmt, ap );
948         va_end( ap );
949
950         if ( ret < 0 ) {
951                 return ret;
952         }
953
954         if ( len ) {
955                 *len = ret;
956         }
957
958         if ( (unsigned) ret >= bufsize ) {
959                 if ( next ) {
960                         *next = &buf[ bufsize - 1 ];
961                 }
962
963                 return 1;
964         }
965
966         if ( next ) {
967                 *next = &buf[ ret ];
968         }
969
970         return 0;
971 }
972