add BIO_socket_wait(), BIO_wait(), and BIO_connect_retry() improving timeout support
[openssl.git] / crypto / bio / b_sock.c
1 /*
2  * Copyright 1995-2018 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 "bio_local.h"
13 #ifndef OPENSSL_NO_SOCK
14 # define SOCKET_PROTOCOL IPPROTO_TCP
15 # ifdef SO_MAXCONN
16 #  define MAX_LISTEN  SO_MAXCONN
17 # elif defined(SOMAXCONN)
18 #  define MAX_LISTEN  SOMAXCONN
19 # else
20 #  define MAX_LISTEN  32
21 # endif
22 # if defined(OPENSSL_SYS_WINDOWS)
23 static int wsa_init_done = 0;
24 # endif
25
26 # ifndef _WIN32
27 #  include <unistd.h>
28 #  include <sys/select.h>
29 # else
30 #  include <winsock.h> /* for type fd_set */
31 # endif
32
33 # ifndef OPENSSL_NO_DEPRECATED_1_1_0
34 int BIO_get_host_ip(const char *str, unsigned char *ip)
35 {
36     BIO_ADDRINFO *res = NULL;
37     int ret = 0;
38
39     if (BIO_sock_init() != 1)
40         return 0;               /* don't generate another error code here */
41
42     if (BIO_lookup(str, NULL, BIO_LOOKUP_CLIENT, AF_INET, SOCK_STREAM, &res)) {
43         size_t l;
44
45         if (BIO_ADDRINFO_family(res) != AF_INET) {
46             BIOerr(BIO_F_BIO_GET_HOST_IP,
47                    BIO_R_GETHOSTBYNAME_ADDR_IS_NOT_AF_INET);
48         } else if (BIO_ADDR_rawaddress(BIO_ADDRINFO_address(res), NULL, &l)) {
49             /*
50              * Because only AF_INET addresses will reach this far, we can assert
51              * that l should be 4
52              */
53             if (ossl_assert(l == 4))
54                 ret = BIO_ADDR_rawaddress(BIO_ADDRINFO_address(res), ip, &l);
55         }
56         BIO_ADDRINFO_free(res);
57     } else {
58         ERR_add_error_data(2, "host=", str);
59     }
60
61     return ret;
62 }
63
64 int BIO_get_port(const char *str, unsigned short *port_ptr)
65 {
66     BIO_ADDRINFO *res = NULL;
67     int ret = 0;
68
69     if (str == NULL) {
70         BIOerr(BIO_F_BIO_GET_PORT, BIO_R_NO_PORT_DEFINED);
71         return 0;
72     }
73
74     if (BIO_sock_init() != 1)
75         return 0;               /* don't generate another error code here */
76
77     if (BIO_lookup(NULL, str, BIO_LOOKUP_CLIENT, AF_INET, SOCK_STREAM, &res)) {
78         if (BIO_ADDRINFO_family(res) != AF_INET) {
79             BIOerr(BIO_F_BIO_GET_PORT,
80                    BIO_R_ADDRINFO_ADDR_IS_NOT_AF_INET);
81         } else {
82             *port_ptr = ntohs(BIO_ADDR_rawport(BIO_ADDRINFO_address(res)));
83             ret = 1;
84         }
85         BIO_ADDRINFO_free(res);
86     } else {
87         ERR_add_error_data(2, "host=", str);
88     }
89
90     return ret;
91 }
92 # endif
93
94 int BIO_sock_error(int sock)
95 {
96     int j = 0, i;
97     socklen_t size = sizeof(j);
98
99     /*
100      * Note: under Windows the third parameter is of type (char *) whereas
101      * under other systems it is (void *) if you don't have a cast it will
102      * choke the compiler: if you do have a cast then you can either go for
103      * (char *) or (void *).
104      */
105     i = getsockopt(sock, SOL_SOCKET, SO_ERROR, (void *)&j, &size);
106     if (i < 0)
107         return get_last_socket_error();
108     else
109         return j;
110 }
111
112 # ifndef OPENSSL_NO_DEPRECATED_1_1_0
113 struct hostent *BIO_gethostbyname(const char *name)
114 {
115     /*
116      * Caching gethostbyname() results forever is wrong, so we have to let
117      * the true gethostbyname() worry about this
118      */
119     return gethostbyname(name);
120 }
121 # endif
122
123 int BIO_sock_init(void)
124 {
125 # ifdef OPENSSL_SYS_WINDOWS
126     static struct WSAData wsa_state;
127
128     if (!wsa_init_done) {
129         wsa_init_done = 1;
130         memset(&wsa_state, 0, sizeof(wsa_state));
131         /*
132          * Not making wsa_state available to the rest of the code is formally
133          * wrong. But the structures we use are [believed to be] invariable
134          * among Winsock DLLs, while API availability is [expected to be]
135          * probed at run-time with DSO_global_lookup.
136          */
137         if (WSAStartup(0x0202, &wsa_state) != 0) {
138             ERR_raise_data(ERR_LIB_SYS, get_last_socket_error(),
139                            "calling wsastartup()");
140             BIOerr(BIO_F_BIO_SOCK_INIT, BIO_R_WSASTARTUP);
141             return -1;
142         }
143     }
144 # endif                         /* OPENSSL_SYS_WINDOWS */
145 # ifdef WATT32
146     extern int _watt_do_exit;
147     _watt_do_exit = 0;          /* don't make sock_init() call exit() */
148     if (sock_init())
149         return -1;
150 # endif
151
152     return 1;
153 }
154
155 void bio_sock_cleanup_int(void)
156 {
157 # ifdef OPENSSL_SYS_WINDOWS
158     if (wsa_init_done) {
159         wsa_init_done = 0;
160         WSACleanup();
161     }
162 # endif
163 }
164
165 int BIO_socket_ioctl(int fd, long type, void *arg)
166 {
167     int i;
168
169 #  ifdef __DJGPP__
170     i = ioctlsocket(fd, type, (char *)arg);
171 #  else
172 #   if defined(OPENSSL_SYS_VMS)
173     /*-
174      * 2011-02-18 SMS.
175      * VMS ioctl() can't tolerate a 64-bit "void *arg", but we
176      * observe that all the consumers pass in an "unsigned long *",
177      * so we arrange a local copy with a short pointer, and use
178      * that, instead.
179      */
180 #    if __INITIAL_POINTER_SIZE == 64
181 #     define ARG arg_32p
182 #     pragma pointer_size save
183 #     pragma pointer_size 32
184     unsigned long arg_32;
185     unsigned long *arg_32p;
186 #     pragma pointer_size restore
187     arg_32p = &arg_32;
188     arg_32 = *((unsigned long *)arg);
189 #    else                       /* __INITIAL_POINTER_SIZE == 64 */
190 #     define ARG arg
191 #    endif                      /* __INITIAL_POINTER_SIZE == 64 [else] */
192 #   else                        /* defined(OPENSSL_SYS_VMS) */
193 #    define ARG arg
194 #   endif                       /* defined(OPENSSL_SYS_VMS) [else] */
195
196     i = ioctlsocket(fd, type, ARG);
197 #  endif                        /* __DJGPP__ */
198     if (i < 0)
199         ERR_raise_data(ERR_LIB_SYS, get_last_socket_error(),
200                        "calling ioctlsocket()");
201     return i;
202 }
203
204 # ifndef OPENSSL_NO_DEPRECATED_1_1_0
205 int BIO_get_accept_socket(char *host, int bind_mode)
206 {
207     int s = INVALID_SOCKET;
208     char *h = NULL, *p = NULL;
209     BIO_ADDRINFO *res = NULL;
210
211     if (!BIO_parse_hostserv(host, &h, &p, BIO_PARSE_PRIO_SERV))
212         return INVALID_SOCKET;
213
214     if (BIO_sock_init() != 1)
215         return INVALID_SOCKET;
216
217     if (BIO_lookup(h, p, BIO_LOOKUP_SERVER, AF_UNSPEC, SOCK_STREAM, &res) != 0)
218         goto err;
219
220     if ((s = BIO_socket(BIO_ADDRINFO_family(res), BIO_ADDRINFO_socktype(res),
221                         BIO_ADDRINFO_protocol(res), 0)) == INVALID_SOCKET) {
222         s = INVALID_SOCKET;
223         goto err;
224     }
225
226     if (!BIO_listen(s, BIO_ADDRINFO_address(res),
227                     bind_mode ? BIO_SOCK_REUSEADDR : 0)) {
228         BIO_closesocket(s);
229         s = INVALID_SOCKET;
230     }
231
232  err:
233     BIO_ADDRINFO_free(res);
234     OPENSSL_free(h);
235     OPENSSL_free(p);
236
237     return s;
238 }
239
240 int BIO_accept(int sock, char **ip_port)
241 {
242     BIO_ADDR res;
243     int ret = -1;
244
245     ret = BIO_accept_ex(sock, &res, 0);
246     if (ret == (int)INVALID_SOCKET) {
247         if (BIO_sock_should_retry(ret)) {
248             ret = -2;
249             goto end;
250         }
251         ERR_raise_data(ERR_LIB_SYS, get_last_socket_error(),
252                        "calling accept()");
253         BIOerr(BIO_F_BIO_ACCEPT, BIO_R_ACCEPT_ERROR);
254         goto end;
255     }
256
257     if (ip_port != NULL) {
258         char *host = BIO_ADDR_hostname_string(&res, 1);
259         char *port = BIO_ADDR_service_string(&res, 1);
260         if (host != NULL && port != NULL)
261             *ip_port = OPENSSL_zalloc(strlen(host) + strlen(port) + 2);
262         else
263             *ip_port = NULL;
264
265         if (*ip_port == NULL) {
266             BIOerr(BIO_F_BIO_ACCEPT, ERR_R_MALLOC_FAILURE);
267             BIO_closesocket(ret);
268             ret = (int)INVALID_SOCKET;
269         } else {
270             strcpy(*ip_port, host);
271             strcat(*ip_port, ":");
272             strcat(*ip_port, port);
273         }
274         OPENSSL_free(host);
275         OPENSSL_free(port);
276     }
277
278  end:
279     return ret;
280 }
281 # endif
282
283 int BIO_set_tcp_ndelay(int s, int on)
284 {
285     int ret = 0;
286 # if defined(TCP_NODELAY) && (defined(IPPROTO_TCP) || defined(SOL_TCP))
287     int opt;
288
289 #  ifdef SOL_TCP
290     opt = SOL_TCP;
291 #  else
292 #   ifdef IPPROTO_TCP
293     opt = IPPROTO_TCP;
294 #   endif
295 #  endif
296
297     ret = setsockopt(s, opt, TCP_NODELAY, (char *)&on, sizeof(on));
298 # endif
299     return (ret == 0);
300 }
301
302 int BIO_socket_nbio(int s, int mode)
303 {
304     int ret = -1;
305     int l;
306
307     l = mode;
308 # ifdef FIONBIO
309     l = mode;
310
311     ret = BIO_socket_ioctl(s, FIONBIO, &l);
312 # elif defined(F_GETFL) && defined(F_SETFL) && (defined(O_NONBLOCK) || defined(FNDELAY))
313     /* make sure this call always pushes an error level; BIO_socket_ioctl() does so, so we do too. */
314
315     l = fcntl(s, F_GETFL, 0);
316     if (l == -1) {
317         ERR_raise_data(ERR_LIB_SYS, get_last_sys_error(),
318                        "calling fcntl()");
319         ret = -1;
320     } else {
321 #  if defined(O_NONBLOCK)
322         l &= ~O_NONBLOCK;
323 #  else
324         l &= ~FNDELAY; /* BSD4.x */
325 #  endif
326         if (mode) {
327 #  if defined(O_NONBLOCK)
328             l |= O_NONBLOCK;
329 #  else
330             l |= FNDELAY; /* BSD4.x */
331 #  endif
332         }
333         ret = fcntl(s, F_SETFL, l);
334
335         if (ret < 0) {
336             ERR_raise_data(ERR_LIB_SYS, get_last_sys_error(),
337                            "calling fcntl()");
338         }
339     }
340 # else
341     /* make sure this call always pushes an error level; BIO_socket_ioctl() does so, so we do too. */
342     BIOerr(BIO_F_BIO_SOCKET_NBIO, ERR_R_PASSED_INVALID_ARGUMENT);
343 # endif
344
345     return (ret == 0);
346 }
347
348 int BIO_sock_info(int sock,
349                   enum BIO_sock_info_type type, union BIO_sock_info_u *info)
350 {
351     switch (type) {
352     case BIO_SOCK_INFO_ADDRESS:
353         {
354             socklen_t addr_len;
355             int ret = 0;
356             addr_len = sizeof(*info->addr);
357             ret = getsockname(sock, BIO_ADDR_sockaddr_noconst(info->addr),
358                               &addr_len);
359             if (ret == -1) {
360                 ERR_raise_data(ERR_LIB_SYS, get_last_socket_error(),
361                                "calling getsockname()");
362                 BIOerr(BIO_F_BIO_SOCK_INFO, BIO_R_GETSOCKNAME_ERROR);
363                 return 0;
364             }
365             if ((size_t)addr_len > sizeof(*info->addr)) {
366                 BIOerr(BIO_F_BIO_SOCK_INFO, BIO_R_GETSOCKNAME_TRUNCATED_ADDRESS);
367                 return 0;
368             }
369         }
370         break;
371     default:
372         BIOerr(BIO_F_BIO_SOCK_INFO, BIO_R_UNKNOWN_INFO_TYPE);
373         return 0;
374     }
375     return 1;
376 }
377
378 /* TODO simplify by BIO_socket_wait() further other uses of select() in apps/ */
379 /*
380  * Wait on fd at most until max_time; succeed immediately if max_time == 0.
381  * If for_read == 0 then assume to wait for writing, else wait for reading.
382  * Returns -1 on error, 0 on timeout, and 1 on success.
383  */
384 int BIO_socket_wait(int fd, int for_read, time_t max_time)
385 {
386     fd_set confds;
387     struct timeval tv;
388     time_t now;
389
390     if (max_time == 0)
391         return 1;
392
393     now = time(NULL);
394     if (max_time <= now)
395         return 0;
396
397     FD_ZERO(&confds);
398     openssl_fdset(fd, &confds);
399     tv.tv_usec = 0;
400     tv.tv_sec = (long)(max_time - now); /* this might overflow */
401     return select(fd + 1, for_read ? &confds : NULL,
402                   for_read ? NULL : &confds, NULL, &tv);
403 }
404
405 /*
406  * Wait on BIO at most until max_time; succeed immediately if max_time == 0.
407  * Returns -1 on error, 0 on timeout, and 1 on success.
408  */
409 static int bio_wait(BIO *bio, time_t max_time)
410 {
411     int fd;
412
413     if (BIO_get_fd(bio, &fd) <= 0)
414         return -1;
415     return BIO_socket_wait(fd, BIO_should_read(bio), max_time);
416 }
417
418 /*
419  * Wait on BIO at most until max_time; succeed immediately if max_time == 0.
420  * Call BIOerr(...) unless success.
421  * Returns -1 on error, 0 on timeout, and 1 on success.
422  */
423 int BIO_wait(BIO *bio, time_t max_time)
424 {
425     int rv = bio_wait(bio, max_time);
426
427     if (rv <= 0)
428         BIOerr(0, rv == 0 ? BIO_R_TRANSFER_TIMEOUT : BIO_R_TRANSFER_ERROR);
429     return rv;
430 }
431
432 /*
433  * Connect via the given BIO using BIO_do_connect() until success/timeout/error.
434  * Parameter timeout == 0 means infinite, < 0 leads to immediate timeout error.
435  * Returns -1 on error, 0 on timeout, and 1 on success.
436  */
437 int BIO_connect_retry(BIO *bio, int timeout)
438 {
439     int blocking = timeout == 0;
440     time_t max_time = timeout > 0 ? time(NULL) + timeout : 0;
441     int rv;
442
443     if (bio == NULL) {
444         BIOerr(0, ERR_R_PASSED_NULL_PARAMETER);
445         return -1;
446     }
447
448     if (timeout < 0) {
449         BIOerr(0, BIO_R_CONNECT_TIMEOUT);
450         return 0;
451     }
452
453     if (!blocking)
454         BIO_set_nbio(bio, 1);
455
456  retry: /* it does not help here to set SSL_MODE_AUTO_RETRY */
457     rv = BIO_do_connect(bio); /* This indirectly calls ERR_clear_error(); */
458
459     if (rv <= 0) {
460         if (get_last_sys_error() == ETIMEDOUT) {
461             /*
462              * if blocking, despite blocking BIO, BIO_do_connect() timed out
463              * when non-blocking, BIO_do_connect() timed out early
464              * with rv == -1 and get_last_sys_error() == 0
465              */
466             ERR_clear_error();
467             (void)BIO_reset(bio);
468             /*
469              * unless using BIO_reset(), blocking next connect() may crash and
470              * non-blocking next BIO_do_connect() will fail
471              */
472             goto retry;
473         } else if (BIO_should_retry(bio)) {
474             /* will not actually wait if timeout == 0 (i.e., blocking BIO) */
475             rv = bio_wait(bio, max_time);
476             if (rv > 0)
477                 goto retry;
478             BIOerr(0, rv == 0 ? BIO_R_CONNECT_TIMEOUT : BIO_R_CONNECT_ERROR);
479         } else {
480             rv = -1;
481             if (ERR_peek_error() == 0) /* missing error queue entry */
482                 BIOerr(0, BIO_R_CONNECT_ERROR); /* workaround: general error */
483         }
484     }
485
486     return rv;
487 }
488
489 #endif /* !defined(OPENSSL_NO_SOCK) */