utils.c 22.8 KB
Newer Older
1
/* $OpenLDAP$ */
Kurt Zeilenga's avatar
Kurt Zeilenga committed
2
3
/* This work is part of OpenLDAP Software <http://www.openldap.org/>.
 *
Quanah Gibson-Mount's avatar
Quanah Gibson-Mount committed
4
 * Copyright 1998-2021 The OpenLDAP Foundation.
Kurt Zeilenga's avatar
Kurt Zeilenga committed
5
6
7
8
9
10
11
12
13
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted only as authorized by the OpenLDAP
 * Public License.
 *
 * A copy of this license is available in the file LICENSE in the
 * top-level directory of the distribution or, alternatively, at
 * <http://www.OpenLDAP.org/license.html>.
14
15
16
17
 */

#include "portable.h"

18
#include <limits.h>
19
#include <stdio.h>
20
#include <ac/stdlib.h>
21
#include <ac/stdarg.h>
22
#include <ac/string.h>
23
#include <ac/ctype.h>
24
#include <ac/unistd.h>
25
#include <ac/time.h>
26
#include <ac/errno.h>
Howard Chu's avatar
Howard Chu committed
27
28
29
#ifdef HAVE_IO_H
#include <io.h>
#endif
30
31
32
#ifdef HAVE_FCNTL_H
#include <fcntl.h>
#endif
33
34
35
#ifdef _WIN32
#include <windows.h>
#endif
36

37
38
39
#include "lutil.h"
#include "ldap_defaults.h"
#include "ldap_pvt.h"
Howard Chu's avatar
Howard Chu committed
40
#include "lber_pvt.h"
41

42
43
44
45
#ifdef HAVE_EBCDIC
int _trans_argv = 1;
#endif

46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#ifdef _WIN32
/* Some Windows versions accept both forward and backslashes in
 * directory paths, but we always use backslashes when generating
 * and parsing...
 */
void lutil_slashpath( char *path )
{
	char *c, *p;

	p = path;
	while (( c=strchr( p, '/' ))) {
		*c++ = '\\';
		p = c;
	}
}
#endif

63
64
65
66
67
char* lutil_progname( const char* name, int argc, char *argv[] )
{
	char *progname;

	if(argc == 0) {
68
		return (char *)name;
69
70
	}

71
72
73
74
75
76
77
#ifdef HAVE_EBCDIC
	if (_trans_argv) {
		int i;
		for (i=0; i<argc; i++) __etoa(argv[i]);
		_trans_argv = 0;
	}
#endif
78
	LUTIL_SLASHPATH( argv[0] );
79
	progname = strrchr ( argv[0], *LDAP_DIRSEP );
80
	progname = progname ? &progname[1] : argv[0];
81
82
83
84
85
86
87
#ifdef _WIN32
	{
		size_t len = strlen( progname );
		if ( len > 4 && strcasecmp( &progname[len - 4], ".exe" ) == 0 )
			progname[len - 4] = '\0';
	}
#endif
88
89
	return progname;
}
Kurt Zeilenga's avatar
Kurt Zeilenga committed
90

91
#if 0
92
size_t lutil_gentime( char *s, size_t smax, const struct tm *tm )
Kurt Zeilenga's avatar
Kurt Zeilenga committed
93
{
94
95
96
97
98
99
	size_t ret;
#ifdef HAVE_EBCDIC
/* We've been compiling in ASCII so far, but we want EBCDIC now since
 * strftime only understands EBCDIC input.
 */
#pragma convlit(suspend)
100
#endif
101
	ret = strftime( s, smax, "%Y%m%d%H%M%SZ", tm );
102
103
104
#ifdef HAVE_EBCDIC
#pragma convlit(resume)
	__etoa( s );
Kurt Zeilenga's avatar
Kurt Zeilenga committed
105
#endif
106
107
	return ret;
}
108
#endif
109

110
111
112
113
114
size_t lutil_localtime( char *s, size_t smax, const struct tm *tm, long delta )
{
	size_t	ret;
	char	*p;

115
116
	if ( smax < 16 ) {	/* YYYYmmddHHMMSSZ */
		return 0;
117
118
119
120
121
122
123
124
125
	}

#ifdef HAVE_EBCDIC
/* We've been compiling in ASCII so far, but we want EBCDIC now since
 * strftime only understands EBCDIC input.
 */
#pragma convlit(suspend)
#endif
	ret = strftime( s, smax, "%Y%m%d%H%M%SZ", tm );
Howard Chu's avatar
Howard Chu committed
126
127
128
129
#ifdef HAVE_EBCDIC
#pragma convlit(resume)
	__etoa( s );
#endif
130
	if ( delta == 0 || ret == 0 ) {
131
132
133
		return ret;
	}

134
135
	if ( smax < 20 ) {	/* YYYYmmddHHMMSS+HHMM */
		return 0;
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
	}

	p = s + 14;

	if ( delta < 0 ) {
		p[ 0 ] = '-';
		delta = -delta;
	} else {
		p[ 0 ] = '+';
	}
	p++;

	snprintf( p, smax - 15, "%02ld%02ld", delta / 3600,
			( delta % 3600 ) / 60 );

151
	return ret + 4;
152
153
}

