2 * Copyright 2016-2021 The OpenSSL Project Authors. All Rights Reserved.
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
17 #include "bio_local.h"
18 #include <openssl/crypto.h>
20 #ifndef OPENSSL_NO_SOCK
21 #include <openssl/err.h>
22 #include <openssl/buffer.h>
23 #include "internal/thread_once.h"
25 CRYPTO_RWLOCK *bio_lookup_lock;
26 static CRYPTO_ONCE bio_lookup_init = CRYPTO_ONCE_STATIC_INIT;
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.
36 /**********************************************************************
42 BIO_ADDR *BIO_ADDR_new(void)
44 BIO_ADDR *ret = OPENSSL_zalloc(sizeof(*ret));
47 BIOerr(BIO_F_BIO_ADDR_NEW, ERR_R_MALLOC_FAILURE);
51 ret->sa.sa_family = AF_UNSPEC;
55 void BIO_ADDR_free(BIO_ADDR *ap)
60 void BIO_ADDR_clear(BIO_ADDR *ap)
62 memset(ap, 0, sizeof(*ap));
63 ap->sa.sa_family = AF_UNSPEC;
67 * BIO_ADDR_make - non-public routine to fill a BIO_ADDR with the contents
68 * of a struct sockaddr.
70 int BIO_ADDR_make(BIO_ADDR *ap, const struct sockaddr *sa)
72 if (sa->sa_family == AF_INET) {
73 memcpy(&(ap->s_in), sa, sizeof(struct sockaddr_in));
77 if (sa->sa_family == AF_INET6) {
78 memcpy(&(ap->s_in6), sa, sizeof(struct sockaddr_in6));
83 if (sa->sa_family == AF_UNIX) {
84 memcpy(&(ap->s_un), sa, sizeof(struct sockaddr_un));
92 int BIO_ADDR_rawmake(BIO_ADDR *ap, int family,
93 const void *where, size_t wherelen,
97 if (family == AF_UNIX) {
98 if (wherelen + 1 > sizeof(ap->s_un.sun_path))
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);
106 if (family == AF_INET) {
107 if (wherelen != sizeof(struct in_addr))
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;
116 if (family == AF_INET6) {
117 if (wherelen != sizeof(struct in6_addr))
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;
130 int BIO_ADDR_family(const BIO_ADDR *ap)
132 return ap->sa.sa_family;
135 int BIO_ADDR_rawaddress(const BIO_ADDR *ap, void *p, size_t *l)
138 const void *addrptr = NULL;
140 if (ap->sa.sa_family == AF_INET) {
141 len = sizeof(ap->s_in.sin_addr);
142 addrptr = &ap->s_in.sin_addr;
145 else if (ap->sa.sa_family == AF_INET6) {
146 len = sizeof(ap->s_in6.sin6_addr);
147 addrptr = &ap->s_in6.sin6_addr;
151 else if (ap->sa.sa_family == AF_UNIX) {
152 len = strlen(ap->s_un.sun_path);
153 addrptr = &ap->s_un.sun_path;
161 memcpy(p, addrptr, len);
169 unsigned short BIO_ADDR_rawport(const BIO_ADDR *ap)
171 if (ap->sa.sa_family == AF_INET)
172 return ap->s_in.sin_port;
174 if (ap->sa.sa_family == AF_INET6)
175 return ap->s_in6.sin6_port;
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.
190 * The return value is 0 on failure, with the error code in the error
191 * stack, and 1 on success.
193 static int addr_strings(const BIO_ADDR *ap, int numeric,
194 char **hostname, char **service)
196 if (BIO_sock_init() != 1)
202 char host[NI_MAXHOST] = "", serv[NI_MAXSERV] = "";
206 flags |= NI_NUMERICHOST | NI_NUMERICSERV;
208 if ((ret = getnameinfo(BIO_ADDR_sockaddr(ap),
209 BIO_ADDR_sockaddr_size(ap),
210 host, sizeof(host), serv, sizeof(serv),
213 if (ret == EAI_SYSTEM) {
214 SYSerr(SYS_F_GETNAMEINFO, get_last_socket_error());
215 BIOerr(BIO_F_ADDR_STRINGS, ERR_R_SYS_LIB);
219 BIOerr(BIO_F_ADDR_STRINGS, ERR_R_SYS_LIB);
220 ERR_add_error_data(1, gai_strerror(ret));
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.
231 if (serv[0] == '\0') {
232 BIO_snprintf(serv, sizeof(serv), "%d",
233 ntohs(BIO_ADDR_rawport(ap)));
236 if (hostname != NULL)
237 *hostname = OPENSSL_strdup(host);
239 *service = OPENSSL_strdup(serv);
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);
251 if ((hostname != NULL && *hostname == NULL)
252 || (service != NULL && *service == NULL)) {
253 if (hostname != NULL) {
254 OPENSSL_free(*hostname);
257 if (service != NULL) {
258 OPENSSL_free(*service);
261 BIOerr(BIO_F_ADDR_STRINGS, ERR_R_MALLOC_FAILURE);
268 char *BIO_ADDR_hostname_string(const BIO_ADDR *ap, int numeric)
270 char *hostname = NULL;
272 if (addr_strings(ap, numeric, &hostname, NULL))
278 char *BIO_ADDR_service_string(const BIO_ADDR *ap, int numeric)
280 char *service = NULL;
282 if (addr_strings(ap, numeric, NULL, &service))
288 char *BIO_ADDR_path_string(const BIO_ADDR *ap)
291 if (ap->sa.sa_family == AF_UNIX)
292 return OPENSSL_strdup(ap->s_un.sun_path);
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.
302 const struct sockaddr *BIO_ADDR_sockaddr(const BIO_ADDR *ap)
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).
313 struct sockaddr *BIO_ADDR_sockaddr_noconst(BIO_ADDR *ap)
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.
324 socklen_t BIO_ADDR_sockaddr_size(const BIO_ADDR *ap)
326 if (ap->sa.sa_family == AF_INET)
327 return sizeof(ap->s_in);
329 if (ap->sa.sa_family == AF_INET6)
330 return sizeof(ap->s_in6);
333 if (ap->sa.sa_family == AF_UNIX)
334 return sizeof(ap->s_un);
339 /**********************************************************************
341 * Address info database
345 const BIO_ADDRINFO *BIO_ADDRINFO_next(const BIO_ADDRINFO *bai)
348 return bai->bai_next;
352 int BIO_ADDRINFO_family(const BIO_ADDRINFO *bai)
355 return bai->bai_family;
359 int BIO_ADDRINFO_socktype(const BIO_ADDRINFO *bai)
362 return bai->bai_socktype;
366 int BIO_ADDRINFO_protocol(const BIO_ADDRINFO *bai)
369 if (bai->bai_protocol != 0)
370 return bai->bai_protocol;
373 if (bai->bai_family == AF_UNIX)
377 switch (bai->bai_socktype) {
390 * BIO_ADDRINFO_sockaddr_size - non-public function that returns the size
391 * of the struct sockaddr inside the BIO_ADDRINFO.
393 socklen_t BIO_ADDRINFO_sockaddr_size(const BIO_ADDRINFO *bai)
396 return bai->bai_addrlen;
401 * BIO_ADDRINFO_sockaddr - non-public function that returns bai_addr
402 * as the struct sockaddr it is.
404 const struct sockaddr *BIO_ADDRINFO_sockaddr(const BIO_ADDRINFO *bai)
407 return bai->bai_addr;
411 const BIO_ADDR *BIO_ADDRINFO_address(const BIO_ADDRINFO *bai)
414 return (BIO_ADDR *)bai->bai_addr;
418 void BIO_ADDRINFO_free(BIO_ADDRINFO *bai)
425 # define _cond bai->bai_family != AF_UNIX
435 /* Free manually when we know that addrinfo_wrap() was used.
436 * See further comment above addrinfo_wrap()
438 while (bai != NULL) {
439 BIO_ADDRINFO *next = bai->bai_next;
440 OPENSSL_free(bai->bai_addr);
446 /**********************************************************************
453 * The specs in hostserv can take these forms:
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"
461 * in case no : is present in the string, the result depends on
462 * hostserv_prio, as follows:
464 * when hostserv_prio == BIO_PARSE_PRIO_HOST
465 * host => *host = "host", *service untouched
467 * when hostserv_prio == BIO_PARSE_PRIO_SERV
468 * service => *host untouched, *service = "service"
471 int BIO_parse_hostserv(const char *hostserv, char **host, char **service,
472 enum BIO_hostserv_priorities hostserv_prio)
474 const char *h = NULL; size_t hl = 0;
475 const char *p = NULL; size_t pl = 0;
477 if (*hostserv == '[') {
478 if ((p = strchr(hostserv, ']')) == NULL)
492 const char *p2 = strrchr(hostserv, ':');
493 p = strchr(hostserv, ':');
496 * Check for more than one colon. There are three possible
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
513 } else if (hostserv_prio == BIO_PARSE_PRIO_HOST) {
522 if (p != NULL && strchr(p, ':'))
525 if (h != NULL && host != NULL) {
527 || (hl == 1 && h[0] == '*')) {
530 *host = OPENSSL_strndup(h, hl);
535 if (p != NULL && service != NULL) {
537 || (pl == 1 && p[0] == '*')) {
540 *service = OPENSSL_strndup(p, pl);
541 if (*service == NULL)
548 BIOerr(BIO_F_BIO_PARSE_HOSTSERV, BIO_R_AMBIGUOUS_HOST_OR_SERVICE);
551 BIOerr(BIO_F_BIO_PARSE_HOSTSERV, BIO_R_MALFORMED_HOST_OR_SERVICE);
554 BIOerr(BIO_F_BIO_PARSE_HOSTSERV, ERR_R_MALLOC_FAILURE);
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
564 * the return value is 1 on success, or 0 on failure, which
565 * only happens if a memory allocation error occurred.
567 static int addrinfo_wrap(int family, int socktype,
568 const void *where, size_t wherelen,
572 if ((*bai = OPENSSL_zalloc(sizeof(**bai))) == NULL) {
573 BIOerr(BIO_F_ADDRINFO_WRAP, ERR_R_MALLOC_FAILURE);
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;
584 if (family == AF_UNIX)
585 (*bai)->bai_protocol = 0;
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
593 BIO_ADDR *addr = BIO_ADDR_new();
595 BIO_ADDR_rawmake(addr, family, where, wherelen, port);
596 (*bai)->bai_addr = BIO_ADDR_sockaddr_noconst(addr);
599 (*bai)->bai_next = NULL;
600 if ((*bai)->bai_addr == NULL) {
601 BIO_ADDRINFO_free(*bai);
608 DEFINE_RUN_ONCE_STATIC(do_bio_lookup_init)
610 if (!OPENSSL_init_crypto(0, NULL))
612 bio_lookup_lock = CRYPTO_THREAD_lock_new();
613 return bio_lookup_lock != NULL;
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)
620 return BIO_lookup_ex(host, service, lookup_type, family, socktype, 0, res);
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
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
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.
641 * When no longer needed you should call BIO_ADDRINFO_free() to free the result.
643 * The return value is 1 on success or 0 in case of error.
645 int BIO_lookup_ex(const char *host, const char *service, int lookup_type,
646 int family, int socktype, int protocol, BIO_ADDRINFO **res)
648 int ret = 0; /* Assume failure */
663 BIOerr(BIO_F_BIO_LOOKUP_EX, BIO_R_UNSUPPORTED_PROTOCOL_FAMILY);
668 if (family == AF_UNIX) {
669 if (addrinfo_wrap(family, socktype, host, strlen(host), 0, res))
672 BIOerr(BIO_F_BIO_LOOKUP_EX, ERR_R_MALLOC_FAILURE);
677 if (BIO_sock_init() != 1)
682 int gai_ret = 0, old_ret = 0;
683 struct addrinfo hints;
685 memset(&hints, 0, sizeof(hints));
687 hints.ai_family = family;
688 hints.ai_socktype = socktype;
689 hints.ai_protocol = protocol;
690 # ifdef AI_ADDRCONFIG
692 if (host != NULL && family == AF_UNSPEC)
694 hints.ai_flags |= AI_ADDRCONFIG;
697 if (lookup_type == BIO_LOOKUP_SERVER)
698 hints.ai_flags |= AI_PASSIVE;
700 /* Note that |res| SHOULD be a 'struct addrinfo **' thanks to
701 * macro magic in bio_local.h
703 # if defined(AI_ADDRCONFIG) && defined(AI_NUMERICHOST)
706 switch ((gai_ret = getaddrinfo(host, service, &hints, res))) {
709 SYSerr(SYS_F_GETADDRINFO, get_last_socket_error());
710 BIOerr(BIO_F_BIO_LOOKUP_EX, ERR_R_SYS_LIB);
715 BIOerr(BIO_F_BIO_LOOKUP_EX, ERR_R_MALLOC_FAILURE);
719 ret = 1; /* Success */
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;
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));
736 const struct hostent *he;
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
742 #if defined(OPENSSL_SYS_VMS) && defined(__DECC)
743 # pragma pointer_size save
744 # pragma pointer_size 32
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 };
752 static in_addr_t he_fallback_address;
753 static const char *he_fallback_addresses[] =
754 { (char *)&he_fallback_address, NULL };
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
764 /* Apparently, on WIN64, s_proto and s_port have traded places... */
766 struct servent se_fallback = { NULL, NULL, NULL, 0 };
768 struct servent se_fallback = { NULL, NULL, 0, NULL };
771 if (!RUN_ONCE(&bio_lookup_init, do_bio_lookup_init)) {
772 BIOerr(BIO_F_BIO_LOOKUP_EX, ERR_R_MALLOC_FAILURE);
777 CRYPTO_THREAD_write_lock(bio_lookup_lock);
778 he_fallback_address = INADDR_ANY;
781 switch(lookup_type) {
782 case BIO_LOOKUP_CLIENT:
783 he_fallback_address = INADDR_LOOPBACK;
785 case BIO_LOOKUP_SERVER:
786 he_fallback_address = INADDR_ANY;
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);
796 he = gethostbyname(host);
799 #ifndef OPENSSL_SYS_WINDOWS
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...
811 # if defined(OPENSSL_SYS_VXWORKS)
812 /* h_errno doesn't exist on VxWorks */
813 SYSerr(SYS_F_GETHOSTBYNAME, 1000 );
815 SYSerr(SYS_F_GETHOSTBYNAME, 1000 + h_errno);
818 SYSerr(SYS_F_GETHOSTBYNAME, WSAGetLastError());
825 if (service == NULL) {
826 se_fallback.s_port = 0;
827 se_fallback.s_proto = NULL;
831 long portnum = strtol(service, &endp, 10);
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.
837 #if defined(OPENSSL_SYS_VMS) && defined(__DECC)
838 # pragma pointer_size save
839 # pragma pointer_size 32
842 #if defined(OPENSSL_SYS_VMS) && defined(__DECC)
843 # pragma pointer_size restore
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;
860 } else if (endp == service) {
861 se = getservbyname(service, proto);
864 #ifndef OPENSSL_SYS_WINDOWS
865 SYSerr(SYS_F_GETSERVBYNAME, errno);
867 SYSerr(SYS_F_GETSERVBYNAME, WSAGetLastError());
872 BIOerr(BIO_F_BIO_LOOKUP_EX, BIO_R_MALFORMED_HOST_OR_SERVICE);
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.
885 #if defined(OPENSSL_SYS_VMS) && defined(__DECC)
886 # pragma pointer_size save
887 # pragma pointer_size 32
890 #if defined(OPENSSL_SYS_VMS) && defined(__DECC)
891 # pragma pointer_size restore
894 BIO_ADDRINFO *tmp_bai = NULL;
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;
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;
912 BIO_ADDRINFO_free(*res);
914 BIOerr(BIO_F_BIO_LOOKUP_EX, ERR_R_MALLOC_FAILURE);
922 CRYPTO_THREAD_unlock(bio_lookup_lock);
928 #endif /* OPENSSL_NO_SOCK */