1 /* os-ip.c -- platform-specific TCP & UDP related code */
2 /* $OpenLDAP$ */
3 /* This work is part of OpenLDAP Software <http://www.openldap.org/>.
4  *
5  * Copyright 1998-2021 The OpenLDAP Foundation.
6  * Portions Copyright 1999 Lars Uffmann.
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 /* Portions Copyright (c) 1995 Regents of the University of Michigan.
18  * All rights reserved.
19  */
20 /* Significant additional contributors include:
21  *    Lars Uffman
22  */
23 
24 #include "portable.h"
25 
26 #include <stdio.h>
27 
28 #include <ac/stdlib.h>
29 
30 #include <ac/errno.h>
31 #include <ac/socket.h>
32 #include <ac/string.h>
33 #include <ac/time.h>
34 #include <ac/unistd.h>
35 
36 #ifdef HAVE_IO_H
37 #include <io.h>
38 #endif /* HAVE_IO_H */
39 #ifdef HAVE_FCNTL_H
40 #include <fcntl.h>
41 #endif
42 
43 #include "ldap-int.h"
44 
45 #if defined( HAVE_GETADDRINFO ) && defined( HAVE_INET_NTOP )
46 #  ifdef LDAP_PF_INET6
47 int ldap_int_inet4or6 = AF_UNSPEC;
48 #  else
49 int ldap_int_inet4or6 = AF_INET;
50 #  endif
51 #endif
52 
53 static void
ldap_pvt_set_errno(int err)54 ldap_pvt_set_errno(int err)
55 {
56 	sock_errset(err);
57 }
58 
59 int
ldap_int_timeval_dup(struct timeval ** dest,const struct timeval * src)60 ldap_int_timeval_dup( struct timeval **dest, const struct timeval *src )
61 {
62 	struct timeval *new;
63 
64 	assert( dest != NULL );
65 
66 	if (src == NULL) {
67 		*dest = NULL;
68 		return 0;
69 	}
70 
71 	new = (struct timeval *) LDAP_MALLOC(sizeof(struct timeval));
72 
73 	if( new == NULL ) {
74 		*dest = NULL;
75 		return 1;
76 	}
77 
78 	AC_MEMCPY( (char *) new, (const char *) src, sizeof(struct timeval));
79 
80 	*dest = new;
81 	return 0;
82 }
83 
84 static int
ldap_pvt_ndelay_on(LDAP * ld,int fd)85 ldap_pvt_ndelay_on(LDAP *ld, int fd)
86 {
87 	Debug1(LDAP_DEBUG_TRACE, "ldap_ndelay_on: %d\n",fd );
88 	return ber_pvt_socket_set_nonblock( fd, 1 );
89 }
90 
91 static int
ldap_pvt_ndelay_off(LDAP * ld,int fd)92 ldap_pvt_ndelay_off(LDAP *ld, int fd)
93 {
94 	Debug1(LDAP_DEBUG_TRACE, "ldap_ndelay_off: %d\n",fd );
95 	return ber_pvt_socket_set_nonblock( fd, 0 );
96 }
97 
98 static ber_socket_t
ldap_int_socket(LDAP * ld,int family,int type)99 ldap_int_socket(LDAP *ld, int family, int type )
100 {
101 	ber_socket_t s = socket(family, type, 0);
102 	Debug1(LDAP_DEBUG_TRACE, "ldap_new_socket: %d\n",s );
103 #ifdef FD_CLOEXEC
104 	fcntl(s, F_SETFD, FD_CLOEXEC);
105 #endif
106 	return ( s );
107 }
108 
109 static int
ldap_pvt_close_socket(LDAP * ld,int s)110 ldap_pvt_close_socket(LDAP *ld, int s)
111 {
112 	Debug1(LDAP_DEBUG_TRACE, "ldap_close_socket: %d\n",s );
113 	return tcp_close(s);
114 }
115 
116 static int
ldap_int_prepare_socket(LDAP * ld,int s,int proto)117 ldap_int_prepare_socket(LDAP *ld, int s, int proto )
118 {
119 	Debug1(LDAP_DEBUG_TRACE, "ldap_prepare_socket: %d\n", s );
120 
121 #if defined( SO_KEEPALIVE ) || defined( TCP_NODELAY ) || defined( TCP_USER_TIMEOUT )
122 	if ( proto == LDAP_PROTO_TCP ) {
123 		int dummy = 1;
124 #ifdef SO_KEEPALIVE
125 		if ( setsockopt( s, SOL_SOCKET, SO_KEEPALIVE,
126 			(char*) &dummy, sizeof(dummy) ) == AC_SOCKET_ERROR )
127 		{
128 			Debug1(LDAP_DEBUG_TRACE, "ldap_prepare_socket: "
129 				"setsockopt(%d, SO_KEEPALIVE) failed (ignored).\n",
130 				s );
131 		}
132 		if ( ld->ld_options.ldo_keepalive_idle > 0 )
133 		{
134 #ifdef TCP_KEEPIDLE
135 			if ( setsockopt( s, IPPROTO_TCP, TCP_KEEPIDLE,
136 					(void*) &ld->ld_options.ldo_keepalive_idle,
137 					sizeof(ld->ld_options.ldo_keepalive_idle) ) == AC_SOCKET_ERROR )
138 			{
139 				Debug1(LDAP_DEBUG_TRACE,
140 					"ldap_prepare_socket: "
141 					"setsockopt(%d, TCP_KEEPIDLE) failed (ignored).\n",
142 					s );
143 			}
144 #else
145 			Debug0(LDAP_DEBUG_TRACE, "ldap_prepare_socket: "
146 					"sockopt TCP_KEEPIDLE not supported on this system.\n" );
147 #endif /* TCP_KEEPIDLE */
148 		}
149 		if ( ld->ld_options.ldo_keepalive_probes > 0 )
150 		{
151 #ifdef TCP_KEEPCNT
152 			if ( setsockopt( s, IPPROTO_TCP, TCP_KEEPCNT,
153 					(void*) &ld->ld_options.ldo_keepalive_probes,
154 					sizeof(ld->ld_options.ldo_keepalive_probes) ) == AC_SOCKET_ERROR )
155 			{
156 				Debug1(LDAP_DEBUG_TRACE,
157 					"ldap_prepare_socket: "
158 					"setsockopt(%d, TCP_KEEPCNT) failed (ignored).\n",
159 					s );
160 			}
161 #else
162 			Debug0(LDAP_DEBUG_TRACE, "ldap_prepare_socket: "
163 					"sockopt TCP_KEEPCNT not supported on this system.\n" );
164 #endif /* TCP_KEEPCNT */
165 		}
166 		if ( ld->ld_options.ldo_keepalive_interval > 0 )
167 		{
168 #ifdef TCP_KEEPINTVL
169 			if ( setsockopt( s, IPPROTO_TCP, TCP_KEEPINTVL,
170 					(void*) &ld->ld_options.ldo_keepalive_interval,
171 					sizeof(ld->ld_options.ldo_keepalive_interval) ) == AC_SOCKET_ERROR )
172 			{
173 				Debug1(LDAP_DEBUG_TRACE,
174 					"ldap_prepare_socket: "
175 					"setsockopt(%d, TCP_KEEPINTVL) failed (ignored).\n",
176 					s );
177 			}
178 #else
179 			Debug0(LDAP_DEBUG_TRACE, "ldap_prepare_socket: "
180 					"sockopt TCP_KEEPINTVL not supported on this system.\n" );
181 #endif /* TCP_KEEPINTVL */
182 		}
183 #endif /* SO_KEEPALIVE */
184 #ifdef TCP_NODELAY
185 		if ( setsockopt( s, IPPROTO_TCP, TCP_NODELAY,
186 			(char*) &dummy, sizeof(dummy) ) == AC_SOCKET_ERROR )
187 		{
188 			Debug1(LDAP_DEBUG_TRACE, "ldap_prepare_socket: "
189 				"setsockopt(%d, TCP_NODELAY) failed (ignored).\n",
190 				s );
191 		}
192 #endif /* TCP_NODELAY */
193 		if ( ld->ld_options.ldo_tcp_user_timeout > 0 )
194 		{
195 #ifdef TCP_USER_TIMEOUT
196 			if ( setsockopt( s, IPPROTO_TCP, TCP_USER_TIMEOUT,
197 					(void*) &ld->ld_options.ldo_tcp_user_timeout,
198 					sizeof(ld->ld_options.ldo_tcp_user_timeout) ) == AC_SOCKET_ERROR )
199 			{
200 				Debug1(LDAP_DEBUG_TRACE,
201 					"ldap_prepare_socket: "
202 					"setsockopt(%d, TCP_USER_TIMEOUT) failed (ignored).\n",
203 					s );
204 			}
205 #else
206 			Debug0(LDAP_DEBUG_TRACE, "ldap_prepare_socket: "
207 			       "sockopt TCP_USER_TIMEOUT not supported on this system.\n" );
208 #endif /* TCP_USER_TIMEOUT */
209 		}
210 	}
211 #endif /* SO_KEEPALIVE || TCP_NODELAY || TCP_USER_TIMEOUT */
212 
213 	return 0;
214 }
215 
216 #ifndef HAVE_WINSOCK
217 
218 #undef TRACE
219 #define TRACE do { \
220 	char ebuf[128]; \
221 	int saved_errno = errno; \
222 	Debug3(LDAP_DEBUG_TRACE, "ldap_is_socket_ready: error on socket %d: errno: %d (%s)\n", \
223 		s, \
224 		saved_errno, \
225 		sock_errstr(saved_errno, ebuf, sizeof(ebuf)) ); \
226 } while( 0 )
227 
228 /*
229  * check the socket for errors after select returned.
230  */
231 static int
ldap_pvt_is_socket_ready(LDAP * ld,int s)232 ldap_pvt_is_socket_ready(LDAP *ld, int s)
233 {
234 	Debug1(LDAP_DEBUG_TRACE, "ldap_is_sock_ready: %d\n",s );
235 
236 #if defined( notyet ) /* && defined( SO_ERROR ) */
237 {
238 	int so_errno;
239 	ber_socklen_t dummy = sizeof(so_errno);
240 	if ( getsockopt( s, SOL_SOCKET, SO_ERROR, &so_errno, &dummy )
241 		== AC_SOCKET_ERROR )
242 	{
243 		return -1;
244 	}
245 	if ( so_errno ) {
246 		ldap_pvt_set_errno(so_errno);
247 		TRACE;
248 		return -1;
249 	}
250 	return 0;
251 }
252 #else
253 {
254 	/* error slippery */
255 #ifdef LDAP_PF_INET6
256 	struct sockaddr_storage sin;
257 #else
258 	struct sockaddr_in sin;
259 #endif
260 	char ch;
261 	ber_socklen_t dummy = sizeof(sin);
262 	if ( getpeername( s, (struct sockaddr *) &sin, &dummy )
263 		== AC_SOCKET_ERROR )
264 	{
265 		/* XXX: needs to be replace with ber_stream_read() */
266 		(void)read(s, &ch, 1);
267 		TRACE;
268 		return -1;
269 	}
270 	return 0;
271 }
272 #endif
273 	return -1;
274 }
275 #undef TRACE
276 
277 #endif /* HAVE_WINSOCK */
278 
279 /* NOTE: this is identical to analogous code in os-local.c */
280 int
ldap_int_poll(LDAP * ld,ber_socket_t s,struct timeval * tvp,int wr)281 ldap_int_poll(
282 	LDAP *ld,
283 	ber_socket_t s,
284 	struct timeval *tvp,
285 	int wr )
286 {
287 	int		rc;
288 
289 
290 	Debug2(LDAP_DEBUG_TRACE, "ldap_int_poll: fd: %d tm: %ld\n",
291 		s, tvp ? tvp->tv_sec : -1L );
292 
293 #ifdef HAVE_POLL
294 	{
295 		struct pollfd fd;
296 		int timeout = INFTIM;
297 		short event = wr ? POLL_WRITE : POLL_READ;
298 
299 		fd.fd = s;
300 		fd.events = event;
301 
302 		if ( tvp != NULL ) {
303 			timeout = TV2MILLISEC( tvp );
304 		}
305 		do {
306 			fd.revents = 0;
307 			rc = poll( &fd, 1, timeout );
308 
309 		} while ( rc == AC_SOCKET_ERROR && errno == EINTR &&
310 			LDAP_BOOL_GET( &ld->ld_options, LDAP_BOOL_RESTART ) );
311 
312 		if ( rc == AC_SOCKET_ERROR ) {
313 			return rc;
314 		}
315 
316 		if ( timeout == 0 && rc == 0 ) {
317 			return -2;
318 		}
319 
320 		if ( fd.revents & event ) {
321 			if ( ldap_pvt_is_socket_ready( ld, s ) == -1 ) {
322 				return -1;
323 			}
324 
325 			if ( ldap_pvt_ndelay_off( ld, s ) == -1 ) {
326 				return -1;
327 			}
328 			return 0;
329 		}
330 	}
331 #else
332 	{
333 		fd_set		wfds, *z = NULL;
334 #ifdef HAVE_WINSOCK
335 		fd_set		efds;
336 #endif
337 		struct timeval	tv = { 0 };
338 
339 #if defined( FD_SETSIZE ) && !defined( HAVE_WINSOCK )
340 		if ( s >= FD_SETSIZE ) {
341 			rc = AC_SOCKET_ERROR;
342 			tcp_close( s );
343 			ldap_pvt_set_errno( EMFILE );
344 			return rc;
345 		}
346 #endif
347 
348 		if ( tvp != NULL ) {
349 			tv = *tvp;
350 		}
351 
352 		do {
353 			FD_ZERO(&wfds);
354 			FD_SET(s, &wfds );
355 
356 #ifdef HAVE_WINSOCK
357 			FD_ZERO(&efds);
358 			FD_SET(s, &efds );
359 #endif
360 
361 			rc = select( ldap_int_tblsize, z, &wfds,
362 #ifdef HAVE_WINSOCK
363 				&efds,
364 #else
365 				z,
366 #endif
367 				tvp ? &tv : NULL );
368 		} while ( rc == AC_SOCKET_ERROR && errno == EINTR &&
369 			LDAP_BOOL_GET( &ld->ld_options, LDAP_BOOL_RESTART ) );
370 
371 		if ( rc == AC_SOCKET_ERROR ) {
372 			return rc;
373 		}
374 
375 		if ( rc == 0 && tvp && tvp->tv_sec == 0 && tvp->tv_usec == 0 ) {
376 			return -2;
377 		}
378 
379 #ifdef HAVE_WINSOCK
380 		/* This means the connection failed */
381 		if ( FD_ISSET(s, &efds) ) {
382 			int so_errno;
383 			ber_socklen_t dummy = sizeof(so_errno);
384 			if ( getsockopt( s, SOL_SOCKET, SO_ERROR,
385 				(char *) &so_errno, &dummy ) == AC_SOCKET_ERROR || !so_errno )
386 			{
387 				/* impossible */
388 				so_errno = WSAGetLastError();
389 			}
390 			ldap_pvt_set_errno( so_errno );
391 			Debug3(LDAP_DEBUG_TRACE,
392 			       "ldap_int_poll: error on socket %d: "
393 			       "errno: %d (%s)\n", s, so_errno, sock_errstr( so_errno, dummy, dummy ));
394 			return -1;
395 		}
396 #endif
397 		if ( FD_ISSET(s, &wfds) ) {
398 #ifndef HAVE_WINSOCK
399 			if ( ldap_pvt_is_socket_ready( ld, s ) == -1 ) {
400 				return -1;
401 			}
402 #endif
403 			if ( ldap_pvt_ndelay_off(ld, s) == -1 ) {
404 				return -1;
405 			}
406 			return 0;
407 		}
408 	}
409 #endif
410 
411 	Debug0(LDAP_DEBUG_TRACE, "ldap_int_poll: timed out\n" );
412 	ldap_pvt_set_errno( ETIMEDOUT );
413 	return -1;
414 }
415 
416 static int
ldap_pvt_connect(LDAP * ld,ber_socket_t s,struct sockaddr * sin,ber_socklen_t addrlen,int async)417 ldap_pvt_connect(LDAP *ld, ber_socket_t s,
418 	struct sockaddr *sin, ber_socklen_t addrlen,
419 	int async)
420 {
421 	int rc, err;
422 	struct timeval	tv, *opt_tv = NULL;
423 
424 #ifdef LDAP_CONNECTIONLESS
425 	/* We could do a connect() but that would interfere with
426 	 * attempts to poll a broadcast address
427 	 */
428 	if (LDAP_IS_UDP(ld)) {
429 		if (ld->ld_options.ldo_peer)
430 			ldap_memfree(ld->ld_options.ldo_peer);
431 		ld->ld_options.ldo_peer=ldap_memcalloc(1, sizeof(struct sockaddr_storage));
432 		AC_MEMCPY(ld->ld_options.ldo_peer,sin,addrlen);
433 		return ( 0 );
434 	}
435 #endif
436 	if ( ld->ld_options.ldo_tm_net.tv_sec >= 0 ) {
437 		tv = ld->ld_options.ldo_tm_net;
438 		opt_tv = &tv;
439 	}
440 
441 	Debug3(LDAP_DEBUG_TRACE,
442 			"ldap_pvt_connect: fd: %d tm: %ld async: %d\n",
443 			s, opt_tv ? tv.tv_sec : -1L, async);
444 
445 	if ( opt_tv && ldap_pvt_ndelay_on(ld, s) == -1 )
446 		return ( -1 );
447 
448 	do{
449 		Debug0(LDAP_DEBUG_TRACE, "attempting to connect: \n" );
450 		if ( connect(s, sin, addrlen) != AC_SOCKET_ERROR ) {
451 			Debug0(LDAP_DEBUG_TRACE, "connect success\n" );
452 
453 			if ( !async && opt_tv && ldap_pvt_ndelay_off(ld, s) == -1 )
454 				return ( -1 );
455 			return ( 0 );
456 		}
457 		err = sock_errno();
458 		Debug1(LDAP_DEBUG_TRACE, "connect errno: %d\n", err );
459 
460 	} while(err == EINTR &&
461 		LDAP_BOOL_GET( &ld->ld_options, LDAP_BOOL_RESTART ));
462 
463 	if ( err != EINPROGRESS && err != EWOULDBLOCK ) {
464 		return ( -1 );
465 	}
466 
467 	if ( async ) {
468 		/* caller will call ldap_int_poll() as appropriate? */
469 		return ( -2 );
470 	}
471 
472 	rc = ldap_int_poll( ld, s, opt_tv, 1 );
473 
474 	Debug1(LDAP_DEBUG_TRACE, "ldap_pvt_connect: %d\n", rc );
475 
476 	return rc;
477 }
478 
479 #ifndef HAVE_INET_ATON
480 int
ldap_pvt_inet_aton(const char * host,struct in_addr * in)481 ldap_pvt_inet_aton( const char *host, struct in_addr *in)
482 {
483 	unsigned long u = inet_addr( host );
484 
485 #ifdef INADDR_NONE
486 	if ( u == INADDR_NONE ) return 0;
487 #endif
488 	if ( u == 0xffffffffUL || u == (unsigned long) -1L ) return 0;
489 
490 	in->s_addr = u;
491 	return 1;
492 }
493 #endif
494 
495 int
ldap_validate_and_fill_sourceip(char ** source_ip_lst,ldapsourceip * temp_source_ip)496 ldap_validate_and_fill_sourceip  (char** source_ip_lst, ldapsourceip* temp_source_ip )
497 {
498 	int i = 0;
499 	int rc = LDAP_PARAM_ERROR;
500 
501 	for ( i = 0; source_ip_lst[i] != NULL; i++ ) {
502 		Debug1( LDAP_DEBUG_TRACE,
503 				"ldap_validate_and_fill_sourceip(%s)\n",
504 				source_ip_lst[i] );
505 
506 		if ( !temp_source_ip->has_ipv4 ) {
507 			if ( inet_aton( source_ip_lst[i], &temp_source_ip->ip4_addr ) ) {
508 				temp_source_ip->has_ipv4 = 1;
509 				rc = LDAP_OPT_SUCCESS;
510 				continue;
511 			}
512 		}
513 #ifdef LDAP_PF_INET6
514 		if ( !temp_source_ip->has_ipv6 ) {
515 			if ( inet_pton( AF_INET6, source_ip_lst[i],
516 				& temp_source_ip->ip6_addr ) ) {
517 				temp_source_ip->has_ipv6 = 1;
518 				rc = LDAP_OPT_SUCCESS;
519 				continue;
520 			}
521 		}
522 #endif
523 		memset( temp_source_ip, 0, sizeof( * (temp_source_ip ) ) );
524 		Debug1( LDAP_DEBUG_TRACE,
525 				"ldap_validate_and_fill_sourceip: validation failed for (%s)\n",
526 				source_ip_lst[i] );
527 		break;
528 	}
529 	return rc;
530 }
531 
532 int
ldap_int_connect_cbs(LDAP * ld,Sockbuf * sb,ber_socket_t * s,LDAPURLDesc * srv,struct sockaddr * addr)533 ldap_int_connect_cbs(LDAP *ld, Sockbuf *sb, ber_socket_t *s, LDAPURLDesc *srv, struct sockaddr *addr)
534 {
535 	struct ldapoptions *lo;
536 	ldaplist *ll;
537 	ldap_conncb *cb;
538 	int rc;
539 
540 	ber_sockbuf_ctrl( sb, LBER_SB_OPT_SET_FD, s );
541 
542 	/* Invoke all handle-specific callbacks first */
543 	lo = &ld->ld_options;
544 	for (ll = lo->ldo_conn_cbs; ll; ll = ll->ll_next) {
545 		cb = ll->ll_data;
546 		rc = cb->lc_add( ld, sb, srv, addr, cb );
547 		/* on any failure, call the teardown functions for anything
548 		 * that previously succeeded
549 		 */
550 		if ( rc ) {
551 			ldaplist *l2;
552 			for (l2 = lo->ldo_conn_cbs; l2 != ll; l2 = l2->ll_next) {
553 				cb = l2->ll_data;
554 				cb->lc_del( ld, sb, cb );
555 			}
556 			/* a failure might have implicitly closed the fd */
557 			ber_sockbuf_ctrl( sb, LBER_SB_OPT_GET_FD, s );
558 			return rc;
559 		}
560 	}
561 	lo = LDAP_INT_GLOBAL_OPT();
562 	for (ll = lo->ldo_conn_cbs; ll; ll = ll->ll_next) {
563 		cb = ll->ll_data;
564 		rc = cb->lc_add( ld, sb, srv, addr, cb );
565 		if ( rc ) {
566 			ldaplist *l2;
567 			for (l2 = lo->ldo_conn_cbs; l2 != ll; l2 = l2->ll_next) {
568 				cb = l2->ll_data;
569 				cb->lc_del( ld, sb, cb );
570 			}
571 			lo = &ld->ld_options;
572 			for (l2 = lo->ldo_conn_cbs; l2; l2 = l2->ll_next) {
573 				cb = l2->ll_data;
574 				cb->lc_del( ld, sb, cb );
575 			}
576 			ber_sockbuf_ctrl( sb, LBER_SB_OPT_GET_FD, s );
577 			return rc;
578 		}
579 	}
580 	return 0;
581 }
582 
583 int
ldap_connect_to_host(LDAP * ld,Sockbuf * sb,int proto,LDAPURLDesc * srv,int async)584 ldap_connect_to_host(LDAP *ld, Sockbuf *sb,
585 	int proto, LDAPURLDesc *srv,
586 	int async )
587 {
588 	int	rc;
589 	int	socktype, port;
590 	ber_socket_t		s = AC_SOCKET_INVALID;
591 	char *host;
592 
593 #if defined( HAVE_GETADDRINFO ) && defined( HAVE_INET_NTOP )
594 	char serv[7];
595 	int err;
596 	struct addrinfo hints, *res, *sai;
597 #else
598 	int i;
599 	int use_hp = 0;
600 	struct hostent *hp = NULL;
601 	struct hostent he_buf;
602 	struct in_addr in;
603 	char *ha_buf=NULL;
604 #endif
605 
606 	if ( srv->lud_host == NULL || *srv->lud_host == 0 ) {
607 		host = "localhost";
608 	} else {
609 		host = srv->lud_host;
610 	}
611 
612 	port = srv->lud_port;
613 
614 	if( !port ) {
615 		if( strcmp(srv->lud_scheme, "ldaps") == 0 ) {
616 			port = LDAPS_PORT;
617 		} else {
618 			port = LDAP_PORT;
619 		}
620 	}
621 
622 	switch(proto) {
623 	case LDAP_PROTO_TCP: socktype = SOCK_STREAM;
624 		Debug2(LDAP_DEBUG_TRACE, "ldap_connect_to_host: TCP %s:%d\n",
625 			host, port );
626 		break;
627 	case LDAP_PROTO_UDP: socktype = SOCK_DGRAM;
628 		Debug2(LDAP_DEBUG_TRACE, "ldap_connect_to_host: UDP %s:%d\n",
629 			host, port );
630 		break;
631 	default:
632 		Debug1(LDAP_DEBUG_TRACE,
633 			"ldap_connect_to_host: unknown proto: %d\n",
634 			proto );
635 		return -1;
636 	}
637 
638 #if defined( HAVE_GETADDRINFO ) && defined( HAVE_INET_NTOP )
639 	memset( &hints, '\0', sizeof(hints) );
640 #ifdef USE_AI_ADDRCONFIG /* FIXME: configure test needed */
641 	/* Use AI_ADDRCONFIG only on systems where its known to be needed. */
642 	hints.ai_flags = AI_ADDRCONFIG;
643 #endif
644 	hints.ai_family = ldap_int_inet4or6;
645 	hints.ai_socktype = socktype;
646 	snprintf(serv, sizeof serv, "%d", port );
647 
648 	/* most getaddrinfo(3) use non-threadsafe resolver libraries */
649 	LDAP_MUTEX_LOCK(&ldap_int_resolv_mutex);
650 
651 	err = getaddrinfo( host, serv, &hints, &res );
652 
653 	LDAP_MUTEX_UNLOCK(&ldap_int_resolv_mutex);
654 
655 	if ( err != 0 ) {
656 		Debug1(LDAP_DEBUG_TRACE,
657 			"ldap_connect_to_host: getaddrinfo failed: %s\n",
658 			AC_GAI_STRERROR(err) );
659 		return -1;
660 	}
661 	rc = -1;
662 
663 	for( sai=res; sai != NULL; sai=sai->ai_next) {
664 		unsigned short bind_success = 1;
665 		if( sai->ai_addr == NULL ) {
666 			Debug0(LDAP_DEBUG_TRACE,
667 				"ldap_connect_to_host: getaddrinfo "
668 				"ai_addr is NULL?\n" );
669 			continue;
670 		}
671 
672 #ifndef LDAP_PF_INET6
673 		if ( sai->ai_family == AF_INET6 ) continue;
674 #endif
675 		/* we assume AF_x and PF_x are equal for all x */
676 		s = ldap_int_socket( ld, sai->ai_family, socktype );
677 		if ( s == AC_SOCKET_INVALID ) {
678 			continue;
679 		}
680 
681 		if ( ldap_int_prepare_socket(ld, s, proto ) == -1 ) {
682 			ldap_pvt_close_socket(ld, s);
683 			break;
684 		}
685 
686 		switch (sai->ai_family) {
687 #ifdef LDAP_PF_INET6
688 			case AF_INET6: {
689 				char addr[INET6_ADDRSTRLEN];
690 				inet_ntop( AF_INET6,
691 					&((struct sockaddr_in6 *)sai->ai_addr)->sin6_addr,
692 					addr, sizeof addr);
693 				Debug2(LDAP_DEBUG_TRACE,
694 				      "ldap_connect_to_host: Trying %s %s\n",
695 					addr, serv );
696 				if( ld->ld_options.ldo_local_ip_addrs.has_ipv6 ) {
697 					struct sockaddr_in6 ip6addr;
698 					char bind_addr[INET6_ADDRSTRLEN];
699 					ip6addr.sin6_family = AF_INET6;
700 					ip6addr.sin6_addr = ld->ld_options.ldo_local_ip_addrs.ip6_addr;
701 					inet_ntop( AF_INET6,
702 						&(ip6addr.sin6_addr),
703 						bind_addr, sizeof bind_addr );
704 					Debug1( LDAP_DEBUG_TRACE,
705 						"ldap_connect_to_host: From source address %s\n",
706 						bind_addr );
707 					if ( bind( s, ( struct sockaddr* ) &ip6addr, sizeof ip6addr ) != 0 ) {
708 						Debug1( LDAP_DEBUG_TRACE,
709 								"ldap_connect_to_host: Failed to bind source address %s\n",
710 								bind_addr );
711 						bind_success = 0;
712 					}
713 				}
714 			} break;
715 #endif
716 			case AF_INET: {
717 				char addr[INET_ADDRSTRLEN];
718 				inet_ntop( AF_INET,
719 					&((struct sockaddr_in *)sai->ai_addr)->sin_addr,
720 					addr, sizeof addr);
721 				Debug2(LDAP_DEBUG_TRACE,
722 				      "ldap_connect_to_host: Trying %s:%s\n",
723 					addr, serv );
724 				if( ld->ld_options.ldo_local_ip_addrs.has_ipv4 ) {
725 					struct sockaddr_in ip4addr;
726 					char bind_addr[INET_ADDRSTRLEN];
727 					ip4addr.sin_family = AF_INET;
728 					ip4addr.sin_addr = ld->ld_options.ldo_local_ip_addrs.ip4_addr;
729 					inet_ntop( AF_INET,
730 						&(ip4addr.sin_addr),
731 						bind_addr, sizeof bind_addr );
732 					Debug1( LDAP_DEBUG_TRACE,
733 						"ldap_connect_to_host: From source address %s\n",
734 						bind_addr );
735 					if ( bind(s, ( struct sockaddr* )&ip4addr, sizeof ip4addr ) != 0 ) {
736 						Debug1( LDAP_DEBUG_TRACE,
737 								"ldap_connect_to_host: Failed to bind source address %s\n",
738 								bind_addr );
739 						bind_success = 0;
740 					}
741 				}
742 			} break;
743 		}
744 		if ( bind_success ) {
745 			rc = ldap_pvt_connect( ld, s,
746 				sai->ai_addr, sai->ai_addrlen, async );
747 			if ( rc == 0 || rc == -2 ) {
748 				err = ldap_int_connect_cbs( ld, sb, &s, srv, sai->ai_addr );
749 				if ( err )
750 					rc = err;
751 				else
752 					break;
753 			}
754 		}
755 		ldap_pvt_close_socket(ld, s);
756 	}
757 	freeaddrinfo(res);
758 
759 #else
760 	if (! inet_aton( host, &in ) ) {
761 		int local_h_errno;
762 		rc = ldap_pvt_gethostbyname_a( host, &he_buf, &ha_buf,
763 			&hp, &local_h_errno );
764 
765 		if ( (rc < 0) || (hp == NULL) ) {
766 #ifdef HAVE_WINSOCK
767 			ldap_pvt_set_errno( WSAGetLastError() );
768 #else
769 			/* not exactly right, but... */
770 			ldap_pvt_set_errno( EHOSTUNREACH );
771 #endif
772 			if (ha_buf) LDAP_FREE(ha_buf);
773 			return -1;
774 		}
775 
776 		use_hp = 1;
777 	}
778 
779 	rc = s = -1;
780 	for ( i = 0; !use_hp || (hp->h_addr_list[i] != 0); ++i, rc = -1 ) {
781 		struct sockaddr_in	sin;
782 		unsigned short bind_success = 1;
783 #ifdef HAVE_INET_NTOA_B
784 		char address[INET_ADDR_LEN];
785 		char bind_addr[INET_ADDR_LEN];
786 #else
787 		char *address;
788 		char *bind_addr;
789 #endif
790 		s = ldap_int_socket( ld, PF_INET, socktype );
791 		if ( s == AC_SOCKET_INVALID ) {
792 			/* use_hp ? continue : break; */
793 			break;
794 		}
795 
796 		if ( ldap_int_prepare_socket( ld, s, proto ) == -1 ) {
797 			ldap_pvt_close_socket(ld, s);
798 			break;
799 		}
800 
801 		(void)memset((char *)&sin, '\0', sizeof sin);
802 		sin.sin_family = AF_INET;
803 		sin.sin_port = htons((unsigned short) port);
804 
805 		if( use_hp ) {
806 			AC_MEMCPY( &sin.sin_addr, hp->h_addr_list[i],
807 				sizeof(sin.sin_addr) );
808 		} else {
809 			AC_MEMCPY( &sin.sin_addr, &in.s_addr,
810 				sizeof(sin.sin_addr) );
811 		}
812 
813 #ifdef HAVE_INET_NTOA_B
814 		/* for VxWorks */
815 		inet_ntoa_b( sin.sin_address, address );
816 #else
817 		address = inet_ntoa( sin.sin_addr );
818 #endif
819 		Debug2( LDAP_DEBUG_TRACE,
820 			"ldap_connect_to_host: Trying %s:%d\n",
821 			address, port );
822 		if( ld->ld_options.ldo_local_ip_addrs.has_ipv4 ) {
823 			struct sockaddr_in ip4addr;
824 			ip4addr.sin_family = AF_INET;
825 			ip4addr.sin_addr = ld->ld_options.ldo_local_ip_addrs.ip4_addr;
826 #ifdef HAVE_INET_NTOA_B
827 			inet_ntoa_b( ip4addr.sin_address, bind_addr );
828 #else
829 			bind_addr = inet_ntoa( ip4addr.sin_addr );
830 #endif
831 			Debug1( LDAP_DEBUG_TRACE,
832 				"ldap_connect_to_host: From source address %s\n",
833 				bind_addr );
834 			if ( bind( s, (struct sockaddr*)&ip4addr, sizeof ip4addr ) != 0 ) {
835 				Debug1( LDAP_DEBUG_TRACE,
836 						"ldap_connect_to_host: Failed to bind source address %s\n",
837 						bind_addr );
838 				bind_success = 0;
839 			}
840 		}
841 		if ( bind_success ) {
842 			rc = ldap_pvt_connect(ld, s,
843 					(struct sockaddr *)&sin, sizeof(sin),
844 					async);
845 
846 			if ( (rc == 0) || (rc == -2) ) {
847 				int err = ldap_int_connect_cbs( ld, sb, &s, srv, (struct sockaddr *)&sin );
848 				if ( err )
849 					rc = err;
850 				else
851 					break;
852 			}
853 		}
854 
855 		ldap_pvt_close_socket(ld, s);
856 
857 		if (!use_hp) break;
858 	}
859 	if (ha_buf) LDAP_FREE(ha_buf);
860 #endif
861 
862 	return rc;
863 }
864 
865 #if defined( HAVE_CYRUS_SASL )
866 char *
ldap_host_connected_to(Sockbuf * sb,const char * host)867 ldap_host_connected_to( Sockbuf *sb, const char *host )
868 {
869 	ber_socklen_t	len;
870 #ifdef LDAP_PF_INET6
871 	struct sockaddr_storage sabuf;
872 #else
873 	struct sockaddr sabuf;
874 #endif
875 	struct sockaddr	*sa = (struct sockaddr *) &sabuf;
876 	ber_socket_t	sd;
877 
878 	(void)memset( (char *)sa, '\0', sizeof sabuf );
879 	len = sizeof sabuf;
880 
881 	ber_sockbuf_ctrl( sb, LBER_SB_OPT_GET_FD, &sd );
882 	if ( getpeername( sd, sa, &len ) == -1 ) {
883 		return( NULL );
884 	}
885 
886 	/*
887 	 * do a reverse lookup on the addr to get the official hostname.
888 	 * this is necessary for kerberos to work right, since the official
889 	 * hostname is used as the kerberos instance.
890 	 */
891 
892 	switch (sa->sa_family) {
893 #ifdef LDAP_PF_LOCAL
894 	case AF_LOCAL:
895 		return LDAP_STRDUP( ldap_int_hostname );
896 #endif
897 #ifdef LDAP_PF_INET6
898 	case AF_INET6:
899 		{
900 			struct in6_addr localhost = IN6ADDR_LOOPBACK_INIT;
901 			if( memcmp ( &((struct sockaddr_in6 *)sa)->sin6_addr,
902 				&localhost, sizeof(localhost)) == 0 )
903 			{
904 				return LDAP_STRDUP( ldap_int_hostname );
905 			}
906 		}
907 		break;
908 #endif
909 	case AF_INET:
910 		{
911 			struct in_addr localhost;
912 			localhost.s_addr = htonl( INADDR_ANY );
913 
914 			if( memcmp ( &((struct sockaddr_in *)sa)->sin_addr,
915 				&localhost, sizeof(localhost) ) == 0 )
916 			{
917 				return LDAP_STRDUP( ldap_int_hostname );
918 			}
919 
920 #ifdef INADDR_LOOPBACK
921 			localhost.s_addr = htonl( INADDR_LOOPBACK );
922 
923 			if( memcmp ( &((struct sockaddr_in *)sa)->sin_addr,
924 				&localhost, sizeof(localhost) ) == 0 )
925 			{
926 				return LDAP_STRDUP( ldap_int_hostname );
927 			}
928 #endif
929 		}
930 		break;
931 
932 	default:
933 		return( NULL );
934 		break;
935 	}
936 
937 	{
938 		char *herr;
939 #ifdef NI_MAXHOST
940 		char hbuf[NI_MAXHOST];
941 #elif defined( MAXHOSTNAMELEN )
942 		char hbuf[MAXHOSTNAMELEN];
943 #else
944 		char hbuf[256];
945 #endif
946 		hbuf[0] = 0;
947 
948 		if (ldap_pvt_get_hname( sa, len, hbuf, sizeof(hbuf), &herr ) == 0
949 			&& hbuf[0] )
950 		{
951 			return LDAP_STRDUP( hbuf );
952 		}
953 	}
954 
955 	return host ? LDAP_STRDUP( host ) : NULL;
956 }
957 #endif
958 
959 
960 struct selectinfo {
961 #ifdef HAVE_POLL
962 	/* for UNIX poll(2) */
963 	int si_maxfd;
964 	struct pollfd si_fds[FD_SETSIZE];
965 #else
966 	/* for UNIX select(2) */
967 	fd_set	si_readfds;
968 	fd_set	si_writefds;
969 	fd_set	si_use_readfds;
970 	fd_set	si_use_writefds;
971 #endif
972 };
973 
974 void
ldap_mark_select_write(LDAP * ld,Sockbuf * sb)975 ldap_mark_select_write( LDAP *ld, Sockbuf *sb )
976 {
977 	struct selectinfo	*sip;
978 	ber_socket_t		sd;
979 
980 	sip = (struct selectinfo *)ld->ld_selectinfo;
981 
982 	ber_sockbuf_ctrl( sb, LBER_SB_OPT_GET_FD, &sd );
983 
984 #ifdef HAVE_POLL
985 	/* for UNIX poll(2) */
986 	{
987 		int empty=-1;
988 		int i;
989 		for(i=0; i < sip->si_maxfd; i++) {
990 			if( sip->si_fds[i].fd == sd ) {
991 				sip->si_fds[i].events |= POLL_WRITE;
992 				return;
993 			}
994 			if( empty==-1 && sip->si_fds[i].fd == -1 ) {
995 				empty=i;
996 			}
997 		}
998 
999 		if( empty == -1 ) {
1000 			if( sip->si_maxfd >= FD_SETSIZE ) {
1001 				/* FIXME */
1002 				return;
1003 			}
1004 			empty = sip->si_maxfd++;
1005 		}
1006 
1007 		sip->si_fds[empty].fd = sd;
1008 		sip->si_fds[empty].events = POLL_WRITE;
1009 	}
1010 #else
1011 	/* for UNIX select(2) */
1012 	if ( !FD_ISSET( sd, &sip->si_writefds )) {
1013 		FD_SET( sd, &sip->si_writefds );
1014 	}
1015 #endif
1016 }
1017 
1018 
1019 void
ldap_mark_select_read(LDAP * ld,Sockbuf * sb)1020 ldap_mark_select_read( LDAP *ld, Sockbuf *sb )
1021 {
1022 	struct selectinfo	*sip;
1023 	ber_socket_t		sd;
1024 
1025 	sip = (struct selectinfo *)ld->ld_selectinfo;
1026 
1027 	ber_sockbuf_ctrl( sb, LBER_SB_OPT_GET_FD, &sd );
1028 
1029 #ifdef HAVE_POLL
1030 	/* for UNIX poll(2) */
1031 	{
1032 		int empty=-1;
1033 		int i;
1034 		for(i=0; i < sip->si_maxfd; i++) {
1035 			if( sip->si_fds[i].fd == sd ) {
1036 				sip->si_fds[i].events |= POLL_READ;
1037 				return;
1038 			}
1039 			if( empty==-1 && sip->si_fds[i].fd == -1 ) {
1040 				empty=i;
1041 			}
1042 		}
1043 
1044 		if( empty == -1 ) {
1045 			if( sip->si_maxfd >= FD_SETSIZE ) {
1046 				/* FIXME */
1047 				return;
1048 			}
1049 			empty = sip->si_maxfd++;
1050 		}
1051 
1052 		sip->si_fds[empty].fd = sd;
1053 		sip->si_fds[empty].events = POLL_READ;
1054 	}
1055 #else
1056 	/* for UNIX select(2) */
1057 	if ( !FD_ISSET( sd, &sip->si_readfds )) {
1058 		FD_SET( sd, &sip->si_readfds );
1059 	}
1060 #endif
1061 }
1062 
1063 
1064 void
ldap_mark_select_clear(LDAP * ld,Sockbuf * sb)1065 ldap_mark_select_clear( LDAP *ld, Sockbuf *sb )
1066 {
1067 	struct selectinfo	*sip;
1068 	ber_socket_t		sd;
1069 
1070 	sip = (struct selectinfo *)ld->ld_selectinfo;
1071 
1072 	ber_sockbuf_ctrl( sb, LBER_SB_OPT_GET_FD, &sd );
1073 
1074 #ifdef HAVE_POLL
1075 	/* for UNIX poll(2) */
1076 	{
1077 		int i;
1078 		for(i=0; i < sip->si_maxfd; i++) {
1079 			if( sip->si_fds[i].fd == sd ) {
1080 				sip->si_fds[i].fd = -1;
1081 			}
1082 		}
1083 	}
1084 #else
1085 	/* for UNIX select(2) */
1086 	FD_CLR( sd, &sip->si_writefds );
1087 	FD_CLR( sd, &sip->si_readfds );
1088 #endif
1089 }
1090 
1091 void
ldap_clear_select_write(LDAP * ld,Sockbuf * sb)1092 ldap_clear_select_write( LDAP *ld, Sockbuf *sb )
1093 {
1094 	struct selectinfo	*sip;
1095 	ber_socket_t		sd;
1096 
1097 	sip = (struct selectinfo *)ld->ld_selectinfo;
1098 
1099 	ber_sockbuf_ctrl( sb, LBER_SB_OPT_GET_FD, &sd );
1100 
1101 #ifdef HAVE_POLL
1102 	/* for UNIX poll(2) */
1103 	{
1104 		int i;
1105 		for(i=0; i < sip->si_maxfd; i++) {
1106 			if( sip->si_fds[i].fd == sd ) {
1107 				sip->si_fds[i].events &= ~POLL_WRITE;
1108 			}
1109 		}
1110 	}
1111 #else
1112 	/* for UNIX select(2) */
1113 	FD_CLR( sd, &sip->si_writefds );
1114 #endif
1115 }
1116 
1117 
1118 int
ldap_is_write_ready(LDAP * ld,Sockbuf * sb)1119 ldap_is_write_ready( LDAP *ld, Sockbuf *sb )
1120 {
1121 	struct selectinfo	*sip;
1122 	ber_socket_t		sd;
1123 
1124 	sip = (struct selectinfo *)ld->ld_selectinfo;
1125 
1126 	ber_sockbuf_ctrl( sb, LBER_SB_OPT_GET_FD, &sd );
1127 
1128 #ifdef HAVE_POLL
1129 	/* for UNIX poll(2) */
1130 	{
1131 		int i;
1132 		for(i=0; i < sip->si_maxfd; i++) {
1133 			if( sip->si_fds[i].fd == sd ) {
1134 				return sip->si_fds[i].revents & POLL_WRITE;
1135 			}
1136 		}
1137 
1138 		return 0;
1139 	}
1140 #else
1141 	/* for UNIX select(2) */
1142 	return( FD_ISSET( sd, &sip->si_use_writefds ));
1143 #endif
1144 }
1145 
1146 
1147 int
ldap_is_read_ready(LDAP * ld,Sockbuf * sb)1148 ldap_is_read_ready( LDAP *ld, Sockbuf *sb )
1149 {
1150 	struct selectinfo	*sip;
1151 	ber_socket_t		sd;
1152 
1153 	sip = (struct selectinfo *)ld->ld_selectinfo;
1154 
1155 	if (ber_sockbuf_ctrl( sb, LBER_SB_OPT_DATA_READY, NULL ))
1156 		return 1;
1157 
1158 	ber_sockbuf_ctrl( sb, LBER_SB_OPT_GET_FD, &sd );
1159 
1160 #ifdef HAVE_POLL
1161 	/* for UNIX poll(2) */
1162 	{
1163 		int i;
1164 		for(i=0; i < sip->si_maxfd; i++) {
1165 			if( sip->si_fds[i].fd == sd ) {
1166 				return sip->si_fds[i].revents & POLL_READ;
1167 			}
1168 		}
1169 
1170 		return 0;
1171 	}
1172 #else
1173 	/* for UNIX select(2) */
1174 	return( FD_ISSET( sd, &sip->si_use_readfds ));
1175 #endif
1176 }
1177 
1178 
1179 void *
ldap_new_select_info(void)1180 ldap_new_select_info( void )
1181 {
1182 	struct selectinfo	*sip;
1183 
1184 	sip = (struct selectinfo *)LDAP_CALLOC( 1, sizeof( struct selectinfo ));
1185 
1186 	if ( sip == NULL ) return NULL;
1187 
1188 #ifdef HAVE_POLL
1189 	/* for UNIX poll(2) */
1190 	/* sip->si_maxfd=0 */
1191 #else
1192 	/* for UNIX select(2) */
1193 	FD_ZERO( &sip->si_readfds );
1194 	FD_ZERO( &sip->si_writefds );
1195 #endif
1196 
1197 	return( (void *)sip );
1198 }
1199 
1200 
1201 void
ldap_free_select_info(void * sip)1202 ldap_free_select_info( void *sip )
1203 {
1204 	LDAP_FREE( sip );
1205 }
1206 
1207 
1208 #ifndef HAVE_POLL
1209 int ldap_int_tblsize = 0;
1210 
1211 void
ldap_int_ip_init(void)1212 ldap_int_ip_init( void )
1213 {
1214 #if defined( HAVE_SYSCONF )
1215 	long tblsize = sysconf( _SC_OPEN_MAX );
1216 	if( tblsize > INT_MAX ) tblsize = INT_MAX;
1217 
1218 #elif defined( HAVE_GETDTABLESIZE )
1219 	int tblsize = getdtablesize();
1220 #else
1221 	int tblsize = FD_SETSIZE;
1222 #endif /* !USE_SYSCONF */
1223 
1224 #ifdef FD_SETSIZE
1225 	if( tblsize > FD_SETSIZE ) tblsize = FD_SETSIZE;
1226 #endif	/* FD_SETSIZE */
1227 
1228 	ldap_int_tblsize = tblsize;
1229 }
1230 #endif
1231 
1232 
1233 int
ldap_int_select(LDAP * ld,struct timeval * timeout)1234 ldap_int_select( LDAP *ld, struct timeval *timeout )
1235 {
1236 	int rc;
1237 	struct selectinfo	*sip;
1238 
1239 	Debug0( LDAP_DEBUG_TRACE, "ldap_int_select\n" );
1240 
1241 #ifndef HAVE_POLL
1242 	if ( ldap_int_tblsize == 0 ) ldap_int_ip_init();
1243 #endif
1244 
1245 	sip = (struct selectinfo *)ld->ld_selectinfo;
1246 	assert( sip != NULL );
1247 
1248 #ifdef HAVE_POLL
1249 	{
1250 		int to = timeout ? TV2MILLISEC( timeout ) : INFTIM;
1251 		rc = poll( sip->si_fds, sip->si_maxfd, to );
1252 	}
1253 #else
1254 	sip->si_use_readfds = sip->si_readfds;
1255 	sip->si_use_writefds = sip->si_writefds;
1256 
1257 	rc = select( ldap_int_tblsize,
1258 		&sip->si_use_readfds, &sip->si_use_writefds,
1259 		NULL, timeout );
1260 #endif
1261 
1262 	return rc;
1263 }
1264