NonStop port updates for 3.0.0.
[openssl.git] / apps / lib / s_socket.c
1 /*
2  * Copyright 1995-2020 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the Apache License 2.0 (the "License").  You may not use
5  * this file except in compliance with the License.  You can obtain a copy
6  * in the file LICENSE in the source distribution or at
7  * https://www.openssl.org/source/license.html
8  */
9
10 /* socket-related functions used by s_client and s_server */
11 #include <stdio.h>
12 #include <stdlib.h>
13 #include <string.h>
14 #include <errno.h>
15 #include <signal.h>
16 #include <openssl/opensslconf.h>
17
18 /*
19  * With IPv6, it looks like Digital has mixed up the proper order of
20  * recursive header file inclusion, resulting in the compiler complaining
21  * that u_int isn't defined, but only if _POSIX_C_SOURCE is defined, which is
22  * needed to have fileno() declared correctly...  So let's define u_int
23  */
24 #if defined(OPENSSL_SYS_VMS_DECC) && !defined(__U_INT)
25 # define __U_INT
26 typedef unsigned int u_int;
27 #endif
28
29 #ifndef OPENSSL_NO_SOCK
30
31 # include "apps.h"
32 # include "s_apps.h"
33 # include "internal/sockets.h"
34
35 # if defined(__TANDEM)
36 #  if defined(OPENSSL_TANDEM_FLOSS)
37 #   include <floss.h(floss_read)>
38 #  endif
39 # endif
40
41 # include <openssl/bio.h>
42 # include <openssl/err.h>
43
44 /* Keep track of our peer's address for the cookie callback */
45 BIO_ADDR *ourpeer = NULL;
46
47 /*
48  * init_client - helper routine to set up socket communication
49  * @sock: pointer to storage of resulting socket.
50  * @host: the host name or path (for AF_UNIX) to connect to.
51  * @port: the port to connect to (ignored for AF_UNIX).
52  * @bindhost: source host or path (for AF_UNIX).
53  * @bindport: source port (ignored for AF_UNIX).
54  * @family: desired socket family, may be AF_INET, AF_INET6, AF_UNIX or
55  *  AF_UNSPEC
56  * @type: socket type, must be SOCK_STREAM or SOCK_DGRAM
57  * @protocol: socket protocol, e.g. IPPROTO_TCP or IPPROTO_UDP (or 0 for any)
58  *
59  * This will create a socket and use it to connect to a host:port, or if
60  * family == AF_UNIX, to the path found in host.
61  *
62  * If the host has more than one address, it will try them one by one until
63  * a successful connection is established.  The resulting socket will be
64  * found in *sock on success, it will be given INVALID_SOCKET otherwise.
65  *
66  * Returns 1 on success, 0 on failure.
67  */
68 int init_client(int *sock, const char *host, const char *port,
69                 const char *bindhost, const char *bindport,
70                 int family, int type, int protocol)
71 {
72     BIO_ADDRINFO *res = NULL;
73     BIO_ADDRINFO *bindaddr = NULL;
74     const BIO_ADDRINFO *ai = NULL;
75     const BIO_ADDRINFO *bi = NULL;
76     int found = 0;
77     int ret;
78
79     if (BIO_sock_init() != 1)
80         return 0;
81
82     ret = BIO_lookup_ex(host, port, BIO_LOOKUP_CLIENT, family, type, protocol,
83                         &res);
84     if (ret == 0) {
85         ERR_print_errors(bio_err);
86         return 0;
87     }
88
89     if (bindhost != NULL || bindport != NULL) {
90         ret = BIO_lookup_ex(bindhost, bindport, BIO_LOOKUP_CLIENT,
91                             family, type, protocol, &bindaddr);
92         if (ret == 0) {
93             ERR_print_errors (bio_err);
94             goto out;
95         }
96     }
97
98     ret = 0;
99     for (ai = res; ai != NULL; ai = BIO_ADDRINFO_next(ai)) {
100         /* Admittedly, these checks are quite paranoid, we should not get
101          * anything in the BIO_ADDRINFO chain that we haven't
102          * asked for. */
103         OPENSSL_assert((family == AF_UNSPEC
104                         || family == BIO_ADDRINFO_family(ai))
105                        && (type == 0 || type == BIO_ADDRINFO_socktype(ai))
106                        && (protocol == 0
107                            || protocol == BIO_ADDRINFO_protocol(ai)));
108
109         if (bindaddr != NULL) {
110             for (bi = bindaddr; bi != NULL; bi = BIO_ADDRINFO_next(bi)) {
111                 if (BIO_ADDRINFO_family(bi) == BIO_ADDRINFO_family(ai))
112                     break;
113             }
114             if (bi == NULL)
115                 continue;
116             ++found;
117         }
118
119         *sock = BIO_socket(BIO_ADDRINFO_family(ai), BIO_ADDRINFO_socktype(ai),
120                            BIO_ADDRINFO_protocol(ai), 0);
121         if (*sock == INVALID_SOCKET) {
122             /* Maybe the kernel doesn't support the socket family, even if
123              * BIO_lookup() added it in the returned result...
124              */
125             continue;
126         }
127
128         if (bi != NULL) {
129             if (!BIO_bind(*sock, BIO_ADDRINFO_address(bi),
130                           BIO_SOCK_REUSEADDR)) {
131                 BIO_closesocket(*sock);
132                 *sock = INVALID_SOCKET;
133                 break;
134             }
135         }
136
137 #ifndef OPENSSL_NO_SCTP
138         if (protocol == IPPROTO_SCTP) {
139             /*
140              * For SCTP we have to set various options on the socket prior to
141              * connecting. This is done automatically by BIO_new_dgram_sctp().
142              * We don't actually need the created BIO though so we free it again
143              * immediately.
144              */
145             BIO *tmpbio = BIO_new_dgram_sctp(*sock, BIO_NOCLOSE);
146
147             if (tmpbio == NULL) {
148                 ERR_print_errors(bio_err);
149                 return 0;
150             }
151             BIO_free(tmpbio);
152         }
153 #endif
154
155         if (!BIO_connect(*sock, BIO_ADDRINFO_address(ai),
156                          protocol == IPPROTO_TCP ? BIO_SOCK_NODELAY : 0)) {
157             BIO_closesocket(*sock);
158             *sock = INVALID_SOCKET;
159             continue;
160         }
161
162         /* Success, don't try any more addresses */
163         break;
164     }
165
166     if (*sock == INVALID_SOCKET) {
167         if (bindaddr != NULL && !found) {
168             BIO_printf(bio_err, "Can't bind %saddress for %s%s%s\n",
169                        BIO_ADDRINFO_family(res) == AF_INET6 ? "IPv6 " :
170                        BIO_ADDRINFO_family(res) == AF_INET ? "IPv4 " :
171                        BIO_ADDRINFO_family(res) == AF_UNIX ? "unix " : "",
172                        bindhost != NULL ? bindhost : "",
173                        bindport != NULL ? ":" : "",
174                        bindport != NULL ? bindport : "");
175             ERR_clear_error();
176             ret = 0;
177         }
178         ERR_print_errors(bio_err);
179     } else {
180         /* Remove any stale errors from previous connection attempts */
181         ERR_clear_error();
182         ret = 1;
183     }
184 out:
185     if (bindaddr != NULL) {
186         BIO_ADDRINFO_free (bindaddr);
187     }
188     BIO_ADDRINFO_free(res);
189     return ret;
190 }
191
192 /*
193  * do_server - helper routine to perform a server operation
194  * @accept_sock: pointer to storage of resulting socket.
195  * @host: the host name or path (for AF_UNIX) to connect to.
196  * @port: the port to connect to (ignored for AF_UNIX).
197  * @family: desired socket family, may be AF_INET, AF_INET6, AF_UNIX or
198  *  AF_UNSPEC
199  * @type: socket type, must be SOCK_STREAM or SOCK_DGRAM
200  * @cb: pointer to a function that receives the accepted socket and
201  *  should perform the communication with the connecting client.
202  * @context: pointer to memory that's passed verbatim to the cb function.
203  * @naccept: number of times an incoming connect should be accepted.  If -1,
204  *  unlimited number.
205  *
206  * This will create a socket and use it to listen to a host:port, or if
207  * family == AF_UNIX, to the path found in host, then start accepting
208  * incoming connections and run cb on the resulting socket.
209  *
210  * 0 on failure, something other on success.
211  */
212 int do_server(int *accept_sock, const char *host, const char *port,
213               int family, int type, int protocol, do_server_cb cb,
214               unsigned char *context, int naccept, BIO *bio_s_out)
215 {
216     int asock = 0;
217     int sock;
218     int i;
219     BIO_ADDRINFO *res = NULL;
220     const BIO_ADDRINFO *next;
221     int sock_family, sock_type, sock_protocol, sock_port;
222     const BIO_ADDR *sock_address;
223     int sock_options = BIO_SOCK_REUSEADDR;
224     int ret = 0;
225
226     if (BIO_sock_init() != 1)
227         return 0;
228
229     if (!BIO_lookup_ex(host, port, BIO_LOOKUP_SERVER, family, type, protocol,
230                        &res)) {
231         ERR_print_errors(bio_err);
232         return 0;
233     }
234
235     /* Admittedly, these checks are quite paranoid, we should not get
236      * anything in the BIO_ADDRINFO chain that we haven't asked for */
237     OPENSSL_assert((family == AF_UNSPEC || family == BIO_ADDRINFO_family(res))
238                    && (type == 0 || type == BIO_ADDRINFO_socktype(res))
239                    && (protocol == 0 || protocol == BIO_ADDRINFO_protocol(res)));
240
241     sock_family = BIO_ADDRINFO_family(res);
242     sock_type = BIO_ADDRINFO_socktype(res);
243     sock_protocol = BIO_ADDRINFO_protocol(res);
244     sock_address = BIO_ADDRINFO_address(res);
245     next = BIO_ADDRINFO_next(res);
246     if (sock_family == AF_INET6)
247         sock_options |= BIO_SOCK_V6_ONLY;
248     if (next != NULL
249             && BIO_ADDRINFO_socktype(next) == sock_type
250             && BIO_ADDRINFO_protocol(next) == sock_protocol) {
251         if (sock_family == AF_INET
252                 && BIO_ADDRINFO_family(next) == AF_INET6) {
253             sock_family = AF_INET6;
254             sock_address = BIO_ADDRINFO_address(next);
255         } else if (sock_family == AF_INET6
256                    && BIO_ADDRINFO_family(next) == AF_INET) {
257             sock_options &= ~BIO_SOCK_V6_ONLY;
258         }
259     }
260
261     asock = BIO_socket(sock_family, sock_type, sock_protocol, 0);
262     if (asock == INVALID_SOCKET
263         || !BIO_listen(asock, sock_address, sock_options)) {
264         BIO_ADDRINFO_free(res);
265         ERR_print_errors(bio_err);
266         if (asock != INVALID_SOCKET)
267             BIO_closesocket(asock);
268         goto end;
269     }
270
271 #ifndef OPENSSL_NO_SCTP
272     if (protocol == IPPROTO_SCTP) {
273         /*
274          * For SCTP we have to set various options on the socket prior to
275          * accepting. This is done automatically by BIO_new_dgram_sctp().
276          * We don't actually need the created BIO though so we free it again
277          * immediately.
278          */
279         BIO *tmpbio = BIO_new_dgram_sctp(asock, BIO_NOCLOSE);
280
281         if (tmpbio == NULL) {
282             BIO_closesocket(asock);
283             ERR_print_errors(bio_err);
284             goto end;
285         }
286         BIO_free(tmpbio);
287     }
288 #endif
289
290     sock_port = BIO_ADDR_rawport(sock_address);
291
292     BIO_ADDRINFO_free(res);
293     res = NULL;
294
295     if (sock_port == 0) {
296         /* dynamically allocated port, report which one */
297         union BIO_sock_info_u info;
298         char *hostname = NULL;
299         char *service = NULL;
300         int success = 0;
301
302         if ((info.addr = BIO_ADDR_new()) != NULL
303             && BIO_sock_info(asock, BIO_SOCK_INFO_ADDRESS, &info)
304             && (hostname = BIO_ADDR_hostname_string(info.addr, 1)) != NULL
305             && (service = BIO_ADDR_service_string(info.addr, 1)) != NULL
306             && BIO_printf(bio_s_out,
307                           strchr(hostname, ':') == NULL
308                           ? /* IPv4 */ "ACCEPT %s:%s\n"
309                           : /* IPv6 */ "ACCEPT [%s]:%s\n",
310                           hostname, service) > 0)
311             success = 1;
312
313         (void)BIO_flush(bio_s_out);
314         OPENSSL_free(hostname);
315         OPENSSL_free(service);
316         BIO_ADDR_free(info.addr);
317         if (!success) {
318             BIO_closesocket(asock);
319             ERR_print_errors(bio_err);
320             goto end;
321         }
322     } else {
323         (void)BIO_printf(bio_s_out, "ACCEPT\n");
324         (void)BIO_flush(bio_s_out);
325     }
326
327     if (accept_sock != NULL)
328         *accept_sock = asock;
329     for (;;) {
330         char sink[64];
331         struct timeval timeout;
332         fd_set readfds;
333
334         if (type == SOCK_STREAM) {
335             BIO_ADDR_free(ourpeer);
336             ourpeer = BIO_ADDR_new();
337             if (ourpeer == NULL) {
338                 BIO_closesocket(asock);
339                 ERR_print_errors(bio_err);
340                 goto end;
341             }
342             do {
343                 sock = BIO_accept_ex(asock, ourpeer, 0);
344             } while (sock < 0 && BIO_sock_should_retry(sock));
345             if (sock < 0) {
346                 ERR_print_errors(bio_err);
347                 BIO_closesocket(asock);
348                 break;
349             }
350             BIO_set_tcp_ndelay(sock, 1);
351             i = (*cb)(sock, type, protocol, context);
352
353             /*
354              * If we ended with an alert being sent, but still with data in the
355              * network buffer to be read, then calling BIO_closesocket() will
356              * result in a TCP-RST being sent. On some platforms (notably
357              * Windows) then this will result in the peer immediately abandoning
358              * the connection including any buffered alert data before it has
359              * had a chance to be read. Shutting down the sending side first,
360              * and then closing the socket sends TCP-FIN first followed by
361              * TCP-RST. This seems to allow the peer to read the alert data.
362              */
363             shutdown(sock, 1); /* SHUT_WR */
364             /*
365              * We just said we have nothing else to say, but it doesn't mean
366              * that the other side has nothing. It's even recommended to
367              * consume incoming data. [In testing context this ensures that
368              * alerts are passed on...]
369              */
370             timeout.tv_sec = 0;
371             timeout.tv_usec = 500000;  /* some extreme round-trip */
372             do {
373                 FD_ZERO(&readfds);
374                 openssl_fdset(sock, &readfds);
375             } while (select(sock + 1, &readfds, NULL, NULL, &timeout) > 0
376                      && readsocket(sock, sink, sizeof(sink)) > 0);
377
378             BIO_closesocket(sock);
379         } else {
380             i = (*cb)(asock, type, protocol, context);
381         }
382
383         if (naccept != -1)
384             naccept--;
385         if (i < 0 || naccept == 0) {
386             BIO_closesocket(asock);
387             ret = i;
388             break;
389         }
390     }
391  end:
392 # ifdef AF_UNIX
393     if (family == AF_UNIX)
394         unlink(host);
395 # endif
396     BIO_ADDR_free(ourpeer);
397     ourpeer = NULL;
398     return ret;
399 }
400
401 void do_ssl_shutdown(SSL *ssl)
402 {
403     int ret;
404
405     do {
406         /* We only do unidirectional shutdown */
407         ret = SSL_shutdown(ssl);
408         if (ret < 0) {
409             switch (SSL_get_error(ssl, ret)) {
410             case SSL_ERROR_WANT_READ:
411             case SSL_ERROR_WANT_WRITE:
412             case SSL_ERROR_WANT_ASYNC:
413             case SSL_ERROR_WANT_ASYNC_JOB:
414                 /* We just do busy waiting. Nothing clever */
415                 continue;
416             }
417             ret = 0;
418         }
419     } while (ret < 0);
420 }
421
422 #endif  /* OPENSSL_NO_SOCK */