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