xref: /openbsd-src/lib/libcrypto/bio/b_sock.c (revision 0b1e30339eeb8f43097c86a51e3f4e526dce5d73)
1 /* crypto/bio/b_sock.c */
2 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
3  * All rights reserved.
4  *
5  * This package is an SSL implementation written
6  * by Eric Young (eay@cryptsoft.com).
7  * The implementation was written so as to conform with Netscapes SSL.
8  *
9  * This library is free for commercial and non-commercial use as long as
10  * the following conditions are aheared to.  The following conditions
11  * apply to all code found in this distribution, be it the RC4, RSA,
12  * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
13  * included with this distribution is covered by the same copyright terms
14  * except that the holder is Tim Hudson (tjh@cryptsoft.com).
15  *
16  * Copyright remains Eric Young's, and as such any Copyright notices in
17  * the code are not to be removed.
18  * If this package is used in a product, Eric Young should be given attribution
19  * as the author of the parts of the library used.
20  * This can be in the form of a textual message at program startup or
21  * in documentation (online or textual) provided with the package.
22  *
23  * Redistribution and use in source and binary forms, with or without
24  * modification, are permitted provided that the following conditions
25  * are met:
26  * 1. Redistributions of source code must retain the copyright
27  *    notice, this list of conditions and the following disclaimer.
28  * 2. Redistributions in binary form must reproduce the above copyright
29  *    notice, this list of conditions and the following disclaimer in the
30  *    documentation and/or other materials provided with the distribution.
31  * 3. All advertising materials mentioning features or use of this software
32  *    must display the following acknowledgement:
33  *    "This product includes cryptographic software written by
34  *     Eric Young (eay@cryptsoft.com)"
35  *    The word 'cryptographic' can be left out if the rouines from the library
36  *    being used are not cryptographic related :-).
37  * 4. If you include any Windows specific code (or a derivative thereof) from
38  *    the apps directory (application code) you must include an acknowledgement:
39  *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
40  *
41  * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
42  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
43  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
44  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
45  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
46  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
47  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
48  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
49  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
50  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
51  * SUCH DAMAGE.
52  *
53  * The licence and distribution terms for any publically available version or
54  * derivative of this code cannot be changed.  i.e. this code cannot simply be
55  * copied and put under another distribution licence
56  * [including the GNU Public Licence.]
57  */
58 
59 #include <sys/ioctl.h>
60 #include <sys/socket.h>
61 
62 #include <netinet/in.h>
63 
64 #include <errno.h>
65 #include <netdb.h>
66 #include <stdio.h>
67 #include <stdlib.h>
68 #include <unistd.h>
69 
70 #include <openssl/bio.h>
71 #include <openssl/dso.h>
72 
73 #include "cryptlib.h"
74 
75 #define SOCKET_PROTOCOL IPPROTO_TCP
76 
77 #ifdef SO_MAXCONN
78 #define MAX_LISTEN  SO_MAXCONN
79 #elif defined(SOMAXCONN)
80 #define MAX_LISTEN  SOMAXCONN
81 #else
82 #define MAX_LISTEN  32
83 #endif
84 
85 static int get_ip(const char *str, unsigned char *ip);
86 
87 int
88 BIO_get_host_ip(const char *str, unsigned char *ip)
89 {
90 	int i;
91 	int err = 1;
92 	int locked = 0;
93 	struct hostent *he;
94 
95 	i = get_ip(str, ip);
96 	if (i < 0) {
97 		BIOerr(BIO_F_BIO_GET_HOST_IP, BIO_R_INVALID_IP_ADDRESS);
98 		goto err;
99 	}
100 
101 	/* At this point, we have something that is most probably correct
102 	   in some way, so let's init the socket. */
103 	if (BIO_sock_init() != 1)
104 		return 0; /* don't generate another error code here */
105 
106 	/* If the string actually contained an IP address, we need not do
107 	   anything more */
108 	if (i > 0)
109 		return (1);
110 
111 	/* do a gethostbyname */
112 	CRYPTO_w_lock(CRYPTO_LOCK_GETHOSTBYNAME);
113 	locked = 1;
114 	he = BIO_gethostbyname(str);
115 	if (he == NULL) {
116 		BIOerr(BIO_F_BIO_GET_HOST_IP, BIO_R_BAD_HOSTNAME_LOOKUP);
117 		goto err;
118 	}
119 
120 	/* cast to short because of win16 winsock definition */
121 	if ((short)he->h_addrtype != AF_INET) {
122 		BIOerr(BIO_F_BIO_GET_HOST_IP, BIO_R_GETHOSTBYNAME_ADDR_IS_NOT_AF_INET);
123 		goto err;
124 	}
125 	for (i = 0; i < 4; i++)
126 		ip[i] = he->h_addr_list[0][i];
127 	err = 0;
128 
129 err:
130 	if (locked)
131 		CRYPTO_w_unlock(CRYPTO_LOCK_GETHOSTBYNAME);
132 	if (err) {
133 		ERR_asprintf_error_data("host=%s", str);
134 		return 0;
135 	} else
136 		return 1;
137 }
138 
139 int
140 BIO_get_port(const char *str, unsigned short *port_ptr)
141 {
142 	int i;
143 	struct servent *s;
144 
145 	if (str == NULL) {
146 		BIOerr(BIO_F_BIO_GET_PORT, BIO_R_NO_PORT_DEFINED);
147 		return (0);
148 	}
149 	i = atoi(str);
150 	if (i != 0)
151 		*port_ptr = (unsigned short)i;
152 	else {
153 		CRYPTO_w_lock(CRYPTO_LOCK_GETSERVBYNAME);
154 		s = getservbyname(str, "tcp");
155 		if (s != NULL)
156 			*port_ptr = ntohs((unsigned short)s->s_port);
157 		CRYPTO_w_unlock(CRYPTO_LOCK_GETSERVBYNAME);
158 		if (s == NULL) {
159 			if (strcmp(str, "http") == 0)
160 				*port_ptr = 80;
161 			else if (strcmp(str, "telnet") == 0)
162 				*port_ptr = 23;
163 			else if (strcmp(str, "socks") == 0)
164 				*port_ptr = 1080;
165 			else if (strcmp(str, "https") == 0)
166 				*port_ptr = 443;
167 			else if (strcmp(str, "ssl") == 0)
168 				*port_ptr = 443;
169 			else if (strcmp(str, "ftp") == 0)
170 				*port_ptr = 21;
171 			else if (strcmp(str, "gopher") == 0)
172 				*port_ptr = 70;
173 			else {
174 				SYSerr(SYS_F_GETSERVBYNAME, errno);
175 				ERR_asprintf_error_data("service='%s'", str);
176 				return (0);
177 			}
178 		}
179 	}
180 	return (1);
181 }
182 
183 int
184 BIO_sock_error(int sock)
185 {
186 	int j, i;
187 	int size;
188 
189 	size = sizeof(int);
190 	/* Note: under Windows the third parameter is of type (char *)
191 	 * whereas under other systems it is (void *) if you don't have
192 	 * a cast it will choke the compiler: if you do have a cast then
193 	 * you can either go for (char *) or (void *).
194 	 */
195 	i = getsockopt(sock, SOL_SOCKET, SO_ERROR, (void *)&j, (void *)&size);
196 	if (i < 0)
197 		return (1);
198 	else
199 		return (j);
200 }
201 
202 struct hostent *
203 BIO_gethostbyname(const char *name)
204 {
205 	return gethostbyname(name);
206 }
207 
208 
209 int
210 BIO_sock_init(void)
211 {
212 	return (1);
213 }
214 
215 void
216 BIO_sock_cleanup(void)
217 {
218 }
219 
220 int
221 BIO_socket_ioctl(int fd, long type, void *arg)
222 {
223 	int i;
224 
225 #  define ARG arg
226 
227 	i = ioctl(fd, type, ARG);
228 	if (i < 0)
229 		SYSerr(SYS_F_IOCTLSOCKET, errno);
230 	return (i);
231 }
232 
233 /* The reason I have implemented this instead of using sscanf is because
234  * Visual C 1.52c gives an unresolved external when linking a DLL :-( */
235 static int
236 get_ip(const char *str, unsigned char ip[4])
237 {
238 	unsigned int tmp[4];
239 	int num = 0, c, ok = 0;
240 
241 	tmp[0] = tmp[1] = tmp[2] = tmp[3] = 0;
242 
243 	for (;;) {
244 		c= *(str++);
245 		if ((c >= '0') && (c <= '9')) {
246 			ok = 1;
247 			tmp[num] = tmp[num]*10 + c-'0';
248 			if (tmp[num] > 255)
249 				return (0);
250 		} else if (c == '.') {
251 			if (!ok)
252 				return (-1);
253 			if (num == 3)
254 				return (0);
255 			num++;
256 			ok = 0;
257 		} else if (c == '\0' && (num == 3) && ok)
258 			break;
259 		else
260 			return (0);
261 	}
262 	ip[0] = tmp[0];
263 	ip[1] = tmp[1];
264 	ip[2] = tmp[2];
265 	ip[3] = tmp[3];
266 	return (1);
267 }
268 
269 int
270 BIO_get_accept_socket(char *host, int bind_mode)
271 {
272 	int ret = 0;
273 	union {
274 		struct sockaddr sa;
275 		struct sockaddr_in sa_in;
276 		struct sockaddr_in6 sa_in6;
277 	} server, client;
278 	int s = -1, cs, addrlen;
279 	unsigned char ip[4];
280 	unsigned short port;
281 	char *str = NULL, *e;
282 	char *h, *p;
283 	unsigned long l;
284 	int err_num;
285 
286 	if (BIO_sock_init() != 1)
287 		return (-1);
288 
289 	if ((str = BUF_strdup(host)) == NULL)
290 		return (-1);
291 
292 	h = p = NULL;
293 	h = str;
294 	for (e = str; *e; e++) {
295 		if (*e == ':') {
296 			p = e;
297 		} else if (*e == '/') {
298 			*e = '\0';
299 			break;
300 		}
301 	}
302 	if (p)
303 		*p++='\0';	/* points at last ':', '::port' is special [see below] */
304 	else
305 		p = h, h = NULL;
306 
307 #ifdef EAI_FAMILY
308 	do {
309 		static union {
310 			void *p;
311 			int (*f)(const char *, const char *,
312 			    const struct addrinfo *,
313 			    struct addrinfo **);
314 		} p_getaddrinfo = {NULL};
315 		static union {
316 			void *p;
317 			void (*f)(struct addrinfo *);
318 		} p_freeaddrinfo = {NULL};
319 		struct addrinfo *res, hint;
320 
321 		if (p_getaddrinfo.p == NULL) {
322 			if ((p_getaddrinfo.p = DSO_global_lookup("getaddrinfo"))==NULL ||
323 			    (p_freeaddrinfo.p = DSO_global_lookup("freeaddrinfo"))==NULL)
324 				p_getaddrinfo.p = (void*) - 1;
325 		}
326 		if (p_getaddrinfo.p == (void *) - 1)
327 			break;
328 
329 		/* '::port' enforces IPv6 wildcard listener. Some OSes,
330 		 * e.g. Solaris, default to IPv6 without any hint. Also
331 		 * note that commonly IPv6 wildchard socket can service
332 		 * IPv4 connections just as well...  */
333 		memset(&hint, 0, sizeof(hint));
334 		hint.ai_flags = AI_PASSIVE;
335 		if (h) {
336 			if (strchr(h, ':')) {
337 				if (h[1] == '\0')
338 					h = NULL;
339 				hint.ai_family = AF_INET6;
340 			} else if (h[0] == '*' && h[1] == '\0') {
341 				hint.ai_family = AF_INET;
342 				h = NULL;
343 			}
344 		}
345 
346 		if ((*p_getaddrinfo.f)(h, p, &hint, &res))
347 			break;
348 
349 		addrlen = res->ai_addrlen <= sizeof(server) ?
350 		    res->ai_addrlen : sizeof(server);
351 		memcpy(&server, res->ai_addr, addrlen);
352 
353 		(*p_freeaddrinfo.f)(res);
354 		goto again;
355 	} while (0);
356 #endif
357 
358 	if (!BIO_get_port(p, &port))
359 		goto err;
360 
361 	memset((char *)&server, 0, sizeof(server));
362 	server.sa_in.sin_family = AF_INET;
363 	server.sa_in.sin_port = htons(port);
364 	addrlen = sizeof(server.sa_in);
365 
366 	if (h == NULL || strcmp(h, "*") == 0)
367 		server.sa_in.sin_addr.s_addr = INADDR_ANY;
368 	else {
369 		if (!BIO_get_host_ip(h, &(ip[0])))
370 			goto err;
371 		l = (unsigned long)((unsigned long)ip[0]<<24L)|
372 		    ((unsigned long)ip[1]<<16L)|
373 		    ((unsigned long)ip[2]<< 8L)|
374 		    ((unsigned long)ip[3]);
375 		server.sa_in.sin_addr.s_addr = htonl(l);
376 	}
377 
378 again:
379 	s = socket(server.sa.sa_family, SOCK_STREAM, SOCKET_PROTOCOL);
380 	if (s == -1) {
381 		SYSerr(SYS_F_SOCKET, errno);
382 		ERR_asprintf_error_data("port='%s'", host);
383 		BIOerr(BIO_F_BIO_GET_ACCEPT_SOCKET, BIO_R_UNABLE_TO_CREATE_SOCKET);
384 		goto err;
385 	}
386 
387 #ifdef SO_REUSEADDR
388 	if (bind_mode == BIO_BIND_REUSEADDR) {
389 		int i = 1;
390 
391 		ret = setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (char *)&i, sizeof(i));
392 		bind_mode = BIO_BIND_NORMAL;
393 	}
394 #endif
395 	if (bind(s, &server.sa, addrlen) == -1) {
396 #ifdef SO_REUSEADDR
397 		err_num = errno;
398 		if ((bind_mode == BIO_BIND_REUSEADDR_IF_UNUSED) &&
399 		    (err_num == EADDRINUSE)) {
400 			client = server;
401 			if (h == NULL || strcmp(h, "*") == 0) {
402 				if (client.sa.sa_family == AF_INET6) {
403 					memset(&client.sa_in6.sin6_addr, 0, sizeof(client.sa_in6.sin6_addr));
404 					client.sa_in6.sin6_addr.s6_addr[15] = 1;
405 				} else if (client.sa.sa_family == AF_INET) {
406 					client.sa_in.sin_addr.s_addr = htonl(0x7F000001);
407 				} else
408 					goto err;
409 			}
410 			cs = socket(client.sa.sa_family, SOCK_STREAM, SOCKET_PROTOCOL);
411 			if (cs != -1) {
412 				int ii;
413 				ii = connect(cs, &client.sa, addrlen);
414 				close(cs);
415 				if (ii == -1) {
416 					bind_mode = BIO_BIND_REUSEADDR;
417 					close(s);
418 					goto again;
419 				}
420 				/* else error */
421 			}
422 			/* else error */
423 		}
424 #endif
425 		SYSerr(SYS_F_BIND, err_num);
426 		ERR_asprintf_error_data("port='%s'", host);
427 		BIOerr(BIO_F_BIO_GET_ACCEPT_SOCKET, BIO_R_UNABLE_TO_BIND_SOCKET);
428 		goto err;
429 	}
430 	if (listen(s, MAX_LISTEN) == -1) {
431 		SYSerr(SYS_F_BIND, errno);
432 		ERR_asprintf_error_data("port='%s'", host);
433 		BIOerr(BIO_F_BIO_GET_ACCEPT_SOCKET, BIO_R_UNABLE_TO_LISTEN_SOCKET);
434 		goto err;
435 	}
436 	ret = 1;
437 err:
438 	free(str);
439 	if ((ret == 0) && (s != -1)) {
440 		close(s);
441 		s = -1;
442 	}
443 	return (s);
444 }
445 
446 int
447 BIO_accept(int sock, char **addr)
448 {
449 	int ret = -1;
450 	unsigned long l;
451 	unsigned short port;
452 	char *p, *tmp;
453 
454 	struct {
455 		socklen_t len;
456 		union {
457 			struct sockaddr sa;
458 			struct sockaddr_in sa_in;
459 			struct sockaddr_in6 sa_in6;
460 		} from;
461 	} sa;
462 
463 	sa.len = sizeof(sa.from);
464 	memset(&sa.from, 0, sizeof(sa.from));
465 	ret = accept(sock, &sa.from.sa, &sa.len);
466 	if (ret == -1) {
467 		if (BIO_sock_should_retry(ret))
468 			return -2;
469 		SYSerr(SYS_F_ACCEPT, errno);
470 		BIOerr(BIO_F_BIO_ACCEPT, BIO_R_ACCEPT_ERROR);
471 		goto end;
472 	}
473 
474 	if (addr == NULL)
475 		goto end;
476 
477 #ifdef EAI_FAMILY
478 	do {
479 		char   h[NI_MAXHOST], s[NI_MAXSERV];
480 		size_t nl;
481 		static union {
482 			void *p;
483 			int (*f)(const struct sockaddr *,
484 			socklen_t, char *, size_t,
485 			    char *, size_t, int);
486 		} p_getnameinfo = {NULL};
487 		/* 2nd argument to getnameinfo is specified to
488 		 * be socklen_t. Unfortunately there is a number
489 		 * of environments where socklen_t is not defined.
490 		 * As it's passed by value, it's safe to pass it
491 		 * as size_t... <appro> */
492 
493 		if (p_getnameinfo.p == NULL) {
494 			if ((p_getnameinfo.p = DSO_global_lookup("getnameinfo")) == NULL)
495 				p_getnameinfo.p = (void*) - 1;
496 		}
497 		if (p_getnameinfo.p == (void *) - 1)
498 			break;
499 
500 		if ((*p_getnameinfo.f)(&sa.from.sa, sa.len, h, sizeof(h),
501 		    s, sizeof(s), NI_NUMERICHOST|NI_NUMERICSERV))
502 			break;
503 		nl = strlen(h) + strlen(s) + 2;
504 		p = *addr;
505 		if (p) {
506 			*p = '\0';
507 			if (!(tmp = realloc(p, nl))) {
508 				close(ret);
509 				ret = -1;
510 				free(p);
511 				*addr = NULL;
512 				BIOerr(BIO_F_BIO_ACCEPT, ERR_R_MALLOC_FAILURE);
513 				goto end;
514 			}
515 			p = tmp;
516 		} else {
517 			p = malloc(nl);
518 		}
519 		if (p == NULL) {
520 			close(ret);
521 			ret = -1;
522 			BIOerr(BIO_F_BIO_ACCEPT, ERR_R_MALLOC_FAILURE);
523 			goto end;
524 		}
525 		*addr = p;
526 		snprintf(*addr, nl, "%s:%s", h, s);
527 		goto end;
528 	} while (0);
529 #endif
530 	if (sa.from.sa.sa_family != AF_INET)
531 		goto end;
532 	l = ntohl(sa.from.sa_in.sin_addr.s_addr);
533 	port = ntohs(sa.from.sa_in.sin_port);
534 	if (*addr == NULL) {
535 		if ((p = malloc(24)) == NULL) {
536 			close(ret);
537 			ret = -1;
538 			BIOerr(BIO_F_BIO_ACCEPT, ERR_R_MALLOC_FAILURE);
539 			goto end;
540 		}
541 		*addr = p;
542 	}
543 	snprintf(*addr, 24, "%d.%d.%d.%d:%d",
544 	    (unsigned char)(l >> 24L) & 0xff, (unsigned char)(l >> 16L) & 0xff,
545 	    (unsigned char)(l >> 8L) & 0xff, (unsigned char)(l) & 0xff, port);
546 
547 end:
548 	return (ret);
549 }
550 
551 int
552 BIO_set_tcp_ndelay(int s, int on)
553 {
554 	int ret = 0;
555 #if defined(TCP_NODELAY) && (defined(IPPROTO_TCP) || defined(SOL_TCP))
556 	int opt;
557 
558 #ifdef SOL_TCP
559 	opt = SOL_TCP;
560 #else
561 #ifdef IPPROTO_TCP
562 	opt = IPPROTO_TCP;
563 #endif
564 #endif
565 
566 	ret = setsockopt(s, opt, TCP_NODELAY, (char *)&on, sizeof(on));
567 #endif
568 	return (ret == 0);
569 }
570 
571 int
572 BIO_socket_nbio(int s, int mode)
573 {
574 	int ret = -1;
575 	int l;
576 
577 	l = mode;
578 	ret = BIO_socket_ioctl(s, FIONBIO, &l);
579 
580 	return (ret == 0);
581 }
582