]> git.sur5r.net Git - openldap/blob - libraries/liblutil/utils.c
ff37d417a05e2b3707fb148ac7e5ec488a73f5ff
[openldap] / libraries / liblutil / utils.c
1 /* $OpenLDAP$ */
2 /* This work is part of OpenLDAP Software <http://www.openldap.org/>.
3  *
4  * Copyright 1998-2008 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 #ifndef HAVE_MKSTEMP
443 int mkstemp( char * template )
444 {
445 #ifdef HAVE_MKTEMP
446         return open ( mktemp ( template ), O_RDWR|O_CREAT|O_EXCL, 0600 );
447 #else
448         return -1;
449 #endif
450 }
451 #endif
452
453 #ifdef _MSC_VER
454 struct dirent {
455         char *d_name;
456 };
457 typedef struct DIR {
458         HANDLE dir;
459         struct dirent data;
460         int first;
461         char buf[MAX_PATH+1];
462 } DIR;
463 DIR *opendir( char *path )
464 {
465         char tmp[32768];
466         int len = strlen(path);
467         DIR *d;
468         HANDLE h;
469         WIN32_FIND_DATA data;
470         
471         if (len+3 >= sizeof(tmp))
472                 return NULL;
473
474         strcpy(tmp, path);
475         tmp[len++] = '\\';
476         tmp[len++] = '*';
477         tmp[len] = '\0';
478
479         h = FindFirstFile( tmp, &data );
480         
481         if ( h == INVALID_HANDLE_VALUE )
482                 return NULL;
483
484         d = ber_memalloc( sizeof(DIR) );
485         if ( !d )
486                 return NULL;
487         d->dir = h;
488         d->data.d_name = d->buf;
489         d->first = 1;
490         strcpy(d->data.d_name, data.cFileName);
491         return d;
492 }
493 struct dirent *readdir(DIR *dir)
494 {
495         WIN32_FIND_DATA data;
496
497         if (dir->first) {
498                 dir->first = 0;
499         } else {
500                 if (!FindNextFile(dir->dir, &data))
501                         return NULL;
502                 strcpy(dir->data.d_name, data.cFileName);
503         }
504         return &dir->data;
505 }
506 void closedir(DIR *dir)
507 {
508         FindClose(dir->dir);
509         ber_memfree(dir);
510 }
511 #endif
512
513 /*
514  * Memory Reverse Search
515  */
516 void *
517 lutil_memrchr(const void *b, int c, size_t n)
518 {
519         if (n != 0) {
520                 const unsigned char *s, *bb = b, cc = c;
521
522                 for ( s = bb + n; s > bb; ) {
523                         if ( *--s == cc ) {
524                                 return (void *) s;
525                         }
526                 }
527         }
528
529         return NULL;
530 }
531
532 int
533 lutil_atoix( int *v, const char *s, int x )
534 {
535         char            *next;
536         long            i;
537
538         assert( s != NULL );
539         assert( v != NULL );
540
541         i = strtol( s, &next, x );
542         if ( next == s || next[ 0 ] != '\0' ) {
543                 return -1;
544         }
545
546         if ( (long)(int)i != i ) {
547                 return 1;
548         }
549
550         *v = (int)i;
551
552         return 0;
553 }
554
555 int
556 lutil_atoux( unsigned *v, const char *s, int x )
557 {
558         char            *next;
559         unsigned long   u;
560
561         assert( s != NULL );
562         assert( v != NULL );
563
564         /* strtoul() has an odd interface */
565         if ( s[ 0 ] == '-' ) {
566                 return -1;
567         }
568
569         u = strtoul( s, &next, x );
570         if ( next == s || next[ 0 ] != '\0' ) {
571                 return -1;
572         }
573
574         if ( (unsigned long)(unsigned)u != u ) {
575                 return 1;
576         }
577
578         *v = u;
579
580         return 0;
581 }
582
583 int
584 lutil_atolx( long *v, const char *s, int x )
585 {
586         char            *next;
587         long            l;
588
589         assert( s != NULL );
590         assert( v != NULL );
591
592         l = strtol( s, &next, x );
593         if ( next == s || next[ 0 ] != '\0' ) {
594                 return -1;
595         }
596
597         *v = l;
598
599         return 0;
600 }
601
602 int
603 lutil_atoulx( unsigned long *v, const char *s, int x )
604 {
605         char            *next;
606         unsigned long   ul;
607
608         assert( s != NULL );
609         assert( v != NULL );
610
611         /* strtoul() has an odd interface */
612         if ( s[ 0 ] == '-' ) {
613                 return -1;
614         }
615
616         ul = strtoul( s, &next, x );
617         if ( next == s || next[ 0 ] != '\0' ) {
618                 return -1;
619         }
620
621         *v = ul;
622
623         return 0;
624 }
625
626 /* Multiply an integer by 100000000 and add new */
627 typedef struct lutil_int_decnum {
628         unsigned char *buf;
629         int bufsiz;
630         int beg;
631         int len;
632 } lutil_int_decnum;
633
634 #define FACTOR1 (100000000&0xffff)
635 #define FACTOR2 (100000000>>16)
636
637 static void
638 scale( int new, lutil_int_decnum *prev, unsigned char *tmp )
639 {
640         int i, j;
641         unsigned char *in = prev->buf+prev->beg;
642         unsigned int part;
643         unsigned char *out = tmp + prev->bufsiz - prev->len;
644
645         memset( tmp, 0, prev->bufsiz );
646         if ( prev->len ) {
647                 for ( i = prev->len-1; i>=0; i-- ) {
648                         part = in[i] * FACTOR1;
649                         for ( j = i; part; j-- ) {
650                                 part += out[j];
651                                 out[j] = part & 0xff;
652                                 part >>= 8;
653                         }
654                         part = in[i] * FACTOR2;
655                         for ( j = i-2; part; j-- ) {
656                                 part += out[j];
657                                 out[j] = part & 0xff;
658                                 part >>= 8;
659                         }
660                 }
661                 j++;
662                 prev->beg += j;
663                 prev->len -= j;
664         }
665
666         out = tmp + prev->bufsiz;
667         i = 0;
668         do {
669                 i--;
670                 new += out[i];
671                 out[i] = new & 0xff;
672                 new >>= 8;
673         } while ( new );
674         i = -i;
675         if ( prev->len < i ) {
676                 prev->beg = prev->bufsiz - i;
677                 prev->len = i;
678         }
679         AC_MEMCPY( prev->buf+prev->beg, tmp+prev->beg, prev->len );
680 }
681
682 /* Convert unlimited length decimal or hex string to binary.
683  * Output buffer must be provided, bv_len must indicate buffer size
684  * Hex input can be "0x1234" or "'1234'H"
685  *
686  * Temporarily modifies the input string.
687  *
688  * Note: High bit of binary form is always the sign bit. If the number
689  * is supposed to be positive but has the high bit set, a zero byte
690  * is prepended. It is assumed that this has already been handled on
691  * any hex input.
692  */
693 int
694 lutil_str2bin( struct berval *in, struct berval *out, void *ctx )
695 {
696         char *pin, *pout, ctmp;
697         char *end;
698         int i, chunk, len, rc = 0, hex = 0;
699         if ( !out || !out->bv_val || out->bv_len < in->bv_len )
700                 return -1;
701
702         pout = out->bv_val;
703         /* Leading "0x" for hex input */
704         if ( in->bv_len > 2 && in->bv_val[0] == '0' &&
705                 ( in->bv_val[1] == 'x' || in->bv_val[1] == 'X' ) )
706         {
707                 len = in->bv_len - 2;
708                 pin = in->bv_val + 2;
709                 hex = 1;
710         } else if ( in->bv_len > 3 && in->bv_val[0] == '\'' &&
711                 in->bv_val[in->bv_len-2] == '\'' &&
712                 in->bv_val[in->bv_len-1] == 'H' )
713         {
714                 len = in->bv_len - 3;
715                 pin = in->bv_val + 1;
716                 hex = 1;
717         }
718         if ( hex ) {
719 #define HEXMAX  (2 * sizeof(long))
720                 unsigned long l;
721                 /* Convert a longword at a time, but handle leading
722                  * odd bytes first
723                  */
724                 chunk = len % HEXMAX;
725                 if ( !chunk )
726                         chunk = HEXMAX;
727
728                 while ( len ) {
729                         int ochunk;
730                         ctmp = pin[chunk];
731                         pin[chunk] = '\0';
732                         errno = 0;
733                         l = strtoul( pin, &end, 16 );
734                         pin[chunk] = ctmp;
735                         if ( errno )
736                                 return -1;
737                         ochunk = (chunk + 1)/2;
738                         for ( i = ochunk - 1; i >= 0; i-- ) {
739                                 pout[i] = l & 0xff;
740                                 l >>= 8;
741                         }
742                         pin += chunk;
743                         pout += ochunk;
744                         len -= chunk;
745                         chunk = HEXMAX;
746                 }
747                 out->bv_len = pout - out->bv_val;
748         } else {
749         /* Decimal */
750                 char tmpbuf[64], *tmp;
751                 lutil_int_decnum num;
752                 int neg = 0;
753                 long l;
754
755                 len = in->bv_len;
756                 pin = in->bv_val;
757                 num.buf = (unsigned char *)out->bv_val;
758                 num.bufsiz = out->bv_len;
759                 num.beg = num.bufsiz-1;
760                 num.len = 0;
761                 if ( pin[0] == '-' ) {
762                         neg = 0xff;
763                         len--;
764                         pin++;
765                 }
766
767 #define DECMAX  8       /* 8 digits at a time */
768
769                 /* tmp must be at least as large as outbuf */
770                 if ( out->bv_len > sizeof(tmpbuf)) {
771                         tmp = ber_memalloc_x( out->bv_len, ctx );
772                 } else {
773                         tmp = tmpbuf;
774                 }
775                 chunk = len & (DECMAX-1);
776                 if ( !chunk )
777                         chunk = DECMAX;
778
779                 while ( len ) {
780                         ctmp = pin[chunk];
781                         pin[chunk] = '\0';
782                         errno = 0;
783                         l = strtol( pin, &end, 10 );
784                         pin[chunk] = ctmp;
785                         if ( errno ) {
786                                 rc = -1;
787                                 goto decfail;
788                         }
789                         scale( l, &num, (unsigned char *)tmp );
790                         pin += chunk;
791                         len -= chunk;
792                         chunk = DECMAX;
793                 }
794                 /* Negate the result */
795                 if ( neg ) {
796                         unsigned char *ptr;
797
798                         ptr = num.buf+num.beg;
799
800                         /* flip all bits */
801                         for ( i=0; i<num.len; i++ )
802                                 ptr[i] ^= 0xff;
803
804                         /* add 1, with carry - overflow handled below */
805                         while ( i-- && ! (ptr[i] = (ptr[i] + 1) & 0xff )) ;
806                 }
807                 /* Prepend sign byte if wrong sign bit */
808                 if (( num.buf[num.beg] ^ neg ) & 0x80 ) {
809                         num.beg--;
810                         num.len++;
811                         num.buf[num.beg] = neg;
812                 }
813                 if ( num.beg )
814                         AC_MEMCPY( num.buf, num.buf+num.beg, num.len );
815                 out->bv_len = num.len;
816 decfail:
817                 if ( tmp != tmpbuf ) {
818                         ber_memfree_x( tmp, ctx );
819                 }
820         }
821         return rc;
822 }
823
824 static  char            time_unit[] = "dhms";
825
826 /* Used to parse and unparse time intervals, not timestamps */
827 int
828 lutil_parse_time(
829         const char      *in,
830         unsigned long   *tp )
831 {
832         unsigned long   t = 0;
833         char            *s,
834                         *next;
835         int             sofar = -1,
836                         scale[] = { 86400, 3600, 60, 1 };
837
838         *tp = 0;
839
840         for ( s = (char *)in; s[ 0 ] != '\0'; ) {
841                 unsigned long   u;
842                 char            *what;
843
844                 /* strtoul() has an odd interface */
845                 if ( s[ 0 ] == '-' ) {
846                         return -1;
847                 }
848
849                 u = strtoul( s, &next, 10 );
850                 if ( next == s ) {
851                         return -1;
852                 }
853
854                 if ( next[ 0 ] == '\0' ) {
855                         /* assume seconds */
856                         t += u;
857                         break;
858                 }
859
860                 what = strchr( time_unit, next[ 0 ] );
861                 if ( what == NULL ) {
862                         return -1;
863                 }
864
865                 if ( what - time_unit <= sofar ) {
866                         return -1;
867                 }
868
869                 sofar = what - time_unit;
870                 t += u * scale[ sofar ];
871
872                 s = &next[ 1 ];
873         }
874
875         *tp = t;
876         return 0;
877 }
878
879 int
880 lutil_unparse_time(
881         char                    *buf,
882         size_t                  buflen,
883         unsigned long           t )
884 {
885         int             len, i;
886         unsigned long   v[ 4 ];
887         char            *ptr = buf;
888
889         v[ 0 ] = t/86400;
890         v[ 1 ] = (t%86400)/3600;
891         v[ 2 ] = (t%3600)/60;
892         v[ 3 ] = t%60;
893
894         for ( i = 0; i < 4; i++ ) {
895                 if ( v[i] > 0 || ( i == 3 && ptr == buf ) ) {
896                         len = snprintf( ptr, buflen, "%lu%c", v[ i ], time_unit[ i ] );
897                         if ( len < 0 || (unsigned)len >= buflen ) {
898                                 return -1;
899                         }
900                         buflen -= len;
901                         ptr += len;
902                 }
903         }
904
905         return 0;
906 }
907
908 /*
909  * formatted print to string
910  *
911  * - if return code < 0, the error code returned by vsnprintf(3) is returned
912  *
913  * - if return code > 0, the buffer was not long enough;
914  *      - if next is not NULL, *next will be set to buf + bufsize - 1
915  *      - if len is not NULL, *len will contain the required buffer length
916  *
917  * - if return code == 0, the buffer was long enough;
918  *      - if next is not NULL, *next will point to the end of the string printed so far
919  *      - if len is not NULL, *len will contain the length of the string printed so far 
920  */
921 int
922 lutil_snprintf( char *buf, ber_len_t bufsize, char **next, ber_len_t *len, LDAP_CONST char *fmt, ... )
923 {
924         va_list         ap;
925         int             ret;
926
927         assert( buf != NULL );
928         assert( bufsize > 0 );
929         assert( fmt != NULL );
930
931         va_start( ap, fmt );
932         ret = vsnprintf( buf, bufsize, fmt, ap );
933         va_end( ap );
934
935         if ( ret < 0 ) {
936                 return ret;
937         }
938
939         if ( len ) {
940                 *len = ret;
941         }
942
943         if ( ret >= bufsize ) {
944                 if ( next ) {
945                         *next = &buf[ bufsize - 1 ];
946                 }
947
948                 return 1;
949         }
950
951         if ( next ) {
952                 *next = &buf[ ret ];
953         }
954
955         return 0;
956 }
957