154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
int lutil_tm2time( struct lutil_tm *tm, struct lutil_timet *tt )
{
	static int moffset[12] = {
		0, 31, 59, 90, 120,
		151, 181, 212, 243,
		273, 304, 334 };
	int sec;

	tt->tt_usec = tm->tm_usec;

	/* special case 0000/01/01+00:00:00 is returned as zero */
	if ( tm->tm_year == -1900 && tm->tm_mon == 0 && tm->tm_mday == 1 &&
		tm->tm_hour == 0 && tm->tm_min == 0 && tm->tm_sec == 0 ) {
		tt->tt_sec = 0;
		tt->tt_gsec = 0;
		return 0;
	}

	/* tm->tm_year is years since 1900 */
	/* calculate days from years since 1970 (epoch) */
	tt->tt_sec = tm->tm_year - 70;
	tt->tt_sec *= 365L;

	/* count leap days in preceding years */
	tt->tt_sec += ((tm->tm_year -69) >> 2);

	/* calculate days from months */
	tt->tt_sec += moffset[tm->tm_mon];

	/* add in this year's leap day, if any */
	if (((tm->tm_year & 3) == 0) && (tm->tm_mon > 1)) {
		tt->tt_sec ++;
	}

	/* add in days in this month */
	tt->tt_sec += (tm->tm_mday - 1);

	/* this function can handle a range of about 17408 years... */
	/* 86400 seconds in a day, divided by 128 = 675 */
	tt->tt_sec *= 675;

	/* move high 7 bits into tt_gsec */
	tt->tt_gsec = tt->tt_sec >> 25;
	tt->tt_sec -= tt->tt_gsec << 25;

	/* get hours */
	sec = tm->tm_hour;

	/* convert to minutes */
	sec *= 60L;
	sec += tm->tm_min;

	/* convert to seconds */
	sec *= 60L;
	sec += tm->tm_sec;

	/* add remaining seconds */
	tt->tt_sec <<= 7;
	tt->tt_sec += sec;

	/* return success */
	return 0;
}

218
219
/* Proleptic Gregorian Calendar, 1BCE = year 0 */

220
int lutil_tm2gtime( struct lutil_tm *tm, struct lutil_timet *tt )
221
222
223
224
{
	static int moffset[12] = {
		0, 31, 59, 90, 120,
		151, 181, 212, 243,
225
		273, 304, 334 };
226
227
	int sec, year;
	long tmp;
228
229
230
231

	tt->tt_usec = tm->tm_usec;

	/* tm->tm_year is years since 1900 */
232
233
234
235
236
237
238
239
240
241
242
243
244
245
	/* calculate days from 0000 */
	year = tm->tm_year + 1900;
	tmp = year * 365;

	/* add in leap days */
	sec = (year - 1) / 4;
	tmp += sec;
	sec /= 25;
	tmp -= sec;
	sec /= 4;
	tmp += sec;
	/* Year 0000 was a leap year */
	if (year > 0)
		tmp++;
246

247
	/* calculate days from months */
248
	tmp += moffset[tm->tm_mon];
249

250
251
252
253
254
	/* add in this year's leap day, if any */
	if (tm->tm_mon > 1) {
		sec = (year % 4) ? 0 : (year % 100) ? 1 : (year % 400) ? 0 : 1;
		tmp += sec;
	}
255

256
257
	/* add in days in this month */
	tmp += (tm->tm_mday - 1);
258

259
	/* this function can handle a range of about 17408 years... */
260
	/* 86400 seconds in a day, divided by 128 = 675 */
261
	tmp *= 675;
262
263

	/* move high 7 bits into tt_gsec */
264
265
266
267
268
269
	tt->tt_gsec = tmp >> 25;
	tmp -= tt->tt_gsec << 25;

	/* toggle sign bit, keep positive greater than negative */
	tt->tt_gsec &= 0x7f;
	tt->tt_gsec ^= 0x40;
270

271
272
	/* get hours */
	sec = tm->tm_hour;
273

274
275
276
	/* convert to minutes */
	sec *= 60L;
	sec += tm->tm_min;
277

278
279
280
	/* convert to seconds */
	sec *= 60L;
	sec += tm->tm_sec;
281
	
282
	/* add remaining seconds */
283
284
285
	tmp <<= 7;
	tmp += sec;
	tt->tt_sec = tmp;
286
287

	/* return success */
288
	return 0;
289
290
}

