move socketaddress to folly
[folly.git] / folly / SocketAddress.cpp
1 /*
2  * Copyright 2014 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 (family == AF_UNIX) {
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 (family == AF_UNIX) {
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 (getFamily() != AF_UNIX) {
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   if (address->sa_family == AF_INET) {
205     storage_.addr = folly::IPAddress(address);
206     port_ = ntohs(((sockaddr_in*)address)->sin_port);
207   } else if (address->sa_family == AF_INET6) {
208     storage_.addr = folly::IPAddress(address);
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   external_ = false;
224 }
225
226 void SocketAddress::setFromSockaddr(const struct sockaddr* address,
227                                      socklen_t addrlen) {
228   // Check the length to make sure we can access address->sa_family
229   if (addrlen < (offsetof(struct sockaddr, sa_family) +
230                  sizeof(address->sa_family))) {
231     throw std::invalid_argument(
232       "SocketAddress::setFromSockaddr() called "
233       "with length too short for a sockaddr");
234   }
235
236   if (address->sa_family == AF_INET) {
237     if (addrlen < sizeof(struct sockaddr_in)) {
238       throw std::invalid_argument(
239         "SocketAddress::setFromSockaddr() called "
240         "with length too short for a sockaddr_in");
241     }
242     setFromSockaddr(reinterpret_cast<const struct sockaddr_in*>(address));
243   } else if (address->sa_family == AF_INET6) {
244     if (addrlen < sizeof(struct sockaddr_in6)) {
245       throw std::invalid_argument(
246         "SocketAddress::setFromSockaddr() called "
247         "with length too short for a sockaddr_in6");
248     }
249     setFromSockaddr(reinterpret_cast<const struct sockaddr_in6*>(address));
250   } else if (address->sa_family == AF_UNIX) {
251     setFromSockaddr(reinterpret_cast<const struct sockaddr_un*>(address),
252                     addrlen);
253   } else {
254     throw std::invalid_argument(
255       "SocketAddress::setFromSockaddr() called "
256       "with unsupported address type");
257   }
258 }
259
260 void SocketAddress::setFromSockaddr(const struct sockaddr_in* address) {
261   assert(address->sin_family == AF_INET);
262   setFromSockaddr((sockaddr*)address);
263 }
264
265 void SocketAddress::setFromSockaddr(const struct sockaddr_in6* address) {
266   assert(address->sin6_family == AF_INET6);
267   setFromSockaddr((sockaddr*)address);
268 }
269
270 void SocketAddress::setFromSockaddr(const struct sockaddr_un* address,
271                                      socklen_t addrlen) {
272   assert(address->sun_family == AF_UNIX);
273   if (addrlen > sizeof(struct sockaddr_un)) {
274     throw std::invalid_argument(
275       "SocketAddress::setFromSockaddr() called "
276       "with length too long for a sockaddr_un");
277   }
278
279   prepFamilyChange(AF_UNIX);
280   memcpy(storage_.un.addr, address, addrlen);
281   updateUnixAddressLength(addrlen);
282
283   // Fill the rest with 0s, just for safety
284   if (addrlen < sizeof(struct sockaddr_un)) {
285     char *p = reinterpret_cast<char*>(storage_.un.addr);
286     memset(p + addrlen, 0, sizeof(struct sockaddr_un) - addrlen);
287   }
288 }
289
290 const folly::IPAddress& SocketAddress::getIPAddress() const {
291   auto family = getFamily();
292   if (family != AF_INET && family != AF_INET6) {
293     throw std::invalid_argument("getIPAddress called on a non-ip address");
294   }
295   return storage_.addr;
296 }
297
298 socklen_t SocketAddress::getActualSize() const {
299   switch (getFamily()) {
300     case AF_UNSPEC:
301     case AF_INET:
302       return sizeof(struct sockaddr_in);
303     case AF_INET6:
304       return sizeof(struct sockaddr_in6);
305     case AF_UNIX:
306       return storage_.un.len;
307     default:
308       throw std::invalid_argument(
309         "SocketAddress::getActualSize() called "
310         "with unrecognized address family");
311   }
312 }
313
314 std::string SocketAddress::getFullyQualified() const {
315   auto family = getFamily();
316   if (family != AF_INET && family != AF_INET6) {
317     throw std::invalid_argument("Can't get address str for non ip address");
318   }
319   return storage_.addr.toFullyQualified();
320 }
321
322 std::string SocketAddress::getAddressStr() const {
323   char buf[INET6_ADDRSTRLEN];
324   getAddressStr(buf, sizeof(buf));
325   return buf;
326 }
327
328 void SocketAddress::getAddressStr(char* buf, size_t buflen) const {
329   auto family = getFamily();
330   if (family != AF_INET && family != AF_INET6) {
331     throw std::invalid_argument("Can't get address str for non ip address");
332   }
333   std::string ret = storage_.addr.str();
334   size_t len = std::min(buflen, ret.size());
335   memcpy(buf, ret.data(), len);
336   buf[len] = '\0';
337 }
338
339 uint16_t SocketAddress::getPort() const {
340   switch (getFamily()) {
341     case AF_INET:
342     case AF_INET6:
343       return port_;
344     default:
345       throw std::invalid_argument(
346         "SocketAddress::getPort() called on non-IP "
347         "address");
348   }
349 }
350
351 void SocketAddress::setPort(uint16_t port) {
352   switch (getFamily()) {
353     case AF_INET:
354     case AF_INET6:
355       port_ = port;
356       return;
357     default:
358       throw std::invalid_argument(
359         "SocketAddress::setPort() called on non-IP "
360         "address");
361   }
362 }
363
364 void SocketAddress::convertToIPv4() {
365   if (!tryConvertToIPv4()) {
366     throw std::invalid_argument(
367       "convertToIPv4() called on an addresse that is "
368       "not an IPv4-mapped address");
369   }
370 }
371
372 bool SocketAddress::tryConvertToIPv4() {
373   if (!isIPv4Mapped()) {
374     return false;
375   }
376
377   storage_.addr = folly::IPAddress::createIPv4(storage_.addr);
378   return true;
379 }
380
381 bool SocketAddress::mapToIPv6() {
382   if (getFamily() != AF_INET) {
383     return false;
384   }
385
386   storage_.addr = folly::IPAddress::createIPv6(storage_.addr);
387   return true;
388 }
389
390 std::string SocketAddress::getHostStr() const {
391   return getIpString(0);
392 }
393
394 std::string SocketAddress::getPath() const {
395   if (getFamily() != AF_UNIX) {
396     throw std::invalid_argument(
397       "SocketAddress: attempting to get path "
398       "for a non-Unix address");
399   }
400
401   if (storage_.un.pathLength() == 0) {
402     // anonymous address
403     return std::string();
404   }
405   if (storage_.un.addr->sun_path[0] == '\0') {
406     // abstract namespace
407     return std::string(storage_.un.addr->sun_path, storage_.un.pathLength());
408   }
409
410   return std::string(storage_.un.addr->sun_path,
411                      strnlen(storage_.un.addr->sun_path,
412                              storage_.un.pathLength()));
413 }
414
415 std::string SocketAddress::describe() const {
416   switch (getFamily()) {
417     case AF_UNSPEC:
418       return "<uninitialized address>";
419     case AF_INET:
420     {
421       char buf[NI_MAXHOST + 16];
422       getAddressStr(buf, sizeof(buf));
423       size_t iplen = strlen(buf);
424       snprintf(buf + iplen, sizeof(buf) - iplen, ":%" PRIu16, getPort());
425       return buf;
426     }
427     case AF_INET6:
428     {
429       char buf[NI_MAXHOST + 18];
430       buf[0] = '[';
431       getAddressStr(buf + 1, sizeof(buf) - 1);
432       size_t iplen = strlen(buf);
433       snprintf(buf + iplen, sizeof(buf) - iplen, "]:%" PRIu16, getPort());
434       return buf;
435     }
436     case AF_UNIX:
437     {
438       if (storage_.un.pathLength() == 0) {
439         return "<anonymous unix address>";
440       }
441
442       if (storage_.un.addr->sun_path[0] == '\0') {
443         // Linux supports an abstract namespace for unix socket addresses
444         return "<abstract unix address>";
445       }
446
447       return std::string(storage_.un.addr->sun_path,
448                          strnlen(storage_.un.addr->sun_path,
449                                  storage_.un.pathLength()));
450     }
451     default:
452     {
453       char buf[64];
454       snprintf(buf, sizeof(buf), "<unknown address family %d>",
455                getFamily());
456       return buf;
457     }
458   }
459 }
460
461 bool SocketAddress::operator==(const SocketAddress& other) const {
462   if (other.getFamily() != getFamily()) {
463     return false;
464   }
465
466   switch (getFamily()) {
467     case AF_INET:
468     case AF_INET6:
469       return (other.storage_.addr == storage_.addr) &&
470         (other.port_ == port_);
471     case AF_UNIX:
472     {
473       // anonymous addresses are never equal to any other addresses
474       if (storage_.un.pathLength() == 0 ||
475           other.storage_.un.pathLength() == 0) {
476         return false;
477       }
478
479       if (storage_.un.len != other.storage_.un.len) {
480         return false;
481       }
482       int cmp = memcmp(storage_.un.addr->sun_path,
483                        other.storage_.un.addr->sun_path,
484                        storage_.un.pathLength());
485       return cmp == 0;
486     }
487     default:
488       throw std::invalid_argument(
489         "SocketAddress: unsupported address family "
490         "for comparison");
491   }
492 }
493
494 bool SocketAddress::prefixMatch(const SocketAddress& other,
495     unsigned prefixLength) const {
496   if (other.getFamily() != getFamily()) {
497     return false;
498   }
499   int mask_length = 128;
500   switch (getFamily()) {
501     case AF_INET:
502       mask_length = 32;
503       // fallthrough
504     case AF_INET6:
505     {
506       auto prefix = folly::IPAddress::longestCommonPrefix(
507         {storage_.addr, mask_length},
508         {other.storage_.addr, mask_length});
509       return prefix.second >= prefixLength;
510     }
511     default:
512       return false;
513   }
514 }
515
516
517 size_t SocketAddress::hash() const {
518   size_t seed = folly::hash::twang_mix64(getFamily());
519
520   switch (getFamily()) {
521     case AF_INET:
522     case AF_INET6: {
523       boost::hash_combine(seed, port_);
524       boost::hash_combine(seed, storage_.addr.hash());
525       break;
526     }
527     case AF_UNIX:
528     {
529       enum { kUnixPathMax = sizeof(storage_.un.addr->sun_path) };
530       const char *path = storage_.un.addr->sun_path;
531       size_t pathLength = storage_.un.pathLength();
532       // TODO: this probably could be made more efficient
533       for (unsigned int n = 0; n < pathLength; ++n) {
534         boost::hash_combine(seed, folly::hash::twang_mix64(path[n]));
535       }
536       break;
537     }
538     case AF_UNSPEC:
539     default:
540       throw std::invalid_argument(
541         "SocketAddress: unsupported address family "
542         "for hashing");
543   }
544
545   return seed;
546 }
547
548 struct addrinfo* SocketAddress::getAddrInfo(const char* host,
549                                              uint16_t port,
550                                              int flags) {
551   // getaddrinfo() requires the port number as a string
552   char portString[sizeof("65535")];
553   snprintf(portString, sizeof(portString), "%" PRIu16, port);
554
555   return getAddrInfo(host, portString, flags);
556 }
557
558 struct addrinfo* SocketAddress::getAddrInfo(const char* host,
559                                              const char* port,
560                                              int flags) {
561   struct addrinfo hints;
562   memset(&hints, 0, sizeof(hints));
563   hints.ai_family = AF_UNSPEC;
564   hints.ai_socktype = SOCK_STREAM;
565   hints.ai_flags = AI_PASSIVE | AI_NUMERICSERV | flags;
566
567   struct addrinfo *results;
568   int error = getaddrinfo(host, port, &hints, &results);
569   if (error != 0) {
570     auto os = folly::to<std::string>(
571       "Failed to resolve address for \"", host,  "\": ",
572       gai_strerror(error), " (error=", error,  ")");
573     throw std::system_error(error, std::generic_category(), os);
574   }
575
576   return results;
577 }
578
579 void SocketAddress::setFromAddrInfo(const struct addrinfo* info) {
580   setFromSockaddr(info->ai_addr, info->ai_addrlen);
581 }
582
583 void SocketAddress::setFromLocalAddr(const struct addrinfo* info) {
584   // If an IPv6 address is present, prefer to use it, since IPv4 addresses
585   // can be mapped into IPv6 space.
586   for (const struct addrinfo* ai = info; ai != nullptr; ai = ai->ai_next) {
587     if (ai->ai_family == AF_INET6) {
588       setFromSockaddr(ai->ai_addr, ai->ai_addrlen);
589       return;
590     }
591   }
592
593   // Otherwise, just use the first address in the list.
594   setFromSockaddr(info->ai_addr, info->ai_addrlen);
595 }
596
597 void SocketAddress::setFromSocket(int socket,
598                                   int (*fn)(int, sockaddr*, socklen_t*)) {
599   // If this was previously an AF_UNIX socket, free the external buffer.
600   // TODO: It would be smarter to just remember the external buffer, and then
601   // re-use it or free it depending on if the new address is also a unix
602   // socket.
603   if (getFamily() == AF_UNIX) {
604     storage_.un.free();
605     external_ = false;
606   }
607
608   // Try to put the address into a local storage buffer.
609   sockaddr_storage tmp_sock;
610   socklen_t addrLen = sizeof(tmp_sock);
611   if (fn(socket, (sockaddr*)&tmp_sock, &addrLen) != 0) {
612     folly::throwSystemError("setFromSocket() failed");
613   }
614
615   setFromSockaddr((sockaddr*)&tmp_sock, addrLen);
616 }
617
618 std::string SocketAddress::getIpString(int flags) const {
619   char addrString[NI_MAXHOST];
620   getIpString(addrString, sizeof(addrString), flags);
621   return std::string(addrString);
622 }
623
624 void SocketAddress::getIpString(char *buf, size_t buflen, int flags) const {
625   auto family = getFamily();
626   if (family != AF_INET &&
627       family != AF_INET6) {
628     throw std::invalid_argument(
629       "SocketAddress: attempting to get IP address "
630       "for a non-IP address");
631   }
632
633   sockaddr_storage tmp_sock;
634   storage_.addr.toSockaddrStorage(&tmp_sock, port_);
635   int rc = getnameinfo((sockaddr*)&tmp_sock, sizeof(sockaddr_storage),
636                        buf, buflen, nullptr, 0, flags);
637   if (rc != 0) {
638     auto os = folly::to<std::string>(
639       "getnameinfo() failed in getIpString() error = ",
640       gai_strerror(rc));
641     throw std::system_error(rc, std::generic_category(), os);
642   }
643 }
644
645 void SocketAddress::updateUnixAddressLength(socklen_t addrlen) {
646   if (addrlen < offsetof(struct sockaddr_un, sun_path)) {
647     throw std::invalid_argument(
648       "SocketAddress: attempted to set a Unix socket "
649       "with a length too short for a sockaddr_un");
650   }
651
652   storage_.un.len = addrlen;
653   if (storage_.un.pathLength() == 0) {
654     // anonymous address
655     return;
656   }
657
658   if (storage_.un.addr->sun_path[0] == '\0') {
659     // abstract namespace.  honor the specified length
660   } else {
661     // Call strnlen(), just in case the length was overspecified.
662     socklen_t maxLength = addrlen - offsetof(struct sockaddr_un, sun_path);
663     size_t pathLength = strnlen(storage_.un.addr->sun_path, maxLength);
664     storage_.un.len = offsetof(struct sockaddr_un, sun_path) + pathLength;
665   }
666 }
667
668 bool SocketAddress::operator<(const SocketAddress& other) const {
669   if (getFamily() != other.getFamily()) {
670     return getFamily() < other.getFamily();
671   }
672
673   switch (getFamily()) {
674     case AF_INET:
675     case AF_INET6: {
676       if (port_ != other.port_) {
677         return port_ < other.port_;
678       }
679
680       return
681         storage_.addr < other.storage_.addr;
682     }
683     case AF_UNIX: {
684       // Anonymous addresses can't be compared to anything else.
685       // Return that they are never less than anything.
686       //
687       // Note that this still meets the requirements for a strict weak
688       // ordering, so we can use this operator<() with standard C++ containers.
689       size_t thisPathLength = storage_.un.pathLength();
690       if (thisPathLength == 0) {
691         return false;
692       }
693       size_t otherPathLength = other.storage_.un.pathLength();
694       if (otherPathLength == 0) {
695         return true;
696       }
697
698       // Compare based on path length first, for efficiency
699       if (thisPathLength != otherPathLength) {
700         return thisPathLength < otherPathLength;
701       }
702       int cmp = memcmp(storage_.un.addr->sun_path,
703                        other.storage_.un.addr->sun_path,
704                        thisPathLength);
705       return cmp < 0;
706     }
707     case AF_UNSPEC:
708     default:
709       throw std::invalid_argument(
710         "SocketAddress: unsupported address family for comparing");
711   }
712 }
713
714 size_t hash_value(const SocketAddress& address) {
715   return address.hash();
716 }
717
718 std::ostream& operator<<(std::ostream& os, const SocketAddress& addr) {
719   os << addr.describe();
720   return os;
721 }
722
723 } // folly