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