Howard Chu's avatar
Howard Chu committed
291
int lutil_parsetime( char *atm, struct lutil_tm *tm )
292
293
{
	while (atm && tm) {
294
		char *ptr;
Pierangelo Masarati's avatar
Pierangelo Masarati committed
295
		unsigned i, fracs;
296
297
298
299
300
301
302
		int neg = 0;

		if (*atm == '-') {
			neg = 1;
			atm++;
		}
		ptr = atm;
303
304

		/* Is the stamp reasonably long? */
305
		for (i=0; isdigit((unsigned char) atm[i]); i++);
306
307
308
309
310
311
312
313
314
315
316
		if (i < sizeof("00000101000000")-1)
			break;

		/*
		 * parse the time into a struct tm
		 */
		/* 4 digit year to year - 1900 */
		tm->tm_year = *ptr++ - '0';
		tm->tm_year *= 10; tm->tm_year += *ptr++ - '0';
		tm->tm_year *= 10; tm->tm_year += *ptr++ - '0';
		tm->tm_year *= 10; tm->tm_year += *ptr++ - '0';
317
318
		if (neg)
			tm->tm_year = -tm->tm_year;
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
		tm->tm_year -= 1900;
		/* month 01-12 to 0-11 */
		tm->tm_mon = *ptr++ - '0';
		tm->tm_mon *=10; tm->tm_mon += *ptr++ - '0';
		if (tm->tm_mon < 1 || tm->tm_mon > 12) break;
		tm->tm_mon--;

		/* day of month 01-31 */
		tm->tm_mday = *ptr++ - '0';
		tm->tm_mday *=10; tm->tm_mday += *ptr++ - '0';
		if (tm->tm_mday < 1 || tm->tm_mday > 31) break;

		/* Hour 00-23 */
		tm->tm_hour = *ptr++ - '0';
		tm->tm_hour *=10; tm->tm_hour += *ptr++ - '0';
		if (tm->tm_hour < 0 || tm->tm_hour > 23) break;

		/* Minute 00-59 */
		tm->tm_min = *ptr++ - '0';
		tm->tm_min *=10; tm->tm_min += *ptr++ - '0';
		if (tm->tm_min < 0 || tm->tm_min > 59) break;

		/* Second 00-61 */
		tm->tm_sec = *ptr++ - '0';
		tm->tm_sec *=10; tm->tm_sec += *ptr++ - '0';
		if (tm->tm_sec < 0 || tm->tm_sec > 61) break;

		/* Fractions of seconds */
347
348
349
350
351
352
353
354
355
356
357
		if ( *ptr == '.' ) {
			ptr++;
			for (i = 0, fracs = 0; isdigit((unsigned char) *ptr); ) {
				i*=10; i+= *ptr++ - '0';
				fracs++;
			}
			tm->tm_usec = i;
			if (i) {
				for (i = fracs; i<6; i++)
					tm->tm_usec *= 10;
			}
358
359
		} else {
			tm->tm_usec = 0;
360
		}
361
		tm->tm_usub = 0;
362
363
364
365
366
367
368
369

		/* Must be UTC */
		if (*ptr != 'Z') break;

		return 0;
	}
	return -1;
}
370

371
372
373
/* strcopy is like strcpy except it returns a pointer to the trailing NUL of
 * the result string. This allows fast construction of catenated strings
 * without the overhead of strlen/strcat.
374
 */
375
376
377
378
379
char *
lutil_strcopy(
	char *a,
	const char *b
)
380
{
381
382
383
384
385
	if (!a || !b)
		return a;
	
	while ((*a++ = *b++)) ;
	return a-1;
386
387
}

388
389
390
391
392
393
394
395
396
397
/* strncopy is like strcpy except it returns a pointer to the trailing NUL of
 * the result string. This allows fast construction of catenated strings
 * without the overhead of strlen/strcat.
 */
char *
lutil_strncopy(
	char *a,
	const char *b,
	size_t n
)
398
{
399
400
401
402
403
404
	if (!a || !b || n == 0)
		return a;
	
	while ((*a++ = *b++) && n-- > 0) ;
	return a-1;
}
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419

/* memcopy is like memcpy except it returns a pointer to the byte past
 * the end of the result buffer, set to NULL. This allows fast construction
 * of catenated buffers.  Provided for API consistency with lutil_str*copy().
 */
char *
lutil_memcopy(
	char *a,
	const char *b,
	size_t n
)
{
	AC_MEMCPY(a, b, n);
	return a + n;
}
420

421
422
423
424
425
426
427
428
#ifndef HAVE_MKSTEMP
int mkstemp( char * template )
{
#ifdef HAVE_MKTEMP
	return open ( mktemp ( template ), O_RDWR|O_CREAT|O_EXCL, 0600 );
#else
	return -1;
#endif
429
}
430
#endif
431

Howard Chu's avatar
Howard Chu committed
432
#ifdef _MSC_VER
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
/* Equivalent of MS CRT's _dosmaperr().
 * @param lastError[in] Result of GetLastError().
 */
