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