Make folly::getCurrentThreadId() return a thread ID on OSX
[folly.git] / folly / IPAddressV6.h
1 /*
2  * Copyright 2017 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 #pragma once
18
19 #include <cstring>
20
21 #include <array>
22 #include <functional>
23 #include <iosfwd>
24 #include <map>
25 #include <stdexcept>
26
27 #include <folly/Hash.h>
28 #include <folly/Optional.h>
29 #include <folly/Range.h>
30 #include <folly/detail/IPAddress.h>
31
32 namespace folly {
33
34 class IPAddress;
35 class IPAddressV4;
36 class IPAddressV6;
37 class MacAddress;
38
39 /**
40  * Pair of IPAddressV6, netmask
41  */
42 typedef std::pair<IPAddressV6, uint8_t> CIDRNetworkV6;
43
44 /**
45  * Specialization for IPv6 addresses
46  */
47 typedef std::array<uint8_t, 16> ByteArray16;
48
49 /**
50  * IPv6 variation of IPAddress.
51  *
52  * Added methods: createIPv4, getIPv4For6To4, is6To4,
53  *                isTeredo, isIPv4Mapped, tryCreateIPv4, type
54  *
55  * @see IPAddress
56  *
57  * Notes on scope ID parsing:
58  *
59  * getaddrinfo() uses if_nametoindex() to convert interface names
60  * into a numerical index. For instance,
61  * "fe80::202:c9ff:fec1:ee08%eth0" may return scope ID 2 on some
62  * hosts, but other numbers on other hosts. It will fail entirely on
63  * hosts without an eth0 interface.
64  *
65  * Serializing / Deserializing IPAddressB6's on different hosts
66  * that use link-local scoping probably won't work.
67  */
68 class IPAddressV6 {
69  public:
70   // V6 Address Type
71   enum Type {
72     TEREDO, T6TO4, NORMAL,
73   };
74   // A constructor parameter to indicate that we should create a link-local
75   // IPAddressV6.
76   enum LinkLocalTag {
77     LINK_LOCAL,
78   };
79   // Thrown when a type assertion fails
80   typedef std::runtime_error TypeError;
81
82   // Binary prefix for teredo networks
83   static const uint32_t PREFIX_TEREDO;
84   // Binary prefix for 6to4 networks
85   static const uint32_t PREFIX_6TO4;
86
87   // Size of std::string returned by toFullyQualified.
88   static constexpr size_t kToFullyQualifiedSize =
89     8 /*words*/ * 4 /*hex chars per word*/ + 7 /*separators*/;
90
91   // returns true iff the input string can be parsed as an ipv6-address
92   static bool validate(StringPiece ip);
93
94   /**
95    * Create a new IPAddress instance from the provided binary data.
96    * @throws IPAddressFormatException if the input length is not 16 bytes.
97    */
98   static IPAddressV6 fromBinary(ByteRange bytes) {
99     IPAddressV6 addr;
100     addr.setFromBinary(bytes);
101     return addr;
102   }
103
104   /**
105    * Returns the address as a Range.
106    */
107   ByteRange toBinary() const {
108     return ByteRange((const unsigned char *) &addr_.in6Addr_.s6_addr, 16);
109   }
110
111   /**
112    * Default constructor for IPAddressV6.
113    *
114    * The address value will be ::0
115    */
116   IPAddressV6();
117
118   // Create an IPAddressV6 from a string
119   // @throws IPAddressFormatException
120   //
121   explicit IPAddressV6(StringPiece ip);
122
123   // ByteArray16 constructor
124   explicit IPAddressV6(const ByteArray16& src);
125
126   // in6_addr constructor
127   explicit IPAddressV6(const in6_addr& src);
128
129   // sockaddr_in6 constructor
130   explicit IPAddressV6(const sockaddr_in6& src);
131
132   /**
133    * Create a link-local IPAddressV6 from the specified ethernet MAC address.
134    */
135   IPAddressV6(LinkLocalTag tag, MacAddress mac);
136
137   // return the mapped V4 address
138   // @throws IPAddressFormatException if !isIPv4Mapped
139   IPAddressV4 createIPv4() const;
140
141   /**
142    * Return a V4 address if this is a 6To4 address.
143    * @throws TypeError if not a 6To4 address
144    */
145   IPAddressV4 getIPv4For6To4() const;
146
147   // Return true if a 6TO4 address
148   bool is6To4() const {
149     return type() == IPAddressV6::Type::T6TO4;
150   }
151
152   // Return true if a TEREDO address
153   bool isTeredo() const {
154     return type() == IPAddressV6::Type::TEREDO;
155   }
156
157   // return true if this is v4-to-v6-mapped
158   bool isIPv4Mapped() const;
159
160   // Return the V6 address type
161   Type type() const;
162
163   /**
164    * @see IPAddress#bitCount
165    * @returns 128
166    */
167   static size_t bitCount() { return 128; }
168
169   /**
170    * @see IPAddress#toJson
171    */
172   std::string toJson() const;
173
174   size_t hash() const;
175
176   // @see IPAddress#inSubnet
177   // @throws IPAddressFormatException if string doesn't contain a V6 address
178   bool inSubnet(StringPiece cidrNetwork) const;
179
180   // return true if address is in subnet
181   bool inSubnet(const IPAddressV6& subnet, uint8_t cidr) const {
182     return inSubnetWithMask(subnet, fetchMask(cidr));
183   }
184   bool inSubnetWithMask(const IPAddressV6& subnet,
185                         const ByteArray16& mask) const;
186
187   // @see IPAddress#isLoopback
188   bool isLoopback() const;
189
190   // @see IPAddress#isNonroutable
191   bool isNonroutable() const {
192     return !isRoutable();
193   }
194
195   /**
196    * Return true if this address is routable.
197    */
198   bool isRoutable() const;
199
200   // @see IPAddress#isPrivate
201   bool isPrivate() const;
202
203   /**
204    * Return true if this is a link-local IPv6 address.
205    *
206    * Note that this only returns true for addresses in the fe80::/10 range.
207    * It returns false for the loopback address (::1), even though this address
208    * is also effectively has link-local scope.  It also returns false for
209    * link-scope and interface-scope multicast addresses.
210    */
211   bool isLinkLocal() const;
212
213   /**
214    * Return the mac address if this is a link-local IPv6 address.
215    *
216    * @return an Optional<MacAddress> union representing the mac address.
217    *
218    * If the address is not a link-local one it will return an empty Optional.
219    * You can use Optional::value() to check whether the mac address is not null.
220    */
221   Optional<MacAddress> getMacAddressFromLinkLocal() const;
222
223   /**
224    * Return true if this is a multicast address.
225    */
226   bool isMulticast() const;
227
228   /**
229    * Return the flags for a multicast address.
230    * This method may only be called on multicast addresses.
231    */
232   uint8_t getMulticastFlags() const;
233
234   /**
235    * Return the scope for a multicast address.
236    * This method may only be called on multicast addresses.
237    */
238   uint8_t getMulticastScope() const;
239
240   // @see IPAddress#isZero
241   bool isZero() const {
242     constexpr auto zero = ByteArray16{{}};
243     return 0 == std::memcmp(bytes(), zero.data(), zero.size());
244   }
245
246   bool isLinkLocalBroadcast() const;
247
248   // @see IPAddress#mask
249   IPAddressV6 mask(size_t numBits) const;
250
251   // return underlying in6_addr structure
252   in6_addr toAddr() const { return addr_.in6Addr_; }
253
254   uint16_t getScopeId() const { return scope_; }
255   void setScopeId(uint16_t scope) {
256     scope_ = scope;
257   }
258
259   sockaddr_in6 toSockAddr() const {
260     sockaddr_in6 addr;
261     memset(&addr, 0, sizeof(sockaddr_in6));
262     addr.sin6_family = AF_INET6;
263     addr.sin6_scope_id = scope_;
264     memcpy(&addr.sin6_addr, &addr_.in6Addr_, sizeof(in6_addr));
265     return addr;
266   }
267
268   ByteArray16 toByteArray() const {
269     ByteArray16 ba{{0}};
270     std::memcpy(ba.data(), bytes(), 16);
271     return ba;
272   }
273
274   // @see IPAddress#toFullyQualified
275   std::string toFullyQualified() const;
276
277   std::string toInverseArpaName() const;
278
279   // @see IPAddress#str
280   std::string str() const;
281
282   // @see IPAddress#version
283   uint8_t version() const { return 6; }
284
285   /**
286    * Return the solicited-node multicast address for this address.
287    */
288   IPAddressV6 getSolicitedNodeAddress() const;
289
290   /**
291    * Return the mask associated with the given number of bits.
292    * If for instance numBits was 24 (e.g. /24) then the V4 mask returned should
293    * be {0xff, 0xff, 0xff, 0x00}.
294    * @param [in] numBits bitmask to retrieve
295    * @throws abort if numBits == 0 or numBits > bitCount()
296    * @return mask associated with numBits
297    */
298   static const ByteArray16 fetchMask(size_t numBits);
299   // Given 2 IPAddressV6,mask pairs extract the longest common IPAddress,
300   // mask pair
301   static CIDRNetworkV6 longestCommonPrefix(
302       const CIDRNetworkV6& one,
303       const CIDRNetworkV6& two);
304   // Number of bytes in the address representation.
305   static constexpr size_t byteCount() { return 16; }
306
307   //get nth most significant bit - 0 indexed
308   bool getNthMSBit(size_t bitIndex) const {
309     return detail::getNthMSBitImpl(*this, bitIndex, AF_INET6);
310   }
311   //get nth most significant byte - 0 indexed
312   uint8_t getNthMSByte(size_t byteIndex) const;
313   //get nth bit - 0 indexed
314   bool getNthLSBit(size_t bitIndex) const {
315     return getNthMSBit(bitCount() - bitIndex - 1);
316   }
317   //get nth byte - 0 indexed
318   uint8_t getNthLSByte(size_t byteIndex) const {
319     return getNthMSByte(byteCount() - byteIndex - 1);
320   }
321
322   const unsigned char* bytes() const { return addr_.in6Addr_.s6_addr; }
323   protected:
324   /**
325    * Helper that returns true if the address is in the binary subnet specified
326    * by addr.
327    */
328   bool inBinarySubnet(const std::array<uint8_t, 2> addr,
329                       size_t numBits) const;
330
331  private:
332   union AddressStorage {
333     in6_addr in6Addr_;
334     ByteArray16 bytes_;
335     AddressStorage() {
336       std::memset(this, 0, sizeof(AddressStorage));
337     }
338     explicit AddressStorage(const ByteArray16& bytes): bytes_(bytes) {}
339     explicit AddressStorage(const in6_addr& addr): in6Addr_(addr) {}
340     explicit AddressStorage(MacAddress mac);
341   } addr_;
342
343   // Link-local scope id.  This should always be 0 for IPAddresses that
344   // are *not* link-local.
345   uint16_t scope_{0};
346
347   static const std::array<ByteArray16, 129> masks_;
348
349   /**
350    * Set the current IPAddressV6 object to have the address specified by bytes.
351    * @throws IPAddressFormatException if bytes.size() is not 16.
352    */
353   void setFromBinary(ByteRange bytes);
354 };
355
356 // boost::hash uses hash_value() so this allows boost::hash to work
357 // automatically for IPAddressV6
358 std::size_t hash_value(const IPAddressV6& addr);
359 std::ostream& operator<<(std::ostream& os, const IPAddressV6& addr);
360 // Define toAppend() to allow IPAddressV6 to be used with to<string>
361 void toAppend(IPAddressV6 addr, std::string* result);
362 void toAppend(IPAddressV6 addr, fbstring* result);
363
364 /**
365  * Return true if two addresses are equal.
366  */
367 inline bool operator==(const IPAddressV6& addr1, const IPAddressV6& addr2) {
368   return (std::memcmp(addr1.toAddr().s6_addr, addr2.toAddr().s6_addr, 16) == 0)
369     && addr1.getScopeId() == addr2.getScopeId();
370 }
371 // Return true if addr1 < addr2
372 inline bool operator<(const IPAddressV6& addr1, const IPAddressV6& addr2) {
373   auto cmp = std::memcmp(addr1.toAddr().s6_addr,
374                          addr2.toAddr().s6_addr, 16) < 0;
375   if (!cmp) {
376     return addr1.getScopeId() < addr2.getScopeId();
377   } else {
378     return cmp;
379   }
380 }
381 // Derived operators
382 inline bool operator!=(const IPAddressV6& a, const IPAddressV6& b) {
383   return !(a == b);
384 }
385 inline bool operator>(const IPAddressV6& a, const IPAddressV6& b) {
386   return b < a;
387 }
388 inline bool operator<=(const IPAddressV6& a, const IPAddressV6& b) {
389   return !(a > b);
390 }
391 inline bool operator>=(const IPAddressV6& a, const IPAddressV6& b) {
392   return !(a < b);
393 }
394
395 }  // folly
396
397 namespace std {
398 template<>
399 struct hash<folly::IPAddressV6> {
400   size_t operator()(const folly::IPAddressV6& addr) const {
401     return addr.hash();
402   }
403 };
404 }  // std