static errno_t win2errno(DWORD lastError)
{
	const struct { 
		DWORD   windows_code;
		errno_t errno_code;
	} WIN2ERRNO_TABLE[] = {
		{ ERROR_SUCCESS, 0 },
		{ ERROR_FILE_NOT_FOUND, ENOENT },
		{ ERROR_PATH_NOT_FOUND, ENOENT },
		{ ERROR_TOO_MANY_OPEN_FILES, EMFILE },
		{ ERROR_ACCESS_DENIED, EACCES },
		{ ERROR_INVALID_HANDLE, EBADF },
		{ ERROR_NOT_ENOUGH_MEMORY, ENOMEM },
		{ ERROR_LOCK_VIOLATION, EACCES },
		{ ERROR_FILE_EXISTS, EEXIST },
		{ ERROR_INVALID_PARAMETER, EINVAL },
		{ ERROR_FILENAME_EXCED_RANGE, ENAMETOOLONG },
	};
	const unsigned int WIN2ERRNO_TABLE_SIZE = sizeof(WIN2ERRNO_TABLE) /
sizeof(WIN2ERRNO_TABLE[0]);
	const errno_t DEFAULT_ERRNO_ERROR = -1;
	unsigned int i;

	for (i = 0; i < WIN2ERRNO_TABLE_SIZE; ++i) {
		if (WIN2ERRNO_TABLE[i].windows_code == lastError) {
			return WIN2ERRNO_TABLE[i].errno_code;
		}
	}
	return DEFAULT_ERRNO_ERROR;
}

Howard Chu's avatar
Howard Chu committed
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
struct dirent {
	char *d_name;
};
typedef struct DIR {
	HANDLE dir;
	struct dirent data;
	int first;
	char buf[MAX_PATH+1];
} DIR;
DIR *opendir( char *path )
{
	char tmp[32768];
	int len = strlen(path);
	DIR *d;
	HANDLE h;
	WIN32_FIND_DATA data;
	
484
485
	if (len+3 >= sizeof(tmp)) {
		errno = ENAMETOOLONG;
Howard Chu's avatar
Howard Chu committed
486
		return NULL;
487
	}
Howard Chu's avatar
Howard Chu committed
488
489
490
491
492
493
494

	strcpy(tmp, path);
	tmp[len++] = '\\';
	tmp[len++] = '*';
	tmp[len] = '\0';

	h = FindFirstFile( tmp, &data );
495
496
497

	if ( h == INVALID_HANDLE_VALUE ) {
		errno = win2errno( GetLastError());
Howard Chu's avatar
Howard Chu committed
498
		return NULL;
499
	}
Howard Chu's avatar
Howard Chu committed
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522

	d = ber_memalloc( sizeof(DIR) );
	if ( !d )
		return NULL;
	d->dir = h;
	d->data.d_name = d->buf;
	d->first = 1;
	strcpy(d->data.d_name, data.cFileName);
	return d;
}
struct dirent *readdir(DIR *dir)
{
	WIN32_FIND_DATA data;

	if (dir->first) {
		dir->first = 0;
	} else {
		if (!FindNextFile(dir->dir, &data))
			return NULL;
		strcpy(dir->data.d_name, data.cFileName);
	}
	return &dir->data;
}
523
int closedir(DIR *dir)
Howard Chu's avatar
Howard Chu committed
524
{
525
	(void) FindClose(dir->dir);
Howard Chu's avatar
Howard Chu committed
526
	ber_memfree(dir);
527
	return 0;
Howard Chu's avatar
Howard Chu committed
528
529
530
}
#endif

Hallvard Furuseth's avatar
Hallvard Furuseth committed
531
/*
532
533
534
 * Memory Reverse Search
 */
void *
535
(lutil_memrchr)(const void *b, int c, size_t n)
536
537
{
	if (n != 0) {
Hallvard Furuseth's avatar
Hallvard Furuseth committed
538
		const unsigned char *s, *bb = b, cc = c;
539

Hallvard Furuseth's avatar
Hallvard Furuseth committed
540
541
542
		for ( s = bb + n; s > bb; ) {
			if ( *--s == cc ) {
				return (void *) s;
543
544
545
546
547
			}
		}
	}

	return NULL;
Hallvard Furuseth's avatar
Hallvard Furuseth committed
548
}
549
550

int
551
lutil_atoix( int *v, const char *s, int x )
552
553
554
555
556
557
558
{
	char		*next;
	long		i;

	assert( s != NULL );
	assert( v != NULL );

559
	i = strtol( s, &next, x );
560
561
562
563
564
565
566
567
568
569
570
571
572
573
	if ( next == s || next[ 0 ] != '\0' ) {
		return -1;
	}

	if ( (long)(int)i != i ) {
		return 1;
	}

	*v = (int)i;

	return 0;
}

