Add the SSL_stateless() function
[openssl.git] / apps / s_socket.c
1 /*
2  * Copyright 1995-2018 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the OpenSSL license (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 # include <openssl/bio.h>
36 # include <openssl/err.h>
37
38 /* Keep track of our peer's address for the cookie callback */
39 BIO_ADDR *ourpeer = NULL;
40
41 /*
42  * init_client - helper routine to set up socket communication
43  * @sock: pointer to storage of resulting socket.
44  * @host: the host name or path (for AF_UNIX) to connect to.
45  * @port: the port to connect to (ignored for AF_UNIX).
46  * @family: desired socket family, may be AF_INET, AF_INET6, AF_UNIX or
47  *  AF_UNSPEC
48  * @type: socket type, must be SOCK_STREAM or SOCK_DGRAM
49  * @protocol: socket protocol, e.g. IPPROTO_TCP or IPPROTO_UDP (or 0 for any)
50  *
51  * This will create a socket and use it to connect to a host:port, or if
52  * family == AF_UNIX, to the path found in host.
53  *
54  * If the host has more than one address, it will try them one by one until
55  * a successful connection is established.  The resulting socket will be
56  * found in *sock on success, it will be given INVALID_SOCKET otherwise.
57  *
58  * Returns 1 on success, 0 on failure.
59  */
60 int init_client(int *sock, const char *host, const char *port,
61                 int family, int type, int protocol)
62 {
63     BIO_ADDRINFO *res = NULL;
64     const BIO_ADDRINFO *ai = NULL;
65     int ret;
66
67     if (BIO_sock_init() != 1)
68         return 0;
69
70     ret = BIO_lookup_ex(host, port, BIO_LOOKUP_CLIENT, family, type, protocol,
71                         &res);
72     if (ret == 0) {
73         ERR_print_errors(bio_err);
74         return 0;
75     }
76
77     ret = 0;
78     for (ai = res; ai != NULL; ai = BIO_ADDRINFO_next(ai)) {
79         /* Admittedly, these checks are quite paranoid, we should not get
80          * anything in the BIO_ADDRINFO chain that we haven't
81          * asked for. */
82         OPENSSL_assert((family == AF_UNSPEC
83                         || family == BIO_ADDRINFO_family(ai))
84                        && (type == 0 || type == BIO_ADDRINFO_socktype(ai))
85                        && (protocol == 0
86                            || protocol == BIO_ADDRINFO_protocol(ai)));
87
88         *sock = BIO_socket(BIO_ADDRINFO_family(ai), BIO_ADDRINFO_socktype(ai),
89                            BIO_ADDRINFO_protocol(ai), 0);
90         if (*sock == INVALID_SOCKET) {
91             /* Maybe the kernel doesn't support the socket family, even if
92              * BIO_lookup() added it in the returned result...
93              */
94             continue;
95         }
96
97 #ifndef OPENSSL_NO_SCTP
98         if (protocol == IPPROTO_SCTP) {
99             /*
100              * For SCTP we have to set various options on the socket prior to
101              * connecting. This is done automatically by BIO_new_dgram_sctp().
102              * We don't actually need the created BIO though so we free it again
103              * immediately.
104              */
105             BIO *tmpbio = BIO_new_dgram_sctp(*sock, BIO_NOCLOSE);
106
107             if (tmpbio == NULL) {
108                 ERR_print_errors(bio_err);
109                 return 0;
110             }
111             BIO_free(tmpbio);
112         }
113 #endif
114
115         if (!BIO_connect(*sock, BIO_ADDRINFO_address(ai), 0)) {
116             BIO_closesocket(*sock);
117             *sock = INVALID_SOCKET;
118             continue;
119         }
120
121         /* Success, don't try any more addresses */
122         break;
123     }
124
125     if (*sock == INVALID_SOCKET) {
126         ERR_print_errors(bio_err);
127     } else {
128         /* Remove any stale errors from previous connection attempts */
129         ERR_clear_error();
130         ret = 1;
131     }
132     BIO_ADDRINFO_free(res);
133     return ret;
134 }
135
136 /*
137  * do_server - helper routine to perform a server operation
138  * @accept_sock: pointer to storage of resulting socket.
139  * @host: the host name or path (for AF_UNIX) to connect to.
140  * @port: the port to connect to (ignored for AF_UNIX).
141  * @family: desired socket family, may be AF_INET, AF_INET6, AF_UNIX or
142  *  AF_UNSPEC
143  * @type: socket type, must be SOCK_STREAM or SOCK_DGRAM
144  * @cb: pointer to a function that receives the accepted socket and
145  *  should perform the communication with the connecting client.
146  * @context: pointer to memory that's passed verbatim to the cb function.
147  * @naccept: number of times an incoming connect should be accepted.  If -1,
148  *  unlimited number.
149  *
150  * This will create a socket and use it to listen to a host:port, or if
151  * family == AF_UNIX, to the path found in host, then start accepting
152  * incoming connections and run cb on the resulting socket.
153  *
154  * 0 on failure, something other on success.
155  */
156 int do_server(int *accept_sock, const char *host, const char *port,
157               int family, int type, int protocol, do_server_cb cb,
158               unsigned char *context, int naccept)
159 {
160     int asock = 0;
161     int sock;
162     int i;
163     BIO_ADDRINFO *res = NULL;
164     int ret = 0;
165
166     if (BIO_sock_init() != 1)
167         return 0;
168
169     if (!BIO_lookup_ex(host, port, BIO_LOOKUP_SERVER, family, type, protocol,
170                        &res)) {
171         ERR_print_errors(bio_err);
172         return 0;
173     }
174
175     /* Admittedly, these checks are quite paranoid, we should not get
176      * anything in the BIO_ADDRINFO chain that we haven't asked for */
177     OPENSSL_assert((family == AF_UNSPEC || family == BIO_ADDRINFO_family(res))
178                    && (type == 0 || type == BIO_ADDRINFO_socktype(res))
179                    && (protocol == 0 || protocol == BIO_ADDRINFO_protocol(res)));
180
181     asock = BIO_socket(BIO_ADDRINFO_family(res), BIO_ADDRINFO_socktype(res),
182                        BIO_ADDRINFO_protocol(res), 0);
183     if (asock == INVALID_SOCKET
184         || !BIO_listen(asock, BIO_ADDRINFO_address(res), BIO_SOCK_REUSEADDR)) {
185         BIO_ADDRINFO_free(res);
186         ERR_print_errors(bio_err);
187         if (asock != INVALID_SOCKET)
188             BIO_closesocket(asock);
189         goto end;
190     }
191
192 #ifndef OPENSSL_NO_SCTP
193     if (protocol == IPPROTO_SCTP) {
194         /*
195          * For SCTP we have to set various options on the socket prior to
196          * accepting. This is done automatically by BIO_new_dgram_sctp().
197          * We don't actually need the created BIO though so we free it again
198          * immediately.
199          */
200         BIO *tmpbio = BIO_new_dgram_sctp(asock, BIO_NOCLOSE);
201
202         if (tmpbio == NULL) {
203             BIO_closesocket(asock);
204             ERR_print_errors(bio_err);
205             goto end;
206         }
207         BIO_free(tmpbio);
208     }
209 #endif
210
211     BIO_ADDRINFO_free(res);
212     res = NULL;
213
214     if (accept_sock != NULL)
215         *accept_sock = asock;
216     for (;;) {
217         if (type == SOCK_STREAM) {
218             BIO_ADDR_free(ourpeer);
219             ourpeer = BIO_ADDR_new();
220             if (ourpeer == NULL) {
221                 BIO_closesocket(asock);
222                 ERR_print_errors(bio_err);
223                 goto end;
224             }
225             do {
226                 sock = BIO_accept_ex(asock, ourpeer, 0);
227             } while (sock < 0 && BIO_sock_should_retry(sock));
228             if (sock < 0) {
229                 ERR_print_errors(bio_err);
230                 BIO_closesocket(asock);
231                 break;
232             }
233             i = (*cb)(sock, type, protocol, context);
234
235             /*
236              * Give the socket time to send its last data before we close it.
237              * No amount of setting SO_LINGER etc on the socket seems to
238              * persuade Windows to send the data before closing the socket...
239              * but sleeping for a short time seems to do it (units in ms)
240              * TODO: Find a better way to do this
241              */
242 #if defined(OPENSSL_SYS_WINDOWS)
243             Sleep(50);
244 #elif defined(OPENSSL_SYS_CYGWIN)
245             usleep(50000);
246 #endif
247
248             /*
249              * If we ended with an alert being sent, but still with data in the
250              * network buffer to be read, then calling BIO_closesocket() will
251              * result in a TCP-RST being sent. On some platforms (notably
252              * Windows) then this will result in the peer immediately abandoning
253              * the connection including any buffered alert data before it has
254              * had a chance to be read. Shutting down the sending side first,
255              * and then closing the socket sends TCP-FIN first followed by
256              * TCP-RST. This seems to allow the peer to read the alert data.
257              */
258             shutdown(sock, 1); /* SHUT_WR */
259             BIO_closesocket(sock);
260         } else {
261             i = (*cb)(asock, type, protocol, context);
262         }
263
264         if (naccept != -1)
265             naccept--;
266         if (i < 0 || naccept == 0) {
267             BIO_closesocket(asock);
268             ret = i;
269             break;
270         }
271     }
272  end:
273 # ifdef AF_UNIX
274     if (family == AF_UNIX)
275         unlink(host);
276 # endif
277     BIO_ADDR_free(ourpeer);
278     ourpeer = NULL;
279     return ret;
280 }
281
282 #endif  /* OPENSSL_NO_SOCK */