2 * Copyright 2017 Facebook, Inc.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 #ifndef __STDC_FORMAT_MACROS
18 #define __STDC_FORMAT_MACROS
21 #include <folly/SocketAddress.h>
23 #include <folly/Exception.h>
24 #include <folly/Hash.h>
26 #include <boost/functional/hash.hpp>
32 #include <system_error>
37 * A structure to free a struct addrinfo when it goes out of scope.
39 struct ScopedAddrInfo {
40 explicit ScopedAddrInfo(struct addrinfo* addrinfo) : info(addrinfo) {}
45 struct addrinfo* info;
49 * A simple data structure for parsing a host-and-port string.
51 * Accepts a string of the form "<host>:<port>" or just "<port>",
52 * and contains two string pointers to the host and the port portion of the
55 * The HostAndPort may contain pointers into the original string. It is
56 * responsible for the user to ensure that the input string is valid for the
57 * lifetime of the HostAndPort structure.
60 HostAndPort(const char* str, bool hostRequired)
65 // Look for the last colon
66 const char* colon = strrchr(str, ':');
67 if (colon == nullptr) {
68 // No colon, just a port number.
70 throw std::invalid_argument(
71 "expected a host and port string of the "
72 "form \"<host>:<port>\"");
78 // We have to make a copy of the string so we can modify it
79 // and change the colon to a NUL terminator.
80 allocated = strdup(str);
82 throw std::bad_alloc();
85 char *allocatedColon = allocated + (colon - str);
86 *allocatedColon = '\0';
88 port = allocatedColon + 1;
89 // bracketed IPv6 address, remove the brackets
90 // allocatedColon[-1] is fine, as allocatedColon >= host and
91 // *allocatedColon != *host therefore allocatedColon > host
92 if (*host == '[' && allocatedColon[-1] == ']') {
93 allocatedColon[-1] = '\0';
107 } // unnamed namespace
111 bool SocketAddress::isPrivateAddress() const {
112 auto family = getFamily();
113 if (family == AF_INET || family == AF_INET6) {
114 return storage_.addr.isPrivate() ||
115 (storage_.addr.isV6() && storage_.addr.asV6().isLinkLocal());
116 } else if (external_) {
117 // Unix addresses are always local to a host. Return true,
118 // since this conforms to the semantics of returning true for IP loopback
125 bool SocketAddress::isLoopbackAddress() const {
126 auto family = getFamily();
127 if (family == AF_INET || family == AF_INET6) {
128 return storage_.addr.isLoopback();
129 } else if (external_) {
130 // Return true for UNIX addresses, since they are always local to a host.
136 void SocketAddress::setFromHostPort(const char* host, uint16_t port) {
137 ScopedAddrInfo results(getAddrInfo(host, port, 0));
138 setFromAddrInfo(results.info);
141 void SocketAddress::setFromIpPort(const char* ip, uint16_t port) {
142 ScopedAddrInfo results(getAddrInfo(ip, port, AI_NUMERICHOST));
143 setFromAddrInfo(results.info);
146 void SocketAddress::setFromIpAddrPort(const IPAddress& ipAddr, uint16_t port) {
151 storage_.addr = ipAddr;
155 void SocketAddress::setFromLocalPort(uint16_t port) {
156 ScopedAddrInfo results(getAddrInfo(nullptr, port, AI_ADDRCONFIG));
157 setFromLocalAddr(results.info);
160 void SocketAddress::setFromLocalPort(const char* port) {
161 ScopedAddrInfo results(getAddrInfo(nullptr, port, AI_ADDRCONFIG));
162 setFromLocalAddr(results.info);
165 void SocketAddress::setFromLocalIpPort(const char* addressAndPort) {
166 HostAndPort hp(addressAndPort, false);
167 ScopedAddrInfo results(getAddrInfo(hp.host, hp.port,
168 AI_NUMERICHOST | AI_ADDRCONFIG));
169 setFromLocalAddr(results.info);
172 void SocketAddress::setFromIpPort(const char* addressAndPort) {
173 HostAndPort hp(addressAndPort, true);
174 ScopedAddrInfo results(getAddrInfo(hp.host, hp.port, AI_NUMERICHOST));
175 setFromAddrInfo(results.info);
178 void SocketAddress::setFromHostPort(const char* hostAndPort) {
179 HostAndPort hp(hostAndPort, true);
180 ScopedAddrInfo results(getAddrInfo(hp.host, hp.port, 0));
181 setFromAddrInfo(results.info);
184 int SocketAddress::getPortFrom(const struct sockaddr* address) {
185 switch (address->sa_family) {
187 return ntohs(((sockaddr_in*)address)->sin_port);
190 return ntohs(((sockaddr_in6*)address)->sin6_port);
197 const char* SocketAddress::getFamilyNameFrom(
198 const struct sockaddr* address,
199 const char* defaultResult) {
200 #define GETFAMILYNAMEFROM_IMPL(Family) \
204 switch (address->sa_family) {
205 GETFAMILYNAMEFROM_IMPL(AF_INET);
206 GETFAMILYNAMEFROM_IMPL(AF_INET6);
207 GETFAMILYNAMEFROM_IMPL(AF_UNIX);
208 GETFAMILYNAMEFROM_IMPL(AF_UNSPEC);
211 return defaultResult;
214 #undef GETFAMILYNAMEFROM_IMPL
217 void SocketAddress::setFromPath(StringPiece path) {
218 // Before we touch storage_, check to see if the length is too big.
219 // Note that "storage_.un.addr->sun_path" may not be safe to evaluate here,
220 // but sizeof() just uses its type, and does't evaluate it.
221 if (path.size() > sizeof(storage_.un.addr->sun_path)) {
222 throw std::invalid_argument(
223 "socket path too large to fit into sockaddr_un");
231 size_t len = path.size();
232 storage_.un.len = socklen_t(offsetof(struct sockaddr_un, sun_path) + len);
233 memcpy(storage_.un.addr->sun_path, path.data(), len);
234 // If there is room, put a terminating NUL byte in sun_path. In general the
235 // path should be NUL terminated, although getsockname() and getpeername()
236 // may return Unix socket addresses with paths that fit exactly in sun_path
237 // with no terminating NUL.
238 if (len < sizeof(storage_.un.addr->sun_path)) {
239 storage_.un.addr->sun_path[len] = '\0';
243 void SocketAddress::setFromPeerAddress(int socket) {
244 setFromSocket(socket, getpeername);
247 void SocketAddress::setFromLocalAddress(int socket) {
248 setFromSocket(socket, getsockname);
251 void SocketAddress::setFromSockaddr(const struct sockaddr* address) {
254 if (address->sa_family == AF_INET) {
255 port = ntohs(((sockaddr_in*)address)->sin_port);
256 } else if (address->sa_family == AF_INET6) {
257 port = ntohs(((sockaddr_in6*)address)->sin6_port);
258 } else if (address->sa_family == AF_UNIX) {
259 // We need an explicitly specified length for AF_UNIX addresses,
260 // to be able to distinguish anonymous addresses from addresses
261 // in Linux's abstract namespace.
262 throw std::invalid_argument(
263 "SocketAddress::setFromSockaddr(): the address "
264 "length must be explicitly specified when "
265 "setting AF_UNIX addresses");
267 throw std::invalid_argument(
268 "SocketAddress::setFromSockaddr() called "
269 "with unsupported address type");
272 setFromIpAddrPort(folly::IPAddress(address), port);
275 void SocketAddress::setFromSockaddr(const struct sockaddr* address,
277 // Check the length to make sure we can access address->sa_family
278 if (addrlen < (offsetof(struct sockaddr, sa_family) +
279 sizeof(address->sa_family))) {
280 throw std::invalid_argument(
281 "SocketAddress::setFromSockaddr() called "
282 "with length too short for a sockaddr");
285 if (address->sa_family == AF_INET) {
286 if (addrlen < sizeof(struct sockaddr_in)) {
287 throw std::invalid_argument(
288 "SocketAddress::setFromSockaddr() called "
289 "with length too short for a sockaddr_in");
291 setFromSockaddr(reinterpret_cast<const struct sockaddr_in*>(address));
292 } else if (address->sa_family == AF_INET6) {
293 if (addrlen < sizeof(struct sockaddr_in6)) {
294 throw std::invalid_argument(
295 "SocketAddress::setFromSockaddr() called "
296 "with length too short for a sockaddr_in6");
298 setFromSockaddr(reinterpret_cast<const struct sockaddr_in6*>(address));
299 } else if (address->sa_family == AF_UNIX) {
300 setFromSockaddr(reinterpret_cast<const struct sockaddr_un*>(address),
303 throw std::invalid_argument(
304 "SocketAddress::setFromSockaddr() called "
305 "with unsupported address type");
309 void SocketAddress::setFromSockaddr(const struct sockaddr_in* address) {
310 assert(address->sin_family == AF_INET);
311 setFromSockaddr((sockaddr*)address);
314 void SocketAddress::setFromSockaddr(const struct sockaddr_in6* address) {
315 assert(address->sin6_family == AF_INET6);
316 setFromSockaddr((sockaddr*)address);
319 void SocketAddress::setFromSockaddr(const struct sockaddr_un* address,
321 assert(address->sun_family == AF_UNIX);
322 if (addrlen > sizeof(struct sockaddr_un)) {
323 throw std::invalid_argument(
324 "SocketAddress::setFromSockaddr() called "
325 "with length too long for a sockaddr_un");
332 memcpy(storage_.un.addr, address, size_t(addrlen));
333 updateUnixAddressLength(addrlen);
335 // Fill the rest with 0s, just for safety
336 if (addrlen < sizeof(struct sockaddr_un)) {
337 char *p = reinterpret_cast<char*>(storage_.un.addr);
338 memset(p + addrlen, 0, sizeof(struct sockaddr_un) - addrlen);
342 const folly::IPAddress& SocketAddress::getIPAddress() const {
343 auto family = getFamily();
344 if (family != AF_INET && family != AF_INET6) {
345 throw InvalidAddressFamilyException(family);
347 return storage_.addr;
350 socklen_t SocketAddress::getActualSize() const {
352 return storage_.un.len;
354 switch (getFamily()) {
357 return sizeof(struct sockaddr_in);
359 return sizeof(struct sockaddr_in6);
361 throw std::invalid_argument(
362 "SocketAddress::getActualSize() called "
363 "with unrecognized address family");
367 std::string SocketAddress::getFullyQualified() const {
368 if (!isFamilyInet()) {
369 throw std::invalid_argument("Can't get address str for non ip address");
371 return storage_.addr.toFullyQualified();
374 std::string SocketAddress::getAddressStr() const {
375 if (!isFamilyInet()) {
376 throw std::invalid_argument("Can't get address str for non ip address");
378 return storage_.addr.str();
381 bool SocketAddress::isFamilyInet() const {
382 auto family = getFamily();
383 return family == AF_INET || family == AF_INET6;
386 void SocketAddress::getAddressStr(char* buf, size_t buflen) const {
387 auto ret = getAddressStr();
388 size_t len = std::min(buflen - 1, ret.size());
389 memcpy(buf, ret.data(), len);
393 uint16_t SocketAddress::getPort() const {
394 switch (getFamily()) {
399 throw std::invalid_argument(
400 "SocketAddress::getPort() called on non-IP "
405 void SocketAddress::setPort(uint16_t port) {
406 switch (getFamily()) {
412 throw std::invalid_argument(
413 "SocketAddress::setPort() called on non-IP "
418 void SocketAddress::convertToIPv4() {
419 if (!tryConvertToIPv4()) {
420 throw std::invalid_argument(
421 "convertToIPv4() called on an addresse that is "
422 "not an IPv4-mapped address");
426 bool SocketAddress::tryConvertToIPv4() {
427 if (!isIPv4Mapped()) {
431 storage_.addr = folly::IPAddress::createIPv4(storage_.addr);
435 bool SocketAddress::mapToIPv6() {
436 if (getFamily() != AF_INET) {
440 storage_.addr = folly::IPAddress::createIPv6(storage_.addr);
444 std::string SocketAddress::getHostStr() const {
445 return getIpString(0);
448 std::string SocketAddress::getPath() const {
450 throw std::invalid_argument(
451 "SocketAddress: attempting to get path "
452 "for a non-Unix address");
455 if (storage_.un.pathLength() == 0) {
457 return std::string();
459 if (storage_.un.addr->sun_path[0] == '\0') {
460 // abstract namespace
462 storage_.un.addr->sun_path, size_t(storage_.un.pathLength()));
466 storage_.un.addr->sun_path,
467 strnlen(storage_.un.addr->sun_path, size_t(storage_.un.pathLength())));
470 std::string SocketAddress::describe() const {
472 if (storage_.un.pathLength() == 0) {
473 return "<anonymous unix address>";
476 if (storage_.un.addr->sun_path[0] == '\0') {
477 // Linux supports an abstract namespace for unix socket addresses
478 return "<abstract unix address>";
482 storage_.un.addr->sun_path,
483 strnlen(storage_.un.addr->sun_path, size_t(storage_.un.pathLength())));
485 switch (getFamily()) {
487 return "<uninitialized address>";
490 char buf[NI_MAXHOST + 16];
491 getAddressStr(buf, sizeof(buf));
492 size_t iplen = strlen(buf);
493 snprintf(buf + iplen, sizeof(buf) - iplen, ":%" PRIu16, getPort());
498 char buf[NI_MAXHOST + 18];
500 getAddressStr(buf + 1, sizeof(buf) - 1);
501 size_t iplen = strlen(buf);
502 snprintf(buf + iplen, sizeof(buf) - iplen, "]:%" PRIu16, getPort());
508 snprintf(buf, sizeof(buf), "<unknown address family %d>",
515 bool SocketAddress::operator==(const SocketAddress& other) const {
516 if (external_ != other.external_ || other.getFamily() != getFamily()) {
520 // anonymous addresses are never equal to any other addresses
521 if (storage_.un.pathLength() == 0 ||
522 other.storage_.un.pathLength() == 0) {
526 if (storage_.un.len != other.storage_.un.len) {
530 storage_.un.addr->sun_path,
531 other.storage_.un.addr->sun_path,
532 size_t(storage_.un.pathLength()));
536 switch (getFamily()) {
539 return (other.storage_.addr == storage_.addr) &&
540 (other.port_ == port_);
542 throw std::invalid_argument(
543 "SocketAddress: unsupported address family "
548 bool SocketAddress::prefixMatch(const SocketAddress& other,
549 unsigned prefixLength) const {
550 if (other.getFamily() != getFamily()) {
553 uint8_t mask_length = 128;
554 switch (getFamily()) {
560 auto prefix = folly::IPAddress::longestCommonPrefix(
561 {storage_.addr, mask_length},
562 {other.storage_.addr, mask_length});
563 return prefix.second >= prefixLength;
571 size_t SocketAddress::hash() const {
572 size_t seed = folly::hash::twang_mix64(getFamily());
575 enum { kUnixPathMax = sizeof(storage_.un.addr->sun_path) };
576 const char *path = storage_.un.addr->sun_path;
577 auto pathLength = storage_.un.pathLength();
578 // TODO: this probably could be made more efficient
579 for (off_t n = 0; n < pathLength; ++n) {
580 boost::hash_combine(seed, folly::hash::twang_mix64(uint64_t(path[n])));
584 switch (getFamily()) {
587 boost::hash_combine(seed, port_);
588 boost::hash_combine(seed, storage_.addr.hash());
596 throw std::invalid_argument(
597 "SocketAddress: unsupported address family "
604 struct addrinfo* SocketAddress::getAddrInfo(const char* host,
607 // getaddrinfo() requires the port number as a string
608 char portString[sizeof("65535")];
609 snprintf(portString, sizeof(portString), "%" PRIu16, port);
611 return getAddrInfo(host, portString, flags);
614 struct addrinfo* SocketAddress::getAddrInfo(const char* host,
617 struct addrinfo hints;
618 memset(&hints, 0, sizeof(hints));
619 hints.ai_family = AF_UNSPEC;
620 hints.ai_socktype = SOCK_STREAM;
621 hints.ai_flags = AI_PASSIVE | AI_NUMERICSERV | flags;
623 struct addrinfo *results;
624 int error = getaddrinfo(host, port, &hints, &results);
626 auto os = folly::to<std::string>(
627 "Failed to resolve address for \"", host, "\": ",
628 gai_strerror(error), " (error=", error, ")");
629 throw std::system_error(error, std::generic_category(), os);
635 void SocketAddress::setFromAddrInfo(const struct addrinfo* info) {
636 setFromSockaddr(info->ai_addr, socklen_t(info->ai_addrlen));
639 void SocketAddress::setFromLocalAddr(const struct addrinfo* info) {
640 // If an IPv6 address is present, prefer to use it, since IPv4 addresses
641 // can be mapped into IPv6 space.
642 for (const struct addrinfo* ai = info; ai != nullptr; ai = ai->ai_next) {
643 if (ai->ai_family == AF_INET6) {
644 setFromSockaddr(ai->ai_addr, socklen_t(ai->ai_addrlen));
649 // Otherwise, just use the first address in the list.
650 setFromSockaddr(info->ai_addr, socklen_t(info->ai_addrlen));
653 void SocketAddress::setFromSocket(
655 int (*fn)(int, struct sockaddr*, socklen_t*)) {
656 // Try to put the address into a local storage buffer.
657 sockaddr_storage tmp_sock;
658 socklen_t addrLen = sizeof(tmp_sock);
659 if (fn(socket, (sockaddr*)&tmp_sock, &addrLen) != 0) {
660 folly::throwSystemError("setFromSocket() failed");
663 setFromSockaddr((sockaddr*)&tmp_sock, addrLen);
666 std::string SocketAddress::getIpString(int flags) const {
667 char addrString[NI_MAXHOST];
668 getIpString(addrString, sizeof(addrString), flags);
669 return std::string(addrString);
672 void SocketAddress::getIpString(char *buf, size_t buflen, int flags) const {
673 auto family = getFamily();
674 if (family != AF_INET &&
675 family != AF_INET6) {
676 throw std::invalid_argument(
677 "SocketAddress: attempting to get IP address "
678 "for a non-IP address");
681 sockaddr_storage tmp_sock;
682 storage_.addr.toSockaddrStorage(&tmp_sock, port_);
683 int rc = getnameinfo((sockaddr*)&tmp_sock, sizeof(sockaddr_storage),
684 buf, buflen, nullptr, 0, flags);
686 auto os = folly::to<std::string>(
687 "getnameinfo() failed in getIpString() error = ",
689 throw std::system_error(rc, std::generic_category(), os);
693 void SocketAddress::updateUnixAddressLength(socklen_t addrlen) {
694 if (addrlen < offsetof(struct sockaddr_un, sun_path)) {
695 throw std::invalid_argument(
696 "SocketAddress: attempted to set a Unix socket "
697 "with a length too short for a sockaddr_un");
700 storage_.un.len = addrlen;
701 if (storage_.un.pathLength() == 0) {
706 if (storage_.un.addr->sun_path[0] == '\0') {
707 // abstract namespace. honor the specified length
709 // Call strnlen(), just in case the length was overspecified.
710 size_t maxLength = addrlen - offsetof(struct sockaddr_un, sun_path);
711 size_t pathLength = strnlen(storage_.un.addr->sun_path, maxLength);
713 socklen_t(offsetof(struct sockaddr_un, sun_path) + pathLength);
717 bool SocketAddress::operator<(const SocketAddress& other) const {
718 if (getFamily() != other.getFamily()) {
719 return getFamily() < other.getFamily();
723 // Anonymous addresses can't be compared to anything else.
724 // Return that they are never less than anything.
726 // Note that this still meets the requirements for a strict weak
727 // ordering, so we can use this operator<() with standard C++ containers.
728 auto thisPathLength = storage_.un.pathLength();
729 if (thisPathLength == 0) {
732 auto otherPathLength = other.storage_.un.pathLength();
733 if (otherPathLength == 0) {
737 // Compare based on path length first, for efficiency
738 if (thisPathLength != otherPathLength) {
739 return thisPathLength < otherPathLength;
742 storage_.un.addr->sun_path,
743 other.storage_.un.addr->sun_path,
744 size_t(thisPathLength));
747 switch (getFamily()) {
750 if (port_ != other.port_) {
751 return port_ < other.port_;
755 storage_.addr < other.storage_.addr;
759 throw std::invalid_argument(
760 "SocketAddress: unsupported address family for comparing");
764 size_t hash_value(const SocketAddress& address) {
765 return address.hash();
768 std::ostream& operator<<(std::ostream& os, const SocketAddress& addr) {
769 os << addr.describe();