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