2 * apps/s_socket.c - socket-related functions used by s_client and s_server
4 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
7 * This package is an SSL implementation written
8 * by Eric Young (eay@cryptsoft.com).
9 * The implementation was written so as to conform with Netscapes SSL.
11 * This library is free for commercial and non-commercial use as long as
12 * the following conditions are aheared to. The following conditions
13 * apply to all code found in this distribution, be it the RC4, RSA,
14 * lhash, DES, etc., code; not just the SSL code. The SSL documentation
15 * included with this distribution is covered by the same copyright terms
16 * except that the holder is Tim Hudson (tjh@cryptsoft.com).
18 * Copyright remains Eric Young's, and as such any Copyright notices in
19 * the code are not to be removed.
20 * If this package is used in a product, Eric Young should be given attribution
21 * as the author of the parts of the library used.
22 * This can be in the form of a textual message at program startup or
23 * in documentation (online or textual) provided with the package.
25 * Redistribution and use in source and binary forms, with or without
26 * modification, are permitted provided that the following conditions
28 * 1. Redistributions of source code must retain the copyright
29 * notice, this list of conditions and the following disclaimer.
30 * 2. Redistributions in binary form must reproduce the above copyright
31 * notice, this list of conditions and the following disclaimer in the
32 * documentation and/or other materials provided with the distribution.
33 * 3. All advertising materials mentioning features or use of this software
34 * must display the following acknowledgement:
35 * "This product includes cryptographic software written by
36 * Eric Young (eay@cryptsoft.com)"
37 * The word 'cryptographic' can be left out if the rouines from the library
38 * being used are not cryptographic related :-).
39 * 4. If you include any Windows specific code (or a derivative thereof) from
40 * the apps directory (application code) you must include an acknowledgement:
41 * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
43 * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
44 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
45 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
46 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
47 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
48 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
49 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
50 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
51 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
52 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
55 * The licence and distribution terms for any publically available version or
56 * derivative of this code cannot be changed. i.e. this code cannot simply be
57 * copied and put under another distribution licence
58 * [including the GNU Public Licence.]
68 * With IPv6, it looks like Digital has mixed up the proper order of
69 * recursive header file inclusion, resulting in the compiler complaining
70 * that u_int isn't defined, but only if _POSIX_C_SOURCE is defined, which is
71 * needed to have fileno() declared correctly... So let's define u_int
73 #if defined(OPENSSL_SYS_VMS_DECC) && !defined(__U_INT)
75 typedef unsigned int u_int;
84 #include <openssl/ssl.h>
92 #ifndef OPENSSL_NO_SOCK
94 # if defined(OPENSSL_SYS_NETWARE) && defined(NETWARE_BSDSOCK)
98 static struct hostent *GetHostByName(const char *name);
99 # if defined(OPENSSL_SYS_WINDOWS) || (defined(OPENSSL_SYS_NETWARE) && !defined(NETWARE_BSDSOCK))
100 static void ssl_sock_cleanup(void);
102 static int ssl_sock_init(void);
103 static int init_client_ip(int *sock, const unsigned char ip[4], int port,
105 static int init_server(int *sock, int port, int type);
106 static int init_server_long(int *sock, int port, char *ip, int type);
107 static int do_accept(int acc_sock, int *sock, char **host);
108 static int host_ip(const char *str, unsigned char ip[4]);
110 static int init_server_unix(int *sock, const char *path);
111 static int do_accept_unix(int acc_sock, int *sock);
114 # if defined(OPENSSL_SYS_NETWARE) && !defined(NETWARE_BSDSOCK)
115 static int wsa_init_done = 0;
118 # ifdef OPENSSL_SYS_WINDOWS
119 static struct WSAData wsa_state;
120 static int wsa_init_done = 0;
122 # endif /* OPENSSL_SYS_WINDOWS */
124 # ifdef OPENSSL_SYS_WINDOWS
125 static void ssl_sock_cleanup(void)
129 # ifndef OPENSSL_SYS_WINCE
130 WSACancelBlockingCall();
135 # elif defined(OPENSSL_SYS_NETWARE) && !defined(NETWARE_BSDSOCK)
136 static void sock_cleanup(void)
145 static int ssl_sock_init(void)
148 extern int _watt_do_exit;
152 # elif defined(OPENSSL_SYS_WINDOWS)
153 if (!wsa_init_done) {
157 signal(SIGINT, (void (*)(int))ssl_sock_cleanup);
160 memset(&wsa_state, 0, sizeof(wsa_state));
161 if (WSAStartup(0x0101, &wsa_state) != 0) {
162 err = WSAGetLastError();
163 BIO_printf(bio_err, "unable to start WINSOCK, error code=%d\n",
168 # elif defined(OPENSSL_SYS_NETWARE) && !defined(NETWARE_BSDSOCK)
173 if (!wsa_init_done) {
176 signal(SIGINT, (void (*)(int))sock_cleanup);
180 wVerReq = MAKEWORD(2, 0);
181 err = WSAStartup(wVerReq, &wsaData);
183 BIO_printf(bio_err, "unable to start WINSOCK2, error code=%d\n",
188 # endif /* OPENSSL_SYS_WINDOWS */
192 int init_client(int *sock, const char *host, int port, int type)
196 ip[0] = ip[1] = ip[2] = ip[3] = 0;
197 if (!host_ip(host, &(ip[0])))
199 return init_client_ip(sock, ip, port, type);
202 static int init_client_ip(int *sock, const unsigned char ip[4], int port,
206 struct sockaddr_in them;
209 if (!ssl_sock_init())
212 memset((char *)&them, 0, sizeof(them));
213 them.sin_family = AF_INET;
214 them.sin_port = htons((unsigned short)port);
215 addr = (unsigned long)
216 ((unsigned long)ip[0] << 24L) |
217 ((unsigned long)ip[1] << 16L) |
218 ((unsigned long)ip[2] << 8L) | ((unsigned long)ip[3]);
219 them.sin_addr.s_addr = htonl(addr);
221 if (type == SOCK_STREAM)
222 s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
223 else /* ( type == SOCK_DGRAM) */
224 s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
226 if (s == INVALID_SOCKET) {
230 # if defined(SO_KEEPALIVE)
231 if (type == SOCK_STREAM) {
233 i = setsockopt(s, SOL_SOCKET, SO_KEEPALIVE, (char *)&i, sizeof(i));
242 if (connect(s, (struct sockaddr *)&them, sizeof(them)) == -1) {
252 int init_client_unix(int *sock, const char *server)
254 struct sockaddr_un them;
257 if (strlen(server) > (UNIX_PATH_MAX + 1))
259 if (!ssl_sock_init())
262 s = socket(AF_UNIX, SOCK_STREAM, 0);
263 if (s == INVALID_SOCKET) {
268 memset((char *)&them, 0, sizeof(them));
269 them.sun_family = AF_UNIX;
270 strcpy(them.sun_path, server);
272 if (connect(s, (struct sockaddr *)&them, sizeof(them)) == -1) {
282 int do_server(int port, int type, int *ret,
283 int (*cb) (char *hostname, int s, int stype,
284 unsigned char *context), unsigned char *context,
289 int accept_socket = 0;
292 if (!init_server(&accept_socket, port, type))
296 *ret = accept_socket;
300 if (type == SOCK_STREAM) {
301 # ifdef OPENSSL_SSL_DEBUG_BROKEN_PROTOCOL
302 if (do_accept(accept_socket, &sock, NULL) == 0)
304 if (do_accept(accept_socket, &sock, &name) == 0)
307 SHUTDOWN(accept_socket);
311 sock = accept_socket;
312 i = (*cb) (name, sock, type, context);
315 if (type == SOCK_STREAM)
319 if (i < 0 || naccept == 0) {
320 SHUTDOWN2(accept_socket);
327 int do_server_unix(const char *path, int *ret,
328 int (*cb) (char *hostname, int s, int stype,
329 unsigned char *context), unsigned char *context,
333 int accept_socket = 0;
336 if (!init_server_unix(&accept_socket, path))
340 *ret = accept_socket;
342 if (do_accept_unix(accept_socket, &sock) == 0) {
343 SHUTDOWN(accept_socket);
347 i = (*cb) (NULL, sock, 0, context);
351 if (i < 0 || naccept == 0) {
352 SHUTDOWN2(accept_socket);
362 static int init_server_long(int *sock, int port, char *ip, int type)
365 struct sockaddr_in server;
368 if (!ssl_sock_init())
371 memset((char *)&server, 0, sizeof(server));
372 server.sin_family = AF_INET;
373 server.sin_port = htons((unsigned short)port);
375 server.sin_addr.s_addr = INADDR_ANY;
377 /* Added for T3E, address-of fails on bit field (beckman@acl.lanl.gov) */
378 # ifndef BIT_FIELD_LIMITS
379 memcpy(&server.sin_addr.s_addr, ip, 4);
381 memcpy(&server.sin_addr, ip, 4);
384 if (type == SOCK_STREAM)
385 s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
386 else /* type == SOCK_DGRAM */
387 s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
389 if (s == INVALID_SOCKET)
391 # if defined SOL_SOCKET && defined SO_REUSEADDR
394 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (void *)&j, sizeof j);
397 if (bind(s, (struct sockaddr *)&server, sizeof(server)) == -1) {
398 # ifndef OPENSSL_SYS_WINDOWS
403 /* Make it 128 for linux */
404 if (type == SOCK_STREAM && listen(s, 128) == -1)
409 if ((ret == 0) && (s != -1)) {
415 static int init_server(int *sock, int port, int type)
417 return (init_server_long(sock, port, NULL, type));
421 static int init_server_unix(int *sock, const char *path)
424 struct sockaddr_un server;
427 if (strlen(path) > (UNIX_PATH_MAX + 1))
429 if (!ssl_sock_init())
432 s = socket(AF_UNIX, SOCK_STREAM, 0);
433 if (s == INVALID_SOCKET)
436 memset((char *)&server, 0, sizeof(server));
437 server.sun_family = AF_UNIX;
438 strcpy(server.sun_path, path);
440 if (bind(s, (struct sockaddr *)&server, sizeof(server)) == -1) {
441 # ifndef OPENSSL_SYS_WINDOWS
446 /* Make it 128 for linux */
447 if (listen(s, 128) == -1) {
448 # ifndef OPENSSL_SYS_WINDOWS
457 if ((ret == 0) && (s != -1)) {
464 static int do_accept(int acc_sock, int *sock, char **host)
467 struct hostent *h1, *h2;
468 static struct sockaddr_in from;
470 /* struct linger ling; */
472 if (!ssl_sock_init())
475 # ifndef OPENSSL_SYS_WINDOWS
479 memset((char *)&from, 0, sizeof(from));
482 * Note: under VMS with SOCKETSHR the fourth parameter is currently of
483 * type (int *) whereas under other systems it is (void *) if you don't
484 * have a cast it will choke the compiler: if you do have a cast then you
485 * can either go for (int *) or (void *).
487 ret = accept(acc_sock, (struct sockaddr *)&from, (void *)&len);
488 if (ret == INVALID_SOCKET) {
489 # if defined(OPENSSL_SYS_WINDOWS) || (defined(OPENSSL_SYS_NETWARE) && !defined(NETWARE_BSDSOCK))
491 i = WSAGetLastError();
492 BIO_printf(bio_err, "accept error %d\n", i);
494 if (errno == EINTR) {
500 fprintf(stderr, "errno=%d ", errno);
509 i=setsockopt(ret,SOL_SOCKET,SO_LINGER,(char *)&ling,sizeof(ling));
510 if (i < 0) { perror("linger"); return(0); }
512 i=setsockopt(ret,SOL_SOCKET,SO_KEEPALIVE,(char *)&i,sizeof(i));
513 if (i < 0) { perror("keepalive"); return(0); }
518 # ifndef BIT_FIELD_LIMITS
519 /* I should use WSAAsyncGetHostByName() under windows */
520 h1 = gethostbyaddr((char *)&from.sin_addr.s_addr,
521 sizeof(from.sin_addr.s_addr), AF_INET);
523 h1 = gethostbyaddr((char *)&from.sin_addr,
524 sizeof(struct in_addr), AF_INET);
527 BIO_printf(bio_err, "bad gethostbyaddr\n");
531 if ((*host = (char *)OPENSSL_malloc(strlen(h1->h_name) + 1)) == NULL) {
532 perror("OPENSSL_malloc");
536 BUF_strlcpy(*host, h1->h_name, strlen(h1->h_name) + 1);
538 h2 = GetHostByName(*host);
540 BIO_printf(bio_err, "gethostbyname failure\n");
544 if (h2->h_addrtype != AF_INET) {
545 BIO_printf(bio_err, "gethostbyname addr is not AF_INET\n");
556 static int do_accept_unix(int acc_sock, int *sock)
560 if (!ssl_sock_init())
564 ret = accept(acc_sock, NULL, NULL);
565 if (ret == INVALID_SOCKET) {
566 if (errno == EINTR) {
572 fprintf(stderr, "errno=%d ", errno);
582 int extract_host_port(char *str, char **host_ptr, unsigned char *ip,
588 p = strchr(str, ':');
590 BIO_printf(bio_err, "no port defined\n");
595 if ((ip != NULL) && !host_ip(str, ip))
597 if (host_ptr != NULL)
600 if (!extract_port(p, port_ptr))
607 static int host_ip(const char *str, unsigned char ip[4])
612 if (sscanf(str, "%u.%u.%u.%u", &(in[0]), &(in[1]), &(in[2]), &(in[3])) ==
614 for (i = 0; i < 4; i++)
616 BIO_printf(bio_err, "invalid IP address\n");
623 } else { /* do a gethostbyname */
626 if (!ssl_sock_init())
629 he = GetHostByName(str);
631 BIO_printf(bio_err, "gethostbyname failure\n");
634 if (he->h_addrtype != AF_INET) {
635 BIO_printf(bio_err, "gethostbyname addr is not AF_INET\n");
638 ip[0] = he->h_addr_list[0][0];
639 ip[1] = he->h_addr_list[0][1];
640 ip[2] = he->h_addr_list[0][2];
641 ip[3] = he->h_addr_list[0][3];
648 int extract_port(const char *str, short *port_ptr)
655 *port_ptr = (unsigned short)i;
657 s = getservbyname(str, "tcp");
659 BIO_printf(bio_err, "getservbyname failure for %s\n", str);
662 *port_ptr = ntohs((unsigned short)s->s_port);
668 static struct ghbn_cache_st {
672 } ghbn_cache[GHBN_NUM];
674 static unsigned long ghbn_hits = 0L;
675 static unsigned long ghbn_miss = 0L;
677 static struct hostent *GetHostByName(const char *name)
681 unsigned long low = (unsigned long)-1;
683 for (i = 0; i < GHBN_NUM; i++) {
684 if (low > ghbn_cache[i].order) {
685 low = ghbn_cache[i].order;
688 if (ghbn_cache[i].order > 0) {
689 if (strncmp(name, ghbn_cache[i].name, 128) == 0)
693 if (i == GHBN_NUM) { /* no hit */
695 ret = gethostbyname(name);
698 /* else add to cache */
699 if (strlen(name) < sizeof ghbn_cache[0].name) {
700 strcpy(ghbn_cache[lowi].name, name);
701 memcpy((char *)&(ghbn_cache[lowi].ent), ret,
702 sizeof(struct hostent));
703 ghbn_cache[lowi].order = ghbn_miss + ghbn_hits;
708 ret = &(ghbn_cache[i].ent);
709 ghbn_cache[i].order = ghbn_miss + ghbn_hits;