]> git.ipfire.org Git - thirdparty/squid.git/blob - src/ip/Address.h
Merged from parent (trunk r11623, v3.2.0.10+).
[thirdparty/squid.git] / src / ip / Address.h
1 /*
2 * DEBUG: section 14 IP Storage and Handling
3 * AUTHOR: Amos Jeffries
4 *
5 * SQUID Internet Object Cache http://squid.nlanr.net/Squid/
6 * ----------------------------------------------------------
7 *
8 * Squid is the result of efforts by numerous individuals from the
9 * Internet community. Development is led by Duane Wessels of the
10 * National Laboratory for Applied Network Research and funded by the
11 * National Science Foundation. Squid is Copyrighted (C) 1998 by
12 * the Regents of the University of California. Please see the
13 * COPYRIGHT file for full details. Squid incorporates software
14 * developed and/or copyrighted by other sources. Please see the
15 * CREDITS file for full details.
16 *
17 * This Ip::Address code is copyright (C) 2007 by Treehouse Networks Ltd
18 * of New Zealand. It is published and Lisenced as an extension of
19 * squid under the same conditions as the main squid application.
20 *
21 * This program is free software; you can redistribute it and/or modify
22 * it under the terms of the GNU General Public License as published by
23 * the Free Software Foundation; either version 2 of the License, or
24 * (at your option) any later version.
25 *
26 * This program is distributed in the hope that it will be useful,
27 * but WITHOUT ANY WARRANTY; without even the implied warranty of
28 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
29 * GNU General Public License for more details.
30 *
31 * You should have received a copy of the GNU General Public License
32 * along with this program; if not, write to the Free Software
33 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
34 *
35 */
36 #ifndef _SQUID_IP_IPADDRESS_H
37 #define _SQUID_IP_IPADDRESS_H
38
39 #if HAVE_SYS_SOCKET_H
40 #include <sys/socket.h>
41 #endif
42 #if HAVE_NETINET_IN_H
43 #include <netinet/in.h>
44 #endif
45 #if HAVE_NETINET_IP_H
46 #include <netinet/ip.h>
47 #endif
48 #if _SQUID_MSWIN_
49 #include <ws2tcpip.h>
50 #endif
51 #if HAVE_NETDB_H
52 #include <netdb.h>
53 #endif
54
55 #if HAVE_IOSFWD
56 #include <iosfwd>
57 #endif
58 #if HAVE_OSTREAM
59 #include <ostream>
60 #endif
61
62 namespace Ip
63 {
64
65 /// Length of buffer that needs to be allocated to old a null-terminated IP-string
66 // Yuck. But there are still structures that need it to be an 'integer constant'.
67 #define MAX_IPSTRLEN 75
68
69 /**
70 * Holds and manipulates IPv4, IPv6, and Socket Addresses.
71 */
72 class Address
73 {
74
75 public:
76 /** @name Constructors and Destructor */
77 /*@{*/
78 Address() { SetEmpty(); }
79 Address(const Address &);
80
81 /**
82 * This constructor takes its own copy of the object pointed to for memory-safe usage later.
83 * The caller must itself perform and ptr memory-management needed.
84 *
85 \deprecated Use of pointers can be nasty. Consider this a last-resort.
86 * Prefer the by-reference (&) version instead.
87 */
88 Address(Address *);
89
90 Address(const struct in_addr &);
91 Address(const struct sockaddr_in &);
92 Address(const struct in6_addr &);
93 Address(const struct sockaddr_in6 &);
94 Address(const struct hostent &);
95 Address(const struct addrinfo &);
96 Address(const char*);
97 ~Address() {}
98 /*@}*/
99
100 /** @name Assignment Operators */
101 /*@{*/
102 Address& operator =(const Address &s);
103 Address& operator =(struct sockaddr_in const &s);
104 Address& operator =(struct sockaddr_storage const &s);
105 Address& operator =(struct in_addr const &s);
106 Address& operator =(struct in6_addr const &s);
107 Address& operator =(struct sockaddr_in6 const &s);
108 bool operator =(const struct hostent &s);
109 bool operator =(const struct addrinfo &s);
110 bool operator =(const char *s);
111 /*@}*/
112
113 /** @name Boolean Operators */
114 /*@{*/
115 bool operator ==(Address const &s) const;
116 bool operator !=(Address const &s) const;
117 bool operator >=(Address const &rhs) const;
118 bool operator <=(Address const &rhs) const;
119 bool operator >(Address const &rhs) const;
120 bool operator <(Address const &rhs) const;
121
122 public:
123 /* methods */
124
125 /** Test whether content can be used as an IPv4 address
126 \retval true if content was received as an IPv4-Mapped address
127 \retval false if content was received as a non-mapped IPv6 native address.
128 */
129 bool IsIPv4() const;
130
131 /** Test whether content can be used as an IPv6 address.
132 \retval true if content is a non IPv4-mapped address.
133 \retval false if content is IPv4-mapped.
134 */
135 bool IsIPv6() const;
136
137 /** Test whether content can be used as a Socket address.
138 \retval true if address AND port are both set
139 \retval true if content was received as a Socket address with port
140 \retval false if port in unset (zero)
141 */
142 bool IsSockAddr() const;
143
144 /** Content-neutral test for whether the specific IP case ANY_ADDR is stored.
145 * This is the default content of a new undefined Ip::Address object.
146 \retval true IPv4 0.0.0.0
147 \retval true IPv6 ::
148 \retval false anything else.
149 */
150 bool IsAnyAddr() const;
151
152 /** Content-neutral test for whether the specific IP case NO_ADDR is stored.
153 \retval true IPv4 255.255.255.255
154 \retval true IPv6 ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff
155 \retval false anything else.
156 */
157 bool IsNoAddr() const;
158
159 /** Content-neutral test for whether the specific IP case LOCALHOST is stored.
160 * This is the default content of a new undefined Ip::Address object.
161 \retval true IPv4 127.0.0.1
162 \retval true IPv6 ::1
163 \retval false anything else.
164 */
165 bool IsLocalhost() const;
166
167 /** Test whether content is an IPv6 Site-Local address.
168 \retval true if address begins with fe80::/10.
169 \retval false if --disable-ipv6 has been compiled.
170 \retval false if address does not match fe80::/10
171 */
172 bool IsSiteLocal6() const;
173
174 /** Test whether content is an IPv6 address with SLAAC EUI-64 embeded.
175 \retval true if address matches ::ff:fe00:0
176 \retval false if --disable-ipv6 has been compiled.
177 \retval false if address does not match ::ff:fe00:0
178 */
179 bool IsSlaac() const;
180
181 /*@}*/
182
183 /** Retrieve the Port if stored.
184 \retval 0 Port is unset or an error occured.
185 \retval n Port associated with this address in host native -endian.
186 */
187 u_short GetPort() const;
188
189 /** Set the Port value for an address.
190 * Replaces any previously existing Port value.
191 \param port Port being assigned in host native -endian.
192 \retval 0 Port is unset or an error occured.
193 \retval n Port associated with this address in host native -endian.
194 */
195 u_short SetPort(u_short port);
196
197 /// Set object to contain the specific IP case ANY_ADDR (format-neutral).
198 /// see IsAnyAddr() for more detail.
199 void SetAnyAddr();
200
201 /// Set object to contain the specific IP case NO_ADDR (format-neutral).
202 /// see IsNoAddr() for more detail.
203 void SetNoAddr();
204
205 /// Set object to contain the specific IP case LOCALHOST (format-neutral).
206 /// see IsLocalhost() for more detail.
207 void SetLocalhost();
208
209 /// Fast reset of the stored content to what would be after default constructor.
210 void SetEmpty();
211
212 /** Require an IPv4-only address for this usage.
213 * Converts the object to prefer only IPv4 output.
214 \retval true Content can be IPv4
215 \retval false Content CANNOT be IPv4
216 */
217 bool SetIPv4();
218
219 /**
220 * Valid results IF and only IF the stored IP address is actually a network bitmask
221 \retval N number of bits which are set in the bitmask stored.
222 */
223 int GetCIDR() const;
224
225 /** Apply a mask to the stored address.
226 \param mask Netmask format to be bit-mask-AND'd over the stored address.
227 */
228 int ApplyMask(const Address &mask);
229
230 /** Apply a mask to the stored address.
231 * CIDR will be converted appropriate to map the stored content.
232 \param cidr CIDR Mask being applied. As an integer in host format.
233 \param mtype Type of CIDR mask being applied (AF_INET or AF_INET6)
234 */
235 bool ApplyMask(const unsigned int cidr, int mtype);
236
237
238 /** Return the ASCII equivalent of the address
239 * Semantically equivalent to the IPv4 inet_ntoa()
240 * eg. 127.0.0.1 (IPv4) or ::1 (IPv6)
241 * But for memory safety it requires a buffer as input
242 * instead of producing one magically.
243 * If buffer is not large enough the data is truncated silently.
244 \param buf Allocated buffer to write address to
245 \param len byte length of buffer available for writing.
246 \param force (optional) require the IPA in a specific format.
247 \return pointer to buffer received.
248 */
249 char* NtoA(char *buf, const unsigned int blen, int force = AF_UNSPEC) const;
250
251 /** Return the ASCII equivalent of the address:port combination
252 * Provides a URL formatted version of the content.
253 * If buffer is not large enough the data is truncated silently.
254 * eg. 127.0.0.1:80 (IPv4) or [::1]:80 (IPv6)
255 \param buf Allocated buffer to write address:port to
256 \param len byte length of buffer available for writing.
257 \return pointer to buffer received.
258 */
259 char* ToURL(char *buf, unsigned int len) const;
260
261 /** Return a properly hostname formatted copy of the address
262 * Provides a URL formatted version of the content.
263 * If buffer is not large enough the data is truncated silently.
264 * eg. 127.0.0.1 (IPv4) or [::1] (IPv6)
265 \param buf Allocated buffer to write address to
266 \param len byte length of buffer available for writing.
267 \return amount of buffer filled.
268 */
269 unsigned int ToHostname(char *buf, const unsigned int len) const;
270
271 /**
272 * Convert the content into a Reverse-DNS string.
273 * The buffer sent MUST be allocated large enough to hold the resulting string.
274 * Name truncation will occur if buf does not have enough space.
275 * The constant MAX_IPSTRLEN is defined to provide for sizing arrays correctly.
276 \param show_type may be one of: AF_INET, AF_INET6 for the format of rDNS string wanted.
277 * AF_UNSPEC the default displays the IP in its most advanced native form.
278 \param buf buffer to receive the text string output.
279 */
280 bool GetReverseString(char buf[MAX_IPSTRLEN], int show_type = AF_UNSPEC) const;
281
282 /** Test how two IP relate to each other.
283 \retval 0 IP are equal
284 \retval 1 IP rhs is greater (numerically) than that stored.
285 \retval -1 IP rhs is less (numerically) than that stored.
286 */
287 int matchIPAddr(const Address &rhs) const;
288
289 /** Compare taking IP, port, protocol, etc. into account. Returns an
290 integer less than, equal to, or greater than zero if the object
291 is found, respectively, to be less than, to match, or to be greater
292 than rhs. The exact ordering algorithm is not specified and may change.
293 */
294 int compareWhole(const Ip::Address &rhs) const;
295
296 /**
297 * Get RFC 3493 addrinfo structure from the Ip::Address data
298 * for protocol-neutral socket operations.
299 * Should be passed a NULL pointer of type struct addrinfo* it will
300 * allocate memory for the structures involved. (see FreeAddrInfo to clear).
301 * Defaults to a TCP streaming socket, if other values (such as UDP) are needed
302 * the caller MUST override these default settings.
303 * Some situations may also require an actual call to the system getaddrinfo()
304 * to pull relevant OS details for the socket.
305 \par
306 * Ip::Address allocated objects MUST be destructed by Ip::Address::FreeAddrInfo
307 * System getaddrinfo() allocated objects MUST be freed with system freeaddrinfo()
308 *
309 \param ai structure to be filled out.
310 \param force a specific sockaddr type is needed. default: don't care.
311 */
312 void GetAddrInfo(struct addrinfo *&ai, int force = AF_UNSPEC) const;
313
314 /**
315 * Equivalent to the sysem call freeaddrinfo() but for Ip::Address allocated data
316 */
317 static void FreeAddrInfo(struct addrinfo *&ai);
318
319 /**
320 * Initializes an empty addrinfo properly for use.
321 * It is intended for use in cases such as getsockopt() where the addrinfo is
322 * about to be changed and the stored details may not match the new ones coming.
323 \param ai addrinfo struct to be initialized as AF_UNSPEC with large address buffer
324 */
325 static void InitAddrInfo(struct addrinfo *&ai);
326
327 /**
328 * Lookup a Host by Name. Equivalent to system call gethostbyname(char*)
329 \param s The textual FQDN of the host being located.
330 \retval true lookup was successful and an IPA was located.
331 \retval false lookup failed or FQDN has no IP associated.
332 */
333 bool GetHostByName(const char *s);
334
335 public:
336 /* FIXME: When C => C++ conversion is done will be fully private.
337 * Legacy Transition Methods.
338 * These are here solely to simplify the transition
339 * when moving from converted code to unconverted
340 * these functions can be used to convert this object
341 * and pull out the data needed by the unconverted code
342 * they are intentionaly hard to use, use GetAddrInfo() instead.
343 * these functiosn WILL NOT be in the final public API after transition.
344 */
345
346 void GetSockAddr(struct sockaddr_storage &addr, const int family) const;
347 void GetSockAddr(struct sockaddr_in &) const;
348 bool GetInAddr(struct in_addr &) const; /* false if could not convert IPv6 down to IPv4 */
349 void GetSockAddr(struct sockaddr_in6 &) const;
350 void GetInAddr(struct in6_addr &) const;
351
352 private:
353 /* Conversion for dual-type internals */
354
355 bool GetReverseString4(char buf[MAX_IPSTRLEN], const struct in_addr &dat) const;
356
357 bool GetReverseString6(char buf[MAX_IPSTRLEN], const struct in6_addr &dat) const;
358
359 void Map4to6(const struct in_addr &src, struct in6_addr &dest) const;
360
361 void Map6to4(const struct in6_addr &src, struct in_addr &dest) const;
362
363 // Worker behind GetHostName and char* converters
364 bool LookupHostIP(const char *s, bool nodns);
365
366 /* variables */
367 struct sockaddr_in6 m_SocketAddr;
368
369 private:
370 /* Internally used constants */
371 static const unsigned int STRLEN_IP4A = 16; // aaa.bbb.ccc.ddd\0
372 static const unsigned int STRLEN_IP4R = 28; // ddd.ccc.bbb.aaa.in-addr.arpa.\0
373 static const unsigned int STRLEN_IP4S = 21; // ddd.ccc.bbb.aaa:ppppp\0
374 static const unsigned int MAX_IP4_STRLEN = STRLEN_IP4R;
375 static const unsigned int STRLEN_IP6A = 42; // [ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff]/0
376 static const unsigned int STRLEN_IP6R = 75; // f.f.f.f f.f.f.f f.f.f.f f.f.f.f f.f.f.f f.f.f.f f.f.f.f f.f.f.f ipv6.arpa./0
377 static const unsigned int STRLEN_IP6S = 48; // [ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff]:00000/0
378 static const unsigned int MAX_IP6_STRLEN = STRLEN_IP6R;
379 static const struct in6_addr v4_localhost;
380 static const struct in6_addr v4_anyaddr;
381 static const struct in6_addr v4_noaddr;
382 static const struct in6_addr v6_noaddr;
383 };
384
385
386 inline std::ostream &
387 operator << (std::ostream &os, const Address &ipa)
388 {
389 char buf[MAX_IPSTRLEN];
390 os << ipa.ToURL(buf,MAX_IPSTRLEN);
391 return os;
392 }
393
394 // WAS _sockaddr_in_list in an earlier incarnation
395 class Address_list
396 {
397 public:
398 Address_list() { next = NULL; };
399 ~Address_list() { if (next) delete next; next = NULL; };
400
401 Address s;
402 Address_list *next;
403 };
404
405 } // namespace Ip
406
407 extern void parse_IpAddress_list_token(Ip::Address_list **, char *);
408
409 #endif /* _SQUID_IP_IPADDRESS_H */