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