int
574
lutil_atoux( unsigned *v, const char *s, int x )
575
576
577
578
579
580
581
{
	char		*next;
	unsigned long	u;

	assert( s != NULL );
	assert( v != NULL );

582
583
584
585
586
	/* strtoul() has an odd interface */
	if ( s[ 0 ] == '-' ) {
		return -1;
	}

587
	u = strtoul( s, &next, x );
588
589
590
591
592
593
594
595
596
597
598
599
600
601
	if ( next == s || next[ 0 ] != '\0' ) {
		return -1;
	}

	if ( (unsigned long)(unsigned)u != u ) {
		return 1;
	}

	*v = u;

	return 0;
}

int
602
lutil_atolx( long *v, const char *s, int x )
603
{
604
605
606
	char *next;
	long l;
	int save_errno;
607
608
609
610

	assert( s != NULL );
	assert( v != NULL );

611
612
613
614
615
	if ( isspace( s[ 0 ] ) ) {
		return -1;
	}

	errno = 0;
616
	l = strtol( s, &next, x );
617
	save_errno = errno;
618
619
620
621
	if ( next == s || next[ 0 ] != '\0' ) {
		return -1;
	}

622
623
624
625
	if ( ( l == LONG_MIN || l == LONG_MAX ) && save_errno != 0 ) {
		return -1;
	}

626
627
628
629
630
631
	*v = l;

	return 0;
}

int
632
lutil_atoulx( unsigned long *v, const char *s, int x )
633
{
634
635
636
	char *next;
	unsigned long ul;
	int save_errno;
637
638
639
640

	assert( s != NULL );
	assert( v != NULL );

641
	/* strtoul() has an odd interface */
642
	if ( s[ 0 ] == '-' || isspace( s[ 0 ] ) ) {
643
644
645
		return -1;
	}

646
	errno = 0;
647
	ul = strtoul( s, &next, x );
648
	save_errno = errno;
649
650
651
652
	if ( next == s || next[ 0 ] != '\0' ) {
		return -1;
	}

653
654
655
656
	if ( ( ul == 0 || ul == ULONG_MAX ) && save_errno != 0 ) {
		return -1;
	}

657
658
659
660
661
	*v = ul;

	return 0;
}

662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
#ifdef HAVE_LONG_LONG
#if defined(HAVE_STRTOLL) || defined(HAVE_STRTOQ)
int
lutil_atollx( long long *v, const char *s, int x )
{
	char *next;
	long long ll;
	int save_errno;

	assert( s != NULL );
	assert( v != NULL );

	if ( isspace( s[ 0 ] ) ) {
		return -1;
	}

	errno = 0;
#ifdef HAVE_STRTOLL
	ll = strtoll( s, &next, x );
#else /* HAVE_STRTOQ */
	ll = (unsigned long long)strtoq( s, &next, x );
#endif /* HAVE_STRTOQ */
	save_errno = errno;
	if ( next == s || next[ 0 ] != '\0' ) {
		return -1;
	}

	/* LLONG_MIN, LLONG_MAX are C99 only */
#if defined (LLONG_MIN) && defined(LLONG_MAX)
	if ( ( ll == LLONG_MIN || ll == LLONG_MAX ) && save_errno != 0 ) {
		return -1;
	}
#endif /* LLONG_MIN && LLONG_MAX */

	*v = ll;

	return 0;
}
#endif /* HAVE_STRTOLL || HAVE_STRTOQ */

#if defined(HAVE_STRTOULL) || defined(HAVE_STRTOUQ)
int
lutil_atoullx( unsigned long long *v, const char *s, int x )
{
	char *next;
	unsigned long long ull;
	int save_errno;

	assert( s != NULL );
	assert( v != NULL );

	/* strtoull() has an odd interface */
	if ( s[ 0 ] == '-' || isspace( s[ 0 ] ) ) {
		return -1;
	}

	errno = 0;
#ifdef HAVE_STRTOULL
	ull = strtoull( s, &next, x );
#else /* HAVE_STRTOUQ */
	ull = (unsigned long long)strtouq( s, &next, x );
#endif /* HAVE_STRTOUQ */
	save_errno = errno;
	if ( next == s || next[ 0 ] != '\0' ) {
		return -1;
	}

	/* ULLONG_MAX is C99 only */
#if defined(ULLONG_MAX)
	if ( ( ull == 0 || ull == ULLONG_MAX ) && save_errno != 0 ) {
		return -1;
	}
#endif /* ULLONG_MAX */

	*v = ull;

	return 0;
}
#endif /* HAVE_STRTOULL || HAVE_STRTOUQ */
#endif /* HAVE_LONG_LONG */

743
/* Multiply an integer by 100000000 and add new */
Pierangelo Masarati's avatar
Pierangelo Masarati committed
744
typedef struct lutil_int_decnum {
745
746
747
748
	unsigned char *buf;
	int bufsiz;
	int beg;
	int len;
Pierangelo Masarati's avatar
Pierangelo Masarati committed
749
} lutil_int_decnum;
750
751
752
753
754

#define	FACTOR1	(100000000&0xffff)
#define FACTOR2 (100000000>>16)

