Update copyright year
[oweals/openssl.git] / crypto / bio / b_sock2.c
1 /*
2  * Copyright 2016-2020 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the Apache License 2.0 (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 #include <stdio.h>
11 #include <stdlib.h>
12 #include <errno.h>
13
14 #include "bio_local.h"
15 #include "internal/ktls.h"
16
17 #include <openssl/err.h>
18
19 #ifndef OPENSSL_NO_SOCK
20 # ifdef SO_MAXCONN
21 #  define MAX_LISTEN  SO_MAXCONN
22 # elif defined(SOMAXCONN)
23 #  define MAX_LISTEN  SOMAXCONN
24 # else
25 #  define MAX_LISTEN  32
26 # endif
27
28 /*-
29  * BIO_socket - create a socket
30  * @domain: the socket domain (AF_INET, AF_INET6, AF_UNIX, ...)
31  * @socktype: the socket type (SOCK_STEAM, SOCK_DGRAM)
32  * @protocol: the protocol to use (IPPROTO_TCP, IPPROTO_UDP)
33  * @options: BIO socket options (currently unused)
34  *
35  * Creates a socket.  This should be called before calling any
36  * of BIO_connect and BIO_listen.
37  *
38  * Returns the file descriptor on success or INVALID_SOCKET on failure.  On
39  * failure errno is set, and a status is added to the OpenSSL error stack.
40  */
41 int BIO_socket(int domain, int socktype, int protocol, int options)
42 {
43     int sock = -1;
44
45     if (BIO_sock_init() != 1)
46         return INVALID_SOCKET;
47
48     sock = socket(domain, socktype, protocol);
49     if (sock == -1) {
50         ERR_raise_data(ERR_LIB_SYS, get_last_socket_error(),
51                        "calling socket()");
52         BIOerr(BIO_F_BIO_SOCKET, BIO_R_UNABLE_TO_CREATE_SOCKET);
53         return INVALID_SOCKET;
54     }
55 # ifndef OPENSSL_NO_KTLS
56     {
57         /*
58          * The new socket is created successfully regardless of ktls_enable.
59          * ktls_enable doesn't change any functionality of the socket, except
60          * changing the setsockopt to enable the processing of ktls_start.
61          * Thus, it is not a problem to call it for non-TLS sockets.
62          */
63         ktls_enable(sock);
64     }
65 # endif
66
67     return sock;
68 }
69
70 /*-
71  * BIO_connect - connect to an address
72  * @sock: the socket to connect with
73  * @addr: the address to connect to
74  * @options: BIO socket options
75  *
76  * Connects to the address using the given socket and options.
77  *
78  * Options can be a combination of the following:
79  * - BIO_SOCK_KEEPALIVE: enable regularly sending keep-alive messages.
80  * - BIO_SOCK_NONBLOCK: Make the socket non-blocking.
81  * - BIO_SOCK_NODELAY: don't delay small messages.
82  *
83  * options holds BIO socket options that can be used
84  * You should call this for every address returned by BIO_lookup
85  * until the connection is successful.
86  *
87  * Returns 1 on success or 0 on failure.  On failure errno is set
88  * and an error status is added to the OpenSSL error stack.
89  */
90 int BIO_connect(int sock, const BIO_ADDR *addr, int options)
91 {
92     const int on = 1;
93
94     if (sock == -1) {
95         BIOerr(BIO_F_BIO_CONNECT, BIO_R_INVALID_SOCKET);
96         return 0;
97     }
98
99     if (!BIO_socket_nbio(sock, (options & BIO_SOCK_NONBLOCK) != 0))
100         return 0;
101
102     if (options & BIO_SOCK_KEEPALIVE) {
103         if (setsockopt(sock, SOL_SOCKET, SO_KEEPALIVE,
104                        (const void *)&on, sizeof(on)) != 0) {
105             ERR_raise_data(ERR_LIB_SYS, get_last_socket_error(),
106                            "calling setsockopt()");
107             BIOerr(BIO_F_BIO_CONNECT, BIO_R_UNABLE_TO_KEEPALIVE);
108             return 0;
109         }
110     }
111
112     if (options & BIO_SOCK_NODELAY) {
113         if (setsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
114                        (const void *)&on, sizeof(on)) != 0) {
115             ERR_raise_data(ERR_LIB_SYS, get_last_socket_error(),
116                            "calling setsockopt()");
117             BIOerr(BIO_F_BIO_CONNECT, BIO_R_UNABLE_TO_NODELAY);
118             return 0;
119         }
120     }
121
122     if (connect(sock, BIO_ADDR_sockaddr(addr),
123                 BIO_ADDR_sockaddr_size(addr)) == -1) {
124         if (!BIO_sock_should_retry(-1)) {
125             ERR_raise_data(ERR_LIB_SYS, get_last_socket_error(),
126                            "calling connect()");
127             BIOerr(BIO_F_BIO_CONNECT, BIO_R_CONNECT_ERROR);
128         }
129         return 0;
130     }
131     return 1;
132 }
133
134 /*-
135  * BIO_bind - bind socket to address
136  * @sock: the socket to set
137  * @addr: local address to bind to
138  * @options: BIO socket options
139  *
140  * Binds to the address using the given socket and options.
141  *
142  * Options can be a combination of the following:
143  * - BIO_SOCK_REUSEADDR: Try to reuse the address and port combination
144  *   for a recently closed port.
145  *
146  * When restarting the program it could be that the port is still in use.  If
147  * you set to BIO_SOCK_REUSEADDR option it will try to reuse the port anyway.
148  * It's recommended that you use this.
149  */
150 int BIO_bind(int sock, const BIO_ADDR *addr, int options)
151 {
152 # ifndef OPENSSL_SYS_WINDOWS
153     int on = 1;
154 # endif
155
156     if (sock == -1) {
157         BIOerr(BIO_F_BIO_BIND, BIO_R_INVALID_SOCKET);
158         return 0;
159     }
160
161 # ifndef OPENSSL_SYS_WINDOWS
162     /*
163      * SO_REUSEADDR has different behavior on Windows than on
164      * other operating systems, don't set it there.
165      */
166     if (options & BIO_SOCK_REUSEADDR) {
167         if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR,
168                        (const void *)&on, sizeof(on)) != 0) {
169             ERR_raise_data(ERR_LIB_SYS, get_last_socket_error(),
170                            "calling setsockopt()");
171             BIOerr(BIO_F_BIO_BIND, BIO_R_UNABLE_TO_REUSEADDR);
172             return 0;
173         }
174     }
175 # endif
176
177     if (bind(sock, BIO_ADDR_sockaddr(addr), BIO_ADDR_sockaddr_size(addr)) != 0) {
178         ERR_raise_data(ERR_LIB_SYS, get_last_socket_error(),
179                        "calling bind()");
180         BIOerr(BIO_F_BIO_BIND, BIO_R_UNABLE_TO_BIND_SOCKET);
181         return 0;
182     }
183
184     return 1;
185 }
186
187 /*-
188  * BIO_listen - Creates a listen socket
189  * @sock: the socket to listen with
190  * @addr: local address to bind to
191  * @options: BIO socket options
192  *
193  * Binds to the address using the given socket and options, then
194  * starts listening for incoming connections.
195  *
196  * Options can be a combination of the following:
197  * - BIO_SOCK_KEEPALIVE: enable regularly sending keep-alive messages.
198  * - BIO_SOCK_NONBLOCK: Make the socket non-blocking.
199  * - BIO_SOCK_NODELAY: don't delay small messages.
200  * - BIO_SOCK_REUSEADDR: Try to reuse the address and port combination
201  *   for a recently closed port.
202  * - BIO_SOCK_V6_ONLY: When creating an IPv6 socket, make it listen only
203  *   for IPv6 addresses and not IPv4 addresses mapped to IPv6.
204  *
205  * It's recommended that you set up both an IPv6 and IPv4 listen socket, and
206  * then check both for new clients that connect to it.  You want to set up
207  * the socket as non-blocking in that case since else it could hang.
208  *
209  * Not all operating systems support IPv4 addresses on an IPv6 socket, and for
210  * others it's an option.  If you pass the BIO_LISTEN_V6_ONLY it will try to
211  * create the IPv6 sockets to only listen for IPv6 connection.
212  *
213  * It could be that the first BIO_listen() call will listen to all the IPv6
214  * and IPv4 addresses and that then trying to bind to the IPv4 address will
215  * fail.  We can't tell the difference between already listening ourself to
216  * it and someone else listening to it when failing and errno is EADDRINUSE, so
217  * it's recommended to not give an error in that case if the first call was
218  * successful.
219  *
220  * When restarting the program it could be that the port is still in use.  If
221  * you set to BIO_SOCK_REUSEADDR option it will try to reuse the port anyway.
222  * It's recommended that you use this.
223  */
224 int BIO_listen(int sock, const BIO_ADDR *addr, int options)
225 {
226     int on = 1;
227     int socktype;
228     socklen_t socktype_len = sizeof(socktype);
229
230     if (sock == -1) {
231         BIOerr(BIO_F_BIO_LISTEN, BIO_R_INVALID_SOCKET);
232         return 0;
233     }
234
235     if (getsockopt(sock, SOL_SOCKET, SO_TYPE,
236                    (void *)&socktype, &socktype_len) != 0
237         || socktype_len != sizeof(socktype)) {
238         ERR_raise_data(ERR_LIB_SYS, get_last_socket_error(),
239                        "calling getsockopt()");
240         BIOerr(BIO_F_BIO_LISTEN, BIO_R_GETTING_SOCKTYPE);
241         return 0;
242     }
243
244     if (!BIO_socket_nbio(sock, (options & BIO_SOCK_NONBLOCK) != 0))
245         return 0;
246
247     if (options & BIO_SOCK_KEEPALIVE) {
248         if (setsockopt(sock, SOL_SOCKET, SO_KEEPALIVE,
249                        (const void *)&on, sizeof(on)) != 0) {
250             ERR_raise_data(ERR_LIB_SYS, get_last_socket_error(),
251                            "calling setsockopt()");
252             BIOerr(BIO_F_BIO_LISTEN, BIO_R_UNABLE_TO_KEEPALIVE);
253             return 0;
254         }
255     }
256
257     if (options & BIO_SOCK_NODELAY) {
258         if (setsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
259                        (const void *)&on, sizeof(on)) != 0) {
260             ERR_raise_data(ERR_LIB_SYS, get_last_socket_error(),
261                            "calling setsockopt()");
262             BIOerr(BIO_F_BIO_LISTEN, BIO_R_UNABLE_TO_NODELAY);
263             return 0;
264         }
265     }
266
267 # ifdef IPV6_V6ONLY
268     if (BIO_ADDR_family(addr) == AF_INET6) {
269         /*
270          * Note: Windows default of IPV6_V6ONLY is ON, and Linux is OFF.
271          * Therefore we always have to use setsockopt here.
272          */
273         on = options & BIO_SOCK_V6_ONLY ? 1 : 0;
274         if (setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY,
275                        (const void *)&on, sizeof(on)) != 0) {
276             ERR_raise_data(ERR_LIB_SYS, get_last_socket_error(),
277                            "calling setsockopt()");
278             BIOerr(BIO_F_BIO_LISTEN, BIO_R_LISTEN_V6_ONLY);
279             return 0;
280         }
281     }
282 # endif
283
284     if (!BIO_bind(sock, addr, options))
285         return 0;
286
287     if (socktype != SOCK_DGRAM && listen(sock, MAX_LISTEN) == -1) {
288         ERR_raise_data(ERR_LIB_SYS, get_last_socket_error(),
289                        "calling listen()");
290         BIOerr(BIO_F_BIO_LISTEN, BIO_R_UNABLE_TO_LISTEN_SOCKET);
291         return 0;
292     }
293
294     return 1;
295 }
296
297 /*-
298  * BIO_accept_ex - Accept new incoming connections
299  * @sock: the listening socket
300  * @addr: the BIO_ADDR to store the peer address in
301  * @options: BIO socket options, applied on the accepted socket.
302  *
303  */
304 int BIO_accept_ex(int accept_sock, BIO_ADDR *addr_, int options)
305 {
306     socklen_t len;
307     int accepted_sock;
308     BIO_ADDR locaddr;
309     BIO_ADDR *addr = addr_ == NULL ? &locaddr : addr_;
310
311     len = sizeof(*addr);
312     accepted_sock = accept(accept_sock,
313                            BIO_ADDR_sockaddr_noconst(addr), &len);
314     if (accepted_sock == -1) {
315         if (!BIO_sock_should_retry(accepted_sock)) {
316             ERR_raise_data(ERR_LIB_SYS, get_last_socket_error(),
317                            "calling accept()");
318             BIOerr(BIO_F_BIO_ACCEPT_EX, BIO_R_ACCEPT_ERROR);
319         }
320         return INVALID_SOCKET;
321     }
322
323     if (!BIO_socket_nbio(accepted_sock, (options & BIO_SOCK_NONBLOCK) != 0)) {
324         closesocket(accepted_sock);
325         return INVALID_SOCKET;
326     }
327
328     return accepted_sock;
329 }
330
331 /*-
332  * BIO_closesocket - Close a socket
333  * @sock: the socket to close
334  */
335 int BIO_closesocket(int sock)
336 {
337     if (closesocket(sock) < 0)
338         return 0;
339     return 1;
340 }
341 #endif