1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "net/dns/address_sorter_posix.h"
7 #include <netinet/in.h>
9 #if defined(OS_MACOSX) || defined(OS_BSD)
10 #include <sys/socket.h> // Must be included before ifaddrs.h.
13 #include <netinet/in_var.h>
15 #include <sys/ioctl.h>
20 #include "base/logging.h"
21 #include "base/memory/scoped_vector.h"
22 #include "net/base/net_errors.h"
23 #include "net/socket/client_socket_factory.h"
24 #include "net/udp/datagram_client_socket.h"
27 #include "net/base/address_tracker_linux.h"
34 // Address sorting is performed according to RFC3484 with revisions.
35 // http://tools.ietf.org/html/draft-ietf-6man-rfc3484bis-06
36 // Precedence and label are separate to support override through /etc/gai.conf.
38 // Returns true if |p1| should precede |p2| in the table.
39 // Sorts table by decreasing prefix size to allow longest prefix matching.
40 bool ComparePolicy(const AddressSorterPosix::PolicyEntry
& p1
,
41 const AddressSorterPosix::PolicyEntry
& p2
) {
42 return p1
.prefix_length
> p2
.prefix_length
;
45 // Creates sorted PolicyTable from |table| with |size| entries.
46 AddressSorterPosix::PolicyTable
LoadPolicy(
47 AddressSorterPosix::PolicyEntry
* table
,
49 AddressSorterPosix::PolicyTable
result(table
, table
+ size
);
50 std::sort(result
.begin(), result
.end(), ComparePolicy
);
54 // Search |table| for matching prefix of |address|. |table| must be sorted by
55 // descending prefix (prefix of another prefix must be later in table).
56 unsigned GetPolicyValue(const AddressSorterPosix::PolicyTable
& table
,
57 const IPAddressNumber
& address
) {
58 if (address
.size() == kIPv4AddressSize
)
59 return GetPolicyValue(table
, ConvertIPv4NumberToIPv6Number(address
));
60 for (unsigned i
= 0; i
< table
.size(); ++i
) {
61 const AddressSorterPosix::PolicyEntry
& entry
= table
[i
];
62 IPAddressNumber
prefix(entry
.prefix
, entry
.prefix
+ kIPv6AddressSize
);
63 if (IPNumberMatchesPrefix(address
, prefix
, entry
.prefix_length
))
67 // The last entry is the least restrictive, so assume it's default.
68 return table
.back().value
;
71 bool IsIPv6Multicast(const IPAddressNumber
& address
) {
72 DCHECK_EQ(kIPv6AddressSize
, address
.size());
73 return address
[0] == 0xFF;
76 AddressSorterPosix::AddressScope
GetIPv6MulticastScope(
77 const IPAddressNumber
& address
) {
78 DCHECK_EQ(kIPv6AddressSize
, address
.size());
79 return static_cast<AddressSorterPosix::AddressScope
>(address
[1] & 0x0F);
82 bool IsIPv6Loopback(const IPAddressNumber
& address
) {
83 DCHECK_EQ(kIPv6AddressSize
, address
.size());
84 // IN6_IS_ADDR_LOOPBACK
85 unsigned char kLoopback
[kIPv6AddressSize
] = {
86 0, 0, 0, 0, 0, 0, 0, 0,
87 0, 0, 0, 0, 0, 0, 0, 1,
89 return address
== IPAddressNumber(kLoopback
, kLoopback
+ kIPv6AddressSize
);
92 bool IsIPv6LinkLocal(const IPAddressNumber
& address
) {
93 DCHECK_EQ(kIPv6AddressSize
, address
.size());
94 // IN6_IS_ADDR_LINKLOCAL
95 return (address
[0] == 0xFE) && ((address
[1] & 0xC0) == 0x80);
98 bool IsIPv6SiteLocal(const IPAddressNumber
& address
) {
99 DCHECK_EQ(kIPv6AddressSize
, address
.size());
100 // IN6_IS_ADDR_SITELOCAL
101 return (address
[0] == 0xFE) && ((address
[1] & 0xC0) == 0xC0);
104 AddressSorterPosix::AddressScope
GetScope(
105 const AddressSorterPosix::PolicyTable
& ipv4_scope_table
,
106 const IPAddressNumber
& address
) {
107 if (address
.size() == kIPv6AddressSize
) {
108 if (IsIPv6Multicast(address
)) {
109 return GetIPv6MulticastScope(address
);
110 } else if (IsIPv6Loopback(address
) || IsIPv6LinkLocal(address
)) {
111 return AddressSorterPosix::SCOPE_LINKLOCAL
;
112 } else if (IsIPv6SiteLocal(address
)) {
113 return AddressSorterPosix::SCOPE_SITELOCAL
;
115 return AddressSorterPosix::SCOPE_GLOBAL
;
117 } else if (address
.size() == kIPv4AddressSize
) {
118 return static_cast<AddressSorterPosix::AddressScope
>(
119 GetPolicyValue(ipv4_scope_table
, address
));
122 return AddressSorterPosix::SCOPE_NODELOCAL
;
126 // Default policy table. RFC 3484, Section 2.1.
127 AddressSorterPosix::PolicyEntry kDefaultPrecedenceTable
[] = {
128 // ::1/128 -- loopback
129 { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 }, 128, 50 },
132 // ::ffff:0:0/96 -- IPv4 mapped
133 { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xFF, 0xFF }, 96, 35 },
135 { { 0x20, 0x02, }, 16, 30 },
136 // 2001::/32 -- Teredo
137 { { 0x20, 0x01, 0, 0 }, 32, 5 },
138 // fc00::/7 -- unique local address
140 // ::/96 -- IPv4 compatible
141 { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, 96, 1 },
142 // fec0::/10 -- site-local expanded scope
143 { { 0xFE, 0xC0 }, 10, 1 },
144 // 3ffe::/16 -- 6bone
145 { { 0x3F, 0xFE }, 16, 1 },
148 AddressSorterPosix::PolicyEntry kDefaultLabelTable
[] = {
149 // ::1/128 -- loopback
150 { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 }, 128, 0 },
153 // ::ffff:0:0/96 -- IPv4 mapped
154 { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xFF, 0xFF }, 96, 4 },
156 { { 0x20, 0x02, }, 16, 2 },
157 // 2001::/32 -- Teredo
158 { { 0x20, 0x01, 0, 0 }, 32, 5 },
159 // fc00::/7 -- unique local address
161 // ::/96 -- IPv4 compatible
162 { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, 96, 3 },
163 // fec0::/10 -- site-local expanded scope
164 { { 0xFE, 0xC0 }, 10, 11 },
165 // 3ffe::/16 -- 6bone
166 { { 0x3F, 0xFE }, 16, 12 },
169 // Default mapping of IPv4 addresses to scope.
170 AddressSorterPosix::PolicyEntry kDefaultIPv4ScopeTable
[] = {
171 { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xFF, 0xFF, 0x7F }, 104,
172 AddressSorterPosix::SCOPE_LINKLOCAL
},
173 { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xFF, 0xFF, 0xA9, 0xFE }, 112,
174 AddressSorterPosix::SCOPE_LINKLOCAL
},
175 { { }, 0, AddressSorterPosix::SCOPE_GLOBAL
},
178 struct DestinationInfo
{
179 IPAddressNumber address
;
180 AddressSorterPosix::AddressScope scope
;
183 const AddressSorterPosix::SourceAddressInfo
* src
;
184 unsigned common_prefix_length
;
187 // Returns true iff |dst_a| should precede |dst_b| in the address list.
188 // RFC 3484, section 6.
189 bool CompareDestinations(const DestinationInfo
* dst_a
,
190 const DestinationInfo
* dst_b
) {
191 // Rule 1: Avoid unusable destinations.
192 // Unusable destinations are already filtered out.
196 // Rule 2: Prefer matching scope.
197 bool scope_match1
= (dst_a
->src
->scope
== dst_a
->scope
);
198 bool scope_match2
= (dst_b
->src
->scope
== dst_b
->scope
);
199 if (scope_match1
!= scope_match2
)
202 // Rule 3: Avoid deprecated addresses.
203 if (dst_a
->src
->deprecated
!= dst_b
->src
->deprecated
)
204 return !dst_a
->src
->deprecated
;
206 // Rule 4: Prefer home addresses.
207 if (dst_a
->src
->home
!= dst_b
->src
->home
)
208 return dst_a
->src
->home
;
210 // Rule 5: Prefer matching label.
211 bool label_match1
= (dst_a
->src
->label
== dst_a
->label
);
212 bool label_match2
= (dst_b
->src
->label
== dst_b
->label
);
213 if (label_match1
!= label_match2
)
216 // Rule 6: Prefer higher precedence.
217 if (dst_a
->precedence
!= dst_b
->precedence
)
218 return dst_a
->precedence
> dst_b
->precedence
;
220 // Rule 7: Prefer native transport.
221 if (dst_a
->src
->native
!= dst_b
->src
->native
)
222 return dst_a
->src
->native
;
224 // Rule 8: Prefer smaller scope.
225 if (dst_a
->scope
!= dst_b
->scope
)
226 return dst_a
->scope
< dst_b
->scope
;
228 // Rule 9: Use longest matching prefix. Only for matching address families.
229 if (dst_a
->address
.size() == dst_b
->address
.size()) {
230 if (dst_a
->common_prefix_length
!= dst_b
->common_prefix_length
)
231 return dst_a
->common_prefix_length
> dst_b
->common_prefix_length
;
234 // Rule 10: Leave the order unchanged.
235 // stable_sort takes care of that.
241 AddressSorterPosix::AddressSorterPosix(ClientSocketFactory
* socket_factory
)
242 : socket_factory_(socket_factory
),
243 precedence_table_(LoadPolicy(kDefaultPrecedenceTable
,
244 arraysize(kDefaultPrecedenceTable
))),
245 label_table_(LoadPolicy(kDefaultLabelTable
,
246 arraysize(kDefaultLabelTable
))),
247 ipv4_scope_table_(LoadPolicy(kDefaultIPv4ScopeTable
,
248 arraysize(kDefaultIPv4ScopeTable
))) {
249 NetworkChangeNotifier::AddIPAddressObserver(this);
250 OnIPAddressChanged();
253 AddressSorterPosix::~AddressSorterPosix() {
254 NetworkChangeNotifier::RemoveIPAddressObserver(this);
257 void AddressSorterPosix::Sort(const AddressList
& list
,
258 const CallbackType
& callback
) const {
259 DCHECK(CalledOnValidThread());
260 ScopedVector
<DestinationInfo
> sort_list
;
262 for (size_t i
= 0; i
< list
.size(); ++i
) {
263 scoped_ptr
<DestinationInfo
> info(new DestinationInfo());
264 info
->address
= list
[i
].address();
265 info
->scope
= GetScope(ipv4_scope_table_
, info
->address
);
266 info
->precedence
= GetPolicyValue(precedence_table_
, info
->address
);
267 info
->label
= GetPolicyValue(label_table_
, info
->address
);
269 // Each socket can only be bound once.
270 scoped_ptr
<DatagramClientSocket
> socket(
271 socket_factory_
->CreateDatagramClientSocket(
272 DatagramSocket::DEFAULT_BIND
,
277 // Even though no packets are sent, cannot use port 0 in Connect.
278 IPEndPoint
dest(info
->address
, 80 /* port */);
279 int rv
= socket
->Connect(dest
);
281 VLOG(1) << "Could not connect to " << dest
.ToStringWithoutPort()
285 // Filter out unusable destinations.
287 rv
= socket
->GetLocalAddress(&src
);
289 LOG(WARNING
) << "Could not get local address for "
290 << dest
.ToStringWithoutPort() << " reason " << rv
;
294 SourceAddressInfo
& src_info
= source_map_
[src
.address()];
295 if (src_info
.scope
== SCOPE_UNDEFINED
) {
296 // If |source_info_| is out of date, |src| might be missing, but we still
297 // want to sort, even though the HostCache will be cleared soon.
298 FillPolicy(src
.address(), &src_info
);
300 info
->src
= &src_info
;
302 if (info
->address
.size() == src
.address().size()) {
303 info
->common_prefix_length
= std::min(
304 CommonPrefixLength(info
->address
, src
.address()),
305 info
->src
->prefix_length
);
307 sort_list
.push_back(info
.Pass());
310 std::stable_sort(sort_list
.begin(), sort_list
.end(), CompareDestinations
);
313 for (size_t i
= 0; i
< sort_list
.size(); ++i
)
314 result
.push_back(IPEndPoint(sort_list
[i
]->address
, 0 /* port */));
316 callback
.Run(true, result
);
319 void AddressSorterPosix::OnIPAddressChanged() {
320 DCHECK(CalledOnValidThread());
322 #if defined(OS_LINUX)
323 const internal::AddressTrackerLinux
* tracker
=
324 NetworkChangeNotifier::GetAddressTracker();
327 typedef internal::AddressTrackerLinux::AddressMap AddressMap
;
328 AddressMap map
= tracker
->GetAddressMap();
329 for (AddressMap::const_iterator it
= map
.begin(); it
!= map
.end(); ++it
) {
330 const IPAddressNumber
& address
= it
->first
;
331 const struct ifaddrmsg
& msg
= it
->second
;
332 SourceAddressInfo
& info
= source_map_
[address
];
333 info
.native
= false; // TODO(szym): obtain this via netlink.
334 info
.deprecated
= msg
.ifa_flags
& IFA_F_DEPRECATED
;
335 info
.home
= msg
.ifa_flags
& IFA_F_HOMEADDRESS
;
336 info
.prefix_length
= msg
.ifa_prefixlen
;
337 FillPolicy(address
, &info
);
339 #elif defined(OS_MACOSX) || defined(OS_BSD)
340 // It's not clear we will receive notification when deprecated flag changes.
342 int ioctl_socket
= socket(AF_INET6
, SOCK_DGRAM
, 0);
343 if (ioctl_socket
< 0)
346 struct ifaddrs
* addrs
;
347 int rv
= getifaddrs(&addrs
);
349 LOG(WARNING
) << "getifaddrs failed " << rv
;
354 for (struct ifaddrs
* ifa
= addrs
; ifa
!= NULL
; ifa
= ifa
->ifa_next
) {
356 if (!src
.FromSockAddr(ifa
->ifa_addr
, ifa
->ifa_addr
->sa_len
))
358 SourceAddressInfo
& info
= source_map_
[src
.address()];
359 // Note: no known way to fill in |native| and |home|.
360 info
.native
= info
.home
= info
.deprecated
= false;
361 if (ifa
->ifa_addr
->sa_family
== AF_INET6
) {
362 struct in6_ifreq ifr
= {};
363 strncpy(ifr
.ifr_name
, ifa
->ifa_name
, sizeof(ifr
.ifr_name
) - 1);
364 DCHECK_LE(ifa
->ifa_addr
->sa_len
, sizeof(ifr
.ifr_ifru
.ifru_addr
));
365 memcpy(&ifr
.ifr_ifru
.ifru_addr
, ifa
->ifa_addr
, ifa
->ifa_addr
->sa_len
);
366 int rv
= ioctl(ioctl_socket
, SIOCGIFAFLAG_IN6
, &ifr
);
368 info
.deprecated
= ifr
.ifr_ifru
.ifru_flags
& IN6_IFF_DEPRECATED
;
370 LOG(WARNING
) << "SIOCGIFAFLAG_IN6 failed " << rv
;
373 if (ifa
->ifa_netmask
) {
375 if (netmask
.FromSockAddr(ifa
->ifa_netmask
, ifa
->ifa_addr
->sa_len
)) {
376 info
.prefix_length
= MaskPrefixLength(netmask
.address());
378 LOG(WARNING
) << "FromSockAddr failed on netmask";
381 FillPolicy(src
.address(), &info
);
388 void AddressSorterPosix::FillPolicy(const IPAddressNumber
& address
,
389 SourceAddressInfo
* info
) const {
390 DCHECK(CalledOnValidThread());
391 info
->scope
= GetScope(ipv4_scope_table_
, address
);
392 info
->label
= GetPolicyValue(label_table_
, address
);
396 scoped_ptr
<AddressSorter
> AddressSorter::CreateAddressSorter() {
397 return scoped_ptr
<AddressSorter
>(
398 new AddressSorterPosix(ClientSocketFactory::GetDefaultFactory()));