5ae689a4db9de62947b90ae13028d64a42782920
[openssl.git] / apps / lib / s_socket.c
1 /*
2  * Copyright 1995-2022 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 #ifdef _WIN32
30 # include <process.h>
31
32 /* MSVC renamed some POSIX functions to have an underscore prefix. */
33 # ifdef _MSC_VER
34 #  define getpid _getpid
35 # endif
36 #endif
37
38 #ifndef OPENSSL_NO_SOCK
39
40 # include "apps.h"
41 # include "s_apps.h"
42 # include "internal/sockets.h"
43
44 # if defined(__TANDEM)
45 #  if defined(OPENSSL_TANDEM_FLOSS)
46 #   include <floss.h(floss_read)>
47 #  endif
48 # endif
49
50 # include <openssl/bio.h>
51 # include <openssl/err.h>
52
53 /* Keep track of our peer's address for the cookie callback */
54 BIO_ADDR *ourpeer = NULL;
55
56 /*
57  * init_client - helper routine to set up socket communication
58  * @sock: pointer to storage of resulting socket.
59  * @host: the hostname or path (for AF_UNIX) to connect to.
60  * @port: the port to connect to (ignored for AF_UNIX).
61  * @bindhost: source host or path (for AF_UNIX).
62  * @bindport: source port (ignored for AF_UNIX).
63  * @family: desired socket family, may be AF_INET, AF_INET6, AF_UNIX or
64  *  AF_UNSPEC
65  * @type: socket type, must be SOCK_STREAM or SOCK_DGRAM
66  * @protocol: socket protocol, e.g. IPPROTO_TCP or IPPROTO_UDP (or 0 for any)
67  * @tfo: flag to enable TCP Fast Open
68  * @doconn: whether we should call BIO_connect() on the socket
69  * @ba_ret: BIO_ADDR for the remote peer, to be freed by caller
70  *
71  * This will create a socket and use it to connect to a host:port, or if
72  * family == AF_UNIX, to the path found in host.
73  *
74  * If the host has more than one address, it will try them one by one until
75  * a successful connection is established.  The resulting socket will be
76  * found in *sock on success, it will be given INVALID_SOCKET otherwise.
77  *
78  * Returns 1 on success, 0 on failure.
79  */
80 int init_client(int *sock, const char *host, const char *port,
81                 const char *bindhost, const char *bindport,
82                 int family, int type, int protocol, int tfo, int doconn,
83                 BIO_ADDR **ba_ret)
84 {
85     BIO_ADDRINFO *res = NULL;
86     BIO_ADDRINFO *bindaddr = NULL;
87     const BIO_ADDRINFO *ai = NULL;
88     const BIO_ADDRINFO *bi = NULL;
89     int found = 0;
90     int ret;
91     int options = 0;
92
93     if (tfo && ba_ret != NULL)
94         *ba_ret = NULL;
95
96     if (BIO_sock_init() != 1)
97         return 0;
98
99     ret = BIO_lookup_ex(host, port, BIO_LOOKUP_CLIENT, family, type, protocol,
100                         &res);
101     if (ret == 0) {
102         ERR_print_errors(bio_err);
103         return 0;
104     }
105
106     if (bindhost != NULL || bindport != NULL) {
107         ret = BIO_lookup_ex(bindhost, bindport, BIO_LOOKUP_CLIENT,
108                             family, type, protocol, &bindaddr);
109         if (ret == 0) {
110             ERR_print_errors (bio_err);
111             goto out;
112         }
113     }
114
115     ret = 0;
116     for (ai = res; ai != NULL; ai = BIO_ADDRINFO_next(ai)) {
117         /* Admittedly, these checks are quite paranoid, we should not get
118          * anything in the BIO_ADDRINFO chain that we haven't
119          * asked for. */
120         OPENSSL_assert((family == AF_UNSPEC
121                         || family == BIO_ADDRINFO_family(ai))
122                        && (type == 0 || type == BIO_ADDRINFO_socktype(ai))
123                        && (protocol == 0
124                            || protocol == BIO_ADDRINFO_protocol(ai)));
125
126         if (bindaddr != NULL) {
127             for (bi = bindaddr; bi != NULL; bi = BIO_ADDRINFO_next(bi)) {
128                 if (BIO_ADDRINFO_family(bi) == BIO_ADDRINFO_family(ai))
129                     break;
130             }
131             if (bi == NULL)
132                 continue;
133             ++found;
134         }
135
136         *sock = BIO_socket(BIO_ADDRINFO_family(ai), BIO_ADDRINFO_socktype(ai),
137                            BIO_ADDRINFO_protocol(ai), 0);
138         if (*sock == INVALID_SOCKET) {
139             /* Maybe the kernel doesn't support the socket family, even if
140              * BIO_lookup() added it in the returned result...
141              */
142             continue;
143         }
144
145         if (bi != NULL) {
146             if (!BIO_bind(*sock, BIO_ADDRINFO_address(bi),
147                           BIO_SOCK_REUSEADDR)) {
148                 BIO_closesocket(*sock);
149                 *sock = INVALID_SOCKET;
150                 break;
151             }
152         }
153
154 #ifndef OPENSSL_NO_SCTP
155         if (protocol == IPPROTO_SCTP) {
156             /*
157              * For SCTP we have to set various options on the socket prior to
158              * connecting. This is done automatically by BIO_new_dgram_sctp().
159              * We don't actually need the created BIO though so we free it again
160              * immediately.
161              */
162             BIO *tmpbio = BIO_new_dgram_sctp(*sock, BIO_NOCLOSE);
163
164             if (tmpbio == NULL) {
165                 ERR_print_errors(bio_err);
166                 return 0;
167             }
168             BIO_free(tmpbio);
169         }
170 #endif
171         if (BIO_ADDRINFO_protocol(ai) == IPPROTO_TCP) {
172             options |= BIO_SOCK_NODELAY;
173             if (tfo)
174                 options |= BIO_SOCK_TFO;
175         }
176
177         if (doconn && !BIO_connect(*sock, BIO_ADDRINFO_address(ai), options)) {
178             BIO_closesocket(*sock);
179             *sock = INVALID_SOCKET;
180             continue;
181         }
182
183         /* Save the address */
184         if (tfo || !doconn)
185             *ba_ret = BIO_ADDR_dup(BIO_ADDRINFO_address(ai));
186
187         /* Success, don't try any more addresses */
188         break;
189     }
190
191     if (*sock == INVALID_SOCKET) {
192         if (bindaddr != NULL && !found) {
193             BIO_printf(bio_err, "Can't bind %saddress for %s%s%s\n",
194 #ifdef AF_INET6
195                        BIO_ADDRINFO_family(res) == AF_INET6 ? "IPv6 " :
196 #endif
197                        BIO_ADDRINFO_family(res) == AF_INET ? "IPv4 " :
198                        BIO_ADDRINFO_family(res) == AF_UNIX ? "unix " : "",
199                        bindhost != NULL ? bindhost : "",
200                        bindport != NULL ? ":" : "",
201                        bindport != NULL ? bindport : "");
202             ERR_clear_error();
203             ret = 0;
204         }
205         ERR_print_errors(bio_err);
206     } else {
207         char *hostname = NULL;
208
209         hostname = BIO_ADDR_hostname_string(BIO_ADDRINFO_address(ai), 1);
210         if (hostname != NULL) {
211             BIO_printf(bio_out, "Connecting to %s\n", hostname);
212             OPENSSL_free(hostname);
213         }
214         /* Remove any stale errors from previous connection attempts */
215         ERR_clear_error();
216         ret = 1;
217     }
218 out:
219     if (bindaddr != NULL) {
220         BIO_ADDRINFO_free (bindaddr);
221     }
222     BIO_ADDRINFO_free(res);
223     return ret;
224 }
225
226 void get_sock_info_address(int asock, char **hostname, char **service)
227 {
228     union BIO_sock_info_u info;
229
230     if (hostname != NULL)
231         *hostname = NULL;
232     if (service != NULL)
233         *service = NULL;
234
235     if ((info.addr = BIO_ADDR_new()) != NULL
236             && BIO_sock_info(asock, BIO_SOCK_INFO_ADDRESS, &info)) {
237         if (hostname != NULL)
238             *hostname = BIO_ADDR_hostname_string(info.addr, 1);
239         if (service != NULL)
240             *service = BIO_ADDR_service_string(info.addr, 1);
241     }
242     BIO_ADDR_free(info.addr);
243 }
244
245 int report_server_accept(BIO *out, int asock, int with_address, int with_pid)
246 {
247     int success = 1;
248
249     if (BIO_printf(out, "ACCEPT") <= 0)
250         return 0;
251     if (with_address) {
252         char *hostname, *service;
253
254         get_sock_info_address(asock, &hostname, &service);
255         success = hostname != NULL && service != NULL;
256         if (success)
257             success = BIO_printf(out,
258                                  strchr(hostname, ':') == NULL
259                                  ? /* IPv4 */ " %s:%s"
260                                  : /* IPv6 */ " [%s]:%s",
261                                  hostname, service) > 0;
262         else
263             (void)BIO_printf(out, "unknown:error\n");
264         OPENSSL_free(hostname);
265         OPENSSL_free(service);
266     }
267     if (with_pid)
268         success *= BIO_printf(out, " PID=%d", getpid()) > 0;
269     success *= BIO_printf(out, "\n") > 0;
270     (void)BIO_flush(out);
271
272     return success;
273 }
274
275 /*
276  * do_server - helper routine to perform a server operation
277  * @accept_sock: pointer to storage of resulting socket.
278  * @host: the hostname or path (for AF_UNIX) to connect to.
279  * @port: the port to connect to (ignored for AF_UNIX).
280  * @family: desired socket family, may be AF_INET, AF_INET6, AF_UNIX or
281  *  AF_UNSPEC
282  * @type: socket type, must be SOCK_STREAM or SOCK_DGRAM
283  * @cb: pointer to a function that receives the accepted socket and
284  *  should perform the communication with the connecting client.
285  * @context: pointer to memory that's passed verbatim to the cb function.
286  * @naccept: number of times an incoming connect should be accepted.  If -1,
287  *  unlimited number.
288  *
289  * This will create a socket and use it to listen to a host:port, or if
290  * family == AF_UNIX, to the path found in host, then start accepting
291  * incoming connections and run cb on the resulting socket.
292  *
293  * 0 on failure, something other on success.
294  */
295 int do_server(int *accept_sock, const char *host, const char *port,
296               int family, int type, int protocol, do_server_cb cb,
297               unsigned char *context, int naccept, BIO *bio_s_out,
298               int tfo)
299 {
300     int asock = 0;
301     int sock;
302     int i;
303     BIO_ADDRINFO *res = NULL;
304     const BIO_ADDRINFO *next;
305     int sock_family, sock_type, sock_protocol, sock_port;
306     const BIO_ADDR *sock_address;
307     int sock_family_fallback = AF_UNSPEC;
308     const BIO_ADDR *sock_address_fallback = NULL;
309     int sock_options = BIO_SOCK_REUSEADDR;
310     int ret = 0;
311
312     if (BIO_sock_init() != 1)
313         return 0;
314
315     if (!BIO_lookup_ex(host, port, BIO_LOOKUP_SERVER, family, type, protocol,
316                        &res)) {
317         ERR_print_errors(bio_err);
318         return 0;
319     }
320
321     /* Admittedly, these checks are quite paranoid, we should not get
322      * anything in the BIO_ADDRINFO chain that we haven't asked for */
323     OPENSSL_assert((family == AF_UNSPEC || family == BIO_ADDRINFO_family(res))
324                    && (type == 0 || type == BIO_ADDRINFO_socktype(res))
325                    && (protocol == 0 || protocol == BIO_ADDRINFO_protocol(res)));
326
327     sock_family = BIO_ADDRINFO_family(res);
328     sock_type = BIO_ADDRINFO_socktype(res);
329     sock_protocol = BIO_ADDRINFO_protocol(res);
330     sock_address = BIO_ADDRINFO_address(res);
331     next = BIO_ADDRINFO_next(res);
332     if (tfo && sock_type == SOCK_STREAM)
333         sock_options |= BIO_SOCK_TFO;
334 #ifdef AF_INET6
335     if (sock_family == AF_INET6)
336         sock_options |= BIO_SOCK_V6_ONLY;
337     if (next != NULL
338             && BIO_ADDRINFO_socktype(next) == sock_type
339             && BIO_ADDRINFO_protocol(next) == sock_protocol) {
340         if (sock_family == AF_INET
341                 && BIO_ADDRINFO_family(next) == AF_INET6) {
342             /* In case AF_INET6 is returned but not supported by the
343              * kernel, retry with the first detected address family */
344             sock_family_fallback = sock_family;
345             sock_address_fallback = sock_address;
346             sock_family = AF_INET6;
347             sock_address = BIO_ADDRINFO_address(next);
348         } else if (sock_family == AF_INET6
349                    && BIO_ADDRINFO_family(next) == AF_INET) {
350             sock_options &= ~BIO_SOCK_V6_ONLY;
351         }
352     }
353 #endif
354
355     asock = BIO_socket(sock_family, sock_type, sock_protocol, 0);
356     if (asock == INVALID_SOCKET && sock_family_fallback != AF_UNSPEC) {
357         asock = BIO_socket(sock_family_fallback, sock_type, sock_protocol, 0);
358         sock_address = sock_address_fallback;
359     }
360     if (asock == INVALID_SOCKET
361         || !BIO_listen(asock, sock_address, sock_options)) {
362         BIO_ADDRINFO_free(res);
363         ERR_print_errors(bio_err);
364         if (asock != INVALID_SOCKET)
365             BIO_closesocket(asock);
366         goto end;
367     }
368
369 #ifndef OPENSSL_NO_SCTP
370     if (protocol == IPPROTO_SCTP) {
371         /*
372          * For SCTP we have to set various options on the socket prior to
373          * accepting. This is done automatically by BIO_new_dgram_sctp().
374          * We don't actually need the created BIO though so we free it again
375          * immediately.
376          */
377         BIO *tmpbio = BIO_new_dgram_sctp(asock, BIO_NOCLOSE);
378
379         if (tmpbio == NULL) {
380             BIO_closesocket(asock);
381             ERR_print_errors(bio_err);
382             goto end;
383         }
384         BIO_free(tmpbio);
385     }
386 #endif
387
388     sock_port = BIO_ADDR_rawport(sock_address);
389
390     BIO_ADDRINFO_free(res);
391     res = NULL;
392
393     if (!report_server_accept(bio_s_out, asock, sock_port == 0, 0)) {
394         BIO_closesocket(asock);
395         ERR_print_errors(bio_err);
396         goto end;
397     }
398
399     if (accept_sock != NULL)
400         *accept_sock = asock;
401     for (;;) {
402         char sink[64];
403         struct timeval timeout;
404         fd_set readfds;
405
406         if (type == SOCK_STREAM) {
407             BIO_ADDR_free(ourpeer);
408             ourpeer = BIO_ADDR_new();
409             if (ourpeer == NULL) {
410                 BIO_closesocket(asock);
411                 ERR_print_errors(bio_err);
412                 goto end;
413             }
414             do {
415                 sock = BIO_accept_ex(asock, ourpeer, 0);
416             } while (sock < 0 && BIO_sock_should_retry(sock));
417             if (sock < 0) {
418                 ERR_print_errors(bio_err);
419                 BIO_closesocket(asock);
420                 break;
421             }
422             BIO_set_tcp_ndelay(sock, 1);
423             i = (*cb)(sock, type, protocol, context);
424
425             /*
426              * If we ended with an alert being sent, but still with data in the
427              * network buffer to be read, then calling BIO_closesocket() will
428              * result in a TCP-RST being sent. On some platforms (notably
429              * Windows) then this will result in the peer immediately abandoning
430              * the connection including any buffered alert data before it has
431              * had a chance to be read. Shutting down the sending side first,
432              * and then closing the socket sends TCP-FIN first followed by
433              * TCP-RST. This seems to allow the peer to read the alert data.
434              */
435             shutdown(sock, 1); /* SHUT_WR */
436             /*
437              * We just said we have nothing else to say, but it doesn't mean
438              * that the other side has nothing. It's even recommended to
439              * consume incoming data. [In testing context this ensures that
440              * alerts are passed on...]
441              */
442             timeout.tv_sec = 0;
443             timeout.tv_usec = 500000;  /* some extreme round-trip */
444             do {
445                 FD_ZERO(&readfds);
446                 openssl_fdset(sock, &readfds);
447             } while (select(sock + 1, &readfds, NULL, NULL, &timeout) > 0
448                      && readsocket(sock, sink, sizeof(sink)) > 0);
449
450             BIO_closesocket(sock);
451         } else {
452             i = (*cb)(asock, type, protocol, context);
453         }
454
455         if (naccept != -1)
456             naccept--;
457         if (i < 0 || naccept == 0) {
458             BIO_closesocket(asock);
459             ret = i;
460             break;
461         }
462     }
463  end:
464 # ifdef AF_UNIX
465     if (family == AF_UNIX)
466         unlink(host);
467 # endif
468     BIO_ADDR_free(ourpeer);
469     ourpeer = NULL;
470     return ret;
471 }
472
473 void do_ssl_shutdown(SSL *ssl)
474 {
475     int ret;
476
477     do {
478         /* We only do unidirectional shutdown */
479         ret = SSL_shutdown(ssl);
480         if (ret < 0) {
481             switch (SSL_get_error(ssl, ret)) {
482             case SSL_ERROR_WANT_READ:
483             case SSL_ERROR_WANT_WRITE:
484             case SSL_ERROR_WANT_ASYNC:
485             case SSL_ERROR_WANT_ASYNC_JOB:
486                 /* We just do busy waiting. Nothing clever */
487                 continue;
488             }
489             ret = 0;
490         }
491     } while (ret < 0);
492 }
493
494 #endif  /* OPENSSL_NO_SOCK */