]> git.sur5r.net Git - openldap/blob - libraries/liblutil/utils.c
ITS#6351,6390: s/memrchr/lutil_memrchr/, but try #define lutil_memrchr->memrchr
[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 /* strcopy is like strcpy except it returns a pointer to the trailing NUL of
286  * the result string. This allows fast construction of catenated strings
287  * without the overhead of strlen/strcat.
288  */
289 char *
290 lutil_strcopy(
291         char *a,
292         const char *b
293 )
294 {
295         if (!a || !b)
296                 return a;
297         
298         while ((*a++ = *b++)) ;
299         return a-1;
300 }
301
302 /* strncopy is like strcpy except it returns a pointer to the trailing NUL of
303  * the result string. This allows fast construction of catenated strings
304  * without the overhead of strlen/strcat.
305  */
306 char *
307 lutil_strncopy(
308         char *a,
309         const char *b,
310         size_t n
311 )
312 {
313         if (!a || !b || n == 0)
314                 return a;
315         
316         while ((*a++ = *b++) && n-- > 0) ;
317         return a-1;
318 }
319
320 /* memcopy is like memcpy except it returns a pointer to the byte past
321  * the end of the result buffer, set to NULL. This allows fast construction
322  * of catenated buffers.  Provided for API consistency with lutil_str*copy().
323  */
324 char *
325 lutil_memcopy(
326         char *a,
327         const char *b,
328         size_t n
329 )
330 {
331         AC_MEMCPY(a, b, n);
332         return a + n;
333 }
334
335 #ifndef HAVE_MKSTEMP
336 int mkstemp( char * template )
337 {
338 #ifdef HAVE_MKTEMP
339         return open ( mktemp ( template ), O_RDWR|O_CREAT|O_EXCL, 0600 );
340 #else
341         return -1;
342 #endif
343 }
344 #endif
345
346 #ifdef _MSC_VER
347 /* Equivalent of MS CRT's _dosmaperr().
348  * @param lastError[in] Result of GetLastError().
349  */
350 static errno_t win2errno(DWORD lastError)
351 {
352         const struct { 
353                 DWORD   windows_code;
354                 errno_t errno_code;
355         } WIN2ERRNO_TABLE[] = {
356                 { ERROR_SUCCESS, 0 },
357                 { ERROR_FILE_NOT_FOUND, ENOENT },
358                 { ERROR_PATH_NOT_FOUND, ENOENT },
359                 { ERROR_TOO_MANY_OPEN_FILES, EMFILE },
360                 { ERROR_ACCESS_DENIED, EACCES },
361                 { ERROR_INVALID_HANDLE, EBADF },
362                 { ERROR_NOT_ENOUGH_MEMORY, ENOMEM },
363                 { ERROR_LOCK_VIOLATION, EACCES },
364                 { ERROR_FILE_EXISTS, EEXIST },
365                 { ERROR_INVALID_PARAMETER, EINVAL },
366                 { ERROR_FILENAME_EXCED_RANGE, ENAMETOOLONG },
367         };
368         const unsigned int WIN2ERRNO_TABLE_SIZE = sizeof(WIN2ERRNO_TABLE) /
369 sizeof(WIN2ERRNO_TABLE[0]);
370         const errno_t DEFAULT_ERRNO_ERROR = -1;
371         unsigned int i;
372
373         for (i = 0; i < WIN2ERRNO_TABLE_SIZE; ++i) {
374                 if (WIN2ERRNO_TABLE[i].windows_code == lastError) {
375                         return WIN2ERRNO_TABLE[i].errno_code;
376                 }
377         }
378         return DEFAULT_ERRNO_ERROR;
379 }
380
381 struct dirent {
382         char *d_name;
383 };
384 typedef struct DIR {
385         HANDLE dir;
386         struct dirent data;
387         int first;
388         char buf[MAX_PATH+1];
389 } DIR;
390 DIR *opendir( char *path )
391 {
392         char tmp[32768];
393         int len = strlen(path);
394         DIR *d;
395         HANDLE h;
396         WIN32_FIND_DATA data;
397         
398         if (len+3 >= sizeof(tmp)) {
399                 errno = ENAMETOOLONG;
400                 return NULL;
401         }
402
403         strcpy(tmp, path);
404         tmp[len++] = '\\';
405         tmp[len++] = '*';
406         tmp[len] = '\0';
407
408         h = FindFirstFile( tmp, &data );
409
410         if ( h == INVALID_HANDLE_VALUE ) {
411                 errno = win2errno( GetLastError());
412                 return NULL;
413         }
414
415         d = ber_memalloc( sizeof(DIR) );
416         if ( !d )
417                 return NULL;
418         d->dir = h;
419         d->data.d_name = d->buf;
420         d->first = 1;
421         strcpy(d->data.d_name, data.cFileName);
422         return d;
423 }
424 struct dirent *readdir(DIR *dir)
425 {
426         WIN32_FIND_DATA data;
427
428         if (dir->first) {
429                 dir->first = 0;
430         } else {
431                 if (!FindNextFile(dir->dir, &data))
432                         return NULL;
433                 strcpy(dir->data.d_name, data.cFileName);
434         }
435         return &dir->data;
436 }
437 int closedir(DIR *dir)
438 {
439         FindClose(dir->dir);
440         ber_memfree(dir);
441 }
442 #endif
443
444 /*
445  * Memory Reverse Search
446  */
447 void *
448 (lutil_memrchr)(const void *b, int c, size_t n)
449 {
450         if (n != 0) {
451                 const unsigned char *s, *bb = b, cc = c;
452
453                 for ( s = bb + n; s > bb; ) {
454                         if ( *--s == cc ) {
455                                 return (void *) s;
456                         }
457                 }
458         }
459
460         return NULL;
461 }
462
463 int
464 lutil_atoix( int *v, const char *s, int x )
465 {
466         char            *next;
467         long            i;
468
469         assert( s != NULL );
470         assert( v != NULL );
471
472         i = strtol( s, &next, x );
473         if ( next == s || next[ 0 ] != '\0' ) {
474                 return -1;
475         }
476
477         if ( (long)(int)i != i ) {
478                 return 1;
479         }
480
481         *v = (int)i;
482
483         return 0;
484 }
485
486 int
487 lutil_atoux( unsigned *v, const char *s, int x )
488 {
489         char            *next;
490         unsigned long   u;
491
492         assert( s != NULL );
493         assert( v != NULL );
494
495         /* strtoul() has an odd interface */
496         if ( s[ 0 ] == '-' ) {
497                 return -1;
498         }
499
500         u = strtoul( s, &next, x );
501         if ( next == s || next[ 0 ] != '\0' ) {
502                 return -1;
503         }
504
505         if ( (unsigned long)(unsigned)u != u ) {
506                 return 1;
507         }
508
509         *v = u;
510
511         return 0;
512 }
513
514 int
515 lutil_atolx( long *v, const char *s, int x )
516 {
517         char            *next;
518         long            l;
519
520         assert( s != NULL );
521         assert( v != NULL );
522
523         l = strtol( s, &next, x );
524         if ( next == s || next[ 0 ] != '\0' ) {
525                 return -1;
526         }
527
528         *v = l;
529
530         return 0;
531 }
532
533 int
534 lutil_atoulx( unsigned long *v, const char *s, int x )
535 {
536         char            *next;
537         unsigned long   ul;
538
539         assert( s != NULL );
540         assert( v != NULL );
541
542         /* strtoul() has an odd interface */
543         if ( s[ 0 ] == '-' ) {
544                 return -1;
545         }
546
547         ul = strtoul( s, &next, x );
548         if ( next == s || next[ 0 ] != '\0' ) {
549                 return -1;
550         }
551
552         *v = ul;
553
554         return 0;
555 }
556
557 /* Multiply an integer by 100000000 and add new */
558 typedef struct lutil_int_decnum {
559         unsigned char *buf;
560         int bufsiz;
561         int beg;
562         int len;
563 } lutil_int_decnum;
564
565 #define FACTOR1 (100000000&0xffff)
566 #define FACTOR2 (100000000>>16)
567
568 static void
569 scale( int new, lutil_int_decnum *prev, unsigned char *tmp )
570 {
571         int i, j;
572         unsigned char *in = prev->buf+prev->beg;
573         unsigned int part;
574         unsigned char *out = tmp + prev->bufsiz - prev->len;
575
576         memset( tmp, 0, prev->bufsiz );
577         if ( prev->len ) {
578                 for ( i = prev->len-1; i>=0; i-- ) {
579                         part = in[i] * FACTOR1;
580                         for ( j = i; part; j-- ) {
581                                 part += out[j];
582                                 out[j] = part & 0xff;
583                                 part >>= 8;
584                         }
585                         part = in[i] * FACTOR2;
586                         for ( j = i-2; part; j-- ) {
587                                 part += out[j];
588                                 out[j] = part & 0xff;
589                                 part >>= 8;
590                         }
591                 }
592                 j++;
593                 prev->beg += j;
594                 prev->len -= j;
595         }
596
597         out = tmp + prev->bufsiz;
598         i = 0;
599         do {
600                 i--;
601                 new += out[i];
602                 out[i] = new & 0xff;
603                 new >>= 8;
604         } while ( new );
605         i = -i;
606         if ( prev->len < i ) {
607                 prev->beg = prev->bufsiz - i;
608                 prev->len = i;
609         }
610         AC_MEMCPY( prev->buf+prev->beg, tmp+prev->beg, prev->len );
611 }
612
613 /* Convert unlimited length decimal or hex string to binary.
614  * Output buffer must be provided, bv_len must indicate buffer size
615  * Hex input can be "0x1234" or "'1234'H"
616  *
617  * Temporarily modifies the input string.
618  *
619  * Note: High bit of binary form is always the sign bit. If the number
620  * is supposed to be positive but has the high bit set, a zero byte
621  * is prepended. It is assumed that this has already been handled on
622  * any hex input.
623  */
624 int
625 lutil_str2bin( struct berval *in, struct berval *out, void *ctx )
626 {
627         char *pin, *pout, ctmp;
628         char *end;
629         int i, chunk, len, rc = 0, hex = 0;
630         if ( !out || !out->bv_val || out->bv_len < in->bv_len )
631                 return -1;
632
633         pout = out->bv_val;
634         /* Leading "0x" for hex input */
635         if ( in->bv_len > 2 && in->bv_val[0] == '0' &&
636                 ( in->bv_val[1] == 'x' || in->bv_val[1] == 'X' ) )
637         {
638                 len = in->bv_len - 2;
639                 pin = in->bv_val + 2;
640                 hex = 1;
641         } else if ( in->bv_len > 3 && in->bv_val[0] == '\'' &&
642                 in->bv_val[in->bv_len-2] == '\'' &&
643                 in->bv_val[in->bv_len-1] == 'H' )
644         {
645                 len = in->bv_len - 3;
646                 pin = in->bv_val + 1;
647                 hex = 1;
648         }
649         if ( hex ) {
650 #define HEXMAX  (2 * sizeof(long))
651                 unsigned long l;
652                 /* Convert a longword at a time, but handle leading
653                  * odd bytes first
654                  */
655                 chunk = len % HEXMAX;
656                 if ( !chunk )
657                         chunk = HEXMAX;
658
659                 while ( len ) {
660                         int ochunk;
661                         ctmp = pin[chunk];
662                         pin[chunk] = '\0';
663                         errno = 0;
664                         l = strtoul( pin, &end, 16 );
665                         pin[chunk] = ctmp;
666                         if ( errno )
667                                 return -1;
668                         ochunk = (chunk + 1)/2;
669                         for ( i = ochunk - 1; i >= 0; i-- ) {
670                                 pout[i] = l & 0xff;
671                                 l >>= 8;
672                         }
673                         pin += chunk;
674                         pout += ochunk;
675                         len -= chunk;
676                         chunk = HEXMAX;
677                 }
678                 out->bv_len = pout - out->bv_val;
679         } else {
680         /* Decimal */
681                 char tmpbuf[64], *tmp;
682                 lutil_int_decnum num;
683                 int neg = 0;
684                 long l;
685
686                 len = in->bv_len;
687                 pin = in->bv_val;
688                 num.buf = (unsigned char *)out->bv_val;
689                 num.bufsiz = out->bv_len;
690                 num.beg = num.bufsiz-1;
691                 num.len = 0;
692                 if ( pin[0] == '-' ) {
693                         neg = 0xff;
694                         len--;
695                         pin++;
696                 }
697
698 #define DECMAX  8       /* 8 digits at a time */
699
700                 /* tmp must be at least as large as outbuf */
701                 if ( out->bv_len > sizeof(tmpbuf)) {
702                         tmp = ber_memalloc_x( out->bv_len, ctx );
703                 } else {
704                         tmp = tmpbuf;
705                 }
706                 chunk = len & (DECMAX-1);
707                 if ( !chunk )
708                         chunk = DECMAX;
709
710                 while ( len ) {
711                         ctmp = pin[chunk];
712                         pin[chunk] = '\0';
713                         errno = 0;
714                         l = strtol( pin, &end, 10 );
715                         pin[chunk] = ctmp;
716                         if ( errno ) {
717                                 rc = -1;
718                                 goto decfail;
719                         }
720                         scale( l, &num, (unsigned char *)tmp );
721                         pin += chunk;
722                         len -= chunk;
723                         chunk = DECMAX;
724                 }
725                 /* Negate the result */
726                 if ( neg ) {
727                         unsigned char *ptr;
728
729                         ptr = num.buf+num.beg;
730
731                         /* flip all bits */
732                         for ( i=0; i<num.len; i++ )
733                                 ptr[i] ^= 0xff;
734
735                         /* add 1, with carry - overflow handled below */
736                         while ( i-- && ! (ptr[i] = (ptr[i] + 1) & 0xff )) ;
737                 }
738                 /* Prepend sign byte if wrong sign bit */
739                 if (( num.buf[num.beg] ^ neg ) & 0x80 ) {
740                         num.beg--;
741                         num.len++;
742                         num.buf[num.beg] = neg;
743                 }
744                 if ( num.beg )
745                         AC_MEMCPY( num.buf, num.buf+num.beg, num.len );
746                 out->bv_len = num.len;
747 decfail:
748                 if ( tmp != tmpbuf ) {
749                         ber_memfree_x( tmp, ctx );
750                 }
751         }
752         return rc;
753 }
754
755 static  char            time_unit[] = "dhms";
756
757 /* Used to parse and unparse time intervals, not timestamps */
758 int
759 lutil_parse_time(
760         const char      *in,
761         unsigned long   *tp )
762 {
763         unsigned long   t = 0;
764         char            *s,
765                         *next;
766         int             sofar = -1,
767                         scale[] = { 86400, 3600, 60, 1 };
768
769         *tp = 0;
770
771         for ( s = (char *)in; s[ 0 ] != '\0'; ) {
772                 unsigned long   u;
773                 char            *what;
774
775                 /* strtoul() has an odd interface */
776                 if ( s[ 0 ] == '-' ) {
777                         return -1;
778                 }
779
780                 u = strtoul( s, &next, 10 );
781                 if ( next == s ) {
782                         return -1;
783                 }
784
785                 if ( next[ 0 ] == '\0' ) {
786                         /* assume seconds */
787                         t += u;
788                         break;
789                 }
790
791                 what = strchr( time_unit, next[ 0 ] );
792                 if ( what == NULL ) {
793                         return -1;
794                 }
795
796                 if ( what - time_unit <= sofar ) {
797                         return -1;
798                 }
799
800                 sofar = what - time_unit;
801                 t += u * scale[ sofar ];
802
803                 s = &next[ 1 ];
804         }
805
806         *tp = t;
807         return 0;
808 }
809
810 int
811 lutil_unparse_time(
812         char                    *buf,
813         size_t                  buflen,
814         unsigned long           t )
815 {
816         int             len, i;
817         unsigned long   v[ 4 ];
818         char            *ptr = buf;
819
820         v[ 0 ] = t/86400;
821         v[ 1 ] = (t%86400)/3600;
822         v[ 2 ] = (t%3600)/60;
823         v[ 3 ] = t%60;
824
825         for ( i = 0; i < 4; i++ ) {
826                 if ( v[i] > 0 || ( i == 3 && ptr == buf ) ) {
827                         len = snprintf( ptr, buflen, "%lu%c", v[ i ], time_unit[ i ] );
828                         if ( len < 0 || (unsigned)len >= buflen ) {
829                                 return -1;
830                         }
831                         buflen -= len;
832                         ptr += len;
833                 }
834         }
835
836         return 0;
837 }
838
839 /*
840  * formatted print to string
841  *
842  * - if return code < 0, the error code returned by vsnprintf(3) is returned
843  *
844  * - if return code > 0, the buffer was not long enough;
845  *      - if next is not NULL, *next will be set to buf + bufsize - 1
846  *      - if len is not NULL, *len will contain the required buffer length
847  *
848  * - if return code == 0, the buffer was long enough;
849  *      - if next is not NULL, *next will point to the end of the string printed so far
850  *      - if len is not NULL, *len will contain the length of the string printed so far 
851  */
852 int
853 lutil_snprintf( char *buf, ber_len_t bufsize, char **next, ber_len_t *len, LDAP_CONST char *fmt, ... )
854 {
855         va_list         ap;
856         int             ret;
857
858         assert( buf != NULL );
859         assert( bufsize > 0 );
860         assert( fmt != NULL );
861
862         va_start( ap, fmt );
863         ret = vsnprintf( buf, bufsize, fmt, ap );
864         va_end( ap );
865
866         if ( ret < 0 ) {
867                 return ret;
868         }
869
870         if ( len ) {
871                 *len = ret;
872         }
873
874         if ( (unsigned) ret >= bufsize ) {
875                 if ( next ) {
876                         *next = &buf[ bufsize - 1 ];
877                 }
878
879                 return 1;
880         }
881
882         if ( next ) {
883                 *next = &buf[ ret ];
884         }
885
886         return 0;
887 }
888