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