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