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