static void
Pierangelo Masarati's avatar
Pierangelo Masarati committed
755
scale( int new, lutil_int_decnum *prev, unsigned char *tmp )
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
{
	int i, j;
	unsigned char *in = prev->buf+prev->beg;
	unsigned int part;
	unsigned char *out = tmp + prev->bufsiz - prev->len;

	memset( tmp, 0, prev->bufsiz );
	if ( prev->len ) {
		for ( i = prev->len-1; i>=0; i-- ) {
			part = in[i] * FACTOR1;
			for ( j = i; part; j-- ) {
				part += out[j];
				out[j] = part & 0xff;
				part >>= 8;
			}
			part = in[i] * FACTOR2;
			for ( j = i-2; part; j-- ) {
				part += out[j];
				out[j] = part & 0xff;
				part >>= 8;
			}
		}
Howard Chu's avatar
Howard Chu committed
778
779
780
		j++;
		prev->beg += j;
		prev->len -= j;
781
782
	}

Howard Chu's avatar
Howard Chu committed
783
	out = tmp + prev->bufsiz;
784
785
786
	i = 0;
	do {
		i--;
787
788
789
		new += out[i];
		out[i] = new & 0xff;
		new >>= 8;
790
	} while ( new );
Howard Chu's avatar
Howard Chu committed
791
792
793
794
795
	i = -i;
	if ( prev->len < i ) {
		prev->beg = prev->bufsiz - i;
		prev->len = i;
	}
796
797
798
799
800
801
	AC_MEMCPY( prev->buf+prev->beg, tmp+prev->beg, prev->len );
}

/* Convert unlimited length decimal or hex string to binary.
 * Output buffer must be provided, bv_len must indicate buffer size
 * Hex input can be "0x1234" or "'1234'H"
802
803
804
805
806
 *
 * Note: High bit of binary form is always the sign bit. If the number
 * is supposed to be positive but has the high bit set, a zero byte
 * is prepended. It is assumed that this has already been handled on
 * any hex input.
807
808
 */
int
Howard Chu's avatar
Howard Chu committed
809
lutil_str2bin( struct berval *in, struct berval *out, void *ctx )
810
{
811
	char *pin, *pout;
812
813
814
815
816
817
818
819
	char *end;
	int i, chunk, len, rc = 0, hex = 0;
	if ( !out || !out->bv_val || out->bv_len < in->bv_len )
		return -1;

	pout = out->bv_val;
	/* Leading "0x" for hex input */
	if ( in->bv_len > 2 && in->bv_val[0] == '0' &&
Pierangelo Masarati's avatar
Pierangelo Masarati committed
820
821
		( in->bv_val[1] == 'x' || in->bv_val[1] == 'X' ) )
	{
822
823
824
825
		len = in->bv_len - 2;
		pin = in->bv_val + 2;
		hex = 1;
	} else if ( in->bv_len > 3 && in->bv_val[0] == '\'' &&
Pierangelo Masarati's avatar
Pierangelo Masarati committed
826
827
828
		in->bv_val[in->bv_len-2] == '\'' &&
		in->bv_val[in->bv_len-1] == 'H' )
	{
829
830
831
832
833
834
		len = in->bv_len - 3;
		pin = in->bv_val + 1;
		hex = 1;
	}
	if ( hex ) {
#define HEXMAX	(2 * sizeof(long))
835
		unsigned long l;
836
837
		char tbuf[HEXMAX+1];

838
839
840
		/* Convert a longword at a time, but handle leading
		 * odd bytes first
		 */
841
		chunk = len % HEXMAX;
842
843
844
845
		if ( !chunk )
			chunk = HEXMAX;

		while ( len ) {
846
			int ochunk;
847
848
			memcpy( tbuf, pin, chunk );
			tbuf[chunk] = '\0';
849
			errno = 0;
850
			l = strtoul( tbuf, &end, 16 );
851
852
			if ( errno )
				return -1;
853
854
			ochunk = (chunk + 1)/2;
			for ( i = ochunk - 1; i >= 0; i-- ) {
855
856
857
858
				pout[i] = l & 0xff;
				l >>= 8;
			}
			pin += chunk;
859
			pout += ochunk;
860
861
862
			len -= chunk;
			chunk = HEXMAX;
		}
863
		out->bv_len = pout - out->bv_val;
864
865
	} else {
	/* Decimal */
866
#define	DECMAX	8	/* 8 digits at a time */
867
		char tmpbuf[64], *tmp;
Pierangelo Masarati's avatar
Pierangelo Masarati committed
868
		lutil_int_decnum num;
869
		int neg = 0;
870
		long l;
871
		char tbuf[DECMAX+1];
872
873
874

		len = in->bv_len;
		pin = in->bv_val;
Pierangelo Masarati's avatar
Pierangelo Masarati committed
875
		num.buf = (unsigned char *)out->bv_val;
876
877
878
		num.bufsiz = out->bv_len;
		num.beg = num.bufsiz-1;
		num.len = 0;
879
		if ( pin[0] == '-' ) {
Howard Chu's avatar
Howard Chu committed
880
			neg = 0xff;
881
882
883
			len--;
			pin++;
		}
884

Howard Chu's avatar
Howard Chu committed
885
886
		/* tmp must be at least as large as outbuf */
		if ( out->bv_len > sizeof(tmpbuf)) {
Howard Chu's avatar
Howard Chu committed
887
			tmp = ber_memalloc_x( out->bv_len, ctx );
888
889
890
891
892
893
894
895
		} else {
			tmp = tmpbuf;
		}
		chunk = len & (DECMAX-1);
		if ( !chunk )
			chunk = DECMAX;

		while ( len ) {
896
897
			memcpy( tbuf, pin, chunk );
			tbuf[chunk] = '\0';
898
			errno = 0;
899
			l = strtol( tbuf, &end, 10 );
900
901
902
903
			if ( errno ) {
				rc = -1;
				goto decfail;
			}
Pierangelo Masarati's avatar
Pierangelo Masarati committed
904
			scale( l, &num, (unsigned char *)tmp );
905
906
			pin += chunk;
			len -= chunk;
Howard Chu's avatar
Howard Chu committed
907
			chunk = DECMAX;
908
		}
909
910
911
912
913
914
915
916
917
918
		/* Negate the result */
		if ( neg ) {
			unsigned char *ptr;

			ptr = num.buf+num.beg;

			/* flip all bits */
			for ( i=0; i<num.len; i++ )
				ptr[i] ^= 0xff;

Howard Chu's avatar
Howard Chu committed
919
920
921
922
923
			/* add 1, with carry - overflow handled below */
			while ( i-- && ! (ptr[i] = (ptr[i] + 1) & 0xff )) ;
		}
		/* Prepend sign byte if wrong sign bit */
		if (( num.buf[num.beg] ^ neg ) & 0x80 ) {
924
925
			num.beg--;
			num.len++;
Howard Chu's avatar
Howard Chu committed
926
			num.buf[num.beg] = neg;
927
		}
928
929
930
931
932
		if ( num.beg )
			AC_MEMCPY( num.buf, num.buf+num.beg, num.len );
		out->bv_len = num.len;
decfail:
		if ( tmp != tmpbuf ) {
Howard Chu's avatar
Howard Chu committed
933
			ber_memfree_x( tmp, ctx );
934
935
936
937
938
		}
	}
	return rc;
}

