]> git.sur5r.net Git - openldap/blob - libraries/liblutil/utils.c
Cleanup extraneous debug
[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 #ifdef _WIN32
277 /* Windows SYSTEMTIME only has 10 millisecond resolution, so we
278  * also need to use a high resolution timer to get microseconds.
279  * This is pretty clunky.
280  */
281 void
282 lutil_gettime( struct lutil_tm *tm )
283 {
284         static LARGE_INTEGER cFreq;
285         static int offset;
286         LARGE_INTEGER count;
287         SYSTEMTIME st;
288
289         GetSystemTime( &st );
290         QueryPerformanceCounter( &count );
291
292         /* We assume Windows has at least a vague idea of
293          * when a second begins. So we align our microsecond count
294          * with the Windows millisecond count using this offset.
295          * We retain the submillisecond portion of our own count.
296          */
297         if ( !cFreq.QuadPart ) {
298                 long long t;
299                 int usec;
300                 QueryPerformanceFrequency( &cFreq );
301
302                 t = count.QuadPart * 1000000;
303                 t /= cFreq.QuadPart;
304                 usec = t % 10000000;
305                 usec /= 1000;
306                 offset = ( usec - st.wMilliseconds ) * 1000;
307         }
308
309         /* convert to microseconds */
310         count.QuadPart *= 1000000;
311         count.QuadPart /= cFreq.QuadPart;
312         count.QuadPart -= offset;
313
314         tm->tm_usec = count.QuadPart % 1000000;
315
316         /* any difference larger than microseconds is
317          * already reflected in st
318          */
319
320         tm->tm_sec = st.wSecond;
321         tm->tm_min = st.wMinute;
322         tm->tm_hour = st.wHour;
323         tm->tm_mday = st.wDay;
324         tm->tm_mon = st.wMonth - 1;
325         tm->tm_year = st.wYear - 1900;
326 }
327 #else
328 void
329 lutil_gettime( struct lutil_tm *ltm )
330 {
331         struct timeval tv;
332 #ifdef HAVE_GMTIME_R
333         struct tm tm_buf;
334 #endif
335         struct tm *tm;
336         time_t t;
337
338         gettimeofday( &tv, NULL );
339         t = tv.tv_sec;
340
341 #ifdef HAVE_GMTIME_R
342         tm = gmtime_r( &t, &tm_buf );
343 #else
344         tm = gmtime( &t );
345 #endif
346
347         ltm->tm_sec = tm->tm_sec;
348         ltm->tm_min = tm->tm_min;
349         ltm->tm_hour = tm->tm_hour;
350         ltm->tm_mday = tm->tm_mday;
351         ltm->tm_mon = tm->tm_mon;
352         ltm->tm_year = tm->tm_year;
353         ltm->tm_usec = tv.tv_usec;
354 }
355 #endif
356
357 /* strcopy is like strcpy except it returns a pointer to the trailing NUL of
358  * the result string. This allows fast construction of catenated strings
359  * without the overhead of strlen/strcat.
360  */
361 char *
362 lutil_strcopy(
363         char *a,
364         const char *b
365 )
366 {
367         if (!a || !b)
368                 return a;
369         
370         while ((*a++ = *b++)) ;
371         return a-1;
372 }
373
374 /* strncopy is like strcpy except it returns a pointer to the trailing NUL of
375  * the result string. This allows fast construction of catenated strings
376  * without the overhead of strlen/strcat.
377  */
378 char *
379 lutil_strncopy(
380         char *a,
381         const char *b,
382         size_t n
383 )
384 {
385         if (!a || !b || n == 0)
386                 return a;
387         
388         while ((*a++ = *b++) && n-- > 0) ;
389         return a-1;
390 }
391
392 #ifndef HAVE_MKSTEMP
393 int mkstemp( char * template )
394 {
395 #ifdef HAVE_MKTEMP
396         return open ( mktemp ( template ), O_RDWR|O_CREAT|O_EXCL, 0600 );
397 #else
398         return -1;
399 #endif
400 }
401 #endif
402
403 #ifdef _MSC_VER
404 struct dirent {
405         char *d_name;
406 };
407 typedef struct DIR {
408         HANDLE dir;
409         struct dirent data;
410         int first;
411         char buf[MAX_PATH+1];
412 } DIR;
413 DIR *opendir( char *path )
414 {
415         char tmp[32768];
416         int len = strlen(path);
417         DIR *d;
418         HANDLE h;
419         WIN32_FIND_DATA data;
420         
421         if (len+3 >= sizeof(tmp))
422                 return NULL;
423
424         strcpy(tmp, path);
425         tmp[len++] = '\\';
426         tmp[len++] = '*';
427         tmp[len] = '\0';
428
429         h = FindFirstFile( tmp, &data );
430         
431         if ( h == INVALID_HANDLE_VALUE )
432                 return NULL;
433
434         d = ber_memalloc( sizeof(DIR) );
435         if ( !d )
436                 return NULL;
437         d->dir = h;
438         d->data.d_name = d->buf;
439         d->first = 1;
440         strcpy(d->data.d_name, data.cFileName);
441         return d;
442 }
443 struct dirent *readdir(DIR *dir)
444 {
445         WIN32_FIND_DATA data;
446
447         if (dir->first) {
448                 dir->first = 0;
449         } else {
450                 if (!FindNextFile(dir->dir, &data))
451                         return NULL;
452                 strcpy(dir->data.d_name, data.cFileName);
453         }
454         return &dir->data;
455 }
456 void closedir(DIR *dir)
457 {
458         FindClose(dir->dir);
459         ber_memfree(dir);
460 }
461 #endif
462
463 /*
464  * Memory Reverse Search
465  */
466 void *
467 lutil_memrchr(const void *b, int c, size_t n)
468 {
469         if (n != 0) {
470                 const unsigned char *s, *bb = b, cc = c;
471
472                 for ( s = bb + n; s > bb; ) {
473                         if ( *--s == cc ) {
474                                 return (void *) s;
475                         }
476                 }
477         }
478
479         return NULL;
480 }
481
482 int
483 lutil_atoix( int *v, const char *s, int x )
484 {
485         char            *next;
486         long            i;
487
488         assert( s != NULL );
489         assert( v != NULL );
490
491         i = strtol( s, &next, x );
492         if ( next == s || next[ 0 ] != '\0' ) {
493                 return -1;
494         }
495
496         if ( (long)(int)i != i ) {
497                 return 1;
498         }
499
500         *v = (int)i;
501
502         return 0;
503 }
504
505 int
506 lutil_atoux( unsigned *v, const char *s, int x )
507 {
508         char            *next;
509         unsigned long   u;
510
511         assert( s != NULL );
512         assert( v != NULL );
513
514         /* strtoul() has an odd interface */
515         if ( s[ 0 ] == '-' ) {
516                 return -1;
517         }
518
519         u = strtoul( s, &next, x );
520         if ( next == s || next[ 0 ] != '\0' ) {
521                 return -1;
522         }
523
524         if ( (unsigned long)(unsigned)u != u ) {
525                 return 1;
526         }
527
528         *v = u;
529
530         return 0;
531 }
532
533 int
534 lutil_atolx( long *v, const char *s, int x )
535 {
536         char            *next;
537         long            l;
538
539         assert( s != NULL );
540         assert( v != NULL );
541
542         l = strtol( s, &next, x );
543         if ( next == s || next[ 0 ] != '\0' ) {
544                 return -1;
545         }
546
547         *v = l;
548
549         return 0;
550 }
551
552 int
553 lutil_atoulx( unsigned long *v, const char *s, int x )
554 {
555         char            *next;
556         unsigned long   ul;
557
558         assert( s != NULL );
559         assert( v != NULL );
560
561         /* strtoul() has an odd interface */
562         if ( s[ 0 ] == '-' ) {
563                 return -1;
564         }
565
566         ul = strtoul( s, &next, x );
567         if ( next == s || next[ 0 ] != '\0' ) {
568                 return -1;
569         }
570
571         *v = ul;
572
573         return 0;
574 }
575
576 static  char            time_unit[] = "dhms";
577
578 /* Used to parse and unparse time intervals, not timestamps */
579 int
580 lutil_parse_time(
581         const char      *in,
582         unsigned long   *tp )
583 {
584         unsigned long   t = 0;
585         char            *s,
586                         *next;
587         int             sofar = -1,
588                         scale[] = { 86400, 3600, 60, 1 };
589
590         *tp = 0;
591
592         for ( s = (char *)in; s[ 0 ] != '\0'; ) {
593                 unsigned long   u;
594                 char            *what;
595
596                 /* strtoul() has an odd interface */
597                 if ( s[ 0 ] == '-' ) {
598                         return -1;
599                 }
600
601                 u = strtoul( s, &next, 10 );
602                 if ( next == s ) {
603                         return -1;
604                 }
605
606                 if ( next[ 0 ] == '\0' ) {
607                         /* assume seconds */
608                         t += u;
609                         break;
610                 }
611
612                 what = strchr( time_unit, next[ 0 ] );
613                 if ( what == NULL ) {
614                         return -1;
615                 }
616
617                 if ( what - time_unit <= sofar ) {
618                         return -1;
619                 }
620
621                 sofar = what - time_unit;
622                 t += u * scale[ sofar ];
623
624                 s = &next[ 1 ];
625         }
626
627         *tp = t;
628         return 0;
629 }
630
631 int
632 lutil_unparse_time(
633         char                    *buf,
634         size_t                  buflen,
635         unsigned long           t )
636 {
637         int             len, i;
638         unsigned long   v[ 4 ];
639         char            *ptr = buf;
640
641         v[ 0 ] = t/86400;
642         v[ 1 ] = (t%86400)/3600;
643         v[ 2 ] = (t%3600)/60;
644         v[ 3 ] = t%60;
645
646         for ( i = 0; i < 4; i++ ) {
647                 if ( v[i] > 0 || ( i == 3 && ptr == buf ) ) {
648                         len = snprintf( ptr, buflen, "%lu%c", v[ i ], time_unit[ i ] );
649                         if ( len < 0 || (unsigned)len >= buflen ) {
650                                 return -1;
651                         }
652                         buflen -= len;
653                         ptr += len;
654                 }
655         }
656
657         return 0;
658 }
659