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