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