939
940
static	char		time_unit[] = "dhms";

941
/* Used to parse and unparse time intervals, not timestamps */
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
int
lutil_parse_time(
	const char	*in,
	unsigned long	*tp )
{
	unsigned long	t = 0;
	char		*s,
			*next;
	int		sofar = -1,
			scale[] = { 86400, 3600, 60, 1 };

	*tp = 0;

	for ( s = (char *)in; s[ 0 ] != '\0'; ) {
		unsigned long	u;
		char		*what;

959
960
961
962
963
		/* strtoul() has an odd interface */
		if ( s[ 0 ] == '-' ) {
			return -1;
		}

964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
		u = strtoul( s, &next, 10 );
		if ( next == s ) {
			return -1;
		}

		if ( next[ 0 ] == '\0' ) {
			/* assume seconds */
			t += u;
			break;
		}

		what = strchr( time_unit, next[ 0 ] );
		if ( what == NULL ) {
			return -1;
		}

		if ( what - time_unit <= sofar ) {
			return -1;
		}

		sofar = what - time_unit;
		t += u * scale[ sofar ];

		s = &next[ 1 ];
	}

	*tp = t;
	return 0;
}

int
lutil_unparse_time(
	char			*buf,
	size_t			buflen,
	unsigned long		t )
{
	int		len, i;
	unsigned long	v[ 4 ];
1002
	char		*ptr = buf;
1003
1004
1005
1006
1007
1008
1009

	v[ 0 ] = t/86400;
	v[ 1 ] = (t%86400)/3600;
	v[ 2 ] = (t%3600)/60;
	v[ 3 ] = t%60;

	for ( i = 0; i < 4; i++ ) {
1010
1011
		if ( v[i] > 0 || ( i == 3 && ptr == buf ) ) {
			len = snprintf( ptr, buflen, "%lu%c", v[ i ], time_unit[ i ] );
1012
1013
1014
1015
			if ( len < 0 || (unsigned)len >= buflen ) {
				return -1;
			}
			buflen -= len;
1016
			ptr += len;
1017
1018
1019
1020
1021
1022
		}
	}

	return 0;
}

1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
/*
 * formatted print to string
 *
 * - if return code < 0, the error code returned by vsnprintf(3) is returned
 *
 * - if return code > 0, the buffer was not long enough;
 *	- if next is not NULL, *next will be set to buf + bufsize - 1
 *	- if len is not NULL, *len will contain the required buffer length
 *
 * - if return code == 0, the buffer was long enough;
 *	- if next is not NULL, *next will point to the end of the string printed so far
 *	- if len is not NULL, *len will contain the length of the string printed so far 
 */
