Make the s_server command listen on IPv6 only when requested
[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     const BIO_ADDRINFO *next;
165     int sock_family, sock_type, sock_protocol;
166     const BIO_ADDR *sock_address;
167     int sock_options = BIO_SOCK_REUSEADDR;
168     int ret = 0;
169
170     if (BIO_sock_init() != 1)
171         return 0;
172
173     if (!BIO_lookup_ex(host, port, BIO_LOOKUP_SERVER, family, type, protocol,
174                        &res)) {
175         ERR_print_errors(bio_err);
176         return 0;
177     }
178
179     /* Admittedly, these checks are quite paranoid, we should not get
180      * anything in the BIO_ADDRINFO chain that we haven't asked for */
181     OPENSSL_assert((family == AF_UNSPEC || family == BIO_ADDRINFO_family(res))
182                    && (type == 0 || type == BIO_ADDRINFO_socktype(res))
183                    && (protocol == 0 || protocol == BIO_ADDRINFO_protocol(res)));
184
185     sock_family = BIO_ADDRINFO_family(res);
186     sock_type = BIO_ADDRINFO_socktype(res);
187     sock_protocol = BIO_ADDRINFO_protocol(res);
188     sock_address = BIO_ADDRINFO_address(res);
189     next = BIO_ADDRINFO_next(res);
190     if(sock_family == AF_INET6)
191         sock_options |= BIO_SOCK_V6_ONLY;
192     if (next != NULL
193         && BIO_ADDRINFO_socktype(next) == sock_type
194         && BIO_ADDRINFO_protocol(next) == sock_protocol) {
195         if (sock_family == AF_INET && BIO_ADDRINFO_family(next) == AF_INET6) {
196             sock_family = AF_INET6;
197             sock_address = BIO_ADDRINFO_address(next);
198         }
199         else if (sock_family == AF_INET6 && BIO_ADDRINFO_family(next) == AF_INET)
200             sock_options &= ~BIO_SOCK_V6_ONLY;
201     }
202
203     asock = BIO_socket(sock_family, sock_type, sock_protocol, 0);
204     if (asock == INVALID_SOCKET
205         || !BIO_listen(asock, sock_address, sock_options)) {
206         BIO_ADDRINFO_free(res);
207         ERR_print_errors(bio_err);
208         if (asock != INVALID_SOCKET)
209             BIO_closesocket(asock);
210         goto end;
211     }
212
213 #ifndef OPENSSL_NO_SCTP
214     if (protocol == IPPROTO_SCTP) {
215         /*
216          * For SCTP we have to set various options on the socket prior to
217          * accepting. This is done automatically by BIO_new_dgram_sctp().
218          * We don't actually need the created BIO though so we free it again
219          * immediately.
220          */
221         BIO *tmpbio = BIO_new_dgram_sctp(asock, BIO_NOCLOSE);
222
223         if (tmpbio == NULL) {
224             BIO_closesocket(asock);
225             ERR_print_errors(bio_err);
226             goto end;
227         }
228         BIO_free(tmpbio);
229     }
230 #endif
231
232     BIO_ADDRINFO_free(res);
233     res = NULL;
234
235     if (accept_sock != NULL)
236         *accept_sock = asock;
237     for (;;) {
238         if (type == SOCK_STREAM) {
239             BIO_ADDR_free(ourpeer);
240             ourpeer = BIO_ADDR_new();
241             if (ourpeer == NULL) {
242                 BIO_closesocket(asock);
243                 ERR_print_errors(bio_err);
244                 goto end;
245             }
246             do {
247                 sock = BIO_accept_ex(asock, ourpeer, 0);
248             } while (sock < 0 && BIO_sock_should_retry(sock));
249             if (sock < 0) {
250                 ERR_print_errors(bio_err);
251                 BIO_closesocket(asock);
252                 break;
253             }
254             i = (*cb)(sock, type, protocol, context);
255
256             /*
257              * Give the socket time to send its last data before we close it.
258              * No amount of setting SO_LINGER etc on the socket seems to
259              * persuade Windows to send the data before closing the socket...
260              * but sleeping for a short time seems to do it (units in ms)
261              * TODO: Find a better way to do this
262              */
263 #if defined(OPENSSL_SYS_WINDOWS)
264             Sleep(50);
265 #elif defined(OPENSSL_SYS_CYGWIN)
266             usleep(50000);
267 #endif
268
269             /*
270              * If we ended with an alert being sent, but still with data in the
271              * network buffer to be read, then calling BIO_closesocket() will
272              * result in a TCP-RST being sent. On some platforms (notably
273              * Windows) then this will result in the peer immediately abandoning
274              * the connection including any buffered alert data before it has
275              * had a chance to be read. Shutting down the sending side first,
276              * and then closing the socket sends TCP-FIN first followed by
277              * TCP-RST. This seems to allow the peer to read the alert data.
278              */
279             shutdown(sock, 1); /* SHUT_WR */
280             BIO_closesocket(sock);
281         } else {
282             i = (*cb)(asock, type, protocol, context);
283         }
284
285         if (naccept != -1)
286             naccept--;
287         if (i < 0 || naccept == 0) {
288             BIO_closesocket(asock);
289             ret = i;
290             break;
291         }
292     }
293  end:
294 # ifdef AF_UNIX
295     if (family == AF_UNIX)
296         unlink(host);
297 # endif
298     BIO_ADDR_free(ourpeer);
299     ourpeer = NULL;
300     return ret;
301 }
302
303 #endif  /* OPENSSL_NO_SOCK */