Copyright 2014->2015
[folly.git] / folly / SocketAddress.cpp
1 /*
2  * Copyright 2015 Facebook, Inc.
3  *
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
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16
17 #ifndef __STDC_FORMAT_MACROS
18   #define __STDC_FORMAT_MACROS
19 #endif
20
21 #include <folly/SocketAddress.h>
22
23 #include <folly/Hash.h>
24
25 #include <boost/functional/hash.hpp>
26 #include <boost/static_assert.hpp>
27 #include <string.h>
28 #include <stdio.h>
29 #include <errno.h>
30 #include <sstream>
31 #include <string>
32
33 namespace {
34
35 /**
36  * A structure to free a struct addrinfo when it goes out of scope.
37  */
38 struct ScopedAddrInfo {
39   explicit ScopedAddrInfo(struct addrinfo* info) : info(info) {}
40   ~ScopedAddrInfo() {
41     freeaddrinfo(info);
42   }
43
44   struct addrinfo* info;
45 };
46
47 /**
48  * A simple data structure for parsing a host-and-port string.
49  *
50  * Accepts a string of the form "<host>:<port>" or just "<port>",
51  * and contains two string pointers to the host and the port portion of the
52  * string.
53  *
54  * The HostAndPort may contain pointers into the original string.  It is
55  * responsible for the user to ensure that the input string is valid for the
56  * lifetime of the HostAndPort structure.
57  */
58 struct HostAndPort {
59   HostAndPort(const char* str, bool hostRequired)
60     : host(nullptr),
61       port(nullptr),
62       allocated(nullptr) {
63
64     // Look for the last colon
65     const char* colon = strrchr(str, ':');
66     if (colon == nullptr) {
67       // No colon, just a port number.
68       if (hostRequired) {
69         throw std::invalid_argument(
70           "expected a host and port string of the "
71           "form \"<host>:<port>\"");
72       }
73       port = str;
74       return;
75     }
76
77     // We have to make a copy of the string so we can modify it
78     // and change the colon to a NUL terminator.
79     allocated = strdup(str);
80     if (!allocated) {
81       throw std::bad_alloc();
82     }
83
84     char *allocatedColon = allocated + (colon - str);
85     *allocatedColon = '\0';
86     host = allocated;
87     port = allocatedColon + 1;
88     // bracketed IPv6 address, remove the brackets
89     // allocatedColon[-1] is fine, as allocatedColon >= host and
90     // *allocatedColon != *host therefore allocatedColon > host
91     if (*host == '[' && allocatedColon[-1] == ']') {
92       allocatedColon[-1] = '\0';
93       ++host;
94     }
95   }
96
97   ~HostAndPort() {
98     free(allocated);
99   }
100
101   const char* host;
102   const char* port;
103   char* allocated;
104 };
105
106 } // unnamed namespace
107
108 namespace folly {
109
110 bool SocketAddress::isPrivateAddress() const {
111   auto family = getFamily();
112   if (family == AF_INET || family == AF_INET6) {
113     return storage_.addr.isPrivate() ||
114       (storage_.addr.isV6() && storage_.addr.asV6().isLinkLocal());
115   } else if (external_) {
116     // Unix addresses are always local to a host.  Return true,
117     // since this conforms to the semantics of returning true for IP loopback
118     // addresses.
119     return true;
120   }
121   return false;
122 }
123
124 bool SocketAddress::isLoopbackAddress() const {
125   auto family = getFamily();
126   if (family == AF_INET || family == AF_INET6) {
127     return storage_.addr.isLoopback();
128   } else if (external_) {
129     // Return true for UNIX addresses, since they are always local to a host.
130     return true;
131   }
132   return false;
133 }
134
135 void SocketAddress::setFromHostPort(const char* host, uint16_t port) {
136   ScopedAddrInfo results(getAddrInfo(host, port, 0));
137   setFromAddrInfo(results.info);
138 }
139
140 void SocketAddress::setFromIpPort(const char* ip, uint16_t port) {
141   ScopedAddrInfo results(getAddrInfo(ip, port, AI_NUMERICHOST));
142   setFromAddrInfo(results.info);
143 }
144
145 void SocketAddress::setFromLocalPort(uint16_t port) {
146   ScopedAddrInfo results(getAddrInfo(nullptr, port, AI_ADDRCONFIG));
147   setFromLocalAddr(results.info);
148 }
149
150 void SocketAddress::setFromLocalPort(const char* port) {
151   ScopedAddrInfo results(getAddrInfo(nullptr, port, AI_ADDRCONFIG));
152   setFromLocalAddr(results.info);
153 }
154
155 void SocketAddress::setFromLocalIpPort(const char* addressAndPort) {
156   HostAndPort hp(addressAndPort, false);
157   ScopedAddrInfo results(getAddrInfo(hp.host, hp.port,
158                                      AI_NUMERICHOST | AI_ADDRCONFIG));
159   setFromLocalAddr(results.info);
160 }
161
162 void SocketAddress::setFromIpPort(const char* addressAndPort) {
163   HostAndPort hp(addressAndPort, true);
164   ScopedAddrInfo results(getAddrInfo(hp.host, hp.port, AI_NUMERICHOST));
165   setFromAddrInfo(results.info);
166 }
167
168 void SocketAddress::setFromHostPort(const char* hostAndPort) {
169   HostAndPort hp(hostAndPort, true);
170   ScopedAddrInfo results(getAddrInfo(hp.host, hp.port, 0));
171   setFromAddrInfo(results.info);
172 }
173
174 void SocketAddress::setFromPath(const char* path, size_t len) {
175   if (!external_) {
176     storage_.un.init();
177     external_ = true;
178   }
179
180   storage_.un.len = offsetof(struct sockaddr_un, sun_path) + len;
181   if (len > sizeof(storage_.un.addr->sun_path)) {
182     throw std::invalid_argument(
183       "socket path too large to fit into sockaddr_un");
184   } else if (len == sizeof(storage_.un.addr->sun_path)) {
185     // Note that there will be no terminating NUL in this case.
186     // We allow this since getsockname() and getpeername() may return
187     // Unix socket addresses with paths that fit exactly in sun_path with no
188     // terminating NUL.
189     memcpy(storage_.un.addr->sun_path, path, len);
190   } else {
191     memcpy(storage_.un.addr->sun_path, path, len + 1);
192   }
193 }
194
195 void SocketAddress::setFromPeerAddress(int socket) {
196   setFromSocket(socket, getpeername);
197 }
198
199 void SocketAddress::setFromLocalAddress(int socket) {
200   setFromSocket(socket, getsockname);
201 }
202
203 void SocketAddress::setFromSockaddr(const struct sockaddr* address) {
204   uint16_t port;
205
206   if (address->sa_family == AF_INET) {
207     port = ntohs(((sockaddr_in*)address)->sin_port);
208   } else if (address->sa_family == AF_INET6) {
209     port = ntohs(((sockaddr_in6*)address)->sin6_port);
210   } else if (address->sa_family == AF_UNIX) {
211     // We need an explicitly specified length for AF_UNIX addresses,
212     // to be able to distinguish anonymous addresses from addresses
213     // in Linux's abstract namespace.
214     throw std::invalid_argument(
215       "SocketAddress::setFromSockaddr(): the address "
216       "length must be explicitly specified when "
217       "setting AF_UNIX addresses");
218   } else {
219     throw std::invalid_argument(
220       "SocketAddress::setFromSockaddr() called "
221       "with unsupported address type");
222   }
223   if (external_) {
224     storage_.un.free();
225     external_ = false;
226   }
227   storage_.addr = folly::IPAddress(address);
228   port_ = port;
229 }
230
231 void SocketAddress::setFromSockaddr(const struct sockaddr* address,
232                                      socklen_t addrlen) {
233   // Check the length to make sure we can access address->sa_family
234   if (addrlen < (offsetof(struct sockaddr, sa_family) +
235                  sizeof(address->sa_family))) {
236     throw std::invalid_argument(
237       "SocketAddress::setFromSockaddr() called "
238       "with length too short for a sockaddr");
239   }
240
241   if (address->sa_family == AF_INET) {
242     if (addrlen < sizeof(struct sockaddr_in)) {
243       throw std::invalid_argument(
244         "SocketAddress::setFromSockaddr() called "
245         "with length too short for a sockaddr_in");
246     }
247     setFromSockaddr(reinterpret_cast<const struct sockaddr_in*>(address));
248   } else if (address->sa_family == AF_INET6) {
249     if (addrlen < sizeof(struct sockaddr_in6)) {
250       throw std::invalid_argument(
251         "SocketAddress::setFromSockaddr() called "
252         "with length too short for a sockaddr_in6");
253     }
254     setFromSockaddr(reinterpret_cast<const struct sockaddr_in6*>(address));
255   } else if (address->sa_family == AF_UNIX) {
256     setFromSockaddr(reinterpret_cast<const struct sockaddr_un*>(address),
257                     addrlen);
258   } else {
259     throw std::invalid_argument(
260       "SocketAddress::setFromSockaddr() called "
261       "with unsupported address type");
262   }
263 }
264
265 void SocketAddress::setFromSockaddr(const struct sockaddr_in* address) {
266   assert(address->sin_family == AF_INET);
267   setFromSockaddr((sockaddr*)address);
268 }
269
270 void SocketAddress::setFromSockaddr(const struct sockaddr_in6* address) {
271   assert(address->sin6_family == AF_INET6);
272   setFromSockaddr((sockaddr*)address);
273 }
274
275 void SocketAddress::setFromSockaddr(const struct sockaddr_un* address,
276                                      socklen_t addrlen) {
277   assert(address->sun_family == AF_UNIX);
278   if (addrlen > sizeof(struct sockaddr_un)) {
279     throw std::invalid_argument(
280       "SocketAddress::setFromSockaddr() called "
281       "with length too long for a sockaddr_un");
282   }
283
284   prepFamilyChange(AF_UNIX);
285   memcpy(storage_.un.addr, address, addrlen);
286   updateUnixAddressLength(addrlen);
287
288   // Fill the rest with 0s, just for safety
289   if (addrlen < sizeof(struct sockaddr_un)) {
290     char *p = reinterpret_cast<char*>(storage_.un.addr);
291     memset(p + addrlen, 0, sizeof(struct sockaddr_un) - addrlen);
292   }
293 }
294
295 const folly::IPAddress& SocketAddress::getIPAddress() const {
296   auto family = getFamily();
297   if (family != AF_INET && family != AF_INET6) {
298     throw InvalidAddressFamilyException(family);
299   }
300   return storage_.addr;
301 }
302
303 socklen_t SocketAddress::getActualSize() const {
304   if (external_) {
305     return storage_.un.len;
306   }
307   switch (getFamily()) {
308     case AF_UNSPEC:
309     case AF_INET:
310       return sizeof(struct sockaddr_in);
311     case AF_INET6:
312       return sizeof(struct sockaddr_in6);
313     default:
314       throw std::invalid_argument(
315         "SocketAddress::getActualSize() called "
316         "with unrecognized address family");
317   }
318 }
319
320 std::string SocketAddress::getFullyQualified() const {
321   auto family = getFamily();
322   if (family != AF_INET && family != AF_INET6) {
323     throw std::invalid_argument("Can't get address str for non ip address");
324   }
325   return storage_.addr.toFullyQualified();
326 }
327
328 std::string SocketAddress::getAddressStr() const {
329   char buf[INET6_ADDRSTRLEN];
330   getAddressStr(buf, sizeof(buf));
331   return buf;
332 }
333
334 void SocketAddress::getAddressStr(char* buf, size_t buflen) const {
335   auto family = getFamily();
336   if (family != AF_INET && family != AF_INET6) {
337     throw std::invalid_argument("Can't get address str for non ip address");
338   }
339   std::string ret = storage_.addr.str();
340   size_t len = std::min(buflen, ret.size());
341   memcpy(buf, ret.data(), len);
342   buf[len] = '\0';
343 }
344
345 uint16_t SocketAddress::getPort() const {
346   switch (getFamily()) {
347     case AF_INET:
348     case AF_INET6:
349       return port_;
350     default:
351       throw std::invalid_argument(
352         "SocketAddress::getPort() called on non-IP "
353         "address");
354   }
355 }
356
357 void SocketAddress::setPort(uint16_t port) {
358   switch (getFamily()) {
359     case AF_INET:
360     case AF_INET6:
361       port_ = port;
362       return;
363     default:
364       throw std::invalid_argument(
365         "SocketAddress::setPort() called on non-IP "
366         "address");
367   }
368 }
369
370 void SocketAddress::convertToIPv4() {
371   if (!tryConvertToIPv4()) {
372     throw std::invalid_argument(
373       "convertToIPv4() called on an addresse that is "
374       "not an IPv4-mapped address");
375   }
376 }
377
378 bool SocketAddress::tryConvertToIPv4() {
379   if (!isIPv4Mapped()) {
380     return false;
381   }
382
383   storage_.addr = folly::IPAddress::createIPv4(storage_.addr);
384   return true;
385 }
386
387 bool SocketAddress::mapToIPv6() {
388   if (getFamily() != AF_INET) {
389     return false;
390   }
391
392   storage_.addr = folly::IPAddress::createIPv6(storage_.addr);
393   return true;
394 }
395
396 std::string SocketAddress::getHostStr() const {
397   return getIpString(0);
398 }
399
400 std::string SocketAddress::getPath() const {
401   if (!external_) {
402     throw std::invalid_argument(
403       "SocketAddress: attempting to get path "
404       "for a non-Unix address");
405   }
406
407   if (storage_.un.pathLength() == 0) {
408     // anonymous address
409     return std::string();
410   }
411   if (storage_.un.addr->sun_path[0] == '\0') {
412     // abstract namespace
413     return std::string(storage_.un.addr->sun_path, storage_.un.pathLength());
414   }
415
416   return std::string(storage_.un.addr->sun_path,
417                      strnlen(storage_.un.addr->sun_path,
418                              storage_.un.pathLength()));
419 }
420
421 std::string SocketAddress::describe() const {
422   if (external_) {
423     if (storage_.un.pathLength() == 0) {
424       return "<anonymous unix address>";
425     }
426
427     if (storage_.un.addr->sun_path[0] == '\0') {
428       // Linux supports an abstract namespace for unix socket addresses
429       return "<abstract unix address>";
430     }
431
432     return std::string(storage_.un.addr->sun_path,
433                        strnlen(storage_.un.addr->sun_path,
434                                storage_.un.pathLength()));
435   }
436   switch (getFamily()) {
437     case AF_UNSPEC:
438       return "<uninitialized address>";
439     case AF_INET:
440     {
441       char buf[NI_MAXHOST + 16];
442       getAddressStr(buf, sizeof(buf));
443       size_t iplen = strlen(buf);
444       snprintf(buf + iplen, sizeof(buf) - iplen, ":%" PRIu16, getPort());
445       return buf;
446     }
447     case AF_INET6:
448     {
449       char buf[NI_MAXHOST + 18];
450       buf[0] = '[';
451       getAddressStr(buf + 1, sizeof(buf) - 1);
452       size_t iplen = strlen(buf);
453       snprintf(buf + iplen, sizeof(buf) - iplen, "]:%" PRIu16, getPort());
454       return buf;
455     }
456     default:
457     {
458       char buf[64];
459       snprintf(buf, sizeof(buf), "<unknown address family %d>",
460                getFamily());
461       return buf;
462     }
463   }
464 }
465
466 bool SocketAddress::operator==(const SocketAddress& other) const {
467   if (external_ != other.external_ || other.getFamily() != getFamily()) {
468     return false;
469   }
470   if (external_) {
471     // anonymous addresses are never equal to any other addresses
472     if (storage_.un.pathLength() == 0 ||
473         other.storage_.un.pathLength() == 0) {
474       return false;
475     }
476
477     if (storage_.un.len != other.storage_.un.len) {
478       return false;
479     }
480     int cmp = memcmp(storage_.un.addr->sun_path,
481                      other.storage_.un.addr->sun_path,
482                      storage_.un.pathLength());
483     return cmp == 0;
484   }
485
486   switch (getFamily()) {
487     case AF_INET:
488     case AF_INET6:
489       return (other.storage_.addr == storage_.addr) &&
490         (other.port_ == port_);
491     default:
492       throw std::invalid_argument(
493         "SocketAddress: unsupported address family "
494         "for comparison");
495   }
496 }
497
498 bool SocketAddress::prefixMatch(const SocketAddress& other,
499     unsigned prefixLength) const {
500   if (other.getFamily() != getFamily()) {
501     return false;
502   }
503   int mask_length = 128;
504   switch (getFamily()) {
505     case AF_INET:
506       mask_length = 32;
507       // fallthrough
508     case AF_INET6:
509     {
510       auto prefix = folly::IPAddress::longestCommonPrefix(
511         {storage_.addr, mask_length},
512         {other.storage_.addr, mask_length});
513       return prefix.second >= prefixLength;
514     }
515     default:
516       return false;
517   }
518 }
519
520
521 size_t SocketAddress::hash() const {
522   size_t seed = folly::hash::twang_mix64(getFamily());
523
524   if (external_) {
525     enum { kUnixPathMax = sizeof(storage_.un.addr->sun_path) };
526     const char *path = storage_.un.addr->sun_path;
527     size_t pathLength = storage_.un.pathLength();
528     // TODO: this probably could be made more efficient
529     for (unsigned int n = 0; n < pathLength; ++n) {
530       boost::hash_combine(seed, folly::hash::twang_mix64(path[n]));
531     }
532   }
533
534   switch (getFamily()) {
535     case AF_INET:
536     case AF_INET6: {
537       boost::hash_combine(seed, port_);
538       boost::hash_combine(seed, storage_.addr.hash());
539       break;
540     }
541     case AF_UNIX:
542       DCHECK(external_);
543       break;
544     case AF_UNSPEC:
545     default:
546       throw std::invalid_argument(
547         "SocketAddress: unsupported address family "
548         "for hashing");
549   }
550
551   return seed;
552 }
553
554 struct addrinfo* SocketAddress::getAddrInfo(const char* host,
555                                              uint16_t port,
556                                              int flags) {
557   // getaddrinfo() requires the port number as a string
558   char portString[sizeof("65535")];
559   snprintf(portString, sizeof(portString), "%" PRIu16, port);
560
561   return getAddrInfo(host, portString, flags);
562 }
563
564 struct addrinfo* SocketAddress::getAddrInfo(const char* host,
565                                              const char* port,
566                                              int flags) {
567   struct addrinfo hints;
568   memset(&hints, 0, sizeof(hints));
569   hints.ai_family = AF_UNSPEC;
570   hints.ai_socktype = SOCK_STREAM;
571   hints.ai_flags = AI_PASSIVE | AI_NUMERICSERV | flags;
572
573   struct addrinfo *results;
574   int error = getaddrinfo(host, port, &hints, &results);
575   if (error != 0) {
576     auto os = folly::to<std::string>(
577       "Failed to resolve address for \"", host,  "\": ",
578       gai_strerror(error), " (error=", error,  ")");
579     throw std::system_error(error, std::generic_category(), os);
580   }
581
582   return results;
583 }
584
585 void SocketAddress::setFromAddrInfo(const struct addrinfo* info) {
586   setFromSockaddr(info->ai_addr, info->ai_addrlen);
587 }
588
589 void SocketAddress::setFromLocalAddr(const struct addrinfo* info) {
590   // If an IPv6 address is present, prefer to use it, since IPv4 addresses
591   // can be mapped into IPv6 space.
592   for (const struct addrinfo* ai = info; ai != nullptr; ai = ai->ai_next) {
593     if (ai->ai_family == AF_INET6) {
594       setFromSockaddr(ai->ai_addr, ai->ai_addrlen);
595       return;
596     }
597   }
598
599   // Otherwise, just use the first address in the list.
600   setFromSockaddr(info->ai_addr, info->ai_addrlen);
601 }
602
603 void SocketAddress::setFromSocket(int socket,
604                                   int (*fn)(int, sockaddr*, socklen_t*)) {
605   // Try to put the address into a local storage buffer.
606   sockaddr_storage tmp_sock;
607   socklen_t addrLen = sizeof(tmp_sock);
608   if (fn(socket, (sockaddr*)&tmp_sock, &addrLen) != 0) {
609     folly::throwSystemError("setFromSocket() failed");
610   }
611
612   setFromSockaddr((sockaddr*)&tmp_sock, addrLen);
613 }
614
615 std::string SocketAddress::getIpString(int flags) const {
616   char addrString[NI_MAXHOST];
617   getIpString(addrString, sizeof(addrString), flags);
618   return std::string(addrString);
619 }
620
621 void SocketAddress::getIpString(char *buf, size_t buflen, int flags) const {
622   auto family = getFamily();
623   if (family != AF_INET &&
624       family != AF_INET6) {
625     throw std::invalid_argument(
626       "SocketAddress: attempting to get IP address "
627       "for a non-IP address");
628   }
629
630   sockaddr_storage tmp_sock;
631   storage_.addr.toSockaddrStorage(&tmp_sock, port_);
632   int rc = getnameinfo((sockaddr*)&tmp_sock, sizeof(sockaddr_storage),
633                        buf, buflen, nullptr, 0, flags);
634   if (rc != 0) {
635     auto os = folly::to<std::string>(
636       "getnameinfo() failed in getIpString() error = ",
637       gai_strerror(rc));
638     throw std::system_error(rc, std::generic_category(), os);
639   }
640 }
641
642 void SocketAddress::updateUnixAddressLength(socklen_t addrlen) {
643   if (addrlen < offsetof(struct sockaddr_un, sun_path)) {
644     throw std::invalid_argument(
645       "SocketAddress: attempted to set a Unix socket "
646       "with a length too short for a sockaddr_un");
647   }
648
649   storage_.un.len = addrlen;
650   if (storage_.un.pathLength() == 0) {
651     // anonymous address
652     return;
653   }
654
655   if (storage_.un.addr->sun_path[0] == '\0') {
656     // abstract namespace.  honor the specified length
657   } else {
658     // Call strnlen(), just in case the length was overspecified.
659     socklen_t maxLength = addrlen - offsetof(struct sockaddr_un, sun_path);
660     size_t pathLength = strnlen(storage_.un.addr->sun_path, maxLength);
661     storage_.un.len = offsetof(struct sockaddr_un, sun_path) + pathLength;
662   }
663 }
664
665 bool SocketAddress::operator<(const SocketAddress& other) const {
666   if (getFamily() != other.getFamily()) {
667     return getFamily() < other.getFamily();
668   }
669
670   if (external_) {
671     // Anonymous addresses can't be compared to anything else.
672     // Return that they are never less than anything.
673     //
674     // Note that this still meets the requirements for a strict weak
675     // ordering, so we can use this operator<() with standard C++ containers.
676     size_t thisPathLength = storage_.un.pathLength();
677     if (thisPathLength == 0) {
678       return false;
679     }
680     size_t otherPathLength = other.storage_.un.pathLength();
681     if (otherPathLength == 0) {
682       return true;
683     }
684
685     // Compare based on path length first, for efficiency
686     if (thisPathLength != otherPathLength) {
687       return thisPathLength < otherPathLength;
688     }
689     int cmp = memcmp(storage_.un.addr->sun_path,
690                      other.storage_.un.addr->sun_path,
691                      thisPathLength);
692     return cmp < 0;
693   }
694   switch (getFamily()) {
695     case AF_INET:
696     case AF_INET6: {
697       if (port_ != other.port_) {
698         return port_ < other.port_;
699       }
700
701       return
702         storage_.addr < other.storage_.addr;
703     }
704     case AF_UNSPEC:
705     default:
706       throw std::invalid_argument(
707         "SocketAddress: unsupported address family for comparing");
708   }
709 }
710
711 size_t hash_value(const SocketAddress& address) {
712   return address.hash();
713 }
714
715 std::ostream& operator<<(std::ostream& os, const SocketAddress& addr) {
716   os << addr.describe();
717   return os;
718 }
719
720 } // folly