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