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 <stdio.h> 60 #include <stdlib.h> 61 #include <unistd.h> 62 #include <errno.h> 63 #include "cryptlib.h" 64 #include <openssl/bio.h> 65 #include <sys/ioctl.h> 66 67 #include <netdb.h> 68 #include <sys/socket.h> 69 #include <netinet/in.h> 70 71 #ifndef OPENSSL_NO_SOCK 72 73 #include <openssl/dso.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_add_error_data(2, "host=", 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_add_error_data(3, "service='", 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_add_error_data(3, "port='", 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_add_error_data(3, "port='", 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_add_error_data(3, "port='", 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 if (str != NULL) 439 free(str); 440 if ((ret == 0) && (s != -1)) { 441 close(s); 442 s = -1; 443 } 444 return (s); 445 } 446 447 int 448 BIO_accept(int sock, char **addr) 449 { 450 int ret = -1; 451 unsigned long l; 452 unsigned short port; 453 char *p; 454 455 struct { 456 /* 457 * As for following union. Trouble is that there are platforms 458 * that have socklen_t and there are platforms that don't, on 459 * some platforms socklen_t is int and on some size_t. So what 460 * one can do? One can cook #ifdef spaghetti, which is nothing 461 * but masochistic. Or one can do union between int and size_t. 462 * One naturally does it primarily for 64-bit platforms where 463 * sizeof(int) != sizeof(size_t). But would it work? Note that 464 * if size_t member is initialized to 0, then later int member 465 * assignment naturally does the job on little-endian platforms 466 * regardless accept's expectations! What about big-endians? 467 * If accept expects int*, then it works, and if size_t*, then 468 * length value would appear as unreasonably large. But this 469 * won't prevent it from filling in the address structure. The 470 * trouble of course would be if accept returns more data than 471 * actual buffer can accomodate and overwrite stack... That's 472 * where early OPENSSL_assert comes into picture. Besides, the 473 * only 64-bit big-endian platform found so far that expects 474 * size_t* is HP-UX, where stack grows towards higher address. 475 * <appro> 476 */ 477 union { 478 size_t s; 479 int i; 480 } len; 481 union { 482 struct sockaddr sa; 483 struct sockaddr_in sa_in; 484 struct sockaddr_in6 sa_in6; 485 } from; 486 } sa; 487 488 sa.len.s = 0; 489 sa.len.i = sizeof(sa.from); 490 memset(&sa.from, 0, sizeof(sa.from)); 491 ret = accept(sock, &sa.from.sa, (void *)&sa.len); 492 if (sizeof(sa.len.i) != sizeof(sa.len.s) && sa.len.i == 0) { 493 OPENSSL_assert(sa.len.s <= sizeof(sa.from)); 494 sa.len.i = (int)sa.len.s; 495 /* use sa.len.i from this point */ 496 } 497 if (ret == -1) { 498 if (BIO_sock_should_retry(ret)) 499 return -2; 500 SYSerr(SYS_F_ACCEPT, errno); 501 BIOerr(BIO_F_BIO_ACCEPT, BIO_R_ACCEPT_ERROR); 502 goto end; 503 } 504 505 if (addr == NULL) 506 goto end; 507 508 #ifdef EAI_FAMILY 509 do { 510 char h[NI_MAXHOST], s[NI_MAXSERV]; 511 size_t nl; 512 static union { 513 void *p; 514 int (*f)(const struct sockaddr *, 515 size_t/*socklen_t*/, char *, size_t, 516 char *, size_t, int); 517 } p_getnameinfo = {NULL}; 518 /* 2nd argument to getnameinfo is specified to 519 * be socklen_t. Unfortunately there is a number 520 * of environments where socklen_t is not defined. 521 * As it's passed by value, it's safe to pass it 522 * as size_t... <appro> */ 523 524 if (p_getnameinfo.p == NULL) { 525 if ((p_getnameinfo.p = DSO_global_lookup("getnameinfo")) == NULL) 526 p_getnameinfo.p = (void*) - 1; 527 } 528 if (p_getnameinfo.p == (void *) - 1) 529 break; 530 531 if ((*p_getnameinfo.f)(&sa.from.sa, sa.len.i, h, sizeof(h), 532 s, sizeof(s), NI_NUMERICHOST|NI_NUMERICSERV)) 533 break; 534 nl = strlen(h) + strlen(s) + 2; 535 p = *addr; 536 if (p) { 537 *p = '\0'; 538 p = realloc(p, nl); 539 } else { 540 p = malloc(nl); 541 } 542 if (p == NULL) { 543 BIOerr(BIO_F_BIO_ACCEPT, ERR_R_MALLOC_FAILURE); 544 goto end; 545 } 546 *addr = p; 547 (void) snprintf(*addr, nl, "%s:%s", h, s); 548 goto end; 549 } while (0); 550 #endif 551 if (sa.from.sa.sa_family != AF_INET) 552 goto end; 553 l = ntohl(sa.from.sa_in.sin_addr.s_addr); 554 port = ntohs(sa.from.sa_in.sin_port); 555 if (*addr == NULL) { 556 if ((p = malloc(24)) == NULL) { 557 BIOerr(BIO_F_BIO_ACCEPT, ERR_R_MALLOC_FAILURE); 558 goto end; 559 } 560 *addr = p; 561 } 562 (void) snprintf(*addr, 24, "%d.%d.%d.%d:%d", 563 (unsigned char)(l >> 24L) & 0xff, (unsigned char)(l >> 16L) & 0xff, 564 (unsigned char)(l >> 8L) & 0xff, (unsigned char)(l) & 0xff, port); 565 566 end: 567 return (ret); 568 } 569 570 int 571 BIO_set_tcp_ndelay(int s, int on) 572 { 573 int ret = 0; 574 #if defined(TCP_NODELAY) && (defined(IPPROTO_TCP) || defined(SOL_TCP)) 575 int opt; 576 577 #ifdef SOL_TCP 578 opt = SOL_TCP; 579 #else 580 #ifdef IPPROTO_TCP 581 opt = IPPROTO_TCP; 582 #endif 583 #endif 584 585 ret = setsockopt(s, opt, TCP_NODELAY, (char *)&on, sizeof(on)); 586 #endif 587 return (ret == 0); 588 } 589 590 int 591 BIO_socket_nbio(int s, int mode) 592 { 593 int ret = -1; 594 int l; 595 596 l = mode; 597 #ifdef FIONBIO 598 ret = BIO_socket_ioctl(s, FIONBIO, &l); 599 #endif 600 return (ret == 0); 601 } 602 #endif 603