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