int
lutil_snprintf( char *buf, ber_len_t bufsize, char **next, ber_len_t *len, LDAP_CONST char *fmt, ... )
{
	va_list		ap;
	int		ret;

	assert( buf != NULL );
	assert( bufsize > 0 );
	assert( fmt != NULL );

	va_start( ap, fmt );
	ret = vsnprintf( buf, bufsize, fmt, ap );
	va_end( ap );

	if ( ret < 0 ) {
		return ret;
	}

	if ( len ) {
		*len = ret;
	}

1058
	if ( (unsigned) ret >= bufsize ) {
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
		if ( next ) {
			*next = &buf[ bufsize - 1 ];
		}

		return 1;
	}

	if ( next ) {
		*next = &buf[ ret ];
	}

	return 0;
}

1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
void
lutil_sockaddrstr( Sockaddr *sa, struct berval *addrbuf )
{
	char *addr;
	switch( sa->sa_addr.sa_family ) {
#ifdef LDAP_PF_LOCAL
	case AF_LOCAL:
		addrbuf->bv_len = snprintf( addrbuf->bv_val, addrbuf->bv_len,
			"PATH=%s", sa->sa_un_addr.sun_path );
		break;
#endif
#ifdef LDAP_PF_INET6
	case AF_INET6:
		strcpy(addrbuf->bv_val, "IP=");
		if ( IN6_IS_ADDR_V4MAPPED(&sa->sa_in6_addr.sin6_addr) ) {
#if defined( HAVE_GETADDRINFO ) && defined( HAVE_INET_NTOP )
			addr = (char *)inet_ntop( AF_INET,
			   ((struct in_addr *)&sa->sa_in6_addr.sin6_addr.s6_addr[12]),
			   addrbuf->bv_val+3, addrbuf->bv_len-3 );
#else /* ! HAVE_GETADDRINFO || ! HAVE_INET_NTOP */
			addr = inet_ntoa( *((struct in_addr *)
					&sa->sa_in6_addr.sin6_addr.s6_addr[12]) );
#endif /* ! HAVE_GETADDRINFO || ! HAVE_INET_NTOP */
			if ( !addr ) addr = LUTIL_STRING_UNKNOWN;
			if ( addr != addrbuf->bv_val+3 ) {
				addrbuf->bv_len = sprintf( addrbuf->bv_val+3, "%s:%d", addr,
				 (unsigned) ntohs( sa->sa_in6_addr.sin6_port ) ) + 3;
			} else {
				int len = strlen( addr );
				addrbuf->bv_len = sprintf( addr+len, ":%d",
				 (unsigned) ntohs( sa->sa_in6_addr.sin6_port ) ) + len + 3;
			}
		} else {
			addr = (char *)inet_ntop( AF_INET6,
				      &sa->sa_in6_addr.sin6_addr,
				      addrbuf->bv_val+4, addrbuf->bv_len-4 );
			if ( !addr ) addr = LUTIL_STRING_UNKNOWN;
			if ( addr != addrbuf->bv_val+4 ) {
				addrbuf->bv_len = sprintf( addrbuf->bv_val+3, "[%s]:%d", addr,
				 (unsigned) ntohs( sa->sa_in6_addr.sin6_port ) ) + 3;
			} else {
				int len = strlen( addr );
				addrbuf->bv_val[3] = '[';
				addrbuf->bv_len = sprintf( addr+len, "]:%d",
				 (unsigned) ntohs( sa->sa_in6_addr.sin6_port ) ) + len + 4;
			}
		}
		break;
#endif /* LDAP_PF_INET6 */
	case AF_INET:
		strcpy(addrbuf->bv_val, "IP=");
#if defined( HAVE_GETADDRINFO ) && defined( HAVE_INET_NTOP )
		addr = (char *)inet_ntop( AF_INET, &sa->sa_in_addr.sin_addr,
			   addrbuf->bv_val+3, addrbuf->bv_len-3 );
#else /* ! HAVE_GETADDRINFO || ! HAVE_INET_NTOP */
		addr = inet_ntoa( sa->sa_in_addr.sin_addr );
#endif /* ! HAVE_GETADDRINFO || ! HAVE_INET_NTOP */
		if ( !addr ) addr = LUTIL_STRING_UNKNOWN;
		if ( addr != addrbuf->bv_val+3 ) {
			addrbuf->bv_len = sprintf( addrbuf->bv_val+3, "%s:%d", addr,
			 (unsigned) ntohs( sa->sa_in_addr.sin_port ) ) + 3;
		} else {
			int len = strlen( addr );
			addrbuf->bv_len = sprintf( addr+len, ":%d",
			 (unsigned) ntohs( sa->sa_in_addr.sin_port ) ) + len + 3;
		}
		break;
	default:
		addrbuf->bv_val[0] = '\0';
	}
}