Make TSocketAddress use folly::IPAddress
[folly.git] / folly / IPAddressV4.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 #include <folly/IPAddressV4.h>
18
19 #include <ostream>
20 #include <string>
21
22 #include <folly/Format.h>
23 #include <folly/IPAddress.h>
24 #include <folly/IPAddressV6.h>
25
26 using std::ostream;
27 using std::string;
28
29 namespace folly {
30
31 static IPAddressV4 loopback_addr("127.0.0.0");
32
33 // free functions
34 size_t hash_value(const IPAddressV4& addr) {
35   return addr.hash();
36 }
37 ostream& operator<<(ostream& os, const IPAddressV4& addr) {
38   os << addr.str();
39   return os;
40 }
41 void toAppend(IPAddressV4 addr, string* result) {
42   result->append(addr.str());
43 }
44 void toAppend(IPAddressV4 addr, fbstring* result) {
45   result->append(addr.str());
46 }
47
48
49 // public static
50 IPAddressV4 IPAddressV4::fromLong(uint32_t src) {
51   in_addr addr;
52   addr.s_addr = src;
53   return IPAddressV4(addr);
54 }
55
56 IPAddressV4 IPAddressV4::fromLongHBO(uint32_t src) {
57   in_addr addr;
58   addr.s_addr = htonl(src);
59   return IPAddressV4(addr);
60 }
61
62 // static public
63 uint32_t IPAddressV4::toLong(StringPiece ip) {
64   auto str = ip.str();
65   in_addr addr;
66   if (inet_pton(AF_INET, str.c_str(), &addr) != 1) {
67     throw IPAddressFormatException("Can't convert invalid IP '", ip, "' ",
68                                    "to long");
69   }
70   return addr.s_addr;
71 }
72
73 // static public
74 uint32_t IPAddressV4::toLongHBO(StringPiece ip) {
75   return ntohl(IPAddressV4::toLong(ip));
76 }
77
78 // public default constructor
79 IPAddressV4::IPAddressV4() {
80 }
81
82 // ByteArray4 constructor
83 IPAddressV4::IPAddressV4(const ByteArray4& src)
84   : addr_(src)
85 {
86 }
87
88 // public string constructor
89 IPAddressV4::IPAddressV4(StringPiece addr)
90   : addr_()
91 {
92   auto ip = addr.str();
93   if (inet_pton(AF_INET, ip.c_str(), &addr_.inAddr_) != 1) {
94     throw IPAddressFormatException("Invalid IPv4 address '", addr, "'");
95   }
96 }
97
98 // in_addr constructor
99 IPAddressV4::IPAddressV4(const in_addr src)
100   : addr_(src)
101 {
102 }
103
104 // public
105 void IPAddressV4::setFromBinary(ByteRange bytes) {
106   if (bytes.size() != 4) {
107     throw IPAddressFormatException("Invalid IPv4 binary data: length must "
108                                    "be 4 bytes, got ", bytes.size());
109   }
110   memcpy(&addr_.inAddr_.s_addr, bytes.data(), sizeof(in_addr));
111 }
112
113 // public
114 IPAddressV6 IPAddressV4::createIPv6() const {
115   ByteArray16 ba{{0}};
116   ba[10] = 0xff;
117   ba[11] = 0xff;
118   std::memcpy(&ba[12], bytes(), 4);
119   return IPAddressV6(ba);
120 }
121
122 // public
123 string IPAddressV4::toJson() const {
124   return format(
125       "{{family:'AF_INET', addr:'{}', hash:{}}}", str(), hash()).str();
126 }
127
128 // public
129 bool IPAddressV4::inSubnet(StringPiece cidrNetwork) const {
130   auto subnetInfo = IPAddress::createNetwork(cidrNetwork);
131   auto addr = subnetInfo.first;
132   if (!addr.isV4()) {
133     throw IPAddressFormatException("Address '", addr.toJson(), "' ",
134                                    "is not a V4 address");
135   }
136   return inSubnetWithMask(addr.asV4(), fetchMask(subnetInfo.second));
137 }
138
139 // public
140 bool IPAddressV4::inSubnetWithMask(const IPAddressV4& subnet,
141                                    const ByteArray4 cidrMask) const {
142   const ByteArray4 mask = detail::Bytes::mask(toByteArray(), cidrMask);
143   const ByteArray4 subMask = detail::Bytes::mask(subnet.toByteArray(),
144                                                  cidrMask);
145   return (mask == subMask);
146 }
147
148 bool IPAddressV4::isLoopback() const {
149   return inSubnetWithMask(loopback_addr, fetchMask(8));
150 }
151
152 // public
153 bool IPAddressV4::isNonroutable() const {
154   auto ip = toLongHBO();
155   return isPrivate() ||
156       (ip <= 0x00FFFFFF)                     || // 0.0.0.0-0.255.255.255
157       (ip >= 0xC0000000 && ip <= 0xC00000FF) || // 192.0.0.0-192.0.0.255
158       (ip >= 0xC0000200 && ip <= 0xC00002FF) || // 192.0.2.0-192.0.2.255
159       (ip >= 0xC6120000 && ip <= 0xC613FFFF) || // 198.18.0.0-198.19.255.255
160       (ip >= 0xC6336400 && ip <= 0xC63364FF) || // 198.51.100.0-198.51.100.255
161       (ip >= 0xCB007100 && ip <= 0xCB0071FF) || // 203.0.113.0-203.0.113.255
162       (ip >= 0xE0000000 && ip <= 0xFFFFFFFF);   // 224.0.0.0-255.255.255.255
163 }
164
165 // public
166 bool IPAddressV4::isPrivate() const {
167   auto ip = toLongHBO();
168   return
169       (ip >= 0x0A000000 && ip <= 0x0AFFFFFF) || // 10.0.0.0-10.255.255.255
170       (ip >= 0x7F000000 && ip <= 0x7FFFFFFF) || // 127.0.0.0-127.255.255.255
171       (ip >= 0xA9FE0000 && ip <= 0xA9FEFFFF) || // 169.254.0.0-169.254.255.255
172       (ip >= 0xAC100000 && ip <= 0xAC1FFFFF) || // 172.16.0.0-172.31.255.255
173       (ip >= 0xC0A80000 && ip <= 0xC0A8FFFF);   // 192.168.0.0-192.168.255.255
174 }
175
176 // public
177 bool IPAddressV4::isMulticast() const {
178   return (toLongHBO() & 0xf0000000) == 0xe0000000;
179 }
180
181 // public
182 IPAddressV4 IPAddressV4::mask(size_t numBits) const {
183   static const auto bits = bitCount();
184   if (numBits > bits) {
185     throw IPAddressFormatException("numBits(", numBits,
186                                    ") > bitsCount(", bits, ")");
187   }
188
189   ByteArray4 ba = detail::Bytes::mask(fetchMask(numBits), addr_.bytes_);
190   return IPAddressV4(ba);
191 }
192
193 // public
194 string IPAddressV4::str() const {
195   return detail::fastIpv4ToString(addr_.inAddr_);
196 }
197
198 // public
199 uint8_t IPAddressV4::getNthMSByte(size_t byteIndex) const {
200   const auto highestIndex = byteCount() - 1;
201   if (byteIndex > highestIndex) {
202     throw std::invalid_argument(to<string>("Byte index must be <= ",
203         to<string>(highestIndex), " for addresses of type :",
204         detail::familyNameStr(AF_INET)));
205   }
206   return bytes()[byteIndex];
207 }
208 // protected
209 const ByteArray4 IPAddressV4::fetchMask(size_t numBits) {
210   static const uint8_t bits = bitCount();
211   if (numBits > bits) {
212     throw IPAddressFormatException("IPv4 addresses are 32 bits");
213   }
214   // masks_ is backed by an array so is zero indexed
215   return masks_[numBits];
216 }
217
218 // static private
219 const std::array<ByteArray4, 33> IPAddressV4::masks_ = {{
220   {{0x00, 0x00, 0x00, 0x00}},
221   {{0x80, 0x00, 0x00, 0x00}},
222   {{0xc0, 0x00, 0x00, 0x00}},
223   {{0xe0, 0x00, 0x00, 0x00}},
224   {{0xf0, 0x00, 0x00, 0x00}},
225   {{0xf8, 0x00, 0x00, 0x00}},
226   {{0xfc, 0x00, 0x00, 0x00}},
227   {{0xfe, 0x00, 0x00, 0x00}},
228   {{0xff, 0x00, 0x00, 0x00}},
229   {{0xff, 0x80, 0x00, 0x00}},
230   {{0xff, 0xc0, 0x00, 0x00}},
231   {{0xff, 0xe0, 0x00, 0x00}},
232   {{0xff, 0xf0, 0x00, 0x00}},
233   {{0xff, 0xf8, 0x00, 0x00}},
234   {{0xff, 0xfc, 0x00, 0x00}},
235   {{0xff, 0xfe, 0x00, 0x00}},
236   {{0xff, 0xff, 0x00, 0x00}},
237   {{0xff, 0xff, 0x80, 0x00}},
238   {{0xff, 0xff, 0xc0, 0x00}},
239   {{0xff, 0xff, 0xe0, 0x00}},
240   {{0xff, 0xff, 0xf0, 0x00}},
241   {{0xff, 0xff, 0xf8, 0x00}},
242   {{0xff, 0xff, 0xfc, 0x00}},
243   {{0xff, 0xff, 0xfe, 0x00}},
244   {{0xff, 0xff, 0xff, 0x00}},
245   {{0xff, 0xff, 0xff, 0x80}},
246   {{0xff, 0xff, 0xff, 0xc0}},
247   {{0xff, 0xff, 0xff, 0xe0}},
248   {{0xff, 0xff, 0xff, 0xf0}},
249   {{0xff, 0xff, 0xff, 0xf8}},
250   {{0xff, 0xff, 0xff, 0xfc}},
251   {{0xff, 0xff, 0xff, 0xfe}},
252   {{0xff, 0xff, 0xff, 0xff}}
253 }};
254
255 } // folly