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