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