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