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