2 * Copyright 2016-2022 The OpenSSL Project Authors. All Rights Reserved.
4 * Licensed under the Apache License 2.0 (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
15 * VC configurations may define UNICODE, to indicate to the C RTL that
16 * WCHAR functions are preferred.
17 * This affects functions like gai_strerror(), which is implemented as
18 * an alias macro for gai_strerrorA() (which returns a const char *) or
19 * gai_strerrorW() (which returns a const WCHAR *). This source file
20 * assumes POSIX declarations, so prefer the non-UNICODE definitions.
27 #include "bio_local.h"
28 #include <openssl/crypto.h>
30 #ifndef OPENSSL_NO_SOCK
31 #include <openssl/err.h>
32 #include <openssl/buffer.h>
33 #include "internal/thread_once.h"
35 CRYPTO_RWLOCK *bio_lookup_lock;
36 static CRYPTO_ONCE bio_lookup_init = CRYPTO_ONCE_STATIC_INIT;
39 * Throughout this file and bio_local.h, the existence of the macro
40 * AI_PASSIVE is used to detect the availability of struct addrinfo,
41 * getnameinfo() and getaddrinfo(). If that macro doesn't exist,
42 * we use our own implementation instead, using gethostbyname,
43 * getservbyname and a few other.
46 /**********************************************************************
52 BIO_ADDR *BIO_ADDR_new(void)
54 BIO_ADDR *ret = OPENSSL_zalloc(sizeof(*ret));
59 ret->sa.sa_family = AF_UNSPEC;
63 void BIO_ADDR_free(BIO_ADDR *ap)
68 BIO_ADDR *BIO_ADDR_dup(const BIO_ADDR *ap)
75 BIO_ADDR_make(ret, &ap->sa);
80 void BIO_ADDR_clear(BIO_ADDR *ap)
82 memset(ap, 0, sizeof(*ap));
83 ap->sa.sa_family = AF_UNSPEC;
87 * BIO_ADDR_make - non-public routine to fill a BIO_ADDR with the contents
88 * of a struct sockaddr.
90 int BIO_ADDR_make(BIO_ADDR *ap, const struct sockaddr *sa)
92 if (sa->sa_family == AF_INET) {
93 memcpy(&(ap->s_in), sa, sizeof(struct sockaddr_in));
97 if (sa->sa_family == AF_INET6) {
98 memcpy(&(ap->s_in6), sa, sizeof(struct sockaddr_in6));
102 #ifndef OPENSSL_NO_UNIX_SOCK
103 if (sa->sa_family == AF_UNIX) {
104 memcpy(&(ap->s_un), sa, sizeof(struct sockaddr_un));
112 int BIO_ADDR_rawmake(BIO_ADDR *ap, int family,
113 const void *where, size_t wherelen,
116 #ifndef OPENSSL_NO_UNIX_SOCK
117 if (family == AF_UNIX) {
118 if (wherelen + 1 > sizeof(ap->s_un.sun_path))
120 memset(&ap->s_un, 0, sizeof(ap->s_un));
121 ap->s_un.sun_family = family;
122 strncpy(ap->s_un.sun_path, where, sizeof(ap->s_un.sun_path) - 1);
126 if (family == AF_INET) {
127 if (wherelen != sizeof(struct in_addr))
129 memset(&ap->s_in, 0, sizeof(ap->s_in));
130 ap->s_in.sin_family = family;
131 ap->s_in.sin_port = port;
132 ap->s_in.sin_addr = *(struct in_addr *)where;
136 if (family == AF_INET6) {
137 if (wherelen != sizeof(struct in6_addr))
139 memset(&ap->s_in6, 0, sizeof(ap->s_in6));
140 ap->s_in6.sin6_family = family;
141 ap->s_in6.sin6_port = port;
142 ap->s_in6.sin6_addr = *(struct in6_addr *)where;
150 int BIO_ADDR_family(const BIO_ADDR *ap)
152 return ap->sa.sa_family;
155 int BIO_ADDR_rawaddress(const BIO_ADDR *ap, void *p, size_t *l)
158 const void *addrptr = NULL;
160 if (ap->sa.sa_family == AF_INET) {
161 len = sizeof(ap->s_in.sin_addr);
162 addrptr = &ap->s_in.sin_addr;
165 else if (ap->sa.sa_family == AF_INET6) {
166 len = sizeof(ap->s_in6.sin6_addr);
167 addrptr = &ap->s_in6.sin6_addr;
170 #ifndef OPENSSL_NO_UNIX_SOCK
171 else if (ap->sa.sa_family == AF_UNIX) {
172 len = strlen(ap->s_un.sun_path);
173 addrptr = &ap->s_un.sun_path;
181 memcpy(p, addrptr, len);
189 unsigned short BIO_ADDR_rawport(const BIO_ADDR *ap)
191 if (ap->sa.sa_family == AF_INET)
192 return ap->s_in.sin_port;
194 if (ap->sa.sa_family == AF_INET6)
195 return ap->s_in6.sin6_port;
201 * addr_strings - helper function to get host and service names
202 * @ap: the BIO_ADDR that has the input info
203 * @numeric: 0 if actual names should be returned, 1 if the numeric
204 * representation should be returned.
205 * @hostname: a pointer to a pointer to a memory area to store the
206 * hostname or numeric representation. Unused if NULL.
207 * @service: a pointer to a pointer to a memory area to store the
208 * service name or numeric representation. Unused if NULL.
210 * The return value is 0 on failure, with the error code in the error
211 * stack, and 1 on success.
213 static int addr_strings(const BIO_ADDR *ap, int numeric,
214 char **hostname, char **service)
216 if (BIO_sock_init() != 1)
222 char host[NI_MAXHOST] = "", serv[NI_MAXSERV] = "";
226 flags |= NI_NUMERICHOST | NI_NUMERICSERV;
228 if ((ret = getnameinfo(BIO_ADDR_sockaddr(ap),
229 BIO_ADDR_sockaddr_size(ap),
230 host, sizeof(host), serv, sizeof(serv),
233 if (ret == EAI_SYSTEM) {
234 ERR_raise_data(ERR_LIB_SYS, get_last_socket_error(),
235 "calling getnameinfo()");
239 ERR_raise_data(ERR_LIB_BIO, ERR_R_SYS_LIB, gai_strerror(ret));
244 /* VMS getnameinfo() has a bug, it doesn't fill in serv, which
245 * leaves it with whatever garbage that happens to be there.
246 * However, we initialise serv with the empty string (serv[0]
247 * is therefore NUL), so it gets real easy to detect when things
248 * didn't go the way one might expect.
250 if (serv[0] == '\0') {
251 BIO_snprintf(serv, sizeof(serv), "%d",
252 ntohs(BIO_ADDR_rawport(ap)));
255 if (hostname != NULL)
256 *hostname = OPENSSL_strdup(host);
258 *service = OPENSSL_strdup(serv);
261 if (hostname != NULL)
262 *hostname = OPENSSL_strdup(inet_ntoa(ap->s_in.sin_addr));
263 if (service != NULL) {
264 char serv[6]; /* port is 16 bits => max 5 decimal digits */
265 BIO_snprintf(serv, sizeof(serv), "%d", ntohs(ap->s_in.sin_port));
266 *service = OPENSSL_strdup(serv);
270 if ((hostname != NULL && *hostname == NULL)
271 || (service != NULL && *service == NULL)) {
272 if (hostname != NULL) {
273 OPENSSL_free(*hostname);
276 if (service != NULL) {
277 OPENSSL_free(*service);
286 char *BIO_ADDR_hostname_string(const BIO_ADDR *ap, int numeric)
288 char *hostname = NULL;
290 if (addr_strings(ap, numeric, &hostname, NULL))
296 char *BIO_ADDR_service_string(const BIO_ADDR *ap, int numeric)
298 char *service = NULL;
300 if (addr_strings(ap, numeric, NULL, &service))
306 char *BIO_ADDR_path_string(const BIO_ADDR *ap)
308 #ifndef OPENSSL_NO_UNIX_SOCK
309 if (ap->sa.sa_family == AF_UNIX)
310 return OPENSSL_strdup(ap->s_un.sun_path);
316 * BIO_ADDR_sockaddr - non-public routine to return the struct sockaddr
317 * for a given BIO_ADDR. In reality, this is simply a type safe cast.
318 * The returned struct sockaddr is const, so it can't be tampered with.
320 const struct sockaddr *BIO_ADDR_sockaddr(const BIO_ADDR *ap)
326 * BIO_ADDR_sockaddr_noconst - non-public function that does the same
327 * as BIO_ADDR_sockaddr, but returns a non-const. USE WITH CARE, as
328 * it allows you to tamper with the data (and thereby the contents
329 * of the input BIO_ADDR).
331 struct sockaddr *BIO_ADDR_sockaddr_noconst(BIO_ADDR *ap)
337 * BIO_ADDR_sockaddr_size - non-public function that returns the size
338 * of the struct sockaddr the BIO_ADDR is using. If the protocol family
339 * isn't set or is something other than AF_INET, AF_INET6 or AF_UNIX,
340 * the size of the BIO_ADDR type is returned.
342 socklen_t BIO_ADDR_sockaddr_size(const BIO_ADDR *ap)
344 if (ap->sa.sa_family == AF_INET)
345 return sizeof(ap->s_in);
347 if (ap->sa.sa_family == AF_INET6)
348 return sizeof(ap->s_in6);
350 #ifndef OPENSSL_NO_UNIX_SOCK
351 if (ap->sa.sa_family == AF_UNIX)
352 return sizeof(ap->s_un);
357 /**********************************************************************
359 * Address info database
363 const BIO_ADDRINFO *BIO_ADDRINFO_next(const BIO_ADDRINFO *bai)
366 return bai->bai_next;
370 int BIO_ADDRINFO_family(const BIO_ADDRINFO *bai)
373 return bai->bai_family;
377 int BIO_ADDRINFO_socktype(const BIO_ADDRINFO *bai)
380 return bai->bai_socktype;
384 int BIO_ADDRINFO_protocol(const BIO_ADDRINFO *bai)
387 if (bai->bai_protocol != 0)
388 return bai->bai_protocol;
390 #ifndef OPENSSL_NO_UNIX_SOCK
391 if (bai->bai_family == AF_UNIX)
395 switch (bai->bai_socktype) {
408 * BIO_ADDRINFO_sockaddr_size - non-public function that returns the size
409 * of the struct sockaddr inside the BIO_ADDRINFO.
411 socklen_t BIO_ADDRINFO_sockaddr_size(const BIO_ADDRINFO *bai)
414 return bai->bai_addrlen;
419 * BIO_ADDRINFO_sockaddr - non-public function that returns bai_addr
420 * as the struct sockaddr it is.
422 const struct sockaddr *BIO_ADDRINFO_sockaddr(const BIO_ADDRINFO *bai)
425 return bai->bai_addr;
429 const BIO_ADDR *BIO_ADDRINFO_address(const BIO_ADDRINFO *bai)
432 return (BIO_ADDR *)bai->bai_addr;
436 void BIO_ADDRINFO_free(BIO_ADDRINFO *bai)
442 # ifndef OPENSSL_NO_UNIX_SOCK
443 # define _cond bai->bai_family != AF_UNIX
453 /* Free manually when we know that addrinfo_wrap() was used.
454 * See further comment above addrinfo_wrap()
456 while (bai != NULL) {
457 BIO_ADDRINFO *next = bai->bai_next;
458 OPENSSL_free(bai->bai_addr);
464 /**********************************************************************
471 * The specs in hostserv can take these forms:
473 * host:service => *host = "host", *service = "service"
474 * host:* => *host = "host", *service = NULL
475 * host: => *host = "host", *service = NULL
476 * :service => *host = NULL, *service = "service"
477 * *:service => *host = NULL, *service = "service"
479 * in case no : is present in the string, the result depends on
480 * hostserv_prio, as follows:
482 * when hostserv_prio == BIO_PARSE_PRIO_HOST
483 * host => *host = "host", *service untouched
485 * when hostserv_prio == BIO_PARSE_PRIO_SERV
486 * service => *host untouched, *service = "service"
489 int BIO_parse_hostserv(const char *hostserv, char **host, char **service,
490 enum BIO_hostserv_priorities hostserv_prio)
492 const char *h = NULL; size_t hl = 0;
493 const char *p = NULL; size_t pl = 0;
495 if (*hostserv == '[') {
496 if ((p = strchr(hostserv, ']')) == NULL)
510 const char *p2 = strrchr(hostserv, ':');
511 p = strchr(hostserv, ':');
514 * Check for more than one colon. There are three possible
516 * 1. IPv6 address with port number, last colon being separator.
517 * 2. IPv6 address only.
518 * 3. IPv6 address only if hostserv_prio == BIO_PARSE_PRIO_HOST,
519 * IPv6 address and port number if hostserv_prio == BIO_PARSE_PRIO_SERV
520 * Because of this ambiguity, we currently choose to make it an
531 } else if (hostserv_prio == BIO_PARSE_PRIO_HOST) {
540 if (p != NULL && strchr(p, ':'))
543 if (h != NULL && host != NULL) {
545 || (hl == 1 && h[0] == '*')) {
548 *host = OPENSSL_strndup(h, hl);
553 if (p != NULL && service != NULL) {
555 || (pl == 1 && p[0] == '*')) {
558 *service = OPENSSL_strndup(p, pl);
559 if (*service == NULL)
566 ERR_raise(ERR_LIB_BIO, BIO_R_AMBIGUOUS_HOST_OR_SERVICE);
569 ERR_raise(ERR_LIB_BIO, BIO_R_MALFORMED_HOST_OR_SERVICE);
573 /* addrinfo_wrap is used to build our own addrinfo "chain".
574 * (it has only one entry, so calling it a chain may be a stretch)
575 * It should ONLY be called when getaddrinfo() and friends
576 * aren't available, OR when dealing with a non IP protocol
577 * family, such as AF_UNIX
579 * the return value is 1 on success, or 0 on failure, which
580 * only happens if a memory allocation error occurred.
582 static int addrinfo_wrap(int family, int socktype,
583 const void *where, size_t wherelen,
587 if ((*bai = OPENSSL_zalloc(sizeof(**bai))) == NULL)
590 (*bai)->bai_family = family;
591 (*bai)->bai_socktype = socktype;
592 if (socktype == SOCK_STREAM)
593 (*bai)->bai_protocol = IPPROTO_TCP;
594 if (socktype == SOCK_DGRAM)
595 (*bai)->bai_protocol = IPPROTO_UDP;
596 #ifndef OPENSSL_NO_UNIX_SOCK
597 if (family == AF_UNIX)
598 (*bai)->bai_protocol = 0;
601 /* Magic: We know that BIO_ADDR_sockaddr_noconst is really
602 just an advanced cast of BIO_ADDR* to struct sockaddr *
603 by the power of union, so while it may seem that we're
604 creating a memory leak here, we are not. It will be
606 BIO_ADDR *addr = BIO_ADDR_new();
608 BIO_ADDR_rawmake(addr, family, where, wherelen, port);
609 (*bai)->bai_addr = BIO_ADDR_sockaddr_noconst(addr);
612 (*bai)->bai_next = NULL;
613 if ((*bai)->bai_addr == NULL) {
614 BIO_ADDRINFO_free(*bai);
621 DEFINE_RUN_ONCE_STATIC(do_bio_lookup_init)
623 bio_lookup_lock = CRYPTO_THREAD_lock_new();
624 return bio_lookup_lock != NULL;
627 int BIO_lookup(const char *host, const char *service,
628 enum BIO_lookup_type lookup_type,
629 int family, int socktype, BIO_ADDRINFO **res)
631 return BIO_lookup_ex(host, service, lookup_type, family, socktype, 0, res);
635 * BIO_lookup_ex - look up the host and service you want to connect to.
636 * @host: the host (or node, in case family == AF_UNIX) you want to connect to.
637 * @service: the service you want to connect to.
638 * @lookup_type: declare intent with the result, client or server.
639 * @family: the address family you want to use. Use AF_UNSPEC for any, or
640 * AF_INET, AF_INET6 or AF_UNIX.
641 * @socktype: The socket type you want to use. Can be SOCK_STREAM, SOCK_DGRAM
643 * @protocol: The protocol to use, e.g. IPPROTO_TCP or IPPROTO_UDP or 0 for all.
644 * Note that some platforms may not return IPPROTO_SCTP without
645 * explicitly requesting it (i.e. IPPROTO_SCTP may not be returned
646 * with 0 for the protocol)
647 * @res: Storage place for the resulting list of returned addresses
649 * This will do a lookup of the host and service that you want to connect to.
650 * It returns a linked list of different addresses you can try to connect to.
652 * When no longer needed you should call BIO_ADDRINFO_free() to free the result.
654 * The return value is 1 on success or 0 in case of error.
656 int BIO_lookup_ex(const char *host, const char *service, int lookup_type,
657 int family, int socktype, int protocol, BIO_ADDRINFO **res)
659 int ret = 0; /* Assume failure */
666 #ifndef OPENSSL_NO_UNIX_SOCK
674 ERR_raise(ERR_LIB_BIO, BIO_R_UNSUPPORTED_PROTOCOL_FAMILY);
678 #ifndef OPENSSL_NO_UNIX_SOCK
679 if (family == AF_UNIX) {
680 if (addrinfo_wrap(family, socktype, host, strlen(host), 0, res))
683 ERR_raise(ERR_LIB_BIO, ERR_R_BIO_LIB);
688 if (BIO_sock_init() != 1)
693 int gai_ret = 0, old_ret = 0;
694 struct addrinfo hints;
696 memset(&hints, 0, sizeof(hints));
698 hints.ai_family = family;
699 hints.ai_socktype = socktype;
700 hints.ai_protocol = protocol;
701 # ifdef AI_ADDRCONFIG
703 if (host != NULL && family == AF_UNSPEC)
705 hints.ai_flags |= AI_ADDRCONFIG;
708 if (lookup_type == BIO_LOOKUP_SERVER)
709 hints.ai_flags |= AI_PASSIVE;
711 /* Note that |res| SHOULD be a 'struct addrinfo **' thanks to
712 * macro magic in bio_local.h
714 # if defined(AI_ADDRCONFIG) && defined(AI_NUMERICHOST)
717 switch ((gai_ret = getaddrinfo(host, service, &hints, res))) {
720 ERR_raise_data(ERR_LIB_SYS, get_last_socket_error(),
721 "calling getaddrinfo()");
722 ERR_raise(ERR_LIB_BIO, ERR_R_SYS_LIB);
727 ERR_raise_data(ERR_LIB_BIO, ERR_R_SYS_LIB,
728 gai_strerror(old_ret ? old_ret : gai_ret));
732 ret = 1; /* Success */
735 # if defined(AI_ADDRCONFIG) && defined(AI_NUMERICHOST)
736 if (hints.ai_flags & AI_ADDRCONFIG) {
737 hints.ai_flags &= ~AI_ADDRCONFIG;
738 hints.ai_flags |= AI_NUMERICHOST;
743 ERR_raise_data(ERR_LIB_BIO, ERR_R_SYS_LIB,
744 gai_strerror(old_ret ? old_ret : gai_ret));
749 const struct hostent *he;
751 * Because struct hostent is defined for 32-bit pointers only with
752 * VMS C, we need to make sure that '&he_fallback_address' and
753 * '&he_fallback_addresses' are 32-bit pointers
755 #if defined(OPENSSL_SYS_VMS) && defined(__DECC)
756 # pragma pointer_size save
757 # pragma pointer_size 32
759 /* Windows doesn't seem to have in_addr_t */
760 #if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS)
761 static uint32_t he_fallback_address;
762 static const char *he_fallback_addresses[] =
763 { (char *)&he_fallback_address, NULL };
765 static in_addr_t he_fallback_address;
766 static const char *he_fallback_addresses[] =
767 { (char *)&he_fallback_address, NULL };
769 static const struct hostent he_fallback =
770 { NULL, NULL, AF_INET, sizeof(he_fallback_address),
771 (char **)&he_fallback_addresses };
772 #if defined(OPENSSL_SYS_VMS) && defined(__DECC)
773 # pragma pointer_size restore
777 /* Apparently, on WIN64, s_proto and s_port have traded places... */
779 struct servent se_fallback = { NULL, NULL, NULL, 0 };
781 struct servent se_fallback = { NULL, NULL, 0, NULL };
784 if (!RUN_ONCE(&bio_lookup_init, do_bio_lookup_init)) {
785 /* Should this be raised inside do_bio_lookup_init()? */
786 ERR_raise(ERR_LIB_BIO, ERR_R_CRYPTO_LIB);
791 if (!CRYPTO_THREAD_write_lock(bio_lookup_lock)) {
795 he_fallback_address = INADDR_ANY;
798 switch (lookup_type) {
799 case BIO_LOOKUP_CLIENT:
800 he_fallback_address = INADDR_LOOPBACK;
802 case BIO_LOOKUP_SERVER:
803 he_fallback_address = INADDR_ANY;
806 /* We forgot to handle a lookup type! */
807 assert("We forgot to handle a lookup type!" == NULL);
808 ERR_raise(ERR_LIB_BIO, ERR_R_INTERNAL_ERROR);
813 he = gethostbyname(host);
816 #ifndef OPENSSL_SYS_WINDOWS
818 * This might be misleading, because h_errno is used as if
819 * it was errno. To minimize mixup add 1000. Underlying
820 * reason for this is that hstrerror is declared obsolete,
821 * not to mention that a) h_errno is not always guaranteed
822 * to be meaningless; b) hstrerror can reside in yet another
823 * library, linking for sake of hstrerror is an overkill;
824 * c) this path is not executed on contemporary systems
825 * anyway [above getaddrinfo/gai_strerror is]. We just let
826 * system administrator figure this out...
828 # if defined(OPENSSL_SYS_VXWORKS)
829 /* h_errno doesn't exist on VxWorks */
830 ERR_raise_data(ERR_LIB_SYS, 1000,
831 "calling gethostbyname()");
833 ERR_raise_data(ERR_LIB_SYS, 1000 + h_errno,
834 "calling gethostbyname()");
837 ERR_raise_data(ERR_LIB_SYS, get_last_socket_error(),
838 "calling gethostbyname()");
845 if (service == NULL) {
846 se_fallback.s_port = 0;
847 se_fallback.s_proto = NULL;
851 long portnum = strtol(service, &endp, 10);
854 * Because struct servent is defined for 32-bit pointers only with
855 * VMS C, we need to make sure that 'proto' is a 32-bit pointer.
857 #if defined(OPENSSL_SYS_VMS) && defined(__DECC)
858 # pragma pointer_size save
859 # pragma pointer_size 32
862 #if defined(OPENSSL_SYS_VMS) && defined(__DECC)
863 # pragma pointer_size restore
875 if (endp != service && *endp == '\0'
876 && portnum > 0 && portnum < 65536) {
877 se_fallback.s_port = htons((unsigned short)portnum);
878 se_fallback.s_proto = proto;
880 } else if (endp == service) {
881 se = getservbyname(service, proto);
884 ERR_raise_data(ERR_LIB_SYS, get_last_socket_error(),
885 "calling getservbyname()");
889 ERR_raise(ERR_LIB_BIO, BIO_R_MALFORMED_HOST_OR_SERVICE);
898 * Because hostent::h_addr_list is an array of 32-bit pointers with VMS C,
899 * we must make sure our iterator designates the same element type, hence
900 * the pointer size dance.
902 #if defined(OPENSSL_SYS_VMS) && defined(__DECC)
903 # pragma pointer_size save
904 # pragma pointer_size 32
907 #if defined(OPENSSL_SYS_VMS) && defined(__DECC)
908 # pragma pointer_size restore
911 BIO_ADDRINFO *tmp_bai = NULL;
913 /* The easiest way to create a linked list from an
914 array is to start from the back */
915 for (addrlistp = he->h_addr_list; *addrlistp != NULL;
919 for (addresses = addrlistp - he->h_addr_list;
920 addrlistp--, addresses-- > 0; ) {
921 if (!addrinfo_wrap(he->h_addrtype, socktype,
922 *addrlistp, he->h_length,
923 se->s_port, &tmp_bai))
924 goto addrinfo_wrap_err;
925 tmp_bai->bai_next = *res;
929 BIO_ADDRINFO_free(*res);
931 ERR_raise(ERR_LIB_BIO, ERR_R_BIO_LIB);
939 CRYPTO_THREAD_unlock(bio_lookup_lock);
945 #endif /* OPENSSL_NO_SOCK */