address_sorter_posix.cc revision f2477e01787aa58f445919b809d89e252beef54f
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. 4 5#include "net/dns/address_sorter_posix.h" 6 7#include <netinet/in.h> 8 9#if defined(OS_MACOSX) || defined(OS_BSD) 10#include <sys/socket.h> // Must be included before ifaddrs.h. 11#include <ifaddrs.h> 12#include <net/if.h> 13#include <netinet/in_var.h> 14#include <string.h> 15#include <sys/ioctl.h> 16#endif 17 18#include <algorithm> 19 20#include "base/logging.h" 21#include "base/memory/scoped_vector.h" 22#include "base/posix/eintr_wrapper.h" 23#include "net/socket/client_socket_factory.h" 24#include "net/udp/datagram_client_socket.h" 25 26#if defined(OS_LINUX) 27#include "net/base/address_tracker_linux.h" 28#endif 29 30namespace net { 31 32namespace { 33 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. 37 38// Returns true if |p1| should precede |p2| in the table. 39// Sorts table by decreasing prefix size to allow longest prefix matching. 40bool ComparePolicy(const AddressSorterPosix::PolicyEntry& p1, 41 const AddressSorterPosix::PolicyEntry& p2) { 42 return p1.prefix_length > p2.prefix_length; 43} 44 45// Creates sorted PolicyTable from |table| with |size| entries. 46AddressSorterPosix::PolicyTable LoadPolicy( 47 AddressSorterPosix::PolicyEntry* table, 48 size_t size) { 49 AddressSorterPosix::PolicyTable result(table, table + size); 50 std::sort(result.begin(), result.end(), ComparePolicy); 51 return result; 52} 53 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). 56unsigned 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)) 64 return entry.value; 65 } 66 NOTREACHED(); 67 // The last entry is the least restrictive, so assume it's default. 68 return table.back().value; 69} 70 71bool IsIPv6Multicast(const IPAddressNumber& address) { 72 DCHECK_EQ(kIPv6AddressSize, address.size()); 73 return address[0] == 0xFF; 74} 75 76AddressSorterPosix::AddressScope GetIPv6MulticastScope( 77 const IPAddressNumber& address) { 78 DCHECK_EQ(kIPv6AddressSize, address.size()); 79 return static_cast<AddressSorterPosix::AddressScope>(address[1] & 0x0F); 80} 81 82bool 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, 88 }; 89 return address == IPAddressNumber(kLoopback, kLoopback + kIPv6AddressSize); 90} 91 92bool IsIPv6LinkLocal(const IPAddressNumber& address) { 93 DCHECK_EQ(kIPv6AddressSize, address.size()); 94 // IN6_IS_ADDR_LINKLOCAL 95 return (address[0] == 0xFE) && ((address[1] & 0xC0) == 0x80); 96} 97 98bool IsIPv6SiteLocal(const IPAddressNumber& address) { 99 DCHECK_EQ(kIPv6AddressSize, address.size()); 100 // IN6_IS_ADDR_SITELOCAL 101 return (address[0] == 0xFE) && ((address[1] & 0xC0) == 0xC0); 102} 103 104AddressSorterPosix::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; 114 } else { 115 return AddressSorterPosix::SCOPE_GLOBAL; 116 } 117 } else if (address.size() == kIPv4AddressSize) { 118 return static_cast<AddressSorterPosix::AddressScope>( 119 GetPolicyValue(ipv4_scope_table, address)); 120 } else { 121 NOTREACHED(); 122 return AddressSorterPosix::SCOPE_NODELOCAL; 123 } 124} 125 126// Default policy table. RFC 3484, Section 2.1. 127AddressSorterPosix::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 }, 130 // ::/0 -- any 131 { { }, 0, 40 }, 132 // ::ffff:0:0/96 -- IPv4 mapped 133 { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xFF, 0xFF }, 96, 35 }, 134 // 2002::/16 -- 6to4 135 { { 0x20, 0x02, }, 16, 30 }, 136 // 2001::/32 -- Teredo 137 { { 0x20, 0x01, 0, 0 }, 32, 5 }, 138 // fc00::/7 -- unique local address 139 { { 0xFC }, 7, 3 }, 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 }, 146}; 147 148AddressSorterPosix::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 }, 151 // ::/0 -- any 152 { { }, 0, 1 }, 153 // ::ffff:0:0/96 -- IPv4 mapped 154 { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xFF, 0xFF }, 96, 4 }, 155 // 2002::/16 -- 6to4 156 { { 0x20, 0x02, }, 16, 2 }, 157 // 2001::/32 -- Teredo 158 { { 0x20, 0x01, 0, 0 }, 32, 5 }, 159 // fc00::/7 -- unique local address 160 { { 0xFC }, 7, 13 }, 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 }, 167}; 168 169// Default mapping of IPv4 addresses to scope. 170AddressSorterPosix::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 }, 176}; 177 178struct DestinationInfo { 179 IPAddressNumber address; 180 AddressSorterPosix::AddressScope scope; 181 unsigned precedence; 182 unsigned label; 183 const AddressSorterPosix::SourceAddressInfo* src; 184 unsigned common_prefix_length; 185}; 186 187// Returns true iff |dst_a| should precede |dst_b| in the address list. 188// RFC 3484, section 6. 189bool CompareDestinations(const DestinationInfo* dst_a, 190 const DestinationInfo* dst_b) { 191 // Rule 1: Avoid unusable destinations. 192 // Unusable destinations are already filtered out. 193 DCHECK(dst_a->src); 194 DCHECK(dst_b->src); 195 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) 200 return scope_match1; 201 202 // Rule 3: Avoid deprecated addresses. 203 if (dst_a->src->deprecated != dst_b->src->deprecated) 204 return !dst_a->src->deprecated; 205 206 // Rule 4: Prefer home addresses. 207 if (dst_a->src->home != dst_b->src->home) 208 return dst_a->src->home; 209 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) 214 return label_match1; 215 216 // Rule 6: Prefer higher precedence. 217 if (dst_a->precedence != dst_b->precedence) 218 return dst_a->precedence > dst_b->precedence; 219 220 // Rule 7: Prefer native transport. 221 if (dst_a->src->native != dst_b->src->native) 222 return dst_a->src->native; 223 224 // Rule 8: Prefer smaller scope. 225 if (dst_a->scope != dst_b->scope) 226 return dst_a->scope < dst_b->scope; 227 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; 232 } 233 234 // Rule 10: Leave the order unchanged. 235 // stable_sort takes care of that. 236 return false; 237} 238 239} // namespace 240 241AddressSorterPosix::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(); 251} 252 253AddressSorterPosix::~AddressSorterPosix() { 254 NetworkChangeNotifier::RemoveIPAddressObserver(this); 255} 256 257void AddressSorterPosix::Sort(const AddressList& list, 258 const CallbackType& callback) const { 259 DCHECK(CalledOnValidThread()); 260 ScopedVector<DestinationInfo> sort_list; 261 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); 268 269 // Each socket can only be bound once. 270 scoped_ptr<DatagramClientSocket> socket( 271 socket_factory_->CreateDatagramClientSocket( 272 DatagramSocket::DEFAULT_BIND, 273 RandIntCallback(), 274 NULL /* NetLog */, 275 NetLog::Source())); 276 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); 280 if (rv != OK) { 281 VLOG(1) << "Could not connect to " << dest.ToStringWithoutPort() 282 << " reason " << rv; 283 continue; 284 } 285 // Filter out unusable destinations. 286 IPEndPoint src; 287 rv = socket->GetLocalAddress(&src); 288 if (rv != OK) { 289 LOG(WARNING) << "Could not get local address for " 290 << dest.ToStringWithoutPort() << " reason " << rv; 291 continue; 292 } 293 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); 299 } 300 info->src = &src_info; 301 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); 306 } 307 sort_list.push_back(info.release()); 308 } 309 310 std::stable_sort(sort_list.begin(), sort_list.end(), CompareDestinations); 311 312 AddressList result; 313 for (size_t i = 0; i < sort_list.size(); ++i) 314 result.push_back(IPEndPoint(sort_list[i]->address, 0 /* port */)); 315 316 callback.Run(true, result); 317} 318 319void AddressSorterPosix::OnIPAddressChanged() { 320 DCHECK(CalledOnValidThread()); 321 source_map_.clear(); 322#if defined(OS_LINUX) 323 const internal::AddressTrackerLinux* tracker = 324 NetworkChangeNotifier::GetAddressTracker(); 325 if (!tracker) 326 return; 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); 338 } 339#elif defined(OS_MACOSX) || defined(OS_BSD) 340 // It's not clear we will receive notification when deprecated flag changes. 341 // Socket for ioctl. 342 int ioctl_socket = socket(AF_INET6, SOCK_DGRAM, 0); 343 if (ioctl_socket < 0) 344 return; 345 346 struct ifaddrs* addrs; 347 int rv = getifaddrs(&addrs); 348 if (rv < 0) { 349 LOG(WARNING) << "getifaddrs failed " << rv; 350 close(ioctl_socket); 351 return; 352 } 353 354 for (struct ifaddrs* ifa = addrs; ifa != NULL; ifa = ifa->ifa_next) { 355 IPEndPoint src; 356 if (!src.FromSockAddr(ifa->ifa_addr, ifa->ifa_addr->sa_len)) 357 continue; 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); 367 if (rv >= 0) { 368 info.deprecated = ifr.ifr_ifru.ifru_flags & IN6_IFF_DEPRECATED; 369 } else { 370 LOG(WARNING) << "SIOCGIFAFLAG_IN6 failed " << rv; 371 } 372 } 373 if (ifa->ifa_netmask) { 374 IPEndPoint netmask; 375 if (netmask.FromSockAddr(ifa->ifa_netmask, ifa->ifa_addr->sa_len)) { 376 info.prefix_length = MaskPrefixLength(netmask.address()); 377 } else { 378 LOG(WARNING) << "FromSockAddr failed on netmask"; 379 } 380 } 381 FillPolicy(src.address(), &info); 382 } 383 freeifaddrs(addrs); 384 close(ioctl_socket); 385#endif 386} 387 388void 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); 393} 394 395// static 396scoped_ptr<AddressSorter> AddressSorter::CreateAddressSorter() { 397 return scoped_ptr<AddressSorter>( 398 new AddressSorterPosix(ClientSocketFactory::GetDefaultFactory())); 399} 400 401} // namespace net 402 403