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