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 <errno.h> 62 #define USE_SOCKETS 63 #include "cryptlib.h" 64 #include <openssl/bio.h> 65 #if defined(OPENSSL_SYS_NETWARE) && defined(NETWARE_BSDSOCK) 66 #include <netdb.h> 67 #if defined(NETWARE_CLIB) 68 #include <sys/ioctl.h> 69 NETDB_DEFINE_CONTEXT 70 #endif 71 #endif 72 73 #ifndef OPENSSL_NO_SOCK 74 75 #include <openssl/dso.h> 76 77 #define SOCKET_PROTOCOL IPPROTO_TCP 78 79 #ifdef SO_MAXCONN 80 #define MAX_LISTEN SO_MAXCONN 81 #elif defined(SOMAXCONN) 82 #define MAX_LISTEN SOMAXCONN 83 #else 84 #define MAX_LISTEN 32 85 #endif 86 87 #if defined(OPENSSL_SYS_WINDOWS) || (defined(OPENSSL_SYS_NETWARE) && !defined(NETWARE_BSDSOCK)) 88 static int wsa_init_done = 0; 89 #endif 90 91 /* 92 * WSAAPI specifier is required to make indirect calls to run-time 93 * linked WinSock 2 functions used in this module, to be specific 94 * [get|free]addrinfo and getnameinfo. This is because WinSock uses 95 * uses non-C calling convention, __stdcall vs. __cdecl, on x86 96 * Windows. On non-WinSock platforms WSAAPI needs to be void. 97 */ 98 #ifndef WSAAPI 99 #define WSAAPI 100 #endif 101 102 #if 0 103 static unsigned long BIO_ghbn_hits = 0L; 104 static unsigned long BIO_ghbn_miss = 0L; 105 106 #define GHBN_NUM 4 107 static struct ghbn_cache_st { 108 char name[129]; 109 struct hostent *ent; 110 unsigned long order; 111 } ghbn_cache[GHBN_NUM]; 112 #endif 113 114 static int get_ip(const char *str, unsigned char *ip); 115 #if 0 116 static void ghbn_free(struct hostent *a); 117 static struct hostent *ghbn_dup(struct hostent *a); 118 #endif 119 120 int 121 BIO_get_host_ip(const char *str, unsigned char *ip) 122 { 123 int i; 124 int err = 1; 125 int locked = 0; 126 struct hostent *he; 127 128 i = get_ip(str, ip); 129 if (i < 0) { 130 BIOerr(BIO_F_BIO_GET_HOST_IP, BIO_R_INVALID_IP_ADDRESS); 131 goto err; 132 } 133 134 /* At this point, we have something that is most probably correct 135 in some way, so let's init the socket. */ 136 if (BIO_sock_init() != 1) 137 return 0; /* don't generate another error code here */ 138 139 /* If the string actually contained an IP address, we need not do 140 anything more */ 141 if (i > 0) 142 return (1); 143 144 /* do a gethostbyname */ 145 CRYPTO_w_lock(CRYPTO_LOCK_GETHOSTBYNAME); 146 locked = 1; 147 he = BIO_gethostbyname(str); 148 if (he == NULL) { 149 BIOerr(BIO_F_BIO_GET_HOST_IP, BIO_R_BAD_HOSTNAME_LOOKUP); 150 goto err; 151 } 152 153 /* cast to short because of win16 winsock definition */ 154 if ((short)he->h_addrtype != AF_INET) { 155 BIOerr(BIO_F_BIO_GET_HOST_IP, BIO_R_GETHOSTBYNAME_ADDR_IS_NOT_AF_INET); 156 goto err; 157 } 158 for (i = 0; i < 4; i++) 159 ip[i] = he->h_addr_list[0][i]; 160 err = 0; 161 162 err: 163 if (locked) 164 CRYPTO_w_unlock(CRYPTO_LOCK_GETHOSTBYNAME); 165 if (err) { 166 ERR_add_error_data(2, "host=", str); 167 return 0; 168 } else 169 return 1; 170 } 171 172 int 173 BIO_get_port(const char *str, unsigned short *port_ptr) 174 { 175 int i; 176 struct servent *s; 177 178 if (str == NULL) { 179 BIOerr(BIO_F_BIO_GET_PORT, BIO_R_NO_PORT_DEFINED); 180 return (0); 181 } 182 i = atoi(str); 183 if (i != 0) 184 *port_ptr = (unsigned short)i; 185 else { 186 CRYPTO_w_lock(CRYPTO_LOCK_GETSERVBYNAME); 187 s = getservbyname(str, "tcp"); 188 if (s != NULL) 189 *port_ptr = ntohs((unsigned short)s->s_port); 190 CRYPTO_w_unlock(CRYPTO_LOCK_GETSERVBYNAME); 191 if (s == NULL) { 192 if (strcmp(str, "http") == 0) 193 *port_ptr = 80; 194 else if (strcmp(str, "telnet") == 0) 195 *port_ptr = 23; 196 else if (strcmp(str, "socks") == 0) 197 *port_ptr = 1080; 198 else if (strcmp(str, "https") == 0) 199 *port_ptr = 443; 200 else if (strcmp(str, "ssl") == 0) 201 *port_ptr = 443; 202 else if (strcmp(str, "ftp") == 0) 203 *port_ptr = 21; 204 else if (strcmp(str, "gopher") == 0) 205 *port_ptr = 70; 206 #if 0 207 else if (strcmp(str, "wais") == 0) 208 *port_ptr = 21; 209 #endif 210 else { 211 SYSerr(SYS_F_GETSERVBYNAME, errno); 212 ERR_add_error_data(3, "service='", str, "'"); 213 return (0); 214 } 215 } 216 } 217 return (1); 218 } 219 220 int 221 BIO_sock_error(int sock) 222 { 223 int j, i; 224 int size; 225 226 #if defined(OPENSSL_SYS_BEOS_R5) 227 return 0; 228 #endif 229 230 size = sizeof(int); 231 /* Note: under Windows the third parameter is of type (char *) 232 * whereas under other systems it is (void *) if you don't have 233 * a cast it will choke the compiler: if you do have a cast then 234 * you can either go for (char *) or (void *). 235 */ 236 i = getsockopt(sock, SOL_SOCKET, SO_ERROR, (void *)&j, (void *)&size); 237 if (i < 0) 238 return (1); 239 else 240 return (j); 241 } 242 243 struct hostent * 244 BIO_gethostbyname(const char *name) 245 { 246 return gethostbyname(name); 247 } 248 249 250 int 251 BIO_sock_init(void) 252 { 253 return (1); 254 } 255 256 void 257 BIO_sock_cleanup(void) 258 { 259 } 260 261 int 262 BIO_socket_ioctl(int fd, long type, void *arg) 263 { 264 int i; 265 266 #ifdef __DJGPP__ 267 i = ioctl(fd, type, (char *)arg); 268 #else 269 # define ARG arg 270 271 i = ioctl(fd, type, ARG); 272 #endif /* __DJGPP__ */ 273 if (i < 0) 274 SYSerr(SYS_F_IOCTLSOCKET, errno); 275 return (i); 276 } 277 278 /* The reason I have implemented this instead of using sscanf is because 279 * Visual C 1.52c gives an unresolved external when linking a DLL :-( */ 280 static int 281 get_ip(const char *str, unsigned char ip[4]) 282 { 283 unsigned int tmp[4]; 284 int num = 0, c, ok = 0; 285 286 tmp[0] = tmp[1] = tmp[2] = tmp[3] = 0; 287 288 for (;;) { 289 c= *(str++); 290 if ((c >= '0') && (c <= '9')) { 291 ok = 1; 292 tmp[num] = tmp[num]*10 + c-'0'; 293 if (tmp[num] > 255) 294 return (0); 295 } else if (c == '.') { 296 if (!ok) 297 return (-1); 298 if (num == 3) 299 return (0); 300 num++; 301 ok = 0; 302 } else if (c == '\0' && (num == 3) && ok) 303 break; 304 else 305 return (0); 306 } 307 ip[0] = tmp[0]; 308 ip[1] = tmp[1]; 309 ip[2] = tmp[2]; 310 ip[3] = tmp[3]; 311 return (1); 312 } 313 314 int 315 BIO_get_accept_socket(char *host, int bind_mode) 316 { 317 int ret = 0; 318 union { 319 struct sockaddr sa; 320 struct sockaddr_in sa_in; 321 #if OPENSSL_USE_IPV6 322 struct sockaddr_in6 sa_in6; 323 #endif 324 } server, client; 325 int s = -1, cs, addrlen; 326 unsigned char ip[4]; 327 unsigned short port; 328 char *str = NULL, *e; 329 char *h, *p; 330 unsigned long l; 331 int err_num; 332 333 if (BIO_sock_init() != 1) 334 return (-1); 335 336 if ((str = BUF_strdup(host)) == NULL) 337 return (-1); 338 339 h = p = NULL; 340 h = str; 341 for (e = str; *e; e++) { 342 if (*e == ':') { 343 p = e; 344 } else if (*e == '/') { 345 *e = '\0'; 346 break; 347 } 348 } 349 if (p) 350 *p++='\0'; /* points at last ':', '::port' is special [see below] */ 351 else 352 p = h, h = NULL; 353 354 #ifdef EAI_FAMILY 355 do { 356 static union { 357 void *p; 358 int (WSAAPI *f)(const char *, const char *, 359 const struct addrinfo *, 360 struct addrinfo **); 361 } p_getaddrinfo = {NULL}; 362 static union { 363 void *p; 364 void (WSAAPI *f)(struct addrinfo *); 365 } p_freeaddrinfo = {NULL}; 366 struct addrinfo *res, hint; 367 368 if (p_getaddrinfo.p == NULL) { 369 if ((p_getaddrinfo.p = DSO_global_lookup("getaddrinfo"))==NULL || 370 (p_freeaddrinfo.p = DSO_global_lookup("freeaddrinfo"))==NULL) 371 p_getaddrinfo.p = (void*) - 1; 372 } 373 if (p_getaddrinfo.p == (void *) - 1) 374 break; 375 376 /* '::port' enforces IPv6 wildcard listener. Some OSes, 377 * e.g. Solaris, default to IPv6 without any hint. Also 378 * note that commonly IPv6 wildchard socket can service 379 * IPv4 connections just as well... */ 380 memset(&hint, 0, sizeof(hint)); 381 hint.ai_flags = AI_PASSIVE; 382 if (h) { 383 if (strchr(h, ':')) { 384 if (h[1] == '\0') 385 h = NULL; 386 #if OPENSSL_USE_IPV6 387 hint.ai_family = AF_INET6; 388 #else 389 h = NULL; 390 #endif 391 } else if (h[0] == '*' && h[1] == '\0') { 392 hint.ai_family = AF_INET; 393 h = NULL; 394 } 395 } 396 397 if ((*p_getaddrinfo.f)(h, p, &hint, &res)) 398 break; 399 400 addrlen = res->ai_addrlen <= sizeof(server) ? 401 res->ai_addrlen : sizeof(server); 402 memcpy(&server, res->ai_addr, addrlen); 403 404 (*p_freeaddrinfo.f)(res); 405 goto again; 406 } while (0); 407 #endif 408 409 if (!BIO_get_port(p, &port)) 410 goto err; 411 412 memset((char *)&server, 0, sizeof(server)); 413 server.sa_in.sin_family = AF_INET; 414 server.sa_in.sin_port = htons(port); 415 addrlen = sizeof(server.sa_in); 416 417 if (h == NULL || strcmp(h, "*") == 0) 418 server.sa_in.sin_addr.s_addr = INADDR_ANY; 419 else { 420 if (!BIO_get_host_ip(h, &(ip[0]))) 421 goto err; 422 l = (unsigned long)((unsigned long)ip[0]<<24L)| 423 ((unsigned long)ip[1]<<16L)| 424 ((unsigned long)ip[2]<< 8L)| 425 ((unsigned long)ip[3]); 426 server.sa_in.sin_addr.s_addr = htonl(l); 427 } 428 429 again: 430 s = socket(server.sa.sa_family, SOCK_STREAM, SOCKET_PROTOCOL); 431 if (s == -1) { 432 SYSerr(SYS_F_SOCKET, errno); 433 ERR_add_error_data(3, "port='", host, "'"); 434 BIOerr(BIO_F_BIO_GET_ACCEPT_SOCKET, BIO_R_UNABLE_TO_CREATE_SOCKET); 435 goto err; 436 } 437 438 #ifdef SO_REUSEADDR 439 if (bind_mode == BIO_BIND_REUSEADDR) { 440 int i = 1; 441 442 ret = setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (char *)&i, sizeof(i)); 443 bind_mode = BIO_BIND_NORMAL; 444 } 445 #endif 446 if (bind(s, &server.sa, addrlen) == -1) { 447 #ifdef SO_REUSEADDR 448 err_num = errno; 449 if ((bind_mode == BIO_BIND_REUSEADDR_IF_UNUSED) && 450 (err_num == EADDRINUSE)) { 451 client = server; 452 if (h == NULL || strcmp(h, "*") == 0) { 453 #if OPENSSL_USE_IPV6 454 if (client.sa.sa_family == AF_INET6) { 455 memset(&client.sa_in6.sin6_addr, 0, sizeof(client.sa_in6.sin6_addr)); 456 client.sa_in6.sin6_addr.s6_addr[15] = 1; 457 } else 458 #endif 459 if (client.sa.sa_family == AF_INET) { 460 client.sa_in.sin_addr.s_addr = htonl(0x7F000001); 461 } else 462 goto err; 463 } 464 cs = socket(client.sa.sa_family, SOCK_STREAM, SOCKET_PROTOCOL); 465 if (cs != -1) { 466 int ii; 467 ii = connect(cs, &client.sa, addrlen); 468 close(cs); 469 if (ii == -1) { 470 bind_mode = BIO_BIND_REUSEADDR; 471 close(s); 472 goto again; 473 } 474 /* else error */ 475 } 476 /* else error */ 477 } 478 #endif 479 SYSerr(SYS_F_BIND, err_num); 480 ERR_add_error_data(3, "port='", host, "'"); 481 BIOerr(BIO_F_BIO_GET_ACCEPT_SOCKET, BIO_R_UNABLE_TO_BIND_SOCKET); 482 goto err; 483 } 484 if (listen(s, MAX_LISTEN) == -1) { 485 SYSerr(SYS_F_BIND, errno); 486 ERR_add_error_data(3, "port='", host, "'"); 487 BIOerr(BIO_F_BIO_GET_ACCEPT_SOCKET, BIO_R_UNABLE_TO_LISTEN_SOCKET); 488 goto err; 489 } 490 ret = 1; 491 err: 492 if (str != NULL) 493 free(str); 494 if ((ret == 0) && (s != -1)) { 495 close(s); 496 s = -1; 497 } 498 return (s); 499 } 500 501 int 502 BIO_accept(int sock, char **addr) 503 { 504 int ret = -1; 505 unsigned long l; 506 unsigned short port; 507 char *p; 508 509 struct { 510 /* 511 * As for following union. Trouble is that there are platforms 512 * that have socklen_t and there are platforms that don't, on 513 * some platforms socklen_t is int and on some size_t. So what 514 * one can do? One can cook #ifdef spaghetti, which is nothing 515 * but masochistic. Or one can do union between int and size_t. 516 * One naturally does it primarily for 64-bit platforms where 517 * sizeof(int) != sizeof(size_t). But would it work? Note that 518 * if size_t member is initialized to 0, then later int member 519 * assignment naturally does the job on little-endian platforms 520 * regardless accept's expectations! What about big-endians? 521 * If accept expects int*, then it works, and if size_t*, then 522 * length value would appear as unreasonably large. But this 523 * won't prevent it from filling in the address structure. The 524 * trouble of course would be if accept returns more data than 525 * actual buffer can accomodate and overwrite stack... That's 526 * where early OPENSSL_assert comes into picture. Besides, the 527 * only 64-bit big-endian platform found so far that expects 528 * size_t* is HP-UX, where stack grows towards higher address. 529 * <appro> 530 */ 531 union { 532 size_t s; 533 int i; 534 } len; 535 union { 536 struct sockaddr sa; 537 struct sockaddr_in sa_in; 538 #if OPENSSL_USE_IPV6 539 struct sockaddr_in6 sa_in6; 540 #endif 541 } from; 542 } sa; 543 544 sa.len.s = 0; 545 sa.len.i = sizeof(sa.from); 546 memset(&sa.from, 0, sizeof(sa.from)); 547 ret = accept(sock, &sa.from.sa, (void *)&sa.len); 548 if (sizeof(sa.len.i) != sizeof(sa.len.s) && sa.len.i == 0) { 549 OPENSSL_assert(sa.len.s <= sizeof(sa.from)); 550 sa.len.i = (int)sa.len.s; 551 /* use sa.len.i from this point */ 552 } 553 if (ret == -1) { 554 if (BIO_sock_should_retry(ret)) 555 return -2; 556 SYSerr(SYS_F_ACCEPT, errno); 557 BIOerr(BIO_F_BIO_ACCEPT, BIO_R_ACCEPT_ERROR); 558 goto end; 559 } 560 561 if (addr == NULL) 562 goto end; 563 564 #ifdef EAI_FAMILY 565 do { 566 char h[NI_MAXHOST], s[NI_MAXSERV]; 567 size_t nl; 568 static union { 569 void *p; 570 int (WSAAPI *f)(const struct sockaddr *, 571 size_t/*socklen_t*/, char *, size_t, 572 char *, size_t, int); 573 } p_getnameinfo = {NULL}; 574 /* 2nd argument to getnameinfo is specified to 575 * be socklen_t. Unfortunately there is a number 576 * of environments where socklen_t is not defined. 577 * As it's passed by value, it's safe to pass it 578 * as size_t... <appro> */ 579 580 if (p_getnameinfo.p == NULL) { 581 if ((p_getnameinfo.p = DSO_global_lookup("getnameinfo")) == NULL) 582 p_getnameinfo.p = (void*) - 1; 583 } 584 if (p_getnameinfo.p == (void *) - 1) 585 break; 586 587 if ((*p_getnameinfo.f)(&sa.from.sa, sa.len.i, h, sizeof(h), 588 s, sizeof(s), NI_NUMERICHOST|NI_NUMERICSERV)) 589 break; 590 nl = strlen(h) + strlen(s) + 2; 591 p = *addr; 592 if (p) { 593 *p = '\0'; 594 p = realloc(p, nl); 595 } else { 596 p = malloc(nl); 597 } 598 if (p == NULL) { 599 BIOerr(BIO_F_BIO_ACCEPT, ERR_R_MALLOC_FAILURE); 600 goto end; 601 } 602 *addr = p; 603 (void) snprintf(*addr, nl, "%s:%s", h, s); 604 goto end; 605 } while (0); 606 #endif 607 if (sa.from.sa.sa_family != AF_INET) 608 goto end; 609 l = ntohl(sa.from.sa_in.sin_addr.s_addr); 610 port = ntohs(sa.from.sa_in.sin_port); 611 if (*addr == NULL) { 612 if ((p = malloc(24)) == NULL) { 613 BIOerr(BIO_F_BIO_ACCEPT, ERR_R_MALLOC_FAILURE); 614 goto end; 615 } 616 *addr = p; 617 } 618 (void) snprintf(*addr, 24, "%d.%d.%d.%d:%d", 619 (unsigned char)(l >> 24L) & 0xff, (unsigned char)(l >> 16L) & 0xff, 620 (unsigned char)(l >> 8L) & 0xff, (unsigned char)(l) & 0xff, port); 621 622 end: 623 return (ret); 624 } 625 626 int 627 BIO_set_tcp_ndelay(int s, int on) 628 { 629 int ret = 0; 630 #if defined(TCP_NODELAY) && (defined(IPPROTO_TCP) || defined(SOL_TCP)) 631 int opt; 632 633 #ifdef SOL_TCP 634 opt = SOL_TCP; 635 #else 636 #ifdef IPPROTO_TCP 637 opt = IPPROTO_TCP; 638 #endif 639 #endif 640 641 ret = setsockopt(s, opt, TCP_NODELAY, (char *)&on, sizeof(on)); 642 #endif 643 return (ret == 0); 644 } 645 646 int 647 BIO_socket_nbio(int s, int mode) 648 { 649 int ret = -1; 650 int l; 651 652 l = mode; 653 #ifdef FIONBIO 654 ret = BIO_socket_ioctl(s, FIONBIO, &l); 655 #endif 656 return (ret == 0); 657 } 658 #endif 659