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