2 * Copyright 2016 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
14 #include <openssl/crypto.h>
16 #ifndef OPENSSL_NO_SOCK
17 #include <openssl/err.h>
18 #include <openssl/buffer.h>
19 #include <internal/thread_once.h>
22 CRYPTO_RWLOCK *bio_lookup_lock;
23 static CRYPTO_ONCE bio_lookup_init = CRYPTO_ONCE_STATIC_INIT;
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.
33 /**********************************************************************
39 BIO_ADDR *BIO_ADDR_new(void)
41 BIO_ADDR *ret = OPENSSL_zalloc(sizeof(*ret));
44 BIOerr(BIO_F_BIO_ADDR_NEW, ERR_R_MALLOC_FAILURE);
48 ret->sa.sa_family = AF_UNSPEC;
52 void BIO_ADDR_free(BIO_ADDR *ap)
57 void BIO_ADDR_clear(BIO_ADDR *ap)
59 memset(ap, 0, sizeof(*ap));
60 ap->sa.sa_family = AF_UNSPEC;
64 * BIO_ADDR_make - non-public routine to fill a BIO_ADDR with the contents
65 * of a struct sockaddr.
67 int BIO_ADDR_make(BIO_ADDR *ap, const struct sockaddr *sa)
69 if (sa->sa_family == AF_INET) {
70 ap->s_in = *(const struct sockaddr_in *)sa;
74 if (sa->sa_family == AF_INET6) {
75 ap->s_in6 = *(const struct sockaddr_in6 *)sa;
80 if (ap->sa.sa_family == AF_UNIX) {
81 ap->s_un = *(const struct sockaddr_un *)sa;
89 int BIO_ADDR_rawmake(BIO_ADDR *ap, int family,
90 const void *where, size_t wherelen,
94 if (family == AF_UNIX) {
95 if (wherelen + 1 > sizeof(ap->s_un.sun_path))
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);
103 if (family == AF_INET) {
104 if (wherelen != sizeof(struct in_addr))
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;
113 if (family == AF_INET6) {
114 if (wherelen != sizeof(struct in6_addr))
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;
127 int BIO_ADDR_family(const BIO_ADDR *ap)
129 return ap->sa.sa_family;
132 int BIO_ADDR_rawaddress(const BIO_ADDR *ap, void *p, size_t *l)
135 const void *addrptr = NULL;
137 if (ap->sa.sa_family == AF_INET) {
138 len = sizeof(ap->s_in.sin_addr);
139 addrptr = &ap->s_in.sin_addr;
142 else if (ap->sa.sa_family == AF_INET6) {
143 len = sizeof(ap->s_in6.sin6_addr);
144 addrptr = &ap->s_in6.sin6_addr;
148 else if (ap->sa.sa_family == AF_UNIX) {
149 len = strlen(ap->s_un.sun_path);
150 addrptr = &ap->s_un.sun_path;
158 memcpy(p, addrptr, len);
166 unsigned short BIO_ADDR_rawport(const BIO_ADDR *ap)
168 if (ap->sa.sa_family == AF_INET)
169 return ap->s_in.sin_port;
171 if (ap->sa.sa_family == AF_INET6)
172 return ap->s_in6.sin6_port;
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.
187 * The return value is 0 on failure, with the error code in the error
188 * stack, and 1 on success.
190 static int addr_strings(const BIO_ADDR *ap, int numeric,
191 char **hostname, char **service)
193 if (BIO_sock_init() != 1)
199 char host[NI_MAXHOST] = "", serv[NI_MAXSERV] = "";
203 flags |= NI_NUMERICHOST | NI_NUMERICSERV;
205 if ((ret = getnameinfo(BIO_ADDR_sockaddr(ap),
206 BIO_ADDR_sockaddr_size(ap),
207 host, sizeof(host), serv, sizeof(serv),
210 if (ret == EAI_SYSTEM) {
211 SYSerr(SYS_F_GETNAMEINFO, get_last_socket_error());
212 BIOerr(BIO_F_ADDR_STRINGS, ERR_R_SYS_LIB);
216 BIOerr(BIO_F_ADDR_STRINGS, ERR_R_SYS_LIB);
217 ERR_add_error_data(1, gai_strerror(ret));
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.
228 if (serv[0] == '\0') {
229 BIO_snprintf(serv, sizeof(serv), "%d",
230 ntohs(BIO_ADDR_rawport(ap)));
233 if (hostname != NULL)
234 *hostname = OPENSSL_strdup(host);
236 *service = OPENSSL_strdup(serv);
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);
248 if ((hostname != NULL && *hostname == NULL)
249 || (service != NULL && *service == NULL)) {
250 if (hostname != NULL) {
251 OPENSSL_free(*hostname);
254 if (service != NULL) {
255 OPENSSL_free(*service);
258 BIOerr(BIO_F_ADDR_STRINGS, ERR_R_MALLOC_FAILURE);
265 char *BIO_ADDR_hostname_string(const BIO_ADDR *ap, int numeric)
267 char *hostname = NULL;
269 if (addr_strings(ap, numeric, &hostname, NULL))
275 char *BIO_ADDR_service_string(const BIO_ADDR *ap, int numeric)
277 char *service = NULL;
279 if (addr_strings(ap, numeric, NULL, &service))
285 char *BIO_ADDR_path_string(const BIO_ADDR *ap)
288 if (ap->sa.sa_family == AF_UNIX)
289 return OPENSSL_strdup(ap->s_un.sun_path);
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.
299 const struct sockaddr *BIO_ADDR_sockaddr(const BIO_ADDR *ap)
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).
310 struct sockaddr *BIO_ADDR_sockaddr_noconst(BIO_ADDR *ap)
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.
321 socklen_t BIO_ADDR_sockaddr_size(const BIO_ADDR *ap)
323 if (ap->sa.sa_family == AF_INET)
324 return sizeof(ap->s_in);
326 if (ap->sa.sa_family == AF_INET6)
327 return sizeof(ap->s_in6);
330 if (ap->sa.sa_family == AF_UNIX)
331 return sizeof(ap->s_un);
336 /**********************************************************************
338 * Address info database
342 const BIO_ADDRINFO *BIO_ADDRINFO_next(const BIO_ADDRINFO *bai)
345 return bai->bai_next;
349 int BIO_ADDRINFO_family(const BIO_ADDRINFO *bai)
352 return bai->bai_family;
356 int BIO_ADDRINFO_socktype(const BIO_ADDRINFO *bai)
359 return bai->bai_socktype;
363 int BIO_ADDRINFO_protocol(const BIO_ADDRINFO *bai)
366 if (bai->bai_protocol != 0)
367 return bai->bai_protocol;
370 if (bai->bai_family == AF_UNIX)
374 switch (bai->bai_socktype) {
387 * BIO_ADDRINFO_sockaddr_size - non-public function that returns the size
388 * of the struct sockaddr inside the BIO_ADDRINFO.
390 socklen_t BIO_ADDRINFO_sockaddr_size(const BIO_ADDRINFO *bai)
393 return bai->bai_addrlen;
398 * BIO_ADDRINFO_sockaddr - non-public function that returns bai_addr
399 * as the struct sockaddr it is.
401 const struct sockaddr *BIO_ADDRINFO_sockaddr(const BIO_ADDRINFO *bai)
404 return bai->bai_addr;
408 const BIO_ADDR *BIO_ADDRINFO_address(const BIO_ADDRINFO *bai)
411 return (BIO_ADDR *)bai->bai_addr;
415 void BIO_ADDRINFO_free(BIO_ADDRINFO *bai)
422 # define _cond bai->bai_family != AF_UNIX
432 /* Free manually when we know that addrinfo_wrap() was used.
433 * See further comment above addrinfo_wrap()
435 while (bai != NULL) {
436 BIO_ADDRINFO *next = bai->bai_next;
437 OPENSSL_free(bai->bai_addr);
443 /**********************************************************************
450 * The specs in hostserv can take these forms:
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"
458 * in case no : is present in the string, the result depends on
459 * hostserv_prio, as follows:
461 * when hostserv_prio == BIO_PARSE_PRIO_HOST
462 * host => *host = "host", *service untouched
464 * when hostserv_prio == BIO_PARSE_PRIO_SERV
465 * service => *host untouched, *service = "service"
468 int BIO_parse_hostserv(const char *hostserv, char **host, char **service,
469 enum BIO_hostserv_priorities hostserv_prio)
471 const char *h = NULL; size_t hl = 0;
472 const char *p = NULL; size_t pl = 0;
474 if (*hostserv == '[') {
475 if ((p = strchr(hostserv, ']')) == NULL)
489 const char *p2 = strrchr(hostserv, ':');
490 p = strchr(hostserv, ':');
493 * Check for more than one colon. There are three possible
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
510 } else if (hostserv_prio == BIO_PARSE_PRIO_HOST) {
519 if (p != NULL && strchr(p, ':'))
522 if (h != NULL && host != NULL) {
524 || (hl == 1 && h[0] == '*')) {
527 *host = OPENSSL_strndup(h, hl);
532 if (p != NULL && service != NULL) {
534 || (pl == 1 && p[0] == '*')) {
537 *service = OPENSSL_strndup(p, pl);
538 if (*service == NULL)
545 BIOerr(BIO_F_BIO_PARSE_HOSTSERV, BIO_R_AMBIGUOUS_HOST_OR_SERVICE);
548 BIOerr(BIO_F_BIO_PARSE_HOSTSERV, BIO_R_MALFORMED_HOST_OR_SERVICE);
551 BIOerr(BIO_F_BIO_PARSE_HOSTSERV, ERR_R_MALLOC_FAILURE);
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
561 * the return value is 1 on success, or 0 on failure, which
562 * only happens if a memory allocation error occurred.
564 static int addrinfo_wrap(int family, int socktype,
565 const void *where, size_t wherelen,
569 *bai = OPENSSL_zalloc(sizeof(**bai));
573 (*bai)->bai_family = family;
574 (*bai)->bai_socktype = socktype;
575 if (socktype == SOCK_STREAM)
576 (*bai)->bai_protocol = IPPROTO_TCP;
577 if (socktype == SOCK_DGRAM)
578 (*bai)->bai_protocol = IPPROTO_UDP;
580 if (family == AF_UNIX)
581 (*bai)->bai_protocol = 0;
584 /* Magic: We know that BIO_ADDR_sockaddr_noconst is really
585 just an advanced cast of BIO_ADDR* to struct sockaddr *
586 by the power of union, so while it may seem that we're
587 creating a memory leak here, we are not. It will be
589 BIO_ADDR *addr = BIO_ADDR_new();
591 BIO_ADDR_rawmake(addr, family, where, wherelen, port);
592 (*bai)->bai_addr = BIO_ADDR_sockaddr_noconst(addr);
595 (*bai)->bai_next = NULL;
596 if ((*bai)->bai_addr == NULL) {
597 BIO_ADDRINFO_free(*bai);
604 DEFINE_RUN_ONCE_STATIC(do_bio_lookup_init)
606 OPENSSL_init_crypto(0, NULL);
607 bio_lookup_lock = CRYPTO_THREAD_lock_new();
608 return bio_lookup_lock != NULL;
611 int BIO_lookup(const char *host, const char *service,
612 enum BIO_lookup_type lookup_type,
613 int family, int socktype, BIO_ADDRINFO **res)
615 return BIO_lookup_ex(host, service, lookup_type, family, socktype, 0, res);
619 * BIO_lookup_ex - look up the node and service you want to connect to.
620 * @node: the node you want to connect to.
621 * @service: the service you want to connect to.
622 * @lookup_type: declare intent with the result, client or server.
623 * @family: the address family you want to use. Use AF_UNSPEC for any, or
624 * AF_INET, AF_INET6 or AF_UNIX.
625 * @socktype: The socket type you want to use. Can be SOCK_STREAM, SOCK_DGRAM
627 * @protocol: The protocol to use, e.g. IPPROTO_TCP or IPPROTO_UDP or 0 for all.
628 * Note that some platforms may not return IPPROTO_SCTP without
629 * explicitly requesting it (i.e. IPPROTO_SCTP may not be returned
630 * with 0 for the protocol)
631 * @res: Storage place for the resulting list of returned addresses
633 * This will do a lookup of the node and service that you want to connect to.
634 * It returns a linked list of different addresses you can try to connect to.
636 * When no longer needed you should call BIO_ADDRINFO_free() to free the result.
638 * The return value is 1 on success or 0 in case of error.
640 int BIO_lookup_ex(const char *host, const char *service, int lookup_type,
641 int family, int socktype, int protocol, BIO_ADDRINFO **res)
643 int ret = 0; /* Assume failure */
658 BIOerr(BIO_F_BIO_LOOKUP_EX, BIO_R_UNSUPPORTED_PROTOCOL_FAMILY);
663 if (family == AF_UNIX) {
664 if (addrinfo_wrap(family, socktype, host, strlen(host), 0, res))
667 BIOerr(BIO_F_BIO_LOOKUP_EX, ERR_R_MALLOC_FAILURE);
672 if (BIO_sock_init() != 1)
678 struct addrinfo hints;
680 memset(&hints, 0, sizeof hints);
682 hints.ai_family = family;
683 hints.ai_socktype = socktype;
684 hints.ai_protocol = protocol;
686 if (lookup_type == BIO_LOOKUP_SERVER)
687 hints.ai_flags |= AI_PASSIVE;
689 /* Note that |res| SHOULD be a 'struct addrinfo **' thanks to
690 * macro magic in bio_lcl.h
692 switch ((gai_ret = getaddrinfo(host, service, &hints, res))) {
695 SYSerr(SYS_F_GETADDRINFO, get_last_socket_error());
696 BIOerr(BIO_F_BIO_LOOKUP_EX, ERR_R_SYS_LIB);
700 ret = 1; /* Success */
703 BIOerr(BIO_F_BIO_LOOKUP_EX, ERR_R_SYS_LIB);
704 ERR_add_error_data(1, gai_strerror(gai_ret));
709 const struct hostent *he;
711 * Because struct hostent is defined for 32-bit pointers only with
712 * VMS C, we need to make sure that '&he_fallback_address' and
713 * '&he_fallback_addresses' are 32-bit pointers
715 #if defined(OPENSSL_SYS_VMS) && defined(__DECC)
716 # pragma pointer_size save
717 # pragma pointer_size 32
719 /* Windows doesn't seem to have in_addr_t */
720 #ifdef OPENSSL_SYS_WINDOWS
721 static uint32_t he_fallback_address;
722 static const char *he_fallback_addresses[] =
723 { (char *)&he_fallback_address, NULL };
725 static in_addr_t he_fallback_address;
726 static const char *he_fallback_addresses[] =
727 { (char *)&he_fallback_address, NULL };
729 static const struct hostent he_fallback =
730 { NULL, NULL, AF_INET, sizeof(he_fallback_address),
731 (char **)&he_fallback_addresses };
732 #if defined(OPENSSL_SYS_VMS) && defined(__DECC)
733 # pragma pointer_size restore
737 /* Apparently, on WIN64, s_proto and s_port have traded places... */
739 struct servent se_fallback = { NULL, NULL, NULL, 0 };
741 struct servent se_fallback = { NULL, NULL, 0, NULL };
744 if (!RUN_ONCE(&bio_lookup_init, do_bio_lookup_init)) {
745 BIOerr(BIO_F_BIO_LOOKUP_EX, ERR_R_MALLOC_FAILURE);
750 CRYPTO_THREAD_write_lock(bio_lookup_lock);
751 he_fallback_address = INADDR_ANY;
754 switch(lookup_type) {
755 case BIO_LOOKUP_CLIENT:
756 he_fallback_address = INADDR_LOOPBACK;
758 case BIO_LOOKUP_SERVER:
759 he_fallback_address = INADDR_ANY;
762 /* We forgot to handle a lookup type! */
763 assert("We forgot to handle a lookup type!" == NULL);
764 BIOerr(BIO_F_BIO_LOOKUP_EX, ERR_R_INTERNAL_ERROR);
769 he = gethostbyname(host);
772 #ifndef OPENSSL_SYS_WINDOWS
774 * This might be misleading, because h_errno is used as if
775 * it was errno. To minimize mixup add 1000. Underlying
776 * reason for this is that hstrerror is declared obsolete,
777 * not to mention that a) h_errno is not always guaranteed
778 * to be meaningless; b) hstrerror can reside in yet another
779 * library, linking for sake of hstrerror is an overkill;
780 * c) this path is not executed on contemporary systems
781 * anyway [above getaddrinfo/gai_strerror is]. We just let
782 * system administrator figure this out...
784 SYSerr(SYS_F_GETHOSTBYNAME, 1000 + h_errno);
786 SYSerr(SYS_F_GETHOSTBYNAME, WSAGetLastError());
793 if (service == NULL) {
794 se_fallback.s_port = 0;
795 se_fallback.s_proto = NULL;
799 long portnum = strtol(service, &endp, 10);
802 * Because struct servent is defined for 32-bit pointers only with
803 * VMS C, we need to make sure that 'proto' is a 32-bit pointer.
805 #if defined(OPENSSL_SYS_VMS) && defined(__DECC)
806 # pragma pointer_size save
807 # pragma pointer_size 32
810 #if defined(OPENSSL_SYS_VMS) && defined(__DECC)
811 # pragma pointer_size restore
823 if (endp != service && *endp == '\0'
824 && portnum > 0 && portnum < 65536) {
825 se_fallback.s_port = htons(portnum);
826 se_fallback.s_proto = proto;
828 } else if (endp == service) {
829 se = getservbyname(service, proto);
832 #ifndef OPENSSL_SYS_WINDOWS
833 SYSerr(SYS_F_GETSERVBYNAME, errno);
835 SYSerr(SYS_F_GETSERVBYNAME, WSAGetLastError());
840 BIOerr(BIO_F_BIO_LOOKUP_EX, BIO_R_MALFORMED_HOST_OR_SERVICE);
849 * Because hostent::h_addr_list is an array of 32-bit pointers with VMS C,
850 * we must make sure our iterator designates the same element type, hence
851 * the pointer size dance.
853 #if defined(OPENSSL_SYS_VMS) && defined(__DECC)
854 # pragma pointer_size save
855 # pragma pointer_size 32
858 #if defined(OPENSSL_SYS_VMS) && defined(__DECC)
859 # pragma pointer_size restore
862 BIO_ADDRINFO *tmp_bai = NULL;
864 /* The easiest way to create a linked list from an
865 array is to start from the back */
866 for(addrlistp = he->h_addr_list; *addrlistp != NULL;
870 for(addresses = addrlistp - he->h_addr_list;
871 addrlistp--, addresses-- > 0; ) {
872 if (!addrinfo_wrap(he->h_addrtype, socktype,
873 *addrlistp, he->h_length,
874 se->s_port, &tmp_bai))
875 goto addrinfo_malloc_err;
876 tmp_bai->bai_next = *res;
880 BIO_ADDRINFO_free(*res);
882 BIOerr(BIO_F_BIO_LOOKUP_EX, ERR_R_MALLOC_FAILURE);
890 CRYPTO_THREAD_unlock(bio_lookup_lock);
896 #endif /* OPENSSL_NO_SOCK */