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