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