]> git.sur5r.net Git - openldap/blob - libraries/liblutil/utils.c
3de49b970b13ab0f62102aa8c789ab912797ebec
[openldap] / libraries / liblutil / utils.c
1 /* $OpenLDAP$ */
2 /* This work is part of OpenLDAP Software <http://www.openldap.org/>.
3  *
4  * Copyright 1998-2013 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         if ( ( ul == 0 || ul == ULONG_MAX ) && save_errno != 0 ) {
568                 return -1;
569         }
570
571         *v = ul;
572
573         return 0;
574 }
575
576 #ifdef HAVE_LONG_LONG
577 #if defined(HAVE_STRTOLL) || defined(HAVE_STRTOQ)
578 int
579 lutil_atollx( long long *v, const char *s, int x )
580 {
581         char *next;
582         long long ll;
583         int save_errno;
584
585         assert( s != NULL );
586         assert( v != NULL );
587
588         if ( isspace( s[ 0 ] ) ) {
589                 return -1;
590         }
591
592         errno = 0;
593 #ifdef HAVE_STRTOLL
594         ll = strtoll( s, &next, x );
595 #else /* HAVE_STRTOQ */
596         ll = (unsigned long long)strtoq( s, &next, x );
597 #endif /* HAVE_STRTOQ */
598         save_errno = errno;
599         if ( next == s || next[ 0 ] != '\0' ) {
600                 return -1;
601         }
602
603         /* LLONG_MIN, LLONG_MAX are C99 only */
604 #if defined (LLONG_MIN) && defined(LLONG_MAX)
605         if ( ( ll == LLONG_MIN || ll == LLONG_MAX ) && save_errno != 0 ) {
606                 return -1;
607         }
608 #endif /* LLONG_MIN && LLONG_MAX */
609
610         *v = ll;
611
612         return 0;
613 }
614 #endif /* HAVE_STRTOLL || HAVE_STRTOQ */
615
616 #if defined(HAVE_STRTOULL) || defined(HAVE_STRTOUQ)
617 int
618 lutil_atoullx( unsigned long long *v, const char *s, int x )
619 {
620         char *next;
621         unsigned long long ull;
622         int save_errno;
623
624         assert( s != NULL );
625         assert( v != NULL );
626
627         /* strtoull() has an odd interface */
628         if ( s[ 0 ] == '-' || isspace( s[ 0 ] ) ) {
629                 return -1;
630         }
631
632         errno = 0;
633 #ifdef HAVE_STRTOULL
634         ull = strtoull( s, &next, x );
635 #else /* HAVE_STRTOUQ */
636         ull = (unsigned long long)strtouq( s, &next, x );
637 #endif /* HAVE_STRTOUQ */
638         save_errno = errno;
639         if ( next == s || next[ 0 ] != '\0' ) {
640                 return -1;
641         }
642
643         /* ULLONG_MAX is C99 only */
644 #if defined(ULLONG_MAX)
645         if ( ( ull == 0 || ull == ULLONG_MAX ) && save_errno != 0 ) {
646                 return -1;
647         }
648 #endif /* ULLONG_MAX */
649
650         *v = ull;
651
652         return 0;
653 }
654 #endif /* HAVE_STRTOULL || HAVE_STRTOUQ */
655 #endif /* HAVE_LONG_LONG */
656
657 /* Multiply an integer by 100000000 and add new */
658 typedef struct lutil_int_decnum {
659         unsigned char *buf;
660         int bufsiz;
661         int beg;
662         int len;
663 } lutil_int_decnum;
664
665 #define FACTOR1 (100000000&0xffff)
666 #define FACTOR2 (100000000>>16)
667
668 static void
669 scale( int new, lutil_int_decnum *prev, unsigned char *tmp )
670 {
671         int i, j;
672         unsigned char *in = prev->buf+prev->beg;
673         unsigned int part;
674         unsigned char *out = tmp + prev->bufsiz - prev->len;
675
676         memset( tmp, 0, prev->bufsiz );
677         if ( prev->len ) {
678                 for ( i = prev->len-1; i>=0; i-- ) {
679                         part = in[i] * FACTOR1;
680                         for ( j = i; part; j-- ) {
681                                 part += out[j];
682                                 out[j] = part & 0xff;
683                                 part >>= 8;
684                         }
685                         part = in[i] * FACTOR2;
686                         for ( j = i-2; part; j-- ) {
687                                 part += out[j];
688                                 out[j] = part & 0xff;
689                                 part >>= 8;
690                         }
691                 }
692                 j++;
693                 prev->beg += j;
694                 prev->len -= j;
695         }
696
697         out = tmp + prev->bufsiz;
698         i = 0;
699         do {
700                 i--;
701                 new += out[i];
702                 out[i] = new & 0xff;
703                 new >>= 8;
704         } while ( new );
705         i = -i;
706         if ( prev->len < i ) {
707                 prev->beg = prev->bufsiz - i;
708                 prev->len = i;
709         }
710         AC_MEMCPY( prev->buf+prev->beg, tmp+prev->beg, prev->len );
711 }
712
713 /* Convert unlimited length decimal or hex string to binary.
714  * Output buffer must be provided, bv_len must indicate buffer size
715  * Hex input can be "0x1234" or "'1234'H"
716  *
717  * Note: High bit of binary form is always the sign bit. If the number
718  * is supposed to be positive but has the high bit set, a zero byte
719  * is prepended. It is assumed that this has already been handled on
720  * any hex input.
721  */
722 int
723 lutil_str2bin( struct berval *in, struct berval *out, void *ctx )
724 {
725         char *pin, *pout;
726         char *end;
727         int i, chunk, len, rc = 0, hex = 0;
728         if ( !out || !out->bv_val || out->bv_len < in->bv_len )
729                 return -1;
730
731         pout = out->bv_val;
732         /* Leading "0x" for hex input */
733         if ( in->bv_len > 2 && in->bv_val[0] == '0' &&
734                 ( in->bv_val[1] == 'x' || in->bv_val[1] == 'X' ) )
735         {
736                 len = in->bv_len - 2;
737                 pin = in->bv_val + 2;
738                 hex = 1;
739         } else if ( in->bv_len > 3 && in->bv_val[0] == '\'' &&
740                 in->bv_val[in->bv_len-2] == '\'' &&
741                 in->bv_val[in->bv_len-1] == 'H' )
742         {
743                 len = in->bv_len - 3;
744                 pin = in->bv_val + 1;
745                 hex = 1;
746         }
747         if ( hex ) {
748 #define HEXMAX  (2 * sizeof(long))
749                 unsigned long l;
750                 char tbuf[HEXMAX+1];
751
752                 /* Convert a longword at a time, but handle leading
753                  * odd bytes first
754                  */
755                 chunk = len % HEXMAX;
756                 if ( !chunk )
757                         chunk = HEXMAX;
758
759                 while ( len ) {
760                         int ochunk;
761                         memcpy( tbuf, pin, chunk );
762                         tbuf[chunk] = '\0';
763                         errno = 0;
764                         l = strtoul( tbuf, &end, 16 );
765                         if ( errno )
766                                 return -1;
767                         ochunk = (chunk + 1)/2;
768                         for ( i = ochunk - 1; i >= 0; i-- ) {
769                                 pout[i] = l & 0xff;
770                                 l >>= 8;
771                         }
772                         pin += chunk;
773                         pout += ochunk;
774                         len -= chunk;
775                         chunk = HEXMAX;
776                 }
777                 out->bv_len = pout - out->bv_val;
778         } else {
779         /* Decimal */
780 #define DECMAX  8       /* 8 digits at a time */
781                 char tmpbuf[64], *tmp;
782                 lutil_int_decnum num;
783                 int neg = 0;
784                 long l;
785                 char tbuf[DECMAX+1];
786
787                 len = in->bv_len;
788                 pin = in->bv_val;
789                 num.buf = (unsigned char *)out->bv_val;
790                 num.bufsiz = out->bv_len;
791                 num.beg = num.bufsiz-1;
792                 num.len = 0;
793                 if ( pin[0] == '-' ) {
794                         neg = 0xff;
795                         len--;
796                         pin++;
797                 }
798
799                 /* tmp must be at least as large as outbuf */
800                 if ( out->bv_len > sizeof(tmpbuf)) {
801                         tmp = ber_memalloc_x( out->bv_len, ctx );
802                 } else {
803                         tmp = tmpbuf;
804                 }
805                 chunk = len & (DECMAX-1);
806                 if ( !chunk )
807                         chunk = DECMAX;
808
809                 while ( len ) {
810                         memcpy( tbuf, pin, chunk );
811                         tbuf[chunk] = '\0';
812                         errno = 0;
813                         l = strtol( tbuf, &end, 10 );
814                         if ( errno ) {
815                                 rc = -1;
816                                 goto decfail;
817                         }
818                         scale( l, &num, (unsigned char *)tmp );
819                         pin += chunk;
820                         len -= chunk;
821                         chunk = DECMAX;
822                 }
823                 /* Negate the result */
824                 if ( neg ) {
825                         unsigned char *ptr;
826
827                         ptr = num.buf+num.beg;
828
829                         /* flip all bits */
830                         for ( i=0; i<num.len; i++ )
831                                 ptr[i] ^= 0xff;
832
833                         /* add 1, with carry - overflow handled below */
834                         while ( i-- && ! (ptr[i] = (ptr[i] + 1) & 0xff )) ;
835                 }
836                 /* Prepend sign byte if wrong sign bit */
837                 if (( num.buf[num.beg] ^ neg ) & 0x80 ) {
838                         num.beg--;
839                         num.len++;
840                         num.buf[num.beg] = neg;
841                 }
842                 if ( num.beg )
843                         AC_MEMCPY( num.buf, num.buf+num.beg, num.len );
844                 out->bv_len = num.len;
845 decfail:
846                 if ( tmp != tmpbuf ) {
847                         ber_memfree_x( tmp, ctx );
848                 }
849         }
850         return rc;
851 }
852
853 static  char            time_unit[] = "dhms";
854
855 /* Used to parse and unparse time intervals, not timestamps */
856 int
857 lutil_parse_time(
858         const char      *in,
859         unsigned long   *tp )
860 {
861         unsigned long   t = 0;
862         char            *s,
863                         *next;
864         int             sofar = -1,
865                         scale[] = { 86400, 3600, 60, 1 };
866
867         *tp = 0;
868
869         for ( s = (char *)in; s[ 0 ] != '\0'; ) {
870                 unsigned long   u;
871                 char            *what;
872
873                 /* strtoul() has an odd interface */
874                 if ( s[ 0 ] == '-' ) {
875                         return -1;
876                 }
877
878                 u = strtoul( s, &next, 10 );
879                 if ( next == s ) {
880                         return -1;
881                 }
882
883                 if ( next[ 0 ] == '\0' ) {
884                         /* assume seconds */
885                         t += u;
886                         break;
887                 }
888
889                 what = strchr( time_unit, next[ 0 ] );
890                 if ( what == NULL ) {
891                         return -1;
892                 }
893
894                 if ( what - time_unit <= sofar ) {
895                         return -1;
896                 }
897
898                 sofar = what - time_unit;
899                 t += u * scale[ sofar ];
900
901                 s = &next[ 1 ];
902         }
903
904         *tp = t;
905         return 0;
906 }
907
908 int
909 lutil_unparse_time(
910         char                    *buf,
911         size_t                  buflen,
912         unsigned long           t )
913 {
914         int             len, i;
915         unsigned long   v[ 4 ];
916         char            *ptr = buf;
917
918         v[ 0 ] = t/86400;
919         v[ 1 ] = (t%86400)/3600;
920         v[ 2 ] = (t%3600)/60;
921         v[ 3 ] = t%60;
922
923         for ( i = 0; i < 4; i++ ) {
924                 if ( v[i] > 0 || ( i == 3 && ptr == buf ) ) {
925                         len = snprintf( ptr, buflen, "%lu%c", v[ i ], time_unit[ i ] );
926                         if ( len < 0 || (unsigned)len >= buflen ) {
927                                 return -1;
928                         }
929                         buflen -= len;
930                         ptr += len;
931                 }
932         }
933
934         return 0;
935 }
936
937 /*
938  * formatted print to string
939  *
940  * - if return code < 0, the error code returned by vsnprintf(3) is returned
941  *
942  * - if return code > 0, the buffer was not long enough;
943  *      - if next is not NULL, *next will be set to buf + bufsize - 1
944  *      - if len is not NULL, *len will contain the required buffer length
945  *
946  * - if return code == 0, the buffer was long enough;
947  *      - if next is not NULL, *next will point to the end of the string printed so far
948  *      - if len is not NULL, *len will contain the length of the string printed so far 
949  */
950 int
951 lutil_snprintf( char *buf, ber_len_t bufsize, char **next, ber_len_t *len, LDAP_CONST char *fmt, ... )
952 {
953         va_list         ap;
954         int             ret;
955
956         assert( buf != NULL );
957         assert( bufsize > 0 );
958         assert( fmt != NULL );
959
960         va_start( ap, fmt );
961         ret = vsnprintf( buf, bufsize, fmt, ap );
962         va_end( ap );
963
964         if ( ret < 0 ) {
965                 return ret;
966         }
967
968         if ( len ) {
969                 *len = ret;
970         }
971
972         if ( (unsigned) ret >= bufsize ) {
973                 if ( next ) {
974                         *next = &buf[ bufsize - 1 ];
975                 }
976
977                 return 1;
978         }
979
980         if ( next ) {
981                 *next = &buf[ ret ];
982         }
983
984         return 0;
985 }
986