Fix no-posix-io compile failure
[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  * @bindhost: source host or path (for AF_UNIX).
47  * @bindport: source port (ignored for AF_UNIX).
48  * @family: desired socket family, may be AF_INET, AF_INET6, AF_UNIX or
49  *  AF_UNSPEC
50  * @type: socket type, must be SOCK_STREAM or SOCK_DGRAM
51  * @protocol: socket protocol, e.g. IPPROTO_TCP or IPPROTO_UDP (or 0 for any)
52  *
53  * This will create a socket and use it to connect to a host:port, or if
54  * family == AF_UNIX, to the path found in host.
55  *
56  * If the host has more than one address, it will try them one by one until
57  * a successful connection is established.  The resulting socket will be
58  * found in *sock on success, it will be given INVALID_SOCKET otherwise.
59  *
60  * Returns 1 on success, 0 on failure.
61  */
62 int init_client(int *sock, const char *host, const char *port,
63                 const char *bindhost, const char *bindport,
64                 int family, int type, int protocol)
65 {
66     BIO_ADDRINFO *res = NULL;
67     BIO_ADDRINFO *bindaddr = NULL;
68     const BIO_ADDRINFO *ai = NULL;
69     const BIO_ADDRINFO *bi = NULL;
70     int found = 0;
71     int ret;
72
73     if (BIO_sock_init() != 1)
74         return 0;
75
76     ret = BIO_lookup_ex(host, port, BIO_LOOKUP_CLIENT, family, type, protocol,
77                         &res);
78     if (ret == 0) {
79         ERR_print_errors(bio_err);
80         return 0;
81     }
82
83     if (bindhost != NULL || bindport != NULL) {
84         ret = BIO_lookup_ex(bindhost, bindport, BIO_LOOKUP_CLIENT,
85                             family, type, protocol, &bindaddr);
86         if (ret == 0) {
87             ERR_print_errors (bio_err);
88             goto out;
89         }
90     }
91
92     ret = 0;
93     for (ai = res; ai != NULL; ai = BIO_ADDRINFO_next(ai)) {
94         /* Admittedly, these checks are quite paranoid, we should not get
95          * anything in the BIO_ADDRINFO chain that we haven't
96          * asked for. */
97         OPENSSL_assert((family == AF_UNSPEC
98                         || family == BIO_ADDRINFO_family(ai))
99                        && (type == 0 || type == BIO_ADDRINFO_socktype(ai))
100                        && (protocol == 0
101                            || protocol == BIO_ADDRINFO_protocol(ai)));
102
103         if (bindaddr != NULL) {
104             for (bi = bindaddr; bi != NULL; bi = BIO_ADDRINFO_next(bi)) {
105                 if (BIO_ADDRINFO_family(bi) == BIO_ADDRINFO_family(ai))
106                     break;
107             }
108             if (bi == NULL)
109                 continue;
110             ++found;
111         }
112
113         *sock = BIO_socket(BIO_ADDRINFO_family(ai), BIO_ADDRINFO_socktype(ai),
114                            BIO_ADDRINFO_protocol(ai), 0);
115         if (*sock == INVALID_SOCKET) {
116             /* Maybe the kernel doesn't support the socket family, even if
117              * BIO_lookup() added it in the returned result...
118              */
119             continue;
120         }
121
122         if (bi != NULL) {
123             if (!BIO_bind(*sock, BIO_ADDRINFO_address(bi),
124                           BIO_SOCK_REUSEADDR)) {
125                 BIO_closesocket(*sock);
126                 *sock = INVALID_SOCKET;
127                 break;
128             }
129         }
130
131 #ifndef OPENSSL_NO_SCTP
132         if (protocol == IPPROTO_SCTP) {
133             /*
134              * For SCTP we have to set various options on the socket prior to
135              * connecting. This is done automatically by BIO_new_dgram_sctp().
136              * We don't actually need the created BIO though so we free it again
137              * immediately.
138              */
139             BIO *tmpbio = BIO_new_dgram_sctp(*sock, BIO_NOCLOSE);
140
141             if (tmpbio == NULL) {
142                 ERR_print_errors(bio_err);
143                 return 0;
144             }
145             BIO_free(tmpbio);
146         }
147 #endif
148
149         if (!BIO_connect(*sock, BIO_ADDRINFO_address(ai), 0)) {
150             BIO_closesocket(*sock);
151             *sock = INVALID_SOCKET;
152             continue;
153         }
154
155         /* Success, don't try any more addresses */
156         break;
157     }
158
159     if (*sock == INVALID_SOCKET) {
160         if (bindaddr != NULL && !found) {
161             BIO_printf(bio_err, "Can't bind %saddress for %s%s%s\n",
162                        BIO_ADDRINFO_family(res) == AF_INET6 ? "IPv6 " :
163                        BIO_ADDRINFO_family(res) == AF_INET ? "IPv4 " :
164                        BIO_ADDRINFO_family(res) == AF_UNIX ? "unix " : "",
165                        bindhost != NULL ? bindhost : "",
166                        bindport != NULL ? ":" : "",
167                        bindport != NULL ? bindport : "");
168             ERR_clear_error();
169             ret = 0;
170         }
171         ERR_print_errors(bio_err);
172     } else {
173         /* Remove any stale errors from previous connection attempts */
174         ERR_clear_error();
175         ret = 1;
176     }
177 out:
178     if (bindaddr != NULL) {
179         BIO_ADDRINFO_free (bindaddr);
180     }
181     BIO_ADDRINFO_free(res);
182     return ret;
183 }
184
185 /*
186  * do_server - helper routine to perform a server operation
187  * @accept_sock: pointer to storage of resulting socket.
188  * @host: the host name or path (for AF_UNIX) to connect to.
189  * @port: the port to connect to (ignored for AF_UNIX).
190  * @family: desired socket family, may be AF_INET, AF_INET6, AF_UNIX or
191  *  AF_UNSPEC
192  * @type: socket type, must be SOCK_STREAM or SOCK_DGRAM
193  * @cb: pointer to a function that receives the accepted socket and
194  *  should perform the communication with the connecting client.
195  * @context: pointer to memory that's passed verbatim to the cb function.
196  * @naccept: number of times an incoming connect should be accepted.  If -1,
197  *  unlimited number.
198  *
199  * This will create a socket and use it to listen to a host:port, or if
200  * family == AF_UNIX, to the path found in host, then start accepting
201  * incoming connections and run cb on the resulting socket.
202  *
203  * 0 on failure, something other on success.
204  */
205 int do_server(int *accept_sock, const char *host, const char *port,
206               int family, int type, int protocol, do_server_cb cb,
207               unsigned char *context, int naccept)
208 {
209     int asock = 0;
210     int sock;
211     int i;
212     BIO_ADDRINFO *res = NULL;
213     const BIO_ADDRINFO *next;
214     int sock_family, sock_type, sock_protocol;
215     const BIO_ADDR *sock_address;
216     int sock_options = BIO_SOCK_REUSEADDR;
217     int ret = 0;
218
219     if (BIO_sock_init() != 1)
220         return 0;
221
222     if (!BIO_lookup_ex(host, port, BIO_LOOKUP_SERVER, family, type, protocol,
223                        &res)) {
224         ERR_print_errors(bio_err);
225         return 0;
226     }
227
228     /* Admittedly, these checks are quite paranoid, we should not get
229      * anything in the BIO_ADDRINFO chain that we haven't asked for */
230     OPENSSL_assert((family == AF_UNSPEC || family == BIO_ADDRINFO_family(res))
231                    && (type == 0 || type == BIO_ADDRINFO_socktype(res))
232                    && (protocol == 0 || protocol == BIO_ADDRINFO_protocol(res)));
233
234     sock_family = BIO_ADDRINFO_family(res);
235     sock_type = BIO_ADDRINFO_socktype(res);
236     sock_protocol = BIO_ADDRINFO_protocol(res);
237     sock_address = BIO_ADDRINFO_address(res);
238     next = BIO_ADDRINFO_next(res);
239     if (sock_family == AF_INET6)
240         sock_options |= BIO_SOCK_V6_ONLY;
241     if (next != NULL
242             && BIO_ADDRINFO_socktype(next) == sock_type
243             && BIO_ADDRINFO_protocol(next) == sock_protocol) {
244         if (sock_family == AF_INET
245                 && BIO_ADDRINFO_family(next) == AF_INET6) {
246             sock_family = AF_INET6;
247             sock_address = BIO_ADDRINFO_address(next);
248         } else if (sock_family == AF_INET6
249                    && BIO_ADDRINFO_family(next) == AF_INET) {
250             sock_options &= ~BIO_SOCK_V6_ONLY;
251         }
252     }
253
254     asock = BIO_socket(sock_family, sock_type, sock_protocol, 0);
255     if (asock == INVALID_SOCKET
256         || !BIO_listen(asock, sock_address, sock_options)) {
257         BIO_ADDRINFO_free(res);
258         ERR_print_errors(bio_err);
259         if (asock != INVALID_SOCKET)
260             BIO_closesocket(asock);
261         goto end;
262     }
263
264 #ifndef OPENSSL_NO_SCTP
265     if (protocol == IPPROTO_SCTP) {
266         /*
267          * For SCTP we have to set various options on the socket prior to
268          * accepting. This is done automatically by BIO_new_dgram_sctp().
269          * We don't actually need the created BIO though so we free it again
270          * immediately.
271          */
272         BIO *tmpbio = BIO_new_dgram_sctp(asock, BIO_NOCLOSE);
273
274         if (tmpbio == NULL) {
275             BIO_closesocket(asock);
276             ERR_print_errors(bio_err);
277             goto end;
278         }
279         BIO_free(tmpbio);
280     }
281 #endif
282
283     BIO_ADDRINFO_free(res);
284     res = NULL;
285
286     if (accept_sock != NULL)
287         *accept_sock = asock;
288     for (;;) {
289         if (type == SOCK_STREAM) {
290             BIO_ADDR_free(ourpeer);
291             ourpeer = BIO_ADDR_new();
292             if (ourpeer == NULL) {
293                 BIO_closesocket(asock);
294                 ERR_print_errors(bio_err);
295                 goto end;
296             }
297             do {
298                 sock = BIO_accept_ex(asock, ourpeer, 0);
299             } while (sock < 0 && BIO_sock_should_retry(sock));
300             if (sock < 0) {
301                 ERR_print_errors(bio_err);
302                 BIO_closesocket(asock);
303                 break;
304             }
305             i = (*cb)(sock, type, protocol, context);
306
307             /*
308              * Give the socket time to send its last data before we close it.
309              * No amount of setting SO_LINGER etc on the socket seems to
310              * persuade Windows to send the data before closing the socket...
311              * but sleeping for a short time seems to do it (units in ms)
312              * TODO: Find a better way to do this
313              */
314 #if defined(OPENSSL_SYS_WINDOWS)
315             Sleep(50);
316 #elif defined(OPENSSL_SYS_CYGWIN)
317             usleep(50000);
318 #endif
319
320             /*
321              * If we ended with an alert being sent, but still with data in the
322              * network buffer to be read, then calling BIO_closesocket() will
323              * result in a TCP-RST being sent. On some platforms (notably
324              * Windows) then this will result in the peer immediately abandoning
325              * the connection including any buffered alert data before it has
326              * had a chance to be read. Shutting down the sending side first,
327              * and then closing the socket sends TCP-FIN first followed by
328              * TCP-RST. This seems to allow the peer to read the alert data.
329              */
330             shutdown(sock, 1); /* SHUT_WR */
331             BIO_closesocket(sock);
332         } else {
333             i = (*cb)(asock, type, protocol, context);
334         }
335
336         if (naccept != -1)
337             naccept--;
338         if (i < 0 || naccept == 0) {
339             BIO_closesocket(asock);
340             ret = i;
341             break;
342         }
343     }
344  end:
345 # ifdef AF_UNIX
346     if (family == AF_UNIX)
347         unlink(host);
348 # endif
349     BIO_ADDR_free(ourpeer);
350     ourpeer = NULL;
351     return ret;
352 }
353
354 #endif  /* OPENSSL_NO_SOCK */