459443b3d986d98dbb3c6778c5165abbef9067fe
[openssl.git] / crypto / bio / b_addr.c
1 /* ====================================================================
2  * Copyright (c) 2015 The OpenSSL Project.  All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  *
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  *
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in
13  *    the documentation and/or other materials provided with the
14  *    distribution.
15  *
16  * 3. All advertising materials mentioning features or use of this
17  *    software must display the following acknowledgment:
18  *    "This product includes software developed by the OpenSSL Project
19  *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
20  *
21  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
22  *    endorse or promote products derived from this software without
23  *    prior written permission. For written permission, please contact
24  *    openssl-core@openssl.org.
25  *
26  * 5. Products derived from this software may not be called "OpenSSL"
27  *    nor may "OpenSSL" appear in their names without prior written
28  *    permission of the OpenSSL Project.
29  *
30  * 6. Redistributions of any form whatsoever must retain the following
31  *    acknowledgment:
32  *    "This product includes software developed by the OpenSSL Project
33  *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
34  *
35  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
36  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
37  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
38  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
39  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
40  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
41  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
42  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
43  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
44  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
45  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
46  * OF THE POSSIBILITY OF SUCH DAMAGE.
47  * ====================================================================
48  *
49  * This product includes cryptographic software written by Eric Young
50  * (eay@cryptsoft.com).  This product includes software written by Tim
51  * Hudson (tjh@cryptsoft.com).
52  *
53  */
54
55 #include <string.h>
56
57 #include "bio_lcl.h"
58
59 #include <openssl/err.h>
60 #include <openssl/buffer.h>
61 #include <ctype.h>
62
63 /*
64  * Throughout this file and bio_lcl.h, the existence of the macro
65  * AI_PASSIVE is used to detect the availability of struct addrinfo,
66  * getnameinfo() and getaddrinfo().  If that macro doesn't exist,
67  * we use our own implementation instead, using gethostbyname,
68  * getservbyname and a few other.
69  */
70
71 /**********************************************************************
72  *
73  * Address structure
74  *
75  */
76
77 BIO_ADDR *BIO_ADDR_new(void)
78 {
79     BIO_ADDR *ret = OPENSSL_zalloc(sizeof(*ret));
80
81     ret->sa.sa_family = AF_UNSPEC;
82     return ret;
83 }
84
85 void BIO_ADDR_free(BIO_ADDR *ap)
86 {
87     OPENSSL_free(ap);
88 }
89
90 void BIO_ADDR_clear(BIO_ADDR *ap)
91 {
92     memset(ap, 0, sizeof(*ap));
93     ap->sa.sa_family = AF_UNSPEC;
94 }
95
96 /*
97  * BIO_ADDR_make - non-public routine to fill a BIO_ADDR with the contents
98  * of a struct sockaddr.
99  */
100 int BIO_ADDR_make(BIO_ADDR *ap, const struct sockaddr *sa)
101 {
102     if (sa->sa_family == AF_INET) {
103         ap->sin = *(const struct sockaddr_in *)sa;
104         return 1;
105     }
106 #ifdef AF_INET6
107     if (sa->sa_family == AF_INET6) {
108         ap->sin6 = *(const struct sockaddr_in6 *)sa;
109         return 1;
110     }
111 #endif
112 #ifdef AF_UNIX
113     if (ap->sa.sa_family == AF_UNIX) {
114         ap->sun = *(const struct sockaddr_un *)sa;
115         return 1;
116     }
117 #endif
118
119     return 0;
120 }
121
122 int BIO_ADDR_rawmake(BIO_ADDR *ap, int family,
123                      const void *where, size_t wherelen,
124                      unsigned short port)
125 {
126 #ifdef AF_UNIX
127     if (family == AF_UNIX) {
128         if (wherelen + 1 > sizeof(ap->sun.sun_path))
129             return 0;
130         memset(&ap->sun, 0, sizeof(ap->sun));
131         ap->sun.sun_family = family;
132         strncpy(ap->sun.sun_path, where, sizeof(ap->sun.sun_path) - 1);
133         return 1;
134     }
135 #endif
136     if (family == AF_INET) {
137         if (wherelen != sizeof(struct in_addr))
138             return 0;
139         memset(&ap->sin, 0, sizeof(ap->sin));
140         ap->sin.sin_family = family;
141         ap->sin.sin_port = port;
142         ap->sin.sin_addr = *(struct in_addr *)where;
143         return 1;
144     }
145 #ifdef AF_INET6
146     if (family == AF_INET6) {
147         if (wherelen != sizeof(struct in6_addr))
148             return 0;
149         memset(&ap->sin6, 0, sizeof(ap->sin6));
150         ap->sin6.sin6_family = family;
151         ap->sin6.sin6_port = port;
152         ap->sin6.sin6_addr = *(struct in6_addr *)where;
153         return 1;
154     }
155 #endif
156
157     return 0;
158 }
159
160 int BIO_ADDR_family(const BIO_ADDR *ap)
161 {
162     return ap->sa.sa_family;
163 }
164
165 int BIO_ADDR_rawaddress(const BIO_ADDR *ap, void *p, size_t *l)
166 {
167     size_t len = 0;
168     const void *addrptr = NULL;
169
170     if (ap->sa.sa_family == AF_INET) {
171         len = sizeof(ap->sin.sin_addr);
172         addrptr = &ap->sin.sin_addr;
173     }
174 #ifdef AF_INET6
175     else if (ap->sa.sa_family == AF_INET6) {
176         len = sizeof(ap->sin6.sin6_addr);
177         addrptr = &ap->sin6.sin6_addr;
178     }
179 #endif
180 #ifdef AF_UNIX
181     else if (ap->sa.sa_family == AF_UNIX) {
182         len = strlen(ap->sun.sun_path);
183         addrptr = &ap->sun.sun_path;
184     }
185 #endif
186
187     if (addrptr == NULL)
188         return 0;
189
190     if (p != NULL) {
191         memcpy(p, addrptr, len);
192     }
193     if (l != NULL)
194         *l = len;
195
196     return 1;
197 }
198
199 unsigned short BIO_ADDR_rawport(const BIO_ADDR *ap)
200 {
201     if (ap->sa.sa_family == AF_INET)
202         return ap->sin.sin_port;
203 #ifdef AF_INET6
204     if (ap->sa.sa_family == AF_INET6)
205         return ap->sin6.sin6_port;
206 #endif
207     return 0;
208 }
209
210 /*-
211  * addr_strings - helper function to get host and service names
212  * @ap: the BIO_ADDR that has the input info
213  * @numeric: 0 if actual names should be returned, 1 if the numeric
214  * representation should be returned.
215  * @hostname: a pointer to a pointer to a memory area to store the
216  * host name or numeric representation.  Unused if NULL.
217  * @service: a pointer to a pointer to a memory area to store the
218  * service name or numeric representation.  Unused if NULL.
219  *
220  * The return value is 0 on failure, with the error code in the error
221  * stack, and 1 on success.
222  */
223 static int addr_strings(const BIO_ADDR *ap, int numeric,
224                         char **hostname, char **service)
225 {
226     if (BIO_sock_init() != 1)
227         return 0;
228
229     if (1) {
230 #ifdef AI_PASSIVE
231         int ret = 0;
232         char host[NI_MAXHOST], serv[NI_MAXSERV];
233         int flags = 0;
234
235         if (numeric)
236             flags |= NI_NUMERICHOST | NI_NUMERICSERV;
237
238         if ((ret = getnameinfo(BIO_ADDR_sockaddr(ap),
239                                BIO_ADDR_sockaddr_size(ap),
240                                host, sizeof(host), serv, sizeof(serv),
241                                flags)) != 0) {
242 # ifdef EAI_SYSTEM
243             if (ret == EAI_SYSTEM) {
244                 SYSerr(SYS_F_GETNAMEINFO, get_last_socket_error());
245                 BIOerr(BIO_F_ADDR_STRINGS, ERR_R_SYS_LIB);
246             } else
247 # endif
248             {
249                 BIOerr(BIO_F_ADDR_STRINGS, ERR_R_SYS_LIB);
250                 ERR_add_error_data(1, gai_strerror(ret));
251             }
252             return 0;
253         }
254
255         /* VMS getnameinfo() seems to have a bug, where serv gets filled
256          * with gibberish.  We can at least check for digits when flags
257          * has NI_NUMERICSERV enabled
258          */
259         if ((flags & NI_NUMERICSERV) != 0 && !isdigit(serv[0])) {
260             BIO_snprintf(serv, sizeof(serv), "%d",
261                          ntohs(BIO_ADDR_rawport(ap)));
262         }
263
264         if (hostname)
265             *hostname = OPENSSL_strdup(host);
266         if (service)
267             *service = OPENSSL_strdup(serv);
268     } else {
269 #endif
270         if (hostname)
271             *hostname = OPENSSL_strdup(inet_ntoa(ap->sin.sin_addr));
272         if (service) {
273             char serv[6];        /* port is 16 bits => max 5 decimal digits */
274             BIO_snprintf(serv, sizeof(serv), "%d", ntohs(ap->sin.sin_port));
275             *service = OPENSSL_strdup(serv);
276         }
277     }
278
279     return 1;
280 }
281
282 char *BIO_ADDR_hostname_string(const BIO_ADDR *ap, int numeric)
283 {
284     char *hostname = NULL;
285
286     if (addr_strings(ap, numeric, &hostname, NULL))
287         return hostname;
288
289     return NULL;
290 }
291
292 char *BIO_ADDR_service_string(const BIO_ADDR *ap, int numeric)
293 {
294     char *service = NULL;
295
296     if (addr_strings(ap, numeric, NULL, &service))
297         return service;
298
299     return NULL;
300 }
301
302 char *BIO_ADDR_path_string(const BIO_ADDR *ap)
303 {
304 #ifdef AF_UNIX
305     if (ap->sa.sa_family == AF_UNIX)
306         return OPENSSL_strdup(ap->sun.sun_path);
307 #endif
308     return NULL;
309 }
310
311 /*
312  * BIO_ADDR_sockaddr - non-public routine to return the struct sockaddr
313  * for a given BIO_ADDR.  In reality, this is simply a type safe cast.
314  * The returned struct sockaddr is const, so it can't be tampered with.
315  */
316 const struct sockaddr *BIO_ADDR_sockaddr(const BIO_ADDR *ap)
317 {
318     return &(ap->sa);
319 }
320
321 /*
322  * BIO_ADDR_sockaddr_noconst - non-public function that does the same
323  * as BIO_ADDR_sockaddr, but returns a non-const.  USE WITH CARE, as
324  * it allows you to tamper with the data (and thereby the contents
325  * of the input BIO_ADDR).
326  */
327 struct sockaddr *BIO_ADDR_sockaddr_noconst(BIO_ADDR *ap)
328 {
329     return &(ap->sa);
330 }
331
332 /*
333  * BIO_ADDR_sockaddr_size - non-public function that returns the size
334  * of the struct sockaddr the BIO_ADDR is using.  If the protocol family
335  * isn't set or is something other than AF_INET, AF_INET6 or AF_UNIX,
336  * the size of the BIO_ADDR type is returned.
337  */
338 socklen_t BIO_ADDR_sockaddr_size(const BIO_ADDR *ap)
339 {
340     if (ap->sa.sa_family == AF_INET)
341         return sizeof(ap->sin);
342 #ifdef AF_INET6
343     if (ap->sa.sa_family == AF_INET6)
344         return sizeof(ap->sin6);
345 #endif
346 #ifdef AF_UNIX
347     if (ap->sa.sa_family == AF_UNIX)
348         return sizeof(ap->sun);
349 #endif
350     return sizeof(*ap);
351 }
352
353 /**********************************************************************
354  *
355  * Address info database
356  *
357  */
358
359 const BIO_ADDRINFO *BIO_ADDRINFO_next(const BIO_ADDRINFO *bai)
360 {
361     if (bai != NULL)
362         return bai->bai_next;
363     return NULL;
364 }
365
366 int BIO_ADDRINFO_family(const BIO_ADDRINFO *bai)
367 {
368     if (bai != NULL)
369         return bai->bai_family;
370     return 0;
371 }
372
373 int BIO_ADDRINFO_socktype(const BIO_ADDRINFO *bai)
374 {
375     if (bai != NULL)
376         return bai->bai_socktype;
377     return 0;
378 }
379
380 int BIO_ADDRINFO_protocol(const BIO_ADDRINFO *bai)
381 {
382     if (bai != NULL) {
383         if (bai->bai_protocol != 0)
384             return bai->bai_protocol;
385
386 #ifdef AF_UNIX
387         if (bai->bai_family == AF_UNIX)
388             return 0;
389 #endif
390
391         switch (bai->bai_socktype) {
392         case SOCK_STREAM:
393             return IPPROTO_TCP;
394         case SOCK_DGRAM:
395             return IPPROTO_UDP;
396         default:
397             break;
398         }
399     }
400     return 0;
401 }
402
403 /*
404  * BIO_ADDRINFO_sockaddr_size - non-public function that returns the size
405  * of the struct sockaddr inside the BIO_ADDRINFO.
406  */
407 socklen_t BIO_ADDRINFO_sockaddr_size(const BIO_ADDRINFO *bai)
408 {
409     if (bai != NULL)
410         return bai->bai_addrlen;
411     return 0;
412 }
413
414 /*
415  * BIO_ADDRINFO_sockaddr - non-public function that returns bai_addr
416  * as the struct sockaddr it is.
417  */
418 const struct sockaddr *BIO_ADDRINFO_sockaddr(const BIO_ADDRINFO *bai)
419 {
420     if (bai != NULL)
421         return bai->bai_addr;
422     return NULL;
423 }
424
425 const BIO_ADDR *BIO_ADDRINFO_address(const BIO_ADDRINFO *bai)
426 {
427     if (bai != NULL)
428         return (BIO_ADDR *)bai->bai_addr;
429     return NULL;
430 }
431
432 void BIO_ADDRINFO_free(BIO_ADDRINFO *bai)
433 {
434     if (bai == NULL)
435         return;
436
437 #ifdef AI_PASSIVE
438 # ifdef AF_UNIX
439 #  define _cond bai->bai_family != AF_UNIX
440 # else
441 #  define _cond 1
442 # endif
443     if (_cond) {
444         freeaddrinfo(bai);
445         return;
446     }
447 #endif
448
449     /* Free manually when we know that addrinfo_wrap() was used.
450      * See further comment above addrinfo_wrap()
451      */
452     while (bai != NULL) {
453         BIO_ADDRINFO *next = bai->bai_next;
454         OPENSSL_free(bai->bai_addr);
455         OPENSSL_free(bai);
456         bai = next;
457     }
458 }
459
460 /**********************************************************************
461  *
462  * Service functions
463  *
464  */
465
466 /*-
467  * The specs in hostserv can take these forms:
468  *
469  * host:service         => *host = "host", *service = "service"
470  * host:*               => *host = "host", *service = NULL
471  * host:                => *host = "host", *service = NULL
472  * :service             => *host = NULL, *service = "service"
473  * *:service            => *host = NULL, *service = "service"
474  *
475  * in case no : is present in the string, the result depends on
476  * hostserv_prio, as follows:
477  *
478  * when hostserv_prio == BIO_PARSE_PRIO_HOST
479  * host                 => *host = "host", *service untouched
480  *
481  * when hostserv_prio == BIO_PARSE_PRIO_SERV
482  * service              => *host untouched, *service = "service"
483  *
484  */
485 int BIO_parse_hostserv(const char *hostserv, char **host, char **service,
486                        enum BIO_hostserv_priorities hostserv_prio)
487 {
488     const char *h = NULL; size_t hl = 0;
489     const char *p = NULL; size_t pl = 0;
490
491     if (*hostserv == '[') {
492         if ((p = strchr(hostserv, ']')) == NULL)
493             goto spec_err;
494         h = hostserv + 1;
495         hl = p - h;
496         p++;
497         if (*p == '\0')
498             p = NULL;
499         else if (*p != ':')
500             goto spec_err;
501         else {
502             p++;
503             pl = strlen(p);
504         }
505     } else {
506         const char *p2 = strrchr(hostserv, ':');
507         p = strchr(hostserv, ':');
508
509         /*-
510          * Check for more than one colon.  There are three possible
511          * interpretations:
512          * 1. IPv6 address with port number, last colon being separator.
513          * 2. IPv6 address only.
514          * 3. IPv6 address only if hostserv_prio == BIO_PARSE_PRIO_HOST,
515          *    IPv6 address and port number if hostserv_prio == BIO_PARSE_PRIO_SERV
516          * Because of this ambiguity, we currently choose to make it an
517          * error.
518          */
519         if (p != p2)
520             goto amb_err;
521
522         if (p != NULL) {
523             h = hostserv;
524             hl = p - h;
525             p++;
526             pl = strlen(p);
527         } else if (hostserv_prio == BIO_PARSE_PRIO_HOST) {
528             h = hostserv;
529             hl = strlen(h);
530         } else {
531             p = hostserv;
532             pl = strlen(p);
533         }
534     }
535
536     if (p != NULL && strchr(p, ':'))
537         goto spec_err;
538
539     if (h != NULL && host != NULL) {
540         if (hl == 0
541             || (hl == 1 && h[0] == '*')) {
542             *host = NULL;
543         } else {
544             *host = OPENSSL_strndup(h, hl);
545             if (*host == NULL)
546                 goto memerr;
547         }
548     }
549     if (p != NULL && service != NULL) {
550         if (pl == 0
551             || (pl == 1 && p[0] == '*')) {
552             *service = NULL;
553         } else {
554             *service = OPENSSL_strndup(p, pl);
555             if (*service == NULL)
556                 goto memerr;
557         }
558     }
559
560     return 1;
561  amb_err:
562     BIOerr(BIO_F_BIO_PARSE_HOSTSERV, BIO_R_AMBIGUOUS_HOST_OR_SERVICE);
563     return 0;
564  spec_err:
565     BIOerr(BIO_F_BIO_PARSE_HOSTSERV, BIO_R_MALFORMED_HOST_OR_SERVICE);
566     return 0;
567  memerr:
568     BIOerr(BIO_F_BIO_PARSE_HOSTSERV, ERR_R_MALLOC_FAILURE);
569     return 0;
570 }
571
572 /* addrinfo_wrap is used to build our own addrinfo "chain".
573  * (it has only one entry, so calling it a chain may be a stretch)
574  * It should ONLY be called when getaddrinfo() and friends
575  * aren't available, OR when dealing with a non IP protocol
576  * family, such as AF_UNIX
577  *
578  * the return value is 1 on success, or 0 on failure, which
579  * only happens if a memory allocation error occured.
580  */
581 static int addrinfo_wrap(int family, int socktype,
582                          const void *where, size_t wherelen,
583                          unsigned short port,
584                          BIO_ADDRINFO **bai)
585 {
586     OPENSSL_assert(bai != NULL);
587
588     *bai = OPENSSL_zalloc(sizeof(**bai));
589     if (*bai == NULL)
590         return 0;
591
592     (*bai)->bai_family = family;
593     (*bai)->bai_socktype = socktype;
594     if (socktype == SOCK_STREAM)
595         (*bai)->bai_protocol = IPPROTO_TCP;
596     if (socktype == SOCK_DGRAM)
597         (*bai)->bai_protocol = IPPROTO_UDP;
598 #ifdef AF_UNIX
599     if (family == AF_UNIX)
600         (*bai)->bai_protocol = 0;
601 #endif
602     {
603         /* Magic: We know that BIO_ADDR_sockaddr_noconst is really
604            just an advanced cast of BIO_ADDR* to struct sockaddr *
605            by the power of union, so while it may seem that we're
606            creating a memory leak here, we are not.  It will be
607            all right. */
608         BIO_ADDR *addr = BIO_ADDR_new();
609         if (addr != NULL) {
610             BIO_ADDR_rawmake(addr, family, where, wherelen, port);
611             (*bai)->bai_addr = BIO_ADDR_sockaddr_noconst(addr);
612         }
613     }
614     (*bai)->bai_next = NULL;
615     if ((*bai)->bai_addr == NULL) {
616         BIO_ADDRINFO_free(*bai);
617         *bai = NULL;
618         return 0;
619     }
620     return 1;
621 }
622
623 /*-
624  * BIO_lookup - look up the node and service you want to connect to.
625  * @node: the node you want to connect to.
626  * @service: the service you want to connect to.
627  * @lookup_type: declare intent with the result, client or server.
628  * @family: the address family you want to use.  Use AF_UNSPEC for any, or
629  *  AF_INET, AF_INET6 or AF_UNIX.
630  * @socktype: The socket type you want to use.  Can be SOCK_STREAM, SOCK_DGRAM
631  *  or 0 for all.
632  * @res: Storage place for the resulting list of returned addresses
633  *
634  * This will do a lookup of the node and service that you want to connect to.
635  * It returns a linked list of different addresses you can try to connect to.
636  *
637  * When no longer needed you should call BIO_ADDRINFO_free() to free the result.
638  *
639  * The return value is 1 on success or 0 in case of error.
640  */
641 int BIO_lookup(const char *host, const char *service,
642                enum BIO_lookup_type lookup_type,
643                int family, int socktype, BIO_ADDRINFO **res)
644 {
645     int ret = 0;                 /* Assume failure */
646
647     switch(family) {
648     case AF_INET:
649 #ifdef AF_INET6
650     case AF_INET6:
651 #endif
652 #ifdef AF_UNIX
653     case AF_UNIX:
654 #endif
655 #ifdef AF_UNSPEC
656     case AF_UNSPEC:
657 #endif
658         break;
659     default:
660         BIOerr(BIO_F_BIO_LOOKUP, BIO_R_UNSUPPORTED_PROTOCOL_FAMILY);
661         return 0;
662     }
663
664 #ifdef AF_UNIX
665     if (family == AF_UNIX) {
666         if (addrinfo_wrap(family, socktype, host, strlen(host), 0, res))
667             return 1;
668         else
669             BIOerr(BIO_F_BIO_LOOKUP, ERR_R_MALLOC_FAILURE);
670         return 0;
671     }
672 #endif
673
674     if (BIO_sock_init() != 1)
675         return 0;
676
677     if (1) {
678         int gai_ret = 0;
679 #ifdef AI_PASSIVE
680         struct addrinfo hints;
681
682         hints.ai_flags = 0;
683 # ifdef AI_ADDRCONFIG
684         hints.ai_flags = AI_ADDRCONFIG;
685 # endif
686         hints.ai_family = family;
687         hints.ai_socktype = socktype;
688         hints.ai_protocol = 0;
689         hints.ai_addrlen = 0;
690         hints.ai_addr = NULL;
691         hints.ai_canonname = NULL;
692         hints.ai_next = NULL;
693
694         if (lookup_type == BIO_LOOKUP_SERVER)
695             hints.ai_flags |= AI_PASSIVE;
696
697         /* Note that |res| SHOULD be a 'struct addrinfo **' thanks to
698          * macro magic in bio_lcl.h
699          */
700         switch ((gai_ret = getaddrinfo(host, service, &hints, res))) {
701 # ifdef EAI_SYSTEM
702         case EAI_SYSTEM:
703             SYSerr(SYS_F_GETADDRINFO, get_last_socket_error());
704             BIOerr(BIO_F_BIO_LOOKUP, ERR_R_SYS_LIB);
705             break;
706 # endif
707         case 0:
708             ret = 1;             /* Success */
709             break;
710         default:
711             BIOerr(BIO_F_BIO_LOOKUP, ERR_R_SYS_LIB);
712             ERR_add_error_data(1, gai_strerror(gai_ret));
713             break;
714         }
715     } else {
716 #endif
717         const struct hostent *he;
718         /* Windows doesn't seem to have in_addr_t */
719 #ifdef OPENSSL_SYS_WINDOWS
720         static uint32_t he_fallback_address;
721         static const uint32_t *he_fallback_addresses[] =
722             { &he_fallback_address, NULL };
723 #else
724         static in_addr_t he_fallback_address;
725         static const in_addr_t *he_fallback_addresses[] =
726             { &he_fallback_address, NULL };
727 #endif
728         static const struct hostent he_fallback =
729             { NULL, NULL, AF_INET, sizeof(he_fallback_address),
730               (char **)&he_fallback_addresses };
731         struct servent *se;
732         /* Apprently, on WIN64, s_proto and s_port have traded places... */
733 #ifdef _WIN64
734         struct servent se_fallback = { NULL, NULL, NULL, 0 };
735 #else
736         struct servent se_fallback = { NULL, NULL, 0, NULL };
737 #endif
738         char *proto = NULL;
739
740         CRYPTO_w_lock(CRYPTO_LOCK_GETHOSTBYNAME);
741         CRYPTO_w_lock(CRYPTO_LOCK_GETSERVBYNAME);
742         he_fallback_address = INADDR_ANY;
743         if (host == NULL) {
744             he = &he_fallback;
745             switch(lookup_type) {
746             case BIO_LOOKUP_CLIENT:
747                 he_fallback_address = INADDR_LOOPBACK;
748                 break;
749             case BIO_LOOKUP_SERVER:
750                 he_fallback_address = INADDR_ANY;
751                 break;
752             default:
753                 OPENSSL_assert(("We forgot to handle a lookup type!" == 0));
754                 break;
755             }
756         } else {
757             he = gethostbyname(host);
758
759             if (he == NULL) {
760 #ifndef OPENSSL_SYS_WINDOWS
761                 BIOerr(BIO_F_BIO_LOOKUP, ERR_R_SYS_LIB);
762                 ERR_add_error_data(1, hstrerror(h_errno));
763 #else
764                 SYSerr(SYS_F_GETHOSTBYNAME, WSAGetLastError());
765 #endif
766                 ret = 0;
767                 goto err;
768             }
769         }
770
771         if (service == NULL) {
772             se_fallback.s_port = 0;
773             se_fallback.s_proto = proto;
774             se = &se_fallback;
775         } else {
776             char *endp = NULL;
777             long portnum = strtol(service, &endp, 10);
778
779             if (endp != service && *endp == '\0'
780                     && portnum > 0 && portnum < 65536) {
781                 se_fallback.s_port = htons(portnum);
782                 se_fallback.s_proto = proto;
783                 se = &se_fallback;
784             } else if (endp == service) {
785                 switch (socktype) {
786                 case SOCK_STREAM:
787                     proto = "tcp";
788                     break;
789                 case SOCK_DGRAM:
790                     proto = "udp";
791                     break;
792                 }
793                 se = getservbyname(service, proto);
794
795                 if (se == NULL) {
796 #ifndef OPENSSL_SYS_WINDOWS
797                     BIOerr(BIO_F_BIO_LOOKUP, ERR_R_SYS_LIB);
798                     ERR_add_error_data(1, hstrerror(h_errno));
799 #else
800                     SYSerr(SYS_F_GETSERVBYNAME, WSAGetLastError());
801 #endif
802                     goto err;
803                 }
804             } else {
805                 BIOerr(BIO_F_BIO_LOOKUP, BIO_R_MALFORMED_HOST_OR_SERVICE);
806                 goto err;
807             }
808         }
809
810         *res = NULL;
811
812         {
813             char **addrlistp;
814             size_t addresses;
815             BIO_ADDRINFO *tmp_bai = NULL;
816
817             /* The easiest way to create a linked list from an
818                array is to start from the back */
819             for(addrlistp = he->h_addr_list; *addrlistp != NULL;
820                 addrlistp++)
821                 ;
822
823             for(addresses = addrlistp - he->h_addr_list;
824                 addrlistp--, addresses-- > 0; ) {
825                 if (!addrinfo_wrap(he->h_addrtype, socktype,
826                                    *addrlistp, he->h_length,
827                                    se->s_port, &tmp_bai))
828                     goto addrinfo_malloc_err;
829                 tmp_bai->bai_next = *res;
830                 *res = tmp_bai;
831                 continue;
832              addrinfo_malloc_err:
833                 BIO_ADDRINFO_free(*res);
834                 *res = NULL;
835                 BIOerr(BIO_F_BIO_LOOKUP, ERR_R_MALLOC_FAILURE);
836                 ret = 0;
837                 goto err;
838             }
839
840             ret = 1;
841         }
842      err:
843         CRYPTO_w_unlock(CRYPTO_LOCK_GETSERVBYNAME);
844         CRYPTO_w_unlock(CRYPTO_LOCK_GETHOSTBYNAME);
845     }
846
847     return ret;
848 }