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