Refactoring BIO: new socket-handling functions, deprecate older ones
[openssl.git] / crypto / bio / b_sock.c
1 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
2  * All rights reserved.
3  *
4  * This package is an SSL implementation written
5  * by Eric Young (eay@cryptsoft.com).
6  * The implementation was written so as to conform with Netscapes SSL.
7  *
8  * This library is free for commercial and non-commercial use as long as
9  * the following conditions are aheared to.  The following conditions
10  * apply to all code found in this distribution, be it the RC4, RSA,
11  * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
12  * included with this distribution is covered by the same copyright terms
13  * except that the holder is Tim Hudson (tjh@cryptsoft.com).
14  *
15  * Copyright remains Eric Young's, and as such any Copyright notices in
16  * the code are not to be removed.
17  * If this package is used in a product, Eric Young should be given attribution
18  * as the author of the parts of the library used.
19  * This can be in the form of a textual message at program startup or
20  * in documentation (online or textual) provided with the package.
21  *
22  * Redistribution and use in source and binary forms, with or without
23  * modification, are permitted provided that the following conditions
24  * are met:
25  * 1. Redistributions of source code must retain the copyright
26  *    notice, this list of conditions and the following disclaimer.
27  * 2. Redistributions in binary form must reproduce the above copyright
28  *    notice, this list of conditions and the following disclaimer in the
29  *    documentation and/or other materials provided with the distribution.
30  * 3. All advertising materials mentioning features or use of this software
31  *    must display the following acknowledgement:
32  *    "This product includes cryptographic software written by
33  *     Eric Young (eay@cryptsoft.com)"
34  *    The word 'cryptographic' can be left out if the rouines from the library
35  *    being used are not cryptographic related :-).
36  * 4. If you include any Windows specific code (or a derivative thereof) from
37  *    the apps directory (application code) you must include an acknowledgement:
38  *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
39  *
40  * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
41  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
42  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
43  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
44  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
45  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
46  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
47  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
48  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
49  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
50  * SUCH DAMAGE.
51  *
52  * The licence and distribution terms for any publically available version or
53  * derivative of this code cannot be changed.  i.e. this code cannot simply be
54  * copied and put under another distribution licence
55  * [including the GNU Public Licence.]
56  */
57
58 #include <stdio.h>
59 #include <stdlib.h>
60 #include <errno.h>
61 #include "bio_lcl.h"
62 #if defined(NETWARE_CLIB)
63 # include <sys/ioctl.h>
64 NETDB_DEFINE_CONTEXT
65 #endif
66 #ifndef OPENSSL_NO_SOCK
67 # include <openssl/dso.h>
68 # define SOCKET_PROTOCOL IPPROTO_TCP
69 # ifdef SO_MAXCONN
70 #  define MAX_LISTEN  SO_MAXCONN
71 # elif defined(SOMAXCONN)
72 #  define MAX_LISTEN  SOMAXCONN
73 # else
74 #  define MAX_LISTEN  32
75 # endif
76 # if defined(OPENSSL_SYS_WINDOWS) || (defined(OPENSSL_SYS_NETWARE) && !defined(NETWARE_BSDSOCK))
77 static int wsa_init_done = 0;
78 # endif
79
80 /*
81  * WSAAPI specifier is required to make indirect calls to run-time
82  * linked WinSock 2 functions used in this module, to be specific
83  * [get|free]addrinfo and getnameinfo. This is because WinSock uses
84  * uses non-C calling convention, __stdcall vs. __cdecl, on x86
85  * Windows. On non-WinSock platforms WSAAPI needs to be void.
86  */
87 # ifndef WSAAPI
88 #  define WSAAPI
89 # endif
90
91 # if OPENSSL_API_COMPAT < 0x10100000L
92 static int get_ip(const char *str, unsigned char *ip);
93 int BIO_get_host_ip(const char *str, unsigned char *ip)
94 {
95     int i;
96     int err = 1;
97     int locked = 0;
98     struct hostent *he;
99
100     i = get_ip(str, ip);
101     if (i < 0) {
102         BIOerr(BIO_F_BIO_GET_HOST_IP, BIO_R_INVALID_IP_ADDRESS);
103         goto err;
104     }
105
106     /*
107      * At this point, we have something that is most probably correct in some
108      * way, so let's init the socket.
109      */
110     if (BIO_sock_init() != 1)
111         return 0;               /* don't generate another error code here */
112
113     /*
114      * If the string actually contained an IP address, we need not do
115      * anything more
116      */
117     if (i > 0)
118         return (1);
119
120     /* do a gethostbyname */
121     CRYPTO_w_lock(CRYPTO_LOCK_GETHOSTBYNAME);
122     locked = 1;
123     he = BIO_gethostbyname(str);
124     if (he == NULL) {
125         BIOerr(BIO_F_BIO_GET_HOST_IP, BIO_R_BAD_HOSTNAME_LOOKUP);
126         goto err;
127     }
128
129     if (he->h_addrtype != AF_INET) {
130         BIOerr(BIO_F_BIO_GET_HOST_IP,
131                BIO_R_GETHOSTBYNAME_ADDR_IS_NOT_AF_INET);
132         goto err;
133     }
134     for (i = 0; i < 4; i++)
135         ip[i] = he->h_addr_list[0][i];
136     err = 0;
137
138  err:
139     if (locked)
140         CRYPTO_w_unlock(CRYPTO_LOCK_GETHOSTBYNAME);
141     if (err) {
142         ERR_add_error_data(2, "host=", str);
143         return 0;
144     } else
145         return 1;
146 }
147
148 int BIO_get_port(const char *str, unsigned short *port_ptr)
149 {
150     int i;
151     struct servent *s;
152
153     if (str == NULL) {
154         BIOerr(BIO_F_BIO_GET_PORT, BIO_R_NO_PORT_DEFINED);
155         return (0);
156     }
157     i = atoi(str);
158     if (i != 0)
159         *port_ptr = (unsigned short)i;
160     else {
161         CRYPTO_w_lock(CRYPTO_LOCK_GETSERVBYNAME);
162         /*
163          * Note: under VMS with SOCKETSHR, it seems like the first parameter
164          * is 'char *', instead of 'const char *'
165          */
166 # ifndef CONST_STRICT
167         s = getservbyname((char *)str, "tcp");
168 # else
169         s = getservbyname(str, "tcp");
170 # endif
171         if (s != NULL)
172             *port_ptr = ntohs((unsigned short)s->s_port);
173         CRYPTO_w_unlock(CRYPTO_LOCK_GETSERVBYNAME);
174         if (s == NULL) {
175             if (strcmp(str, "http") == 0)
176                 *port_ptr = 80;
177             else if (strcmp(str, "telnet") == 0)
178                 *port_ptr = 23;
179             else if (strcmp(str, "socks") == 0)
180                 *port_ptr = 1080;
181             else if (strcmp(str, "https") == 0)
182                 *port_ptr = 443;
183             else if (strcmp(str, "ssl") == 0)
184                 *port_ptr = 443;
185             else if (strcmp(str, "ftp") == 0)
186                 *port_ptr = 21;
187             else if (strcmp(str, "gopher") == 0)
188                 *port_ptr = 70;
189             else {
190                 SYSerr(SYS_F_GETSERVBYNAME, get_last_socket_error());
191                 ERR_add_error_data(3, "service='", str, "'");
192                 return (0);
193             }
194         }
195     }
196     return (1);
197 }
198 # endif
199
200 int BIO_sock_error(int sock)
201 {
202     int j, i;
203     union {
204         size_t s;
205         int i;
206     } size;
207
208     /* heuristic way to adapt for platforms that expect 64-bit optlen */
209     size.s = 0, size.i = sizeof(j);
210     /*
211      * Note: under Windows the third parameter is of type (char *) whereas
212      * under other systems it is (void *) if you don't have a cast it will
213      * choke the compiler: if you do have a cast then you can either go for
214      * (char *) or (void *).
215      */
216     i = getsockopt(sock, SOL_SOCKET, SO_ERROR, (void *)&j, (void *)&size);
217     if (i < 0)
218         return (1);
219     else
220         return (j);
221 }
222
223 # if OPENSSL_API_COMPAT < 0x10100000L
224 struct hostent *BIO_gethostbyname(const char *name)
225 {
226     /*
227      * Caching gethostbyname() results forever is wrong, so we have to let
228      * the true gethostbyname() worry about this
229      */
230 # if (defined(NETWARE_BSDSOCK) && !defined(__NOVELL_LIBC__))
231     return gethostbyname((char *)name);
232 # else
233     return gethostbyname(name);
234 # endif
235 }
236 # endif
237
238 int BIO_sock_init(void)
239 {
240 # ifdef OPENSSL_SYS_WINDOWS
241     static struct WSAData wsa_state;
242
243     if (!wsa_init_done) {
244         int err;
245
246         wsa_init_done = 1;
247         memset(&wsa_state, 0, sizeof(wsa_state));
248         /*
249          * Not making wsa_state available to the rest of the code is formally
250          * wrong. But the structures we use are [beleived to be] invariable
251          * among Winsock DLLs, while API availability is [expected to be]
252          * probed at run-time with DSO_global_lookup.
253          */
254         if (WSAStartup(0x0202, &wsa_state) != 0) {
255             err = WSAGetLastError();
256             SYSerr(SYS_F_WSASTARTUP, err);
257             BIOerr(BIO_F_BIO_SOCK_INIT, BIO_R_WSASTARTUP);
258             return (-1);
259         }
260     }
261 # endif                         /* OPENSSL_SYS_WINDOWS */
262 # ifdef WATT32
263     extern int _watt_do_exit;
264     _watt_do_exit = 0;          /* don't make sock_init() call exit() */
265     if (sock_init())
266         return (-1);
267 # endif
268
269 # if defined(OPENSSL_SYS_NETWARE) && !defined(NETWARE_BSDSOCK)
270     WORD wVerReq;
271     WSADATA wsaData;
272     int err;
273
274     if (!wsa_init_done) {
275         wsa_init_done = 1;
276         wVerReq = MAKEWORD(2, 0);
277         err = WSAStartup(wVerReq, &wsaData);
278         if (err != 0) {
279             SYSerr(SYS_F_WSASTARTUP, err);
280             BIOerr(BIO_F_BIO_SOCK_INIT, BIO_R_WSASTARTUP);
281             return (-1);
282         }
283     }
284 # endif
285
286     return (1);
287 }
288
289 void BIO_sock_cleanup(void)
290 {
291 # ifdef OPENSSL_SYS_WINDOWS
292     if (wsa_init_done) {
293         wsa_init_done = 0;
294         WSACleanup();
295     }
296 # elif defined(OPENSSL_SYS_NETWARE) && !defined(NETWARE_BSDSOCK)
297     if (wsa_init_done) {
298         wsa_init_done = 0;
299         WSACleanup();
300     }
301 # endif
302 }
303
304 # if !defined(OPENSSL_SYS_VMS) || __VMS_VER >= 70000000
305
306 int BIO_socket_ioctl(int fd, long type, void *arg)
307 {
308     int i;
309
310 #  ifdef __DJGPP__
311     i = ioctlsocket(fd, type, (char *)arg);
312 #  else
313 #   if defined(OPENSSL_SYS_VMS)
314     /*-
315      * 2011-02-18 SMS.
316      * VMS ioctl() can't tolerate a 64-bit "void *arg", but we
317      * observe that all the consumers pass in an "unsigned long *",
318      * so we arrange a local copy with a short pointer, and use
319      * that, instead.
320      */
321 #    if __INITIAL_POINTER_SIZE == 64
322 #     define ARG arg_32p
323 #     pragma pointer_size save
324 #     pragma pointer_size 32
325     unsigned long arg_32;
326     unsigned long *arg_32p;
327 #     pragma pointer_size restore
328     arg_32p = &arg_32;
329     arg_32 = *((unsigned long *)arg);
330 #    else                       /* __INITIAL_POINTER_SIZE == 64 */
331 #     define ARG arg
332 #    endif                      /* __INITIAL_POINTER_SIZE == 64 [else] */
333 #   else                        /* defined(OPENSSL_SYS_VMS) */
334 #    define ARG arg
335 #   endif                       /* defined(OPENSSL_SYS_VMS) [else] */
336
337     i = ioctlsocket(fd, type, ARG);
338 #  endif                        /* __DJGPP__ */
339     if (i < 0)
340         SYSerr(SYS_F_IOCTLSOCKET, get_last_socket_error());
341     return (i);
342 }
343 # endif                         /* __VMS_VER */
344
345 # if OPENSSL_API_COMPAT < 0x10100000L
346 /*
347  * The reason I have implemented this instead of using sscanf is because
348  * Visual C 1.52c gives an unresolved external when linking a DLL :-(
349  */
350 static int get_ip(const char *str, unsigned char ip[4])
351 {
352     unsigned int tmp[4];
353     int num = 0, c, ok = 0;
354
355     tmp[0] = tmp[1] = tmp[2] = tmp[3] = 0;
356
357     for (;;) {
358         c = *(str++);
359         if ((c >= '0') && (c <= '9')) {
360             ok = 1;
361             tmp[num] = tmp[num] * 10 + c - '0';
362             if (tmp[num] > 255)
363                 return (0);
364         } else if (c == '.') {
365             if (!ok)
366                 return (-1);
367             if (num == 3)
368                 return (0);
369             num++;
370             ok = 0;
371         } else if (c == '\0' && (num == 3) && ok)
372             break;
373         else
374             return (0);
375     }
376     ip[0] = tmp[0];
377     ip[1] = tmp[1];
378     ip[2] = tmp[2];
379     ip[3] = tmp[3];
380     return (1);
381 }
382
383 int BIO_get_accept_socket(char *host, int bind_mode)
384 {
385     int ret = 0;
386     union {
387         struct sockaddr sa;
388         struct sockaddr_in sa_in;
389 # if OPENSSL_USE_IPV6
390         struct sockaddr_in6 sa_in6;
391 # endif
392     } server, client;
393     int s = (int)INVALID_SOCKET, cs, addrlen;
394     unsigned char ip[4];
395     unsigned short port;
396     char *str = NULL, *e;
397     char *h, *p;
398     unsigned long l;
399     int err_num;
400
401     if (BIO_sock_init() != 1)
402         return ((int)INVALID_SOCKET);
403
404     if ((str = OPENSSL_strdup(host)) == NULL)
405         return ((int)INVALID_SOCKET);
406
407     h = p = NULL;
408     h = str;
409     for (e = str; *e; e++) {
410         if (*e == ':') {
411             p = e;
412         } else if (*e == '/') {
413             *e = '\0';
414             break;
415         }
416     }
417     if (p)
418         *p++ = '\0';            /* points at last ':', '::port' is special
419                                  * [see below] */
420     else
421         p = h, h = NULL;
422
423 # ifdef EAI_FAMILY
424     do {
425         static union {
426             void *p;
427             int (WSAAPI *f) (const char *, const char *,
428                              const struct addrinfo *, struct addrinfo **);
429         } p_getaddrinfo = {
430             NULL
431         };
432         static union {
433             void *p;
434             void (WSAAPI *f) (struct addrinfo *);
435         } p_freeaddrinfo = {
436             NULL
437         };
438         struct addrinfo *res, hint;
439
440         if (p_getaddrinfo.p == NULL) {
441             if ((p_getaddrinfo.p = DSO_global_lookup("getaddrinfo")) == NULL
442                 || (p_freeaddrinfo.p =
443                     DSO_global_lookup("freeaddrinfo")) == NULL)
444                 p_getaddrinfo.p = (void *)-1;
445         }
446         if (p_getaddrinfo.p == (void *)-1)
447             break;
448
449         /*
450          * '::port' enforces IPv6 wildcard listener. Some OSes, e.g. Solaris,
451          * default to IPv6 without any hint. Also note that commonly IPv6
452          * wildchard socket can service IPv4 connections just as well...
453          */
454         memset(&hint, 0, sizeof(hint));
455         hint.ai_flags = AI_PASSIVE;
456         if (h) {
457             if (strchr(h, ':')) {
458                 if (h[1] == '\0')
459                     h = NULL;
460 #  if OPENSSL_USE_IPV6
461                 hint.ai_family = AF_INET6;
462 #  else
463                 h = NULL;
464 #  endif
465             } else if (h[0] == '*' && h[1] == '\0') {
466                 hint.ai_family = AF_INET;
467                 h = NULL;
468             }
469         }
470
471         if ((*p_getaddrinfo.f) (h, p, &hint, &res))
472             break;
473
474         addrlen = res->ai_addrlen <= sizeof(server) ?
475             res->ai_addrlen : sizeof(server);
476         memcpy(&server, res->ai_addr, addrlen);
477
478         (*p_freeaddrinfo.f) (res);
479         goto again;
480     } while (0);
481 # endif
482
483     if (!BIO_get_port(p, &port))
484         goto err;
485
486     memset(&server, 0, sizeof(server));
487     server.sa_in.sin_family = AF_INET;
488     server.sa_in.sin_port = htons(port);
489     addrlen = sizeof(server.sa_in);
490
491     if (h == NULL || strcmp(h, "*") == 0)
492         server.sa_in.sin_addr.s_addr = INADDR_ANY;
493     else {
494         if (!BIO_get_host_ip(h, &(ip[0])))
495             goto err;
496         l = (unsigned long)
497             ((unsigned long)ip[0] << 24L) |
498             ((unsigned long)ip[1] << 16L) |
499             ((unsigned long)ip[2] << 8L) | ((unsigned long)ip[3]);
500         server.sa_in.sin_addr.s_addr = htonl(l);
501     }
502
503  again:
504     s = socket(server.sa.sa_family, SOCK_STREAM, SOCKET_PROTOCOL);
505     if (s == (int)INVALID_SOCKET) {
506         SYSerr(SYS_F_SOCKET, get_last_socket_error());
507         ERR_add_error_data(3, "port='", host, "'");
508         BIOerr(BIO_F_BIO_GET_ACCEPT_SOCKET, BIO_R_UNABLE_TO_CREATE_SOCKET);
509         goto err;
510     }
511 # ifdef SO_REUSEADDR
512     if (bind_mode == BIO_BIND_REUSEADDR) {
513         int i = 1;
514
515         ret = setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (char *)&i, sizeof(i));
516         bind_mode = BIO_BIND_NORMAL;
517     }
518 # endif
519     if (bind(s, &server.sa, addrlen) == -1) {
520 # ifdef SO_REUSEADDR
521         err_num = get_last_socket_error();
522         if ((bind_mode == BIO_BIND_REUSEADDR_IF_UNUSED) &&
523 #  ifdef OPENSSL_SYS_WINDOWS
524             /*
525              * Some versions of Windows define EADDRINUSE to a dummy value.
526              */
527             (err_num == WSAEADDRINUSE))
528 #  else
529             (err_num == EADDRINUSE))
530 #  endif
531         {
532             client = server;
533             if (h == NULL || strcmp(h, "*") == 0) {
534 #  if OPENSSL_USE_IPV6
535                 if (client.sa.sa_family == AF_INET6) {
536                     memset(&client.sa_in6.sin6_addr, 0,
537                            sizeof(client.sa_in6.sin6_addr));
538                     client.sa_in6.sin6_addr.s6_addr[15] = 1;
539                 } else
540 #  endif
541                 if (client.sa.sa_family == AF_INET) {
542                     client.sa_in.sin_addr.s_addr = htonl(0x7F000001);
543                 } else
544                     goto err;
545             }
546             cs = socket(client.sa.sa_family, SOCK_STREAM, SOCKET_PROTOCOL);
547             if (cs != (int)INVALID_SOCKET) {
548                 int ii;
549                 ii = connect(cs, &client.sa, addrlen);
550                 closesocket(cs);
551                 if (ii == (int)INVALID_SOCKET) {
552                     bind_mode = BIO_BIND_REUSEADDR;
553                     closesocket(s);
554                     goto again;
555                 }
556                 /* else error */
557             }
558             /* else error */
559         }
560 # endif
561         SYSerr(SYS_F_BIND, err_num);
562         ERR_add_error_data(3, "port='", host, "'");
563         BIOerr(BIO_F_BIO_GET_ACCEPT_SOCKET, BIO_R_UNABLE_TO_BIND_SOCKET);
564         goto err;
565     }
566     if (listen(s, MAX_LISTEN) == -1) {
567         SYSerr(SYS_F_BIND, get_last_socket_error());
568         ERR_add_error_data(3, "port='", host, "'");
569         BIOerr(BIO_F_BIO_GET_ACCEPT_SOCKET, BIO_R_UNABLE_TO_LISTEN_SOCKET);
570         goto err;
571     }
572     ret = 1;
573  err:
574     OPENSSL_free(str);
575     if ((ret == 0) && (s != (int)INVALID_SOCKET)) {
576         closesocket(s);
577         s = (int)INVALID_SOCKET;
578     }
579     return (s);
580 }
581
582 int BIO_accept(int sock, char **addr)
583 {
584     int ret = (int)INVALID_SOCKET;
585     unsigned long l;
586     unsigned short port;
587     char *p;
588
589     struct {
590         /*
591          * As for following union. Trouble is that there are platforms
592          * that have socklen_t and there are platforms that don't, on
593          * some platforms socklen_t is int and on some size_t. So what
594          * one can do? One can cook #ifdef spaghetti, which is nothing
595          * but masochistic. Or one can do union between int and size_t.
596          * One naturally does it primarily for 64-bit platforms where
597          * sizeof(int) != sizeof(size_t). But would it work? Note that
598          * if size_t member is initialized to 0, then later int member
599          * assignment naturally does the job on little-endian platforms
600          * regardless accept's expectations! What about big-endians?
601          * If accept expects int*, then it works, and if size_t*, then
602          * length value would appear as unreasonably large. But this
603          * won't prevent it from filling in the address structure. The
604          * trouble of course would be if accept returns more data than
605          * actual buffer can accomodate and overwrite stack... That's
606          * where early OPENSSL_assert comes into picture. Besides, the
607          * only 64-bit big-endian platform found so far that expects
608          * size_t* is HP-UX, where stack grows towards higher address.
609          * <appro>
610          */
611         union {
612             size_t s;
613             int i;
614         } len;
615         union {
616             struct sockaddr sa;
617             struct sockaddr_in sa_in;
618 # if OPENSSL_USE_IPV6
619             struct sockaddr_in6 sa_in6;
620 # endif
621         } from;
622     } sa;
623
624     sa.len.s = 0;
625     sa.len.i = sizeof(sa.from);
626     memset(&sa.from, 0, sizeof(sa.from));
627     ret = accept(sock, &sa.from.sa, (void *)&sa.len);
628     if (sizeof(sa.len.i) != sizeof(sa.len.s) && sa.len.i == 0) {
629         OPENSSL_assert(sa.len.s <= sizeof(sa.from));
630         sa.len.i = (int)sa.len.s;
631         /* use sa.len.i from this point */
632     }
633     if (ret == (int)INVALID_SOCKET) {
634         if (BIO_sock_should_retry(ret))
635             return -2;
636         SYSerr(SYS_F_ACCEPT, get_last_socket_error());
637         BIOerr(BIO_F_BIO_ACCEPT, BIO_R_ACCEPT_ERROR);
638         goto end;
639     }
640
641     if (addr == NULL)
642         goto end;
643
644 # ifdef EAI_FAMILY
645     do {
646         char h[NI_MAXHOST], s[NI_MAXSERV];
647         size_t nl;
648         static union {
649             void *p;
650             int (WSAAPI *f) (const struct sockaddr *, size_t /* socklen_t */ ,
651                              char *, size_t, char *, size_t, int);
652         } p_getnameinfo = {
653             NULL
654         };
655         /*
656          * 2nd argument to getnameinfo is specified to be socklen_t.
657          * Unfortunately there is a number of environments where socklen_t is
658          * not defined. As it's passed by value, it's safe to pass it as
659          * size_t... <appro>
660          */
661
662         if (p_getnameinfo.p == NULL) {
663             if ((p_getnameinfo.p = DSO_global_lookup("getnameinfo")) == NULL)
664                 p_getnameinfo.p = (void *)-1;
665         }
666         if (p_getnameinfo.p == (void *)-1)
667             break;
668
669         if ((*p_getnameinfo.f) (&sa.from.sa, sa.len.i, h, sizeof(h), s,
670                                 sizeof(s), NI_NUMERICHOST | NI_NUMERICSERV))
671             break;
672         nl = strlen(h) + strlen(s) + 2;
673         p = *addr;
674         if (p)
675             *p = '\0';
676         p = OPENSSL_realloc(p, nl);
677         if (p == NULL) {
678             BIOerr(BIO_F_BIO_ACCEPT, ERR_R_MALLOC_FAILURE);
679             goto end;
680         }
681         *addr = p;
682         BIO_snprintf(*addr, nl, "%s:%s", h, s);
683         goto end;
684     } while (0);
685 # endif
686     if (sa.from.sa.sa_family != AF_INET)
687         goto end;
688     l = ntohl(sa.from.sa_in.sin_addr.s_addr);
689     port = ntohs(sa.from.sa_in.sin_port);
690     if (*addr == NULL) {
691         if ((p = OPENSSL_malloc(24)) == NULL) {
692             BIOerr(BIO_F_BIO_ACCEPT, ERR_R_MALLOC_FAILURE);
693             goto end;
694         }
695         *addr = p;
696     }
697     BIO_snprintf(*addr, 24, "%d.%d.%d.%d:%d",
698                  (unsigned char)(l >> 24L) & 0xff,
699                  (unsigned char)(l >> 16L) & 0xff,
700                  (unsigned char)(l >> 8L) & 0xff,
701                  (unsigned char)(l) & 0xff, port);
702  end:
703     return (ret);
704 }
705 # endif
706
707 int BIO_set_tcp_ndelay(int s, int on)
708 {
709     int ret = 0;
710 # if defined(TCP_NODELAY) && (defined(IPPROTO_TCP) || defined(SOL_TCP))
711     int opt;
712
713 #  ifdef SOL_TCP
714     opt = SOL_TCP;
715 #  else
716 #   ifdef IPPROTO_TCP
717     opt = IPPROTO_TCP;
718 #   endif
719 #  endif
720
721     ret = setsockopt(s, opt, TCP_NODELAY, (char *)&on, sizeof(on));
722 # endif
723     return (ret == 0);
724 }
725
726 int BIO_socket_nbio(int s, int mode)
727 {
728     int ret = -1;
729     int l;
730
731     l = mode;
732 # ifdef FIONBIO
733     ret = BIO_socket_ioctl(s, FIONBIO, &l);
734 # endif
735     return (ret == 0);
736 }
737
738 int BIO_sock_info(int sock,
739                   enum BIO_sock_info_type type, union BIO_sock_info_u *info)
740 {
741     switch (type) {
742     case BIO_SOCK_INFO_ADDRESS:
743         {
744             socklen_t addr_len;
745             int ret = 0;
746             addr_len = sizeof(*info->addr);
747             ret = getsockname(sock, BIO_ADDR_sockaddr_noconst(info->addr),
748                               &addr_len);
749             if (ret == -1) {
750                 SYSerr(SYS_F_GETSOCKNAME, get_last_socket_error());
751                 BIOerr(BIO_F_BIO_SOCK_INFO, BIO_R_GETSOCKNAME_ERROR);
752                 return 0;
753             }
754             if (addr_len > sizeof(*info->addr)) {
755                 BIOerr(BIO_F_BIO_SOCK_INFO, BIO_R_GETSOCKNAME_TRUNCATED_ADDRESS);
756                 return 0;
757             }
758         }
759         break;
760     default:
761         BIOerr(BIO_F_BIO_SOCK_INFO, BIO_R_UNKNOWN_INFO_TYPE);
762         return 0;
763     }
764     return 1;
765 }
766
767 #endif