]> git.sur5r.net Git - openldap/blob - libraries/liblutil/utils.c
ITS#4840 fix typo
[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 #ifdef HAVE_IO_H
25 #include <io.h>
26 #endif
27 #ifdef HAVE_FCNTL_H
28 #include <fcntl.h>
29 #endif
30 #ifdef _WIN32
31 #include <windows.h>
32 #endif
33
34 #include "lutil.h"
35 #include "ldap_defaults.h"
36 #include "ldap_pvt.h"
37
38 #ifdef HAVE_EBCDIC
39 int _trans_argv = 1;
40 #endif
41
42 #ifdef _WIN32
43 /* Some Windows versions accept both forward and backslashes in
44  * directory paths, but we always use backslashes when generating
45  * and parsing...
46  */
47 void lutil_slashpath( char *path )
48 {
49         char *c, *p;
50
51         p = path;
52         while (( c=strchr( p, '/' ))) {
53                 *c++ = '\\';
54                 p = c;
55         }
56 }
57 #endif
58
59 char* lutil_progname( const char* name, int argc, char *argv[] )
60 {
61         char *progname;
62
63         if(argc == 0) {
64                 return (char *)name;
65         }
66
67 #ifdef HAVE_EBCDIC
68         if (_trans_argv) {
69                 int i;
70                 for (i=0; i<argc; i++) __etoa(argv[i]);
71                 _trans_argv = 0;
72         }
73 #endif
74         LUTIL_SLASHPATH( argv[0] );
75         progname = strrchr ( argv[0], *LDAP_DIRSEP );
76         progname = progname ? &progname[1] : argv[0];
77         return progname;
78 }
79
80 #if 0
81 size_t lutil_gentime( char *s, size_t smax, const struct tm *tm )
82 {
83         size_t ret;
84 #ifdef HAVE_EBCDIC
85 /* We've been compiling in ASCII so far, but we want EBCDIC now since
86  * strftime only understands EBCDIC input.
87  */
88 #pragma convlit(suspend)
89 #endif
90         ret = strftime( s, smax, "%Y%m%d%H%M%SZ", tm );
91 #ifdef HAVE_EBCDIC
92 #pragma convlit(resume)
93         __etoa( s );
94 #endif
95         return ret;
96 }
97 #endif
98
99 size_t lutil_localtime( char *s, size_t smax, const struct tm *tm, long delta )
100 {
101         size_t  ret;
102         char    *p;
103
104         if ( smax < 16 ) {      /* YYYYmmddHHMMSSZ */
105                 return 0;
106         }
107
108 #ifdef HAVE_EBCDIC
109 /* We've been compiling in ASCII so far, but we want EBCDIC now since
110  * strftime only understands EBCDIC input.
111  */
112 #pragma convlit(suspend)
113 #endif
114         ret = strftime( s, smax, "%Y%m%d%H%M%SZ", tm );
115 #ifdef HAVE_EBCDIC
116 #pragma convlit(resume)
117         __etoa( s );
118 #endif
119         if ( delta == 0 || ret == 0 ) {
120                 return ret;
121         }
122
123         if ( smax < 20 ) {      /* YYYYmmddHHMMSS+HHMM */
124                 return 0;
125         }
126
127         p = s + 14;
128
129         if ( delta < 0 ) {
130                 p[ 0 ] = '-';
131                 delta = -delta;
132         } else {
133                 p[ 0 ] = '+';
134         }
135         p++;
136
137         snprintf( p, smax - 15, "%02ld%02ld", delta / 3600,
138                         ( delta % 3600 ) / 60 );
139
140         return ret + 5;
141 }
142
143 int lutil_tm2time( struct lutil_tm *tm, struct lutil_timet *tt )
144 {
145         static int moffset[12] = {
146                 0, 31, 59, 90, 120,
147                 151, 181, 212, 243,
148                 273, 304, 334 }; 
149         int sec;
150
151         tt->tt_usec = tm->tm_usec;
152
153         /* special case 0000/01/01+00:00:00 is returned as zero */
154         if ( tm->tm_year == -1900 && tm->tm_mon == 0 && tm->tm_mday == 1 &&
155                 tm->tm_hour == 0 && tm->tm_min == 0 && tm->tm_sec == 0 ) {
156                 tt->tt_sec = 0;
157                 tt->tt_gsec = 0;
158                 return 0;
159         }
160
161         /* tm->tm_year is years since 1900 */
162         /* calculate days from years since 1970 (epoch) */ 
163         tt->tt_sec = tm->tm_year - 70; 
164         tt->tt_sec *= 365L; 
165
166         /* count leap days in preceding years */ 
167         tt->tt_sec += ((tm->tm_year -69) >> 2); 
168
169         /* calculate days from months */ 
170         tt->tt_sec += moffset[tm->tm_mon]; 
171
172         /* add in this year's leap day, if any */ 
173         if (((tm->tm_year & 3) == 0) && (tm->tm_mon > 1)) { 
174                 tt->tt_sec ++; 
175         } 
176
177         /* add in days in this month */ 
178         tt->tt_sec += (tm->tm_mday - 1); 
179
180         /* this function can handle a range of about 17408 years... */
181         /* 86400 seconds in a day, divided by 128 = 675 */
182         tt->tt_sec *= 675;
183
184         /* move high 7 bits into tt_gsec */
185         tt->tt_gsec = tt->tt_sec >> 25;
186         tt->tt_sec -= tt->tt_gsec << 25;
187
188         /* get hours */ 
189         sec = tm->tm_hour; 
190
191         /* convert to minutes */ 
192         sec *= 60L; 
193         sec += tm->tm_min; 
194
195         /* convert to seconds */ 
196         sec *= 60L; 
197         sec += tm->tm_sec; 
198         
199         /* add remaining seconds */
200         tt->tt_sec <<= 7;
201         tt->tt_sec += sec;
202
203         /* return success */
204         return 0; 
205 }
206
207 int lutil_parsetime( char *atm, struct lutil_tm *tm )
208 {
209         while (atm && tm) {
210                 char *ptr = atm;
211                 unsigned i, fracs;
212
213                 /* Is the stamp reasonably long? */
214                 for (i=0; isdigit((unsigned char) atm[i]); i++);
215                 if (i < sizeof("00000101000000")-1)
216                         break;
217
218                 /*
219                  * parse the time into a struct tm
220                  */
221                 /* 4 digit year to year - 1900 */
222                 tm->tm_year = *ptr++ - '0';
223                 tm->tm_year *= 10; 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 -= 1900;
227                 /* month 01-12 to 0-11 */
228                 tm->tm_mon = *ptr++ - '0';
229                 tm->tm_mon *=10; tm->tm_mon += *ptr++ - '0';
230                 if (tm->tm_mon < 1 || tm->tm_mon > 12) break;
231                 tm->tm_mon--;
232
233                 /* day of month 01-31 */
234                 tm->tm_mday = *ptr++ - '0';
235                 tm->tm_mday *=10; tm->tm_mday += *ptr++ - '0';
236                 if (tm->tm_mday < 1 || tm->tm_mday > 31) break;
237
238                 /* Hour 00-23 */
239                 tm->tm_hour = *ptr++ - '0';
240                 tm->tm_hour *=10; tm->tm_hour += *ptr++ - '0';
241                 if (tm->tm_hour < 0 || tm->tm_hour > 23) break;
242
243                 /* Minute 00-59 */
244                 tm->tm_min = *ptr++ - '0';
245                 tm->tm_min *=10; tm->tm_min += *ptr++ - '0';
246                 if (tm->tm_min < 0 || tm->tm_min > 59) break;
247
248                 /* Second 00-61 */
249                 tm->tm_sec = *ptr++ - '0';
250                 tm->tm_sec *=10; tm->tm_sec += *ptr++ - '0';
251                 if (tm->tm_sec < 0 || tm->tm_sec > 61) break;
252
253                 /* Fractions of seconds */
254                 if ( *ptr == '.' ) {
255                         ptr++;
256                         for (i = 0, fracs = 0; isdigit((unsigned char) *ptr); ) {
257                                 i*=10; i+= *ptr++ - '0';
258                                 fracs++;
259                         }
260                         tm->tm_usec = i;
261                         if (i) {
262                                 for (i = fracs; i<6; i++)
263                                         tm->tm_usec *= 10;
264                         }
265                 }
266
267                 /* Must be UTC */
268                 if (*ptr != 'Z') break;
269
270                 return 0;
271         }
272         return -1;
273 }
274
275 /* return a broken out time, with microseconds
276  * Must be mutex-protected.
277  */
278 #ifdef _WIN32
279 /* Windows SYSTEMTIME only has 10 millisecond resolution, so we
280  * also need to use a high resolution timer to get microseconds.
281  * This is pretty clunky.
282  */
283 void
284 lutil_gettime( struct lutil_tm *tm )
285 {
286         static LARGE_INTEGER cFreq;
287         static LARGE_INTEGER prevCount;
288         static int subs;
289         static int offset;
290         LARGE_INTEGER count;
291         SYSTEMTIME st;
292
293         GetSystemTime( &st );
294         QueryPerformanceCounter( &count );
295
296         /* We assume Windows has at least a vague idea of
297          * when a second begins. So we align our microsecond count
298          * with the Windows millisecond count using this offset.
299          * We retain the submillisecond portion of our own count.
300          */
301         if ( !cFreq.QuadPart ) {
302                 long long t;
303                 int usec;
304                 QueryPerformanceFrequency( &cFreq );
305
306                 t = count.QuadPart * 1000000;
307                 t /= cFreq.QuadPart;
308                 usec = t % 10000000;
309                 usec /= 1000;
310                 offset = ( usec - st.wMilliseconds ) * 1000;
311         }
312
313         /* It shouldn't ever go backwards, but multiple CPUs might
314          * be able to hit in the same tick.
315          */
316         if ( count.QuadPart <= prevCount.QuadPart ) {
317                 subs++;
318         } else {
319                 subs = 0;
320                 prevCount = count;
321         }
322
323         tm->tm_usub = subs;
324
325         /* convert to microseconds */
326         count.QuadPart *= 1000000;
327         count.QuadPart /= cFreq.QuadPart;
328         count.QuadPart -= offset;
329
330         tm->tm_usec = count.QuadPart % 1000000;
331
332         /* any difference larger than microseconds is
333          * already reflected in st
334          */
335
336         tm->tm_sec = st.wSecond;
337         tm->tm_min = st.wMinute;
338         tm->tm_hour = st.wHour;
339         tm->tm_mday = st.wDay;
340         tm->tm_mon = st.wMonth - 1;
341         tm->tm_year = st.wYear - 1900;
342 }
343 #else
344 void
345 lutil_gettime( struct lutil_tm *ltm )
346 {
347         struct timeval tv;
348         static struct timeval prevTv;
349         static int subs;
350
351 #ifdef HAVE_GMTIME_R
352         struct tm tm_buf;
353 #endif
354         struct tm *tm;
355         time_t t;
356
357         gettimeofday( &tv, NULL );
358         t = tv.tv_sec;
359
360         if ( tv.tv_sec < prevTv.tv_sec
361                 || ( tv.tv_sec == prevTv.tv_sec && tv.tv_usec == prevTv.tv_usec )) {
362                 subs++;
363         } else {
364                 subs = 0;
365                 prevTv = tv;
366         }
367
368         ltm->tm_usub = subs;
369
370 #ifdef HAVE_GMTIME_R
371         tm = gmtime_r( &t, &tm_buf );
372 #else
373         tm = gmtime( &t );
374 #endif
375
376         ltm->tm_sec = tm->tm_sec;
377         ltm->tm_min = tm->tm_min;
378         ltm->tm_hour = tm->tm_hour;
379         ltm->tm_mday = tm->tm_mday;
380         ltm->tm_mon = tm->tm_mon;
381         ltm->tm_year = tm->tm_year;
382         ltm->tm_usec = tv.tv_usec;
383 }
384 #endif
385
386 /* strcopy is like strcpy except it returns a pointer to the trailing NUL of
387  * the result string. This allows fast construction of catenated strings
388  * without the overhead of strlen/strcat.
389  */
390 char *
391 lutil_strcopy(
392         char *a,
393         const char *b
394 )
395 {
396         if (!a || !b)
397                 return a;
398         
399         while ((*a++ = *b++)) ;
400         return a-1;
401 }
402
403 /* strncopy is like strcpy except it returns a pointer to the trailing NUL of
404  * the result string. This allows fast construction of catenated strings
405  * without the overhead of strlen/strcat.
406  */
407 char *
408 lutil_strncopy(
409         char *a,
410         const char *b,
411         size_t n
412 )
413 {
414         if (!a || !b || n == 0)
415                 return a;
416         
417         while ((*a++ = *b++) && n-- > 0) ;
418         return a-1;
419 }
420
421 #ifndef HAVE_MKSTEMP
422 int mkstemp( char * template )
423 {
424 #ifdef HAVE_MKTEMP
425         return open ( mktemp ( template ), O_RDWR|O_CREAT|O_EXCL, 0600 );
426 #else
427         return -1;
428 #endif
429 }
430 #endif
431
432 #ifdef _MSC_VER
433 struct dirent {
434         char *d_name;
435 };
436 typedef struct DIR {
437         HANDLE dir;
438         struct dirent data;
439         int first;
440         char buf[MAX_PATH+1];
441 } DIR;
442 DIR *opendir( char *path )
443 {
444         char tmp[32768];
445         int len = strlen(path);
446         DIR *d;
447         HANDLE h;
448         WIN32_FIND_DATA data;
449         
450         if (len+3 >= sizeof(tmp))
451                 return NULL;
452
453         strcpy(tmp, path);
454         tmp[len++] = '\\';
455         tmp[len++] = '*';
456         tmp[len] = '\0';
457
458         h = FindFirstFile( tmp, &data );
459         
460         if ( h == INVALID_HANDLE_VALUE )
461                 return NULL;
462
463         d = ber_memalloc( sizeof(DIR) );
464         if ( !d )
465                 return NULL;
466         d->dir = h;
467         d->data.d_name = d->buf;
468         d->first = 1;
469         strcpy(d->data.d_name, data.cFileName);
470         return d;
471 }
472 struct dirent *readdir(DIR *dir)
473 {
474         WIN32_FIND_DATA data;
475
476         if (dir->first) {
477                 dir->first = 0;
478         } else {
479                 if (!FindNextFile(dir->dir, &data))
480                         return NULL;
481                 strcpy(dir->data.d_name, data.cFileName);
482         }
483         return &dir->data;
484 }
485 void closedir(DIR *dir)
486 {
487         FindClose(dir->dir);
488         ber_memfree(dir);
489 }
490 #endif
491
492 /*
493  * Memory Reverse Search
494  */
495 void *
496 lutil_memrchr(const void *b, int c, size_t n)
497 {
498         if (n != 0) {
499                 const unsigned char *s, *bb = b, cc = c;
500
501                 for ( s = bb + n; s > bb; ) {
502                         if ( *--s == cc ) {
503                                 return (void *) s;
504                         }
505                 }
506         }
507
508         return NULL;
509 }
510
511 int
512 lutil_atoix( int *v, const char *s, int x )
513 {
514         char            *next;
515         long            i;
516
517         assert( s != NULL );
518         assert( v != NULL );
519
520         i = strtol( s, &next, x );
521         if ( next == s || next[ 0 ] != '\0' ) {
522                 return -1;
523         }
524
525         if ( (long)(int)i != i ) {
526                 return 1;
527         }
528
529         *v = (int)i;
530
531         return 0;
532 }
533
534 int
535 lutil_atoux( unsigned *v, const char *s, int x )
536 {
537         char            *next;
538         unsigned long   u;
539
540         assert( s != NULL );
541         assert( v != NULL );
542
543         /* strtoul() has an odd interface */
544         if ( s[ 0 ] == '-' ) {
545                 return -1;
546         }
547
548         u = strtoul( s, &next, x );
549         if ( next == s || next[ 0 ] != '\0' ) {
550                 return -1;
551         }
552
553         if ( (unsigned long)(unsigned)u != u ) {
554                 return 1;
555         }
556
557         *v = u;
558
559         return 0;
560 }
561
562 int
563 lutil_atolx( long *v, const char *s, int x )
564 {
565         char            *next;
566         long            l;
567
568         assert( s != NULL );
569         assert( v != NULL );
570
571         l = strtol( s, &next, x );
572         if ( next == s || next[ 0 ] != '\0' ) {
573                 return -1;
574         }
575
576         *v = l;
577
578         return 0;
579 }
580
581 int
582 lutil_atoulx( unsigned long *v, const char *s, int x )
583 {
584         char            *next;
585         unsigned long   ul;
586
587         assert( s != NULL );
588         assert( v != NULL );
589
590         /* strtoul() has an odd interface */
591         if ( s[ 0 ] == '-' ) {
592                 return -1;
593         }
594
595         ul = strtoul( s, &next, x );
596         if ( next == s || next[ 0 ] != '\0' ) {
597                 return -1;
598         }
599
600         *v = ul;
601
602         return 0;
603 }
604
605 static  char            time_unit[] = "dhms";
606
607 /* Used to parse and unparse time intervals, not timestamps */
608 int
609 lutil_parse_time(
610         const char      *in,
611         unsigned long   *tp )
612 {
613         unsigned long   t = 0;
614         char            *s,
615                         *next;
616         int             sofar = -1,
617                         scale[] = { 86400, 3600, 60, 1 };
618
619         *tp = 0;
620
621         for ( s = (char *)in; s[ 0 ] != '\0'; ) {
622                 unsigned long   u;
623                 char            *what;
624
625                 /* strtoul() has an odd interface */
626                 if ( s[ 0 ] == '-' ) {
627                         return -1;
628                 }
629
630                 u = strtoul( s, &next, 10 );
631                 if ( next == s ) {
632                         return -1;
633                 }
634
635                 if ( next[ 0 ] == '\0' ) {
636                         /* assume seconds */
637                         t += u;
638                         break;
639                 }
640
641                 what = strchr( time_unit, next[ 0 ] );
642                 if ( what == NULL ) {
643                         return -1;
644                 }
645
646                 if ( what - time_unit <= sofar ) {
647                         return -1;
648                 }
649
650                 sofar = what - time_unit;
651                 t += u * scale[ sofar ];
652
653                 s = &next[ 1 ];
654         }
655
656         *tp = t;
657         return 0;
658 }
659
660 int
661 lutil_unparse_time(
662         char                    *buf,
663         size_t                  buflen,
664         unsigned long           t )
665 {
666         int             len, i;
667         unsigned long   v[ 4 ];
668         char            *ptr = buf;
669
670         v[ 0 ] = t/86400;
671         v[ 1 ] = (t%86400)/3600;
672         v[ 2 ] = (t%3600)/60;
673         v[ 3 ] = t%60;
674
675         for ( i = 0; i < 4; i++ ) {
676                 if ( v[i] > 0 || ( i == 3 && ptr == buf ) ) {
677                         len = snprintf( ptr, buflen, "%lu%c", v[ i ], time_unit[ i ] );
678                         if ( len < 0 || (unsigned)len >= buflen ) {
679                                 return -1;
680                         }
681                         buflen -= len;
682                         ptr += len;
683                 }
684         }
685
686         return 0;
687 }
688