1 /* $OpenLDAP$ */
2 /* This work is part of OpenLDAP Software <http://www.openldap.org/>.
3  *
4  * Copyright 1998-2021 The OpenLDAP Foundation.
5  * Portions Copyright 1998 A. Hartgers.
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted only as authorized by the OpenLDAP
10  * Public License.
11  *
12  * A copy of this license is available in the file LICENSE in the
13  * top-level directory of the distribution or, alternatively, at
14  * <http://www.OpenLDAP.org/license.html>.
15  */
16 /* ACKNOWLEDGEMENTS:
17  * This work was initially developed by Bart Hartgers for inclusion in
18  * OpenLDAP Software.
19  */
20 
21 /*
22  * util-int.c	Various functions to replace missing threadsafe ones.
23  *				Without the real *_r funcs, things will
24  *				work, but might not be threadsafe.
25  */
26 
27 #include "portable.h"
28 
29 #include <ac/stdlib.h>
30 
31 #include <ac/errno.h>
32 #include <ac/socket.h>
33 #include <ac/string.h>
34 #include <ac/time.h>
35 #include <ac/unistd.h>
36 
37 #include "ldap-int.h"
38 
39 #ifndef h_errno
40 /* newer systems declare this in <netdb.h> for you, older ones don't.
41  * harmless to declare it again (unless defined by a macro).
42  */
43 extern int h_errno;
44 #endif
45 
46 #ifdef HAVE_HSTRERROR
47 # define HSTRERROR(e)	hstrerror(e)
48 #else
49 # define HSTRERROR(e)	hp_strerror(e)
50 #endif
51 
52 #ifndef LDAP_R_COMPILE
53 # undef HAVE_REENTRANT_FUNCTIONS
54 # undef HAVE_CTIME_R
55 # undef HAVE_GETHOSTBYNAME_R
56 # undef HAVE_GETHOSTBYADDR_R
57 
58 #else
59 # include <ldap_pvt_thread.h>
60   ldap_pvt_thread_mutex_t ldap_int_resolv_mutex;
61   ldap_pvt_thread_mutex_t ldap_int_hostname_mutex;
62   static ldap_pvt_thread_mutex_t ldap_int_gettime_mutex;
63 
64 # if (defined( HAVE_CTIME_R ) || defined( HAVE_REENTRANT_FUNCTIONS)) \
65 	 && defined( CTIME_R_NARGS )
66 #   define USE_CTIME_R
67 # else
68 	static ldap_pvt_thread_mutex_t ldap_int_ctime_mutex;
69 # endif
70 
71 /* USE_GMTIME_R and USE_LOCALTIME_R defined in ldap_pvt.h */
72 
73 #if !defined( USE_GMTIME_R ) || !defined( USE_LOCALTIME_R )
74 	/* we use the same mutex for gmtime(3) and localtime(3)
75 	 * because implementations may use the same buffer
76 	 * for both functions */
77 	static ldap_pvt_thread_mutex_t ldap_int_gmtime_mutex;
78 #endif
79 
80 # if defined(HAVE_GETHOSTBYNAME_R) && \
81 	(GETHOSTBYNAME_R_NARGS < 5) || (6 < GETHOSTBYNAME_R_NARGS)
82 	/* Don't know how to handle this version, pretend it's not there */
83 #	undef HAVE_GETHOSTBYNAME_R
84 # endif
85 # if defined(HAVE_GETHOSTBYADDR_R) && \
86 	(GETHOSTBYADDR_R_NARGS < 7) || (8 < GETHOSTBYADDR_R_NARGS)
87 	/* Don't know how to handle this version, pretend it's not there */
88 #	undef HAVE_GETHOSTBYADDR_R
89 # endif
90 #endif /* LDAP_R_COMPILE */
91 
ldap_pvt_ctime(const time_t * tp,char * buf)92 char *ldap_pvt_ctime( const time_t *tp, char *buf )
93 {
94 #ifdef USE_CTIME_R
95 # if (CTIME_R_NARGS > 3) || (CTIME_R_NARGS < 2)
96 #	error "CTIME_R_NARGS should be 2 or 3"
97 # elif CTIME_R_NARGS > 2 && defined(CTIME_R_RETURNS_INT)
98 	return( ctime_r(tp,buf,26) < 0 ? 0 : buf );
99 # elif CTIME_R_NARGS > 2
100 	return ctime_r(tp,buf,26);
101 # else
102 	return ctime_r(tp,buf);
103 # endif
104 
105 #else
106 
107 	LDAP_MUTEX_LOCK( &ldap_int_ctime_mutex );
108 	AC_MEMCPY( buf, ctime(tp), 26 );
109 	LDAP_MUTEX_UNLOCK( &ldap_int_ctime_mutex );
110 
111 	return buf;
112 #endif
113 }
114 
115 #if !defined( USE_GMTIME_R ) || !defined( USE_LOCALTIME_R )
116 int
ldap_pvt_gmtime_lock(void)117 ldap_pvt_gmtime_lock( void )
118 {
119 # ifndef LDAP_R_COMPILE
120 	return 0;
121 # else /* LDAP_R_COMPILE */
122 	return ldap_pvt_thread_mutex_lock( &ldap_int_gmtime_mutex );
123 # endif /* LDAP_R_COMPILE */
124 }
125 
126 int
ldap_pvt_gmtime_unlock(void)127 ldap_pvt_gmtime_unlock( void )
128 {
129 # ifndef LDAP_R_COMPILE
130 	return 0;
131 # else /* LDAP_R_COMPILE */
132 	return ldap_pvt_thread_mutex_unlock( &ldap_int_gmtime_mutex );
133 # endif /* LDAP_R_COMPILE */
134 }
135 #endif /* !USE_GMTIME_R || !USE_LOCALTIME_R */
136 
137 #ifndef USE_GMTIME_R
138 struct tm *
ldap_pvt_gmtime(const time_t * timep,struct tm * result)139 ldap_pvt_gmtime( const time_t *timep, struct tm *result )
140 {
141 	struct tm *tm_ptr;
142 
143 	LDAP_MUTEX_LOCK( &ldap_int_gmtime_mutex );
144 	tm_ptr = gmtime( timep );
145 	if ( tm_ptr == NULL ) {
146 		result = NULL;
147 
148 	} else {
149 		*result = *tm_ptr;
150 	}
151 	LDAP_MUTEX_UNLOCK( &ldap_int_gmtime_mutex );
152 
153 	return result;
154 }
155 #endif /* !USE_GMTIME_R */
156 
157 #ifndef USE_LOCALTIME_R
158 struct tm *
ldap_pvt_localtime(const time_t * timep,struct tm * result)159 ldap_pvt_localtime( const time_t *timep, struct tm *result )
160 {
161 	struct tm *tm_ptr;
162 
163 	LDAP_MUTEX_LOCK( &ldap_int_gmtime_mutex );
164 	tm_ptr = localtime( timep );
165 	if ( tm_ptr == NULL ) {
166 		result = NULL;
167 
168 	} else {
169 		*result = *tm_ptr;
170 	}
171 	LDAP_MUTEX_UNLOCK( &ldap_int_gmtime_mutex );
172 
173 	return result;
174 }
175 #endif /* !USE_LOCALTIME_R */
176 
177 static int _ldap_pvt_gt_subs;
178 
179 #ifdef _WIN32
180 /* Windows SYSTEMTIME only has 10 millisecond resolution, so we
181  * also need to use a high resolution timer to get nanoseconds.
182  * This is pretty clunky.
183  */
184 static LARGE_INTEGER _ldap_pvt_gt_freq;
185 static LARGE_INTEGER _ldap_pvt_gt_prev;
186 static int _ldap_pvt_gt_offset;
187 
188 #define SEC_TO_UNIX_EPOCH 11644473600LL
189 #define TICKS_PER_SECOND 10000000
190 #define BILLION	1000000000L
191 
192 static int
ldap_pvt_gettimensec(int * sec)193 ldap_pvt_gettimensec(int *sec)
194 {
195 	LARGE_INTEGER count;
196 
197 	QueryPerformanceCounter( &count );
198 
199 	/* It shouldn't ever go backwards, but multiple CPUs might
200 	 * be able to hit in the same tick.
201 	 */
202 	LDAP_MUTEX_LOCK( &ldap_int_gettime_mutex );
203 	/* We assume Windows has at least a vague idea of
204 	 * when a second begins. So we align our nanosecond count
205 	 * with the Windows millisecond count using this offset.
206 	 * We retain the submillisecond portion of our own count.
207 	 *
208 	 * Note - this also assumes that the relationship between
209 	 * the PerformanceCounter and SystemTime stays constant;
210 	 * that assumption breaks if the SystemTime is adjusted by
211 	 * an external action.
212 	 */
213 	if ( !_ldap_pvt_gt_freq.QuadPart ) {
214 		LARGE_INTEGER c2;
215 		ULARGE_INTEGER ut;
216 		FILETIME ft0, ft1;
217 		long long t;
218 		int nsec;
219 
220 		/* Initialize our offset */
221 		QueryPerformanceFrequency( &_ldap_pvt_gt_freq );
222 
223 		/* Wait for a tick of the system time: 10-15ms */
224 		GetSystemTimeAsFileTime( &ft0 );
225 		do {
226 			GetSystemTimeAsFileTime( &ft1 );
227 		} while ( ft1.dwLowDateTime == ft0.dwLowDateTime );
228 
229 		ut.LowPart = ft1.dwLowDateTime;
230 		ut.HighPart = ft1.dwHighDateTime;
231 		QueryPerformanceCounter( &c2 );
232 
233 		/* get second and fraction portion of counter */
234 		t = c2.QuadPart % (_ldap_pvt_gt_freq.QuadPart*10);
235 
236 		/* convert to nanoseconds */
237 		t *= BILLION;
238 		nsec = t / _ldap_pvt_gt_freq.QuadPart;
239 
240 		ut.QuadPart /= 10;
241 		ut.QuadPart %= (10 * BILLION);
242 		_ldap_pvt_gt_offset = nsec - ut.QuadPart;
243 		count = c2;
244 	}
245 	if ( count.QuadPart <= _ldap_pvt_gt_prev.QuadPart ) {
246 		_ldap_pvt_gt_subs++;
247 	} else {
248 		_ldap_pvt_gt_subs = 0;
249 		_ldap_pvt_gt_prev = count;
250 	}
251 	LDAP_MUTEX_UNLOCK( &ldap_int_gettime_mutex );
252 
253 	/* convert to nanoseconds */
254 	count.QuadPart %= _ldap_pvt_gt_freq.QuadPart*10;
255 	count.QuadPart *= BILLION;
256 	count.QuadPart /= _ldap_pvt_gt_freq.QuadPart;
257 	count.QuadPart -= _ldap_pvt_gt_offset;
258 
259 	/* We've extracted the 1s and nanoseconds.
260 	 * The 1sec digit is used to detect wraparound in nanosecnds.
261 	 */
262 	if (count.QuadPart < 0)
263 		count.QuadPart += (10 * BILLION);
264 	else if (count.QuadPart >= (10 * BILLION))
265 		count.QuadPart -= (10 * BILLION);
266 
267 	*sec = count.QuadPart / BILLION;
268 	return count.QuadPart % BILLION;
269 }
270 
271 
272 /* emulate POSIX clock_gettime */
273 int
ldap_pvt_clock_gettime(int clk_id,struct timespec * tv)274 ldap_pvt_clock_gettime( int clk_id, struct timespec *tv )
275 {
276 	FILETIME ft;
277 	ULARGE_INTEGER ut;
278 	int sec, sec0;
279 
280 	GetSystemTimeAsFileTime( &ft );
281 	ut.LowPart = ft.dwLowDateTime;
282 	ut.HighPart = ft.dwHighDateTime;
283 
284 	/* convert to sec */
285 	ut.QuadPart /= TICKS_PER_SECOND;
286 
287 	tv->tv_nsec = ldap_pvt_gettimensec(&sec);
288 	tv->tv_sec = ut.QuadPart - SEC_TO_UNIX_EPOCH;
289 
290 	/* check for carry from microseconds */
291 	sec0 = tv->tv_sec % 10;
292 	if (sec0 < sec || (sec0 == 9 && !sec))
293 		tv->tv_sec++;
294 
295 	return 0;
296 }
297 
298 /* emulate POSIX gettimeofday */
299 int
ldap_pvt_gettimeofday(struct timeval * tv,void * unused)300 ldap_pvt_gettimeofday( struct timeval *tv, void *unused )
301 {
302 	struct timespec ts;
303 	ldap_pvt_clock_gettime( 0, &ts );
304 	tv->tv_sec = ts.tv_sec;
305 	tv->tv_usec = ts.tv_nsec / 1000;
306 	return 0;
307 }
308 
309 
310 /* return a broken out time, with nanoseconds
311  */
312 void
ldap_pvt_gettime(struct lutil_tm * tm)313 ldap_pvt_gettime( struct lutil_tm *tm )
314 {
315 	SYSTEMTIME st;
316 	int sec, sec0;
317 	static const char daysPerMonth[] = {
318 	31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
319 
320 	GetSystemTime( &st );
321 	tm->tm_nsec = ldap_pvt_gettimensec(&sec);
322 	tm->tm_usub = _ldap_pvt_gt_subs;
323 
324 	/* any difference larger than nanoseconds is
325 	 * already reflected in st
326 	 */
327 	tm->tm_sec = st.wSecond;
328 	tm->tm_min = st.wMinute;
329 	tm->tm_hour = st.wHour;
330 	tm->tm_mday = st.wDay;
331 	tm->tm_mon = st.wMonth - 1;
332 	tm->tm_year = st.wYear - 1900;
333 
334 	/* check for carry from nanoseconds */
335 	sec0 = tm->tm_sec % 10;
336 	if (sec0 < sec || (sec0 == 9 && !sec)) {
337 		tm->tm_sec++;
338 		/* FIXME: we don't handle leap seconds */
339 		if (tm->tm_sec > 59) {
340 			tm->tm_sec = 0;
341 			tm->tm_min++;
342 			if (tm->tm_min > 59) {
343 				tm->tm_min = 0;
344 				tm->tm_hour++;
345 				if (tm->tm_hour > 23) {
346 					int days = daysPerMonth[tm->tm_mon];
347 					tm->tm_hour = 0;
348 					tm->tm_mday++;
349 
350 					/* if it's February of a leap year,
351 					 * add 1 day to this month
352 					 */
353 					if (tm->tm_mon == 1 &&
354 						((!(st.wYear % 4) && (st.wYear % 100)) ||
355 						!(st.wYear % 400)))
356 						days++;
357 
358 					if (tm->tm_mday > days) {
359 						tm->tm_mday = 1;
360 						tm->tm_mon++;
361 						if (tm->tm_mon > 11) {
362 							tm->tm_mon = 0;
363 							tm->tm_year++;
364 						}
365 					}
366 				}
367 			}
368 		}
369 	}
370 }
371 #else
372 
373 #ifdef HAVE_CLOCK_GETTIME
374 static struct timespec _ldap_pvt_gt_prevTv;
375 #else
376 static struct timeval _ldap_pvt_gt_prevTv;
377 #endif
378 
379 void
ldap_pvt_gettime(struct lutil_tm * ltm)380 ldap_pvt_gettime( struct lutil_tm *ltm )
381 {
382 	struct tm tm;
383 	time_t t;
384 #ifdef HAVE_CLOCK_GETTIME
385 #define	FRAC	tv_nsec
386 #define	NSECS(x)	x
387 	struct timespec tv;
388 
389 	clock_gettime( CLOCK_REALTIME, &tv );
390 #else
391 #define	FRAC	tv_usec
392 #define	NSECS(x)	x * 1000
393 	struct timeval tv;
394 
395 	gettimeofday( &tv, NULL );
396 #endif
397 	t = tv.tv_sec;
398 
399 	LDAP_MUTEX_LOCK( &ldap_int_gettime_mutex );
400 	if ( tv.tv_sec < _ldap_pvt_gt_prevTv.tv_sec
401 		|| ( tv.tv_sec == _ldap_pvt_gt_prevTv.tv_sec
402 		&& tv.FRAC <= _ldap_pvt_gt_prevTv.FRAC )) {
403 		_ldap_pvt_gt_subs++;
404 	} else {
405 		_ldap_pvt_gt_subs = 0;
406 		_ldap_pvt_gt_prevTv = tv;
407 	}
408 	LDAP_MUTEX_UNLOCK( &ldap_int_gettime_mutex );
409 
410 	ltm->tm_usub = _ldap_pvt_gt_subs;
411 
412 	ldap_pvt_gmtime( &t, &tm );
413 
414 	ltm->tm_sec = tm.tm_sec;
415 	ltm->tm_min = tm.tm_min;
416 	ltm->tm_hour = tm.tm_hour;
417 	ltm->tm_mday = tm.tm_mday;
418 	ltm->tm_mon = tm.tm_mon;
419 	ltm->tm_year = tm.tm_year;
420 	ltm->tm_nsec = NSECS(tv.FRAC);
421 }
422 #endif
423 
424 size_t
ldap_pvt_csnstr(char * buf,size_t len,unsigned int replica,unsigned int mod)425 ldap_pvt_csnstr(char *buf, size_t len, unsigned int replica, unsigned int mod)
426 {
427 	struct lutil_tm tm;
428 	int n;
429 
430 	ldap_pvt_gettime( &tm );
431 
432 	n = snprintf( buf, len,
433 		"%4d%02d%02d%02d%02d%02d.%06dZ#%06x#%03x#%06x",
434 		tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour,
435 		tm.tm_min, tm.tm_sec, tm.tm_nsec / 1000, tm.tm_usub, replica, mod );
436 
437 	if( n < 0 ) return 0;
438 	return ( (size_t) n < len ) ? n : 0;
439 }
440 
441 #define BUFSTART (1024-32)
442 #define BUFMAX (32*1024-32)
443 
444 #if defined(LDAP_R_COMPILE)
445 static char *safe_realloc( char **buf, int len );
446 
447 #if !(defined(HAVE_GETHOSTBYNAME_R) && defined(HAVE_GETHOSTBYADDR_R))
448 static int copy_hostent( struct hostent *res,
449 	char **buf, struct hostent * src );
450 #endif
451 #endif
452 
ldap_pvt_gethostbyname_a(const char * name,struct hostent * resbuf,char ** buf,struct hostent ** result,int * herrno_ptr)453 int ldap_pvt_gethostbyname_a(
454 	const char *name,
455 	struct hostent *resbuf,
456 	char **buf,
457 	struct hostent **result,
458 	int *herrno_ptr )
459 {
460 #if defined( HAVE_GETHOSTBYNAME_R )
461 
462 # define NEED_SAFE_REALLOC 1
463 	int r=-1;
464 	int buflen=BUFSTART;
465 	*buf = NULL;
466 	for(;buflen<BUFMAX;) {
467 		if (safe_realloc( buf, buflen )==NULL)
468 			return r;
469 
470 #if (GETHOSTBYNAME_R_NARGS < 6)
471 		*result=gethostbyname_r( name, resbuf, *buf, buflen, herrno_ptr );
472 		r = (*result == NULL) ?  -1 : 0;
473 #else
474 		while((r = gethostbyname_r( name, resbuf, *buf, buflen, result, herrno_ptr )) == ERANGE) {
475 			/* Increase the buffer */
476 			buflen*=2;
477 			if (safe_realloc(buf, buflen) == NULL)
478 				return -1;
479 		}
480 #endif
481 
482 		Debug2( LDAP_DEBUG_TRACE, "ldap_pvt_gethostbyname_a: host=%s, r=%d\n",
483 		       name, r );
484 
485 #ifdef NETDB_INTERNAL
486 		if ((r<0) &&
487 			(*herrno_ptr==NETDB_INTERNAL) &&
488 			(errno==ERANGE))
489 		{
490 			buflen*=2;
491 			continue;
492 	 	}
493 #endif
494 		return r;
495 	}
496 	return -1;
497 #elif defined( LDAP_R_COMPILE )
498 # define NEED_COPY_HOSTENT
499 	struct hostent *he;
500 	int	retval;
501 	*buf = NULL;
502 
503 	LDAP_MUTEX_LOCK( &ldap_int_resolv_mutex );
504 
505 	he = gethostbyname( name );
506 
507 	if (he==NULL) {
508 		*herrno_ptr = h_errno;
509 		retval = -1;
510 	} else if (copy_hostent( resbuf, buf, he )<0) {
511 		*herrno_ptr = -1;
512 		retval = -1;
513 	} else {
514 		*result = resbuf;
515 		retval = 0;
516 	}
517 
518 	LDAP_MUTEX_UNLOCK( &ldap_int_resolv_mutex );
519 
520 	return retval;
521 #else
522 	*buf = NULL;
523 	*result = gethostbyname( name );
524 
525 	if (*result!=NULL) {
526 		return 0;
527 	}
528 
529 	*herrno_ptr = h_errno;
530 
531 	return -1;
532 #endif
533 }
534 
535 #if !defined( HAVE_GETNAMEINFO ) && !defined( HAVE_HSTRERROR )
536 static const char *
hp_strerror(int err)537 hp_strerror( int err )
538 {
539 	switch (err) {
540 	case HOST_NOT_FOUND:	return _("Host not found (authoritative)");
541 	case TRY_AGAIN:			return _("Host not found (server fail?)");
542 	case NO_RECOVERY:		return _("Non-recoverable failure");
543 	case NO_DATA:			return _("No data of requested type");
544 #ifdef NETDB_INTERNAL
545 	case NETDB_INTERNAL:	return STRERROR( errno );
546 #endif
547 	}
548 	return _("Unknown resolver error");
549 }
550 #endif
551 
ldap_pvt_get_hname(const struct sockaddr * sa,int len,char * name,int namelen,char ** err)552 int ldap_pvt_get_hname(
553 	const struct sockaddr *sa,
554 	int len,
555 	char *name,
556 	int namelen,
557 	char **err )
558 {
559 	int rc;
560 #if defined( HAVE_GETNAMEINFO )
561 
562 	LDAP_MUTEX_LOCK( &ldap_int_resolv_mutex );
563 	rc = getnameinfo( sa, len, name, namelen, NULL, 0, 0 );
564 	LDAP_MUTEX_UNLOCK( &ldap_int_resolv_mutex );
565 	if ( rc ) *err = (char *)AC_GAI_STRERROR( rc );
566 	return rc;
567 
568 #else /* !HAVE_GETNAMEINFO */
569 	char *addr;
570 	int alen;
571 	struct hostent *hp = NULL;
572 #ifdef HAVE_GETHOSTBYADDR_R
573 	struct hostent hb;
574 	int buflen=BUFSTART, h_errno;
575 	char *buf=NULL;
576 #endif
577 
578 #ifdef LDAP_PF_INET6
579 	if (sa->sa_family == AF_INET6) {
580 		struct sockaddr_in6 *sin = (struct sockaddr_in6 *)sa;
581 		addr = (char *)&sin->sin6_addr;
582 		alen = sizeof(sin->sin6_addr);
583 	} else
584 #endif
585 	if (sa->sa_family == AF_INET) {
586 		struct sockaddr_in *sin = (struct sockaddr_in *)sa;
587 		addr = (char *)&sin->sin_addr;
588 		alen = sizeof(sin->sin_addr);
589 	} else {
590 		rc = NO_RECOVERY;
591 		*err = (char *)HSTRERROR( rc );
592 		return rc;
593 	}
594 #if defined( HAVE_GETHOSTBYADDR_R )
595 	for(;buflen<BUFMAX;) {
596 		if (safe_realloc( &buf, buflen )==NULL) {
597 			*err = (char *)STRERROR( ENOMEM );
598 			return ENOMEM;
599 		}
600 #if (GETHOSTBYADDR_R_NARGS < 8)
601 		hp=gethostbyaddr_r( addr, alen, sa->sa_family,
602 			&hb, buf, buflen, &h_errno );
603 		rc = (hp == NULL) ? -1 : 0;
604 #else
605 		rc = gethostbyaddr_r( addr, alen, sa->sa_family,
606 			&hb, buf, buflen,
607 			&hp, &h_errno );
608 #endif
609 #ifdef NETDB_INTERNAL
610 		if ((rc<0) &&
611 			(h_errno==NETDB_INTERNAL) &&
612 			(errno==ERANGE))
613 		{
614 			buflen*=2;
615 			continue;
616 		}
617 #endif
618 		break;
619 	}
620 	if (hp) {
621 		strncpy( name, hp->h_name, namelen );
622 	} else {
623 		*err = (char *)HSTRERROR( h_errno );
624 	}
625 	LDAP_FREE(buf);
626 #else /* HAVE_GETHOSTBYADDR_R */
627 
628 	LDAP_MUTEX_LOCK( &ldap_int_resolv_mutex );
629 	hp = gethostbyaddr( addr, alen, sa->sa_family );
630 	if (hp) {
631 		strncpy( name, hp->h_name, namelen );
632 		rc = 0;
633 	} else {
634 		rc = h_errno;
635 		*err = (char *)HSTRERROR( h_errno );
636 	}
637 	LDAP_MUTEX_UNLOCK( &ldap_int_resolv_mutex );
638 
639 #endif	/* !HAVE_GETHOSTBYADDR_R */
640 	return rc;
641 #endif	/* !HAVE_GETNAMEINFO */
642 }
643 
ldap_pvt_gethostbyaddr_a(const char * addr,int len,int type,struct hostent * resbuf,char ** buf,struct hostent ** result,int * herrno_ptr)644 int ldap_pvt_gethostbyaddr_a(
645 	const char *addr,
646 	int len,
647 	int type,
648 	struct hostent *resbuf,
649 	char **buf,
650 	struct hostent **result,
651 	int *herrno_ptr )
652 {
653 #if defined( HAVE_GETHOSTBYADDR_R )
654 
655 # undef NEED_SAFE_REALLOC
656 # define NEED_SAFE_REALLOC
657 	int r=-1;
658 	int buflen=BUFSTART;
659 	*buf = NULL;
660 	for(;buflen<BUFMAX;) {
661 		if (safe_realloc( buf, buflen )==NULL)
662 			return r;
663 #if (GETHOSTBYADDR_R_NARGS < 8)
664 		*result=gethostbyaddr_r( addr, len, type,
665 			resbuf, *buf, buflen, herrno_ptr );
666 		r = (*result == NULL) ? -1 : 0;
667 #else
668 		r = gethostbyaddr_r( addr, len, type,
669 			resbuf, *buf, buflen,
670 			result, herrno_ptr );
671 #endif
672 
673 #ifdef NETDB_INTERNAL
674 		if ((r<0) &&
675 			(*herrno_ptr==NETDB_INTERNAL) &&
676 			(errno==ERANGE))
677 		{
678 			buflen*=2;
679 			continue;
680 		}
681 #endif
682 		return r;
683 	}
684 	return -1;
685 #elif defined( LDAP_R_COMPILE )
686 # undef NEED_COPY_HOSTENT
687 # define NEED_COPY_HOSTENT
688 	struct hostent *he;
689 	int	retval;
690 	*buf = NULL;
691 
692 	LDAP_MUTEX_LOCK( &ldap_int_resolv_mutex );
693 	he = gethostbyaddr( addr, len, type );
694 
695 	if (he==NULL) {
696 		*herrno_ptr = h_errno;
697 		retval = -1;
698 	} else if (copy_hostent( resbuf, buf, he )<0) {
699 		*herrno_ptr = -1;
700 		retval = -1;
701 	} else {
702 		*result = resbuf;
703 		retval = 0;
704 	}
705 	LDAP_MUTEX_UNLOCK( &ldap_int_resolv_mutex );
706 
707 	return retval;
708 
709 #else /* gethostbyaddr() */
710 	*buf = NULL;
711 	*result = gethostbyaddr( addr, len, type );
712 
713 	if (*result!=NULL) {
714 		return 0;
715 	}
716 	return -1;
717 #endif
718 }
719 /*
720  * ldap_int_utils_init() should be called before any other function.
721  */
722 
ldap_int_utils_init(void)723 void ldap_int_utils_init( void )
724 {
725 	static int done=0;
726 	if (done)
727 	  return;
728 	done=1;
729 
730 #ifdef LDAP_R_COMPILE
731 #if !defined( USE_CTIME_R ) && !defined( HAVE_REENTRANT_FUNCTIONS )
732 	ldap_pvt_thread_mutex_init( &ldap_int_ctime_mutex );
733 #endif
734 #if !defined( USE_GMTIME_R ) && !defined( USE_LOCALTIME_R )
735 	ldap_pvt_thread_mutex_init( &ldap_int_gmtime_mutex );
736 #endif
737 	ldap_pvt_thread_mutex_init( &ldap_int_resolv_mutex );
738 
739 	ldap_pvt_thread_mutex_init( &ldap_int_hostname_mutex );
740 
741 	ldap_pvt_thread_mutex_init( &ldap_int_gettime_mutex );
742 
743 #endif
744 
745 	/* call other module init functions here... */
746 }
747 
748 #if defined( NEED_COPY_HOSTENT )
749 # undef NEED_SAFE_REALLOC
750 #define NEED_SAFE_REALLOC
751 
cpy_aliases(char *** tgtio,char * buf,char ** src)752 static char *cpy_aliases(
753 	char ***tgtio,
754 	char *buf,
755 	char **src )
756 {
757 	int len;
758 	char **tgt=*tgtio;
759 	for( ; (*src) ; src++ ) {
760 		len = strlen( *src ) + 1;
761 		AC_MEMCPY( buf, *src, len );
762 		*tgt++=buf;
763 		buf+=len;
764 	}
765 	*tgtio=tgt;
766 	return buf;
767 }
768 
cpy_addresses(char *** tgtio,char * buf,char ** src,int len)769 static char *cpy_addresses(
770 	char ***tgtio,
771 	char *buf,
772 	char **src,
773 	int len )
774 {
775    	char **tgt=*tgtio;
776 	for( ; (*src) ; src++ ) {
777 		AC_MEMCPY( buf, *src, len );
778 		*tgt++=buf;
779 		buf+=len;
780 	}
781 	*tgtio=tgt;
782 	return buf;
783 }
784 
copy_hostent(struct hostent * res,char ** buf,struct hostent * src)785 static int copy_hostent(
786 	struct hostent *res,
787 	char **buf,
788 	struct hostent * src )
789 {
790 	char	**p;
791 	char	**tp;
792 	char	*tbuf;
793 	int	name_len;
794 	int	n_alias=0;
795 	int	total_alias_len=0;
796 	int	n_addr=0;
797 	int	total_addr_len=0;
798 	int	total_len;
799 
800 	/* calculate the size needed for the buffer */
801 	name_len = strlen( src->h_name ) + 1;
802 
803 	if( src->h_aliases != NULL ) {
804 		for( p = src->h_aliases; (*p) != NULL; p++ ) {
805 			total_alias_len += strlen( *p ) + 1;
806 			n_alias++;
807 		}
808 	}
809 
810 	if( src->h_addr_list != NULL ) {
811 		for( p = src->h_addr_list; (*p) != NULL; p++ ) {
812 			n_addr++;
813 		}
814 		total_addr_len = n_addr * src->h_length;
815 	}
816 
817 	total_len = (n_alias + n_addr + 2) * sizeof( char * ) +
818 		total_addr_len + total_alias_len + name_len;
819 
820 	if (safe_realloc( buf, total_len )) {
821 		tp = (char **) *buf;
822 		tbuf = *buf + (n_alias + n_addr + 2) * sizeof( char * );
823 		AC_MEMCPY( res, src, sizeof( struct hostent ) );
824 		/* first the name... */
825 		AC_MEMCPY( tbuf, src->h_name, name_len );
826 		res->h_name = tbuf; tbuf+=name_len;
827 		/* now the aliases */
828 		res->h_aliases = tp;
829 		if ( src->h_aliases != NULL ) {
830 			tbuf = cpy_aliases( &tp, tbuf, src->h_aliases );
831 		}
832 		*tp++=NULL;
833 		/* finally the addresses */
834 		res->h_addr_list = tp;
835 		if ( src->h_addr_list != NULL ) {
836 			tbuf = cpy_addresses( &tp, tbuf, src->h_addr_list, src->h_length );
837 		}
838 		*tp++=NULL;
839 		return 0;
840 	}
841 	return -1;
842 }
843 #endif
844 
845 #if defined( NEED_SAFE_REALLOC )
safe_realloc(char ** buf,int len)846 static char *safe_realloc( char **buf, int len )
847 {
848 	char *tmpbuf;
849 	tmpbuf = LDAP_REALLOC( *buf, len );
850 	if (tmpbuf) {
851 		*buf=tmpbuf;
852 	}
853 	return tmpbuf;
854 }
855 #endif
856 
ldap_pvt_get_fqdn(char * name)857 char * ldap_pvt_get_fqdn( char *name )
858 {
859 #ifdef HAVE_GETADDRINFO
860 	struct addrinfo hints, *res;
861 #else
862 	char *ha_buf;
863 	struct hostent *hp, he_buf;
864 	int local_h_errno;
865 #endif
866 	int rc;
867 	char *fqdn, hostbuf[MAXHOSTNAMELEN+1];
868 
869 	if( name == NULL ) {
870 		if( gethostname( hostbuf, MAXHOSTNAMELEN ) == 0 ) {
871 			hostbuf[MAXHOSTNAMELEN] = '\0';
872 			name = hostbuf;
873 		} else {
874 			name = "localhost";
875 		}
876 	}
877 
878 #ifdef HAVE_GETADDRINFO
879 	memset( &hints, 0, sizeof( hints ));
880 	hints.ai_family = AF_UNSPEC;
881 	hints.ai_flags = AI_CANONNAME;
882 
883 	LDAP_MUTEX_LOCK( &ldap_int_resolv_mutex );
884 	rc = getaddrinfo( name, NULL, &hints, &res );
885 	LDAP_MUTEX_UNLOCK( &ldap_int_resolv_mutex );
886 	if ( rc == 0 && res->ai_canonname ) {
887 		fqdn = LDAP_STRDUP( res->ai_canonname );
888 	} else {
889 		fqdn = LDAP_STRDUP( name );
890 	}
891 	if ( rc == 0 )
892 		freeaddrinfo( res );
893 #else
894 	rc = ldap_pvt_gethostbyname_a( name,
895 		&he_buf, &ha_buf, &hp, &local_h_errno );
896 
897 	if( rc < 0 || hp == NULL || hp->h_name == NULL ) {
898 		fqdn = LDAP_STRDUP( name );
899 	} else {
900 		fqdn = LDAP_STRDUP( hp->h_name );
901 	}
902 
903 	LDAP_FREE( ha_buf );
904 #endif
905 	return fqdn;
906 }
907 
908 #if ( defined( HAVE_GETADDRINFO ) || defined( HAVE_GETNAMEINFO ) ) \
909 	&& !defined( HAVE_GAI_STRERROR )
ldap_pvt_gai_strerror(int code)910 char *ldap_pvt_gai_strerror (int code) {
911 	static struct {
912 		int code;
913 		const char *msg;
914 	} values[] = {
915 #ifdef EAI_ADDRFAMILY
916 		{ EAI_ADDRFAMILY, N_("Address family for hostname not supported") },
917 #endif
918 		{ EAI_AGAIN, N_("Temporary failure in name resolution") },
919 		{ EAI_BADFLAGS, N_("Bad value for ai_flags") },
920 		{ EAI_FAIL, N_("Non-recoverable failure in name resolution") },
921 		{ EAI_FAMILY, N_("ai_family not supported") },
922 		{ EAI_MEMORY, N_("Memory allocation failure") },
923 #ifdef EAI_NODATA
924 		{ EAI_NODATA, N_("No address associated with hostname") },
925 #endif
926 		{ EAI_NONAME, N_("Name or service not known") },
927 		{ EAI_SERVICE, N_("Servname not supported for ai_socktype") },
928 		{ EAI_SOCKTYPE, N_("ai_socktype not supported") },
929 #ifdef EAI_SYSTEM
930 		{ EAI_SYSTEM, N_("System error") },
931 #endif
932 		{ 0, NULL }
933 	};
934 
935 	int i;
936 
937 	for ( i = 0; values[i].msg != NULL; i++ ) {
938 		if ( values[i].code == code ) {
939 			return (char *) _(values[i].msg);
940 		}
941 	}
942 
943 	return _("Unknown error");
944 }
945 #endif
946 
947 /* format a socket address as a string */
948 
949 #ifdef HAVE_TCPD
950 # include <tcpd.h>
951 # define SOCKADDR_STRING_UNKNOWN	STRING_UNKNOWN
952 #else /* ! TCP Wrappers */
953 # define SOCKADDR_STRING_UNKNOWN	"unknown"
954 #endif /* ! TCP Wrappers */
955 
956 void
ldap_pvt_sockaddrstr(Sockaddr * sa,struct berval * addrbuf)957 ldap_pvt_sockaddrstr( Sockaddr *sa, struct berval *addrbuf )
958 {
959 	char *addr;
960 	switch( sa->sa_addr.sa_family ) {
961 #ifdef LDAP_PF_LOCAL
962 	case AF_LOCAL:
963 		addrbuf->bv_len = snprintf( addrbuf->bv_val, addrbuf->bv_len,
964 			"PATH=%s", sa->sa_un_addr.sun_path );
965 		break;
966 #endif
967 #ifdef LDAP_PF_INET6
968 	case AF_INET6:
969 		strcpy(addrbuf->bv_val, "IP=");
970 		if ( IN6_IS_ADDR_V4MAPPED(&sa->sa_in6_addr.sin6_addr) ) {
971 #if defined( HAVE_GETADDRINFO ) && defined( HAVE_INET_NTOP )
972 			addr = (char *)inet_ntop( AF_INET,
973 			   ((struct in_addr *)&sa->sa_in6_addr.sin6_addr.s6_addr[12]),
974 			   addrbuf->bv_val+3, addrbuf->bv_len-3 );
975 #else /* ! HAVE_GETADDRINFO || ! HAVE_INET_NTOP */
976 			addr = inet_ntoa( *((struct in_addr *)
977 					&sa->sa_in6_addr.sin6_addr.s6_addr[12]) );
978 #endif /* ! HAVE_GETADDRINFO || ! HAVE_INET_NTOP */
979 			if ( !addr ) addr = SOCKADDR_STRING_UNKNOWN;
980 			if ( addr != addrbuf->bv_val+3 ) {
981 				addrbuf->bv_len = sprintf( addrbuf->bv_val+3, "%s:%d", addr,
982 				 (unsigned) ntohs( sa->sa_in6_addr.sin6_port ) ) + 3;
983 			} else {
984 				int len = strlen( addr );
985 				addrbuf->bv_len = sprintf( addr+len, ":%d",
986 				 (unsigned) ntohs( sa->sa_in6_addr.sin6_port ) ) + len + 3;
987 			}
988 		} else {
989 			addr = (char *)inet_ntop( AF_INET6,
990 				      &sa->sa_in6_addr.sin6_addr,
991 				      addrbuf->bv_val+4, addrbuf->bv_len-4 );
992 			if ( !addr ) addr = SOCKADDR_STRING_UNKNOWN;
993 			if ( addr != addrbuf->bv_val+4 ) {
994 				addrbuf->bv_len = sprintf( addrbuf->bv_val+3, "[%s]:%d", addr,
995 				 (unsigned) ntohs( sa->sa_in6_addr.sin6_port ) ) + 3;
996 			} else {
997 				int len = strlen( addr );
998 				addrbuf->bv_val[3] = '[';
999 				addrbuf->bv_len = sprintf( addr+len, "]:%d",
1000 				 (unsigned) ntohs( sa->sa_in6_addr.sin6_port ) ) + len + 4;
1001 			}
1002 		}
1003 		break;
1004 #endif /* LDAP_PF_INET6 */
1005 	case AF_INET:
1006 		strcpy(addrbuf->bv_val, "IP=");
1007 #if defined( HAVE_GETADDRINFO ) && defined( HAVE_INET_NTOP )
1008 		addr = (char *)inet_ntop( AF_INET, &sa->sa_in_addr.sin_addr,
1009 			   addrbuf->bv_val+3, addrbuf->bv_len-3 );
1010 #else /* ! HAVE_GETADDRINFO || ! HAVE_INET_NTOP */
1011 		addr = inet_ntoa( sa->sa_in_addr.sin_addr );
1012 #endif /* ! HAVE_GETADDRINFO || ! HAVE_INET_NTOP */
1013 		if ( !addr ) addr = SOCKADDR_STRING_UNKNOWN;
1014 		if ( addr != addrbuf->bv_val+3 ) {
1015 			addrbuf->bv_len = sprintf( addrbuf->bv_val+3, "%s:%d", addr,
1016 			 (unsigned) ntohs( sa->sa_in_addr.sin_port ) ) + 3;
1017 		} else {
1018 			int len = strlen( addr );
1019 			addrbuf->bv_len = sprintf( addr+len, ":%d",
1020 			 (unsigned) ntohs( sa->sa_in_addr.sin_port ) ) + len + 3;
1021 		}
1022 		break;
1023 	default:
1024 		addrbuf->bv_val[0] = '\0';
1025 	}
1026 }
1027