Fix return value checking for BIO_sock_init
[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 # 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  * @protocol: socket protocol, e.g. IPPROTO_TCP or IPPROTO_UDP (or 0 for any)
48  *
49  * This will create a socket and use it to connect to a host:port, or if
50  * family == AF_UNIX, to the path found in host.
51  *
52  * If the host has more than one address, it will try them one by one until
53  * a successful connection is established.  The resulting socket will be
54  * found in *sock on success, it will be given INVALID_SOCKET otherwise.
55  *
56  * Returns 1 on success, 0 on failure.
57  */
58 int init_client(int *sock, const char *host, const char *port,
59                 int family, int type, int protocol)
60 {
61     BIO_ADDRINFO *res = NULL;
62     const BIO_ADDRINFO *ai = NULL;
63     int ret;
64
65     if (BIO_sock_init() != 1)
66         return 0;
67
68     ret = BIO_lookup_ex(host, port, BIO_LOOKUP_CLIENT, family, type, protocol,
69                         &res);
70     if (ret == 0) {
71         ERR_print_errors(bio_err);
72         return 0;
73     }
74
75     ret = 0;
76     for (ai = res; ai != NULL; ai = BIO_ADDRINFO_next(ai)) {
77         /* Admittedly, these checks are quite paranoid, we should not get
78          * anything in the BIO_ADDRINFO chain that we haven't
79          * asked for. */
80         OPENSSL_assert((family == AF_UNSPEC
81                         || family == BIO_ADDRINFO_family(ai))
82                        && (type == 0 || type == BIO_ADDRINFO_socktype(ai))
83                        && (protocol == 0
84                            || protocol == BIO_ADDRINFO_protocol(ai)));
85
86         *sock = BIO_socket(BIO_ADDRINFO_family(ai), BIO_ADDRINFO_socktype(ai),
87                            BIO_ADDRINFO_protocol(ai), 0);
88         if (*sock == INVALID_SOCKET) {
89             /* Maybe the kernel doesn't support the socket family, even if
90              * BIO_lookup() added it in the returned result...
91              */
92             continue;
93         }
94
95 #ifndef OPENSSL_NO_SCTP
96         if (protocol == IPPROTO_SCTP) {
97             /*
98              * For SCTP we have to set various options on the socket prior to
99              * connecting. This is done automatically by BIO_new_dgram_sctp().
100              * We don't actually need the created BIO though so we free it again
101              * immediately.
102              */
103             BIO *tmpbio = BIO_new_dgram_sctp(*sock, BIO_NOCLOSE);
104
105             if (tmpbio == NULL) {
106                 ERR_print_errors(bio_err);
107                 return 0;
108             }
109             BIO_free(tmpbio);
110         }
111 #endif
112
113         if (!BIO_connect(*sock, BIO_ADDRINFO_address(ai), 0)) {
114             BIO_closesocket(*sock);
115             *sock = INVALID_SOCKET;
116             continue;
117         }
118
119         /* Success, don't try any more addresses */
120         break;
121     }
122
123     if (*sock == INVALID_SOCKET) {
124         ERR_print_errors(bio_err);
125     } else {
126         /* Remove any stale errors from previous connection attempts */
127         ERR_clear_error();
128         ret = 1;
129     }
130     BIO_ADDRINFO_free(res);
131     return ret;
132 }
133
134 /*
135  * do_server - helper routine to perform a server operation
136  * @accept_sock: pointer to storage of resulting socket.
137  * @host: the host name or path (for AF_UNIX) to connect to.
138  * @port: the port to connect to (ignored for AF_UNIX).
139  * @family: desired socket family, may be AF_INET, AF_INET6, AF_UNIX or
140  *  AF_UNSPEC
141  * @type: socket type, must be SOCK_STREAM or SOCK_DGRAM
142  * @cb: pointer to a function that receives the accepted socket and
143  *  should perform the communication with the connecting client.
144  * @context: pointer to memory that's passed verbatim to the cb function.
145  * @naccept: number of times an incoming connect should be accepted.  If -1,
146  *  unlimited number.
147  *
148  * This will create a socket and use it to listen to a host:port, or if
149  * family == AF_UNIX, to the path found in host, then start accepting
150  * incoming connections and run cb on the resulting socket.
151  *
152  * 0 on failure, something other on success.
153  */
154 int do_server(int *accept_sock, const char *host, const char *port,
155               int family, int type, int protocol, do_server_cb cb,
156               unsigned char *context, int naccept)
157 {
158     int asock = 0;
159     int sock;
160     int i;
161     BIO_ADDRINFO *res = NULL;
162     int ret = 0;
163
164     if (BIO_sock_init() != 1)
165         return 0;
166
167     if (!BIO_lookup_ex(host, port, BIO_LOOKUP_SERVER, family, type, protocol,
168                        &res)) {
169         ERR_print_errors(bio_err);
170         return 0;
171     }
172
173     /* Admittedly, these checks are quite paranoid, we should not get
174      * anything in the BIO_ADDRINFO chain that we haven't asked for */
175     OPENSSL_assert((family == AF_UNSPEC || family == BIO_ADDRINFO_family(res))
176                    && (type == 0 || type == BIO_ADDRINFO_socktype(res))
177                    && (protocol == 0 || protocol == BIO_ADDRINFO_protocol(res)));
178
179     asock = BIO_socket(BIO_ADDRINFO_family(res), BIO_ADDRINFO_socktype(res),
180                        BIO_ADDRINFO_protocol(res), 0);
181     if (asock == INVALID_SOCKET
182         || !BIO_listen(asock, BIO_ADDRINFO_address(res), BIO_SOCK_REUSEADDR)) {
183         BIO_ADDRINFO_free(res);
184         ERR_print_errors(bio_err);
185         if (asock != INVALID_SOCKET)
186             BIO_closesocket(asock);
187         goto end;
188     }
189
190 #ifndef OPENSSL_NO_SCTP
191     if (protocol == IPPROTO_SCTP) {
192         /*
193          * For SCTP we have to set various options on the socket prior to
194          * accepting. This is done automatically by BIO_new_dgram_sctp().
195          * We don't actually need the created BIO though so we free it again
196          * immediately.
197          */
198         BIO *tmpbio = BIO_new_dgram_sctp(asock, BIO_NOCLOSE);
199
200         if (tmpbio == NULL) {
201             BIO_closesocket(asock);
202             ERR_print_errors(bio_err);
203             goto end;
204         }
205         BIO_free(tmpbio);
206     }
207 #endif
208
209     BIO_ADDRINFO_free(res);
210     res = NULL;
211
212     if (accept_sock != NULL)
213         *accept_sock = asock;
214     for (;;) {
215         if (type == SOCK_STREAM) {
216             do {
217                 sock = BIO_accept_ex(asock, NULL, 0);
218             } while (sock < 0 && BIO_sock_should_retry(ret));
219             if (sock < 0) {
220                 ERR_print_errors(bio_err);
221                 BIO_closesocket(asock);
222                 break;
223             }
224             i = (*cb)(sock, type, protocol, context);
225             BIO_closesocket(sock);
226         } else {
227             i = (*cb)(asock, type, protocol, context);
228         }
229
230         if (naccept != -1)
231             naccept--;
232         if (i < 0 || naccept == 0) {
233             BIO_closesocket(asock);
234             ret = i;
235             break;
236         }
237     }
238  end:
239 # ifdef AF_UNIX
240     if (family == AF_UNIX)
241         unlink(host);
242 # endif
243     return ret;
244 }
245
246 #endif  /* OPENSSL_NO_SOCK */