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