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