| 6 | * tree. An additional intellectual property rights grant can be found |
| 7 | * in the file PATENTS. All contributing project authors may |
| 8 | * be found in the AUTHORS file in the root of the source tree. |
| 9 | */ |
| 10 |
| 11 | #include "rtc_base/network.h" |
| 12 |
| 13 | #include "absl/strings/string_view.h" |
| 14 | #include "rtc_base/experiments/field_trial_parser.h" |
| 15 |
| 16 | #if defined(WEBRTC_POSIX) |
| 17 | #include <net/if.h> |
| 18 | #endif // WEBRTC_POSIX |
| 19 |
| 20 | #if defined(WEBRTC_WIN) |
| 21 | #include <iphlpapi.h> |
| 22 |
| 23 | #include "rtc_base/win32.h" |
| 24 | #elif !defined(__native_client__) |
| 25 | #include "rtc_base/ifaddrs_converter.h" |
| 26 | #endif |
| 27 |
| 28 | #include <memory> |
| 29 |
| 30 | #include "absl/algorithm/container.h" |
| 31 | #include "absl/memory/memory.h" |
| 32 | #include "absl/strings/match.h" |
| 33 | #include "absl/strings/string_view.h" |
| 34 | #include "api/task_queue/pending_task_safety_flag.h" |
| 35 | #include "api/transport/field_trial_based_config.h" |
| 36 | #include "api/units/time_delta.h" |
| 37 | #include "rtc_base/checks.h" |
| 38 | #include "rtc_base/logging.h" |
| 39 | #include "rtc_base/memory/always_valid_pointer.h" |
| 40 | #include "rtc_base/network_monitor.h" |
| 41 | #include "rtc_base/socket.h" // includes something that makes windows happy |
| 42 | #include "rtc_base/string_encode.h" |
| 43 | #include "rtc_base/string_utils.h" |
| 44 | #include "rtc_base/strings/string_builder.h" |
| 45 | #include "rtc_base/thread.h" |
| 46 |
| 47 | namespace rtc { |
| 48 | namespace { |
| 49 | using ::webrtc::SafeTask; |
| 50 | using ::webrtc::TimeDelta; |
| 51 |
| 52 | // List of MAC addresses of known VPN (for windows). |
| 53 | constexpr uint8_t kVpns[3][6] = { |
| 54 | // Cisco AnyConnect SSL VPN Client. |
| 55 | {0x0, 0x5, 0x9A, 0x3C, 0x7A, 0x0}, |
| 56 | // Cisco AnyConnect IPSEC VPN Client. |
| 57 | {0x0, 0x5, 0x9A, 0x3C, 0x78, 0x0}, |
| 58 | // GlobalProtect Virtual Ethernet. |
| 59 | {0x2, 0x50, 0x41, 0x0, 0x0, 0x1}, |
| 60 | }; |
| 61 |
| 62 | // Fetch list of networks every two seconds. |
| 63 | const int kNetworksUpdateIntervalMs = 2000; |
| 64 |
| 65 | const int kHighestNetworkPreference = 127; |
| 66 |
| 67 | struct AddressList { |
| 68 | std::unique_ptr<Network> net; |
| 69 | std::vector<InterfaceAddress> ips; |
| 70 | }; |
| 71 |
| 72 | bool SortNetworks(const Network* a, const Network* b) { |
| 73 | // Network types will be preferred above everything else while sorting |
| 74 | // Networks. |
| 75 |
| 76 | // Networks are sorted first by type. |
| 77 | if (a->type() != b->type()) { |
| 78 | return a->type() < b->type(); |
| 79 | } |
| 80 |
| 81 | IPAddress ip_a = a->GetBestIP(); |
| 82 | IPAddress ip_b = b->GetBestIP(); |
| 83 |
| 84 | // After type, networks are sorted by IP address precedence values |
| 85 | // from RFC 3484-bis |
| 86 | if (IPAddressPrecedence(ip_a) != IPAddressPrecedence(ip_b)) { |
| 87 | return IPAddressPrecedence(ip_a) > IPAddressPrecedence(ip_b); |
| 88 | } |
| 89 |
| 90 | // TODO(mallinath) - Add VPN and Link speed conditions while sorting. |
| 91 |
| 92 | // Networks are sorted last by key. |
| 93 | return a->key() < b->key(); |
| 94 | } |
| 95 |
| 96 | uint16_t ComputeNetworkCostByType(int type, |
| 97 | bool is_vpn, |
| 98 | bool use_differentiated_cellular_costs, |
| 99 | bool add_network_cost_to_vpn) { |
| 100 | // TODO(jonaso) : Rollout support for cellular network cost using A/B |
| 101 | // experiment to make sure it does not introduce regressions. |
| 102 | int vpnCost = (is_vpn && add_network_cost_to_vpn) ? kNetworkCostVpn : 0; |
| 103 | switch (type) { |
| 104 | case rtc::ADAPTER_TYPE_ETHERNET: |
| 105 | case rtc::ADAPTER_TYPE_LOOPBACK: |
| 106 | return kNetworkCostMin + vpnCost; |
| 107 | case rtc::ADAPTER_TYPE_WIFI: |
| 108 | return kNetworkCostLow + vpnCost; |
| 109 | case rtc::ADAPTER_TYPE_CELLULAR: |
| 110 | return kNetworkCostCellular + vpnCost; |
| 111 | case rtc::ADAPTER_TYPE_CELLULAR_2G: |
| 112 | return (use_differentiated_cellular_costs ? kNetworkCostCellular2G |
| 113 | : kNetworkCostCellular) + |
| 114 | vpnCost; |
| 115 | case rtc::ADAPTER_TYPE_CELLULAR_3G: |
| 116 | return (use_differentiated_cellular_costs ? kNetworkCostCellular3G |
| 117 | : kNetworkCostCellular) + |
| 118 | vpnCost; |
| 119 | case rtc::ADAPTER_TYPE_CELLULAR_4G: |
| 120 | return (use_differentiated_cellular_costs ? kNetworkCostCellular4G |
| 121 | : kNetworkCostCellular) + |
| 122 | vpnCost; |
| 123 | case rtc::ADAPTER_TYPE_CELLULAR_5G: |
| 124 | return (use_differentiated_cellular_costs ? kNetworkCostCellular5G |
| 125 | : kNetworkCostCellular) + |
| 126 | vpnCost; |
| 127 | case rtc::ADAPTER_TYPE_ANY: |
| 128 | // Candidates gathered from the any-address/wildcard ports, as backups, |
| 129 | // are given the maximum cost so that if there are other candidates with |
| 130 | // known interface types, we would not select candidate pairs using these |
| 131 | // backup candidates if other selection criteria with higher precedence |
| 132 | // (network conditions over the route) are the same. Note that setting the |
| 133 | // cost to kNetworkCostUnknown would be problematic since |
| 134 | // ADAPTER_TYPE_CELLULAR would then have a higher cost. See |
| 135 | // P2PTransportChannel::SortConnectionsAndUpdateState for how we rank and |
| 136 | // select candidate pairs, where the network cost is among the criteria. |
| 137 | return kNetworkCostMax + vpnCost; |
| 138 | case rtc::ADAPTER_TYPE_VPN: |
| 139 | // The cost of a VPN should be computed using its underlying network type. |
| 140 | RTC_DCHECK_NOTREACHED(); |
| 141 | return kNetworkCostUnknown; |
| 142 | default: |
| 143 | return kNetworkCostUnknown + vpnCost; |
| 144 | } |
| 145 | } |
| 146 |
| 147 | #if !defined(__native_client__) |
| 148 | bool IsIgnoredIPv6(bool allow_mac_based_ipv6, const InterfaceAddress& ip) { |
| 149 | if (ip.family() != AF_INET6) { |
| 150 | return false; |
| 151 | } |
| 152 |
| 153 | // Link-local addresses require scope id to be bound successfully. |
| 154 | // However, our IPAddress structure doesn't carry that so the |
| 155 | // information is lost and causes binding failure. |
| 156 | if (IPIsLinkLocal(ip)) { |
| 157 | RTC_LOG(LS_VERBOSE) << "Ignore link local IP:" << ip.ToSensitiveString(); |
| 158 | return true; |
| 159 | } |
| 160 |
| 161 | // Any MAC based IPv6 should be avoided to prevent the MAC tracking. |
| 162 | if (IPIsMacBased(ip) && !allow_mac_based_ipv6) { |
| 163 | RTC_LOG(LS_INFO) << "Ignore Mac based IP:" << ip.ToSensitiveString(); |
| 164 | return true; |
| 165 | } |
| 166 |
| 167 | // Ignore deprecated IPv6. |
| 168 | if (ip.ipv6_flags() & IPV6_ADDRESS_FLAG_DEPRECATED) { |
| 169 | RTC_LOG(LS_INFO) << "Ignore deprecated IP:" << ip.ToSensitiveString(); |
| 170 | return true; |
| 171 | } |
| 172 |
| 173 | return false; |
| 174 | } |
| 175 | #endif // !defined(__native_client__) |
| 176 |
| 177 | // Note: consider changing to const Network* as arguments |
| 178 | // if/when considering other changes that should not trigger |
| 179 | // OnNetworksChanged. |
| 180 | bool ShouldAdapterChangeTriggerNetworkChange(rtc::AdapterType old_type, |
| 181 | rtc::AdapterType new_type) { |
| 182 | // skip triggering OnNetworksChanged if |
| 183 | // changing from one cellular to another. |
| 184 | if (Network::IsCellular(old_type) && Network::IsCellular(new_type)) |
| 185 | return false; |
| 186 | return true; |
| 187 | } |
| 188 |
| 189 | #if defined(WEBRTC_WIN) |
| 190 | bool IpAddressAttributesEnabled(const webrtc::FieldTrialsView* field_trials) { |
| 191 | // Field trial key reserved in bugs.webrtc.org/14334 |
| 192 | if (field_trials && |
| 193 | field_trials->IsEnabled("WebRTC-IPv6NetworkResolutionFixes")) { |
| 194 | webrtc::FieldTrialParameter<bool> ip_address_attributes_enabled( |
| 195 | "IpAddressAttributesEnabled", false); |
| 196 | webrtc::ParseFieldTrial( |
| 197 | {&ip_address_attributes_enabled}, |
| 198 | field_trials->Lookup("WebRTC-IPv6NetworkResolutionFixes")); |
| 199 | return ip_address_attributes_enabled; |
| 200 | } |
| 201 | return false; |
| 202 | } |
| 203 | #endif // WEBRTC_WIN |
| 204 |
| 205 | } // namespace |
| 206 |
| 207 | // These addresses are used as the targets to find out the default local address |
| 208 | // on a multi-homed endpoint. They are actually DNS servers. |
| 209 | const char kPublicIPv4Host[] = "8.8.8.8"; |
| 210 | const char kPublicIPv6Host[] = "2001:4860:4860::8888"; |
| 211 | const int kPublicPort = 53; // DNS port. |
| 212 |
| 213 | namespace webrtc_network_internal { |
| 214 | bool CompareNetworks(const std::unique_ptr<Network>& a, |
| 215 | const std::unique_ptr<Network>& b) { |
| 216 | if (a->prefix_length() != b->prefix_length()) { |
| 217 | return a->prefix_length() < b->prefix_length(); |
| 218 | } |
| 219 | if (a->name() != b->name()) { |
| 220 | return a->name() < b->name(); |
| 221 | } |
| 222 | return a->prefix() < b->prefix(); |
| 223 | } |
| 224 | } // namespace webrtc_network_internal |
| 225 |
| 226 | std::string MakeNetworkKey(absl::string_view name, |
| 227 | const IPAddress& prefix, |
| 228 | int prefix_length) { |
| 229 | rtc::StringBuilder ost; |
| 230 | ost << name << "%" << prefix.ToString() << "/" << prefix_length; |
| 231 | return ost.Release(); |
| 232 | } |
| 233 | // Test if the network name matches the type<number> pattern, e.g. eth0. The |
| 234 | // matching is case-sensitive. |
| 235 | bool MatchTypeNameWithIndexPattern(absl::string_view network_name, |
| 236 | absl::string_view type_name) { |
| 237 | if (!absl::StartsWith(network_name, type_name)) { |
| 238 | return false; |
| 239 | } |
| 240 | return absl::c_none_of(network_name.substr(type_name.size()), |
| 241 | [](char c) { return !isdigit(c); }); |
| 242 | } |
| 243 |
| 244 | // A cautious note that this method may not provide an accurate adapter type |
| 245 | // based on the string matching. Incorrect type of adapters can affect the |
| 246 | // result of the downstream network filtering, see e.g. |
| 247 | // BasicPortAllocatorSession::GetNetworks when |
| 248 | // PORTALLOCATOR_DISABLE_COSTLY_NETWORKS is turned on. |
| 249 | AdapterType GetAdapterTypeFromName(absl::string_view network_name) { |
| 250 | if (MatchTypeNameWithIndexPattern(network_name, "lo")) { |
| 251 | // Note that we have a more robust way to determine if a network interface |
| 252 | // is a loopback interface by checking the flag IFF_LOOPBACK in ifa_flags of |
| 253 | // an ifaddr struct. See ConvertIfAddrs in this file. |
| 254 | return ADAPTER_TYPE_LOOPBACK; |
| 255 | } |
| 256 |
| 257 | if (MatchTypeNameWithIndexPattern(network_name, "eth")) { |
| 258 | return ADAPTER_TYPE_ETHERNET; |
| 259 | } |
| 260 |
| 261 | if (MatchTypeNameWithIndexPattern(network_name, "wlan") || |
| 262 | MatchTypeNameWithIndexPattern(network_name, "v4-wlan")) { |
| 263 | return ADAPTER_TYPE_WIFI; |
| 264 | } |
| 265 |
| 266 | if (MatchTypeNameWithIndexPattern(network_name, "ipsec") || |
| 267 | MatchTypeNameWithIndexPattern(network_name, "tun") || |
| 268 | MatchTypeNameWithIndexPattern(network_name, "utun") || |
| 269 | MatchTypeNameWithIndexPattern(network_name, "tap")) { |
| 270 | return ADAPTER_TYPE_VPN; |
| 271 | } |
| 272 | #if defined(WEBRTC_IOS) |
| 273 | // Cell networks are pdp_ipN on iOS. |
| 274 | if (MatchTypeNameWithIndexPattern(network_name, "pdp_ip")) { |
| 275 | return ADAPTER_TYPE_CELLULAR; |
| 276 | } |
| 277 | if (MatchTypeNameWithIndexPattern(network_name, "en")) { |
| 278 | // This may not be most accurate because sometimes Ethernet interface |
| 279 | // name also starts with "en" but it is better than showing it as |
| 280 | // "unknown" type. |
| 281 | // TODO(honghaiz): Write a proper IOS network manager. |
| 282 | return ADAPTER_TYPE_WIFI; |
| 283 | } |
| 284 | #elif defined(WEBRTC_ANDROID) |
| 285 | if (MatchTypeNameWithIndexPattern(network_name, "rmnet") || |
| 286 | MatchTypeNameWithIndexPattern(network_name, "rmnet_data") || |
| 287 | MatchTypeNameWithIndexPattern(network_name, "v4-rmnet") || |
| 288 | MatchTypeNameWithIndexPattern(network_name, "v4-rmnet_data") || |
| 289 | MatchTypeNameWithIndexPattern(network_name, "clat") || |
| 290 | MatchTypeNameWithIndexPattern(network_name, "ccmni")) { |
| 291 | return ADAPTER_TYPE_CELLULAR; |
| 292 | } |
| 293 | #endif |
| 294 |
| 295 | return ADAPTER_TYPE_UNKNOWN; |
| 296 | } |
| 297 |
| 298 | NetworkManager::EnumerationPermission NetworkManager::enumeration_permission() |
| 299 | const { |
| 300 | return ENUMERATION_ALLOWED; |
| 301 | } |
| 302 |
| 303 | bool NetworkManager::GetDefaultLocalAddress(int family, IPAddress* addr) const { |
| 304 | return false; |
| 305 | } |
| 306 |
| 307 | webrtc::MdnsResponderInterface* NetworkManager::GetMdnsResponder() const { |
| 308 | return nullptr; |
| 309 | } |
| 310 |
| 311 | NetworkManagerBase::NetworkManagerBase( |
| 312 | const webrtc::FieldTrialsView* field_trials) |
| 313 | : field_trials_(field_trials), |
| 314 | enumeration_permission_(NetworkManager::ENUMERATION_ALLOWED), |
| 315 | signal_network_preference_change_( |
| 316 | field_trials |
| 317 | ? field_trials->IsEnabled("WebRTC-SignalNetworkPreferenceChange") |
| 318 | : false) {} |
| 319 |
| 320 | NetworkManager::EnumerationPermission |
| 321 | NetworkManagerBase::enumeration_permission() const { |
| 322 | return enumeration_permission_; |
| 323 | } |
| 324 |
| 325 | std::unique_ptr<Network> NetworkManagerBase::CreateNetwork( |
| 326 | absl::string_view name, |
| 327 | absl::string_view description, |
| 328 | const IPAddress& prefix, |
| 329 | int prefix_length, |
| 330 | AdapterType type) const { |
| 331 | return std::make_unique<Network>(name, description, prefix, prefix_length, |
| 332 | type); |
| 333 | } |
| 334 |
| 335 | std::vector<const Network*> NetworkManagerBase::GetAnyAddressNetworks() { |
| 336 | std::vector<const Network*> networks; |
| 337 | if (!ipv4_any_address_network_) { |
| 338 | const rtc::IPAddress ipv4_any_address(INADDR_ANY); |
| 339 | ipv4_any_address_network_ = |
| 340 | CreateNetwork("any", "any", ipv4_any_address, 0, ADAPTER_TYPE_ANY); |
| 341 | ipv4_any_address_network_->set_default_local_address_provider(this); |
| 342 | ipv4_any_address_network_->set_mdns_responder_provider(this); |
| 343 | ipv4_any_address_network_->AddIP(ipv4_any_address); |
| 344 | } |
| 345 | networks.push_back(ipv4_any_address_network_.get()); |
| 346 |
| 347 | if (!ipv6_any_address_network_) { |
| 348 | const rtc::IPAddress ipv6_any_address(in6addr_any); |
| 349 | ipv6_any_address_network_ = |
| 350 | CreateNetwork("any", "any", ipv6_any_address, 0, ADAPTER_TYPE_ANY); |
| 351 | ipv6_any_address_network_->set_default_local_address_provider(this); |
| 352 | ipv6_any_address_network_->set_mdns_responder_provider(this); |
| 353 | ipv6_any_address_network_->AddIP(ipv6_any_address); |
| 354 | } |
| 355 | networks.push_back(ipv6_any_address_network_.get()); |
| 356 | return networks; |
| 357 | } |
| 358 |
| 359 | std::vector<const Network*> NetworkManagerBase::GetNetworks() const { |
| 360 | std::vector<const Network*> result; |
| 361 | result.insert(result.begin(), networks_.begin(), networks_.end()); |
| 362 | return result; |
| 363 | } |
| 364 |
| 365 | void NetworkManagerBase::MergeNetworkList( |
| 366 | std::vector<std::unique_ptr<Network>> new_networks, |
| 367 | bool* changed) { |
| 368 | NetworkManager::Stats stats; |
| 369 | MergeNetworkList(std::move(new_networks), changed, &stats); |
| 370 | } |
| 371 |
| 372 | void NetworkManagerBase::MergeNetworkList( |
| 373 | std::vector<std::unique_ptr<Network>> new_networks, |
| 374 | bool* changed, |
| 375 | NetworkManager::Stats* stats) { |
| 376 | *changed = false; |
| 377 | // AddressList in this map will track IP addresses for all Networks |
| 378 | // with the same key. |
| 379 | std::map<std::string, AddressList> consolidated_address_list; |
| 380 | absl::c_sort(new_networks, rtc::webrtc_network_internal::CompareNetworks); |
| 381 | // First, build a set of network-keys to the ipaddresses. |
| 382 | for (auto& network : new_networks) { |
| 383 | bool might_add_to_merged_list = false; |
| 384 | std::string key = MakeNetworkKey(network->name(), network->prefix(), |
| 385 | network->prefix_length()); |
| 386 | const std::vector<InterfaceAddress>& addresses = network->GetIPs(); |
| 387 | if (consolidated_address_list.find(key) == |
| 388 | consolidated_address_list.end()) { |
| 389 | AddressList addrlist; |
| 390 | addrlist.net = std::move(network); |
| 391 | consolidated_address_list[key] = std::move(addrlist); |
| 392 | might_add_to_merged_list = true; |
| 393 | } |
| 394 | AddressList& current_list = consolidated_address_list[key]; |
| 395 | for (const InterfaceAddress& address : addresses) { |
| 396 | current_list.ips.push_back(address); |
| 397 | } |
| 398 | if (might_add_to_merged_list) { |
| 399 | if (current_list.ips[0].family() == AF_INET) { |
| 400 | stats->ipv4_network_count++; |
| 401 | } else { |
| 402 | RTC_DCHECK(current_list.ips[0].family() == AF_INET6); |
| 403 | stats->ipv6_network_count++; |
| 404 | } |
| 405 | } |
| 406 | } |
| 407 |
| 408 | // Next, look for existing network objects to re-use. |
| 409 | // Result of Network merge. Element in this list should have unique key. |
| 410 | std::vector<Network*> merged_list; |
| 411 | for (auto& kv : consolidated_address_list) { |
| 412 | const std::string& key = kv.first; |
| 413 | std::unique_ptr<Network> net = std::move(kv.second.net); |
| 414 | auto existing = networks_map_.find(key); |
| 415 | if (existing == networks_map_.end()) { |
| 416 | // This network is new. |
| 417 | net->set_id(next_available_network_id_++); |
| 418 | // We might have accumulated IPAddresses from the first |
| 419 | // step, set it here. |
| 420 | net->SetIPs(kv.second.ips, true); |
| 421 | // Place it in the network map. |
| 422 | merged_list.push_back(net.get()); |
| 423 | networks_map_[key] = std::move(net); |
| 424 | *changed = true; |
| 425 | } else { |
| 426 | // This network exists in the map already. Reset its IP addresses. |
| 427 | Network* existing_net = existing->second.get(); |
| 428 | *changed = existing_net->SetIPs(kv.second.ips, *changed); |
| 429 | merged_list.push_back(existing_net); |
| 430 | if (net->type() != ADAPTER_TYPE_UNKNOWN && |
| 431 | net->type() != existing_net->type()) { |
| 432 | if (ShouldAdapterChangeTriggerNetworkChange(existing_net->type(), |
| 433 | net->type())) { |
| 434 | *changed = true; |
| 435 | } |
| 436 | existing_net->set_type(net->type()); |
| 437 | } |
| 438 | // If the existing network was not active, networks have changed. |
| 439 | if (!existing_net->active()) { |
| 440 | *changed = true; |
| 441 | } |
| 442 | if (net->network_preference() != existing_net->network_preference()) { |
| 443 | existing_net->set_network_preference(net->network_preference()); |
| 444 | if (signal_network_preference_change_) { |
| 445 | *changed = true; |
| 446 | } |
| 447 | } |
| 448 | RTC_DCHECK(net->active()); |
| 449 | } |
| 450 | networks_map_[key]->set_mdns_responder_provider(this); |
| 451 | } |
| 452 | // It may still happen that the merged list is a subset of `networks_`. |
| 453 | // To detect this change, we compare their sizes. |
| 454 | if (merged_list.size() != networks_.size()) { |
| 455 | *changed = true; |
| 456 | } |
| 457 |
| 458 | // If the network list changes, we re-assign `networks_` to the merged list |
| 459 | // and re-sort it. |
| 460 | if (*changed) { |
| 461 | networks_ = merged_list; |
| 462 | // Reset the active states of all networks. |
| 463 | for (const auto& kv : networks_map_) { |
| 464 | const std::unique_ptr<Network>& network = kv.second; |
| 465 | // If `network` is in the newly generated `networks_`, it is active. |
| 466 | bool found = absl::c_linear_search(networks_, network.get()); |
| 467 | network->set_active(found); |
| 468 | } |
| 469 | absl::c_sort(networks_, SortNetworks); |
| 470 | // Now network interfaces are sorted, we should set the preference value |
| 471 | // for each of the interfaces we are planning to use. |
| 472 | // Preference order of network interfaces might have changed from previous |
| 473 | // sorting due to addition of higher preference network interface. |
| 474 | // Since we have already sorted the network interfaces based on our |
| 475 | // requirements, we will just assign a preference value starting with 127, |
| 476 | // in decreasing order. |
| 477 | int pref = kHighestNetworkPreference; |
| 478 | for (Network* network : networks_) { |
| 479 | network->set_preference(pref); |
| 480 | if (pref > 0) { |
| 481 | --pref; |
| 482 | } else { |
| 483 | RTC_LOG(LS_ERROR) << "Too many network interfaces to handle!"; |
| 484 | break; |
| 485 | } |
| 486 | } |
| 487 | } |
| 488 | } |
| 489 |
| 490 | void NetworkManagerBase::set_default_local_addresses(const IPAddress& ipv4, |
| 491 | const IPAddress& ipv6) { |
| 492 | if (ipv4.family() == AF_INET) { |
| 493 | default_local_ipv4_address_ = ipv4; |
| 494 | } |
| 495 | if (ipv6.family() == AF_INET6) { |
| 496 | default_local_ipv6_address_ = ipv6; |
| 497 | } |
| 498 | } |
| 499 |
| 500 | bool NetworkManagerBase::GetDefaultLocalAddress(int family, |
| 501 | IPAddress* ipaddr) const { |
| 502 | if (family == AF_INET && !default_local_ipv4_address_.IsNil()) { |
| 503 | *ipaddr = default_local_ipv4_address_; |
| 504 | return true; |
| 505 | } else if (family == AF_INET6 && !default_local_ipv6_address_.IsNil()) { |
| 506 | Network* ipv6_network = GetNetworkFromAddress(default_local_ipv6_address_); |
| 507 | if (ipv6_network) { |
| 508 | // If the default ipv6 network's BestIP is different than |
| 509 | // default_local_ipv6_address_, use it instead. |
| 510 | // This is to prevent potential IP address leakage. See WebRTC bug 5376. |
| 511 | *ipaddr = ipv6_network->GetBestIP(); |
| 512 | } else { |
| 513 | *ipaddr = default_local_ipv6_address_; |
| 514 | } |
| 515 | return true; |
| 516 | } |
| 517 | return false; |
| 518 | } |
| 519 |
| 520 | Network* NetworkManagerBase::GetNetworkFromAddress( |
| 521 | const rtc::IPAddress& ip) const { |
| 522 | for (Network* network : networks_) { |
| 523 | const auto& ips = network->GetIPs(); |
| 524 | if (absl::c_any_of(ips, [&](const InterfaceAddress& existing_ip) { |
| 525 | return ip == static_cast<rtc::IPAddress>(existing_ip); |
| 526 | })) { |
| 527 | return network; |
| 528 | } |
| 529 | } |
| 530 | return nullptr; |
| 531 | } |
| 532 |
| 533 | bool NetworkManagerBase::IsVpnMacAddress( |
| 534 | rtc::ArrayView<const uint8_t> address) { |
| 535 | if (address.data() == nullptr && address.size() == 0) { |
| 536 | return false; |
| 537 | } |
| 538 | for (const auto& vpn : kVpns) { |
| 539 | if (sizeof(vpn) == address.size() && |
| 540 | memcmp(vpn, address.data(), address.size()) == 0) { |
| 541 | return true; |
| 542 | } |
| 543 | } |
| 544 | return false; |
| 545 | } |
| 546 |
| 547 | BasicNetworkManager::BasicNetworkManager( |
| 548 | NetworkMonitorFactory* network_monitor_factory, |
| 549 | SocketFactory* socket_factory, |
| 550 | const webrtc::FieldTrialsView* field_trials_view) |
| 551 | : NetworkManagerBase(field_trials_view), |
| 552 | field_trials_(field_trials_view), |
| 553 | network_monitor_factory_(network_monitor_factory), |
| 554 | socket_factory_(socket_factory), |
| 555 | allow_mac_based_ipv6_( |
| 556 | field_trials()->IsEnabled("WebRTC-AllowMACBasedIPv6")), |
| 557 | bind_using_ifname_( |
| 558 | !field_trials()->IsDisabled("WebRTC-BindUsingInterfaceName")) { |
| 559 | RTC_DCHECK(socket_factory_); |
| 560 | } |
| 561 |
| 562 | BasicNetworkManager::~BasicNetworkManager() { |
| 563 | if (task_safety_flag_) { |
| 564 | task_safety_flag_->SetNotAlive(); |
| 565 | } |
| 566 | } |
| 567 |
| 568 | void BasicNetworkManager::OnNetworksChanged() { |
| 569 | RTC_DCHECK_RUN_ON(thread_); |
| 570 | RTC_LOG(LS_INFO) << "Network change was observed"; |
| 571 | UpdateNetworksOnce(); |
| 572 | } |
| 573 |
| 574 | #if defined(__native_client__) |
| 575 |
| 576 | bool BasicNetworkManager::CreateNetworks( |
| 577 | bool include_ignored, |
| 578 | std::vector<std::unique_ptr<Network>>* networks) const { |
| 579 | RTC_DCHECK_NOTREACHED(); |
| 580 | RTC_LOG(LS_WARNING) << "BasicNetworkManager doesn't work on NaCl yet"; |
| 581 | return false; |
| 582 | } |
| 583 |
| 584 | #elif defined(WEBRTC_POSIX) |
| 585 | NetworkMonitorInterface::InterfaceInfo BasicNetworkManager::GetInterfaceInfo( |
| 586 | struct ifaddrs* cursor) const { |
| 587 | if (cursor->ifa_flags & IFF_LOOPBACK) { |
| 588 | return { |
| 589 | .adapter_type = ADAPTER_TYPE_LOOPBACK, |
| 590 | .underlying_type_for_vpn = ADAPTER_TYPE_UNKNOWN, |
| 591 | .network_preference = NetworkPreference::NEUTRAL, |
| 592 | .available = true, |
| 593 | }; |
| 594 | } else if (network_monitor_) { |
| 595 | return network_monitor_->GetInterfaceInfo(cursor->ifa_name); |
| 596 | } else { |
| 597 | return {.adapter_type = GetAdapterTypeFromName(cursor->ifa_name), |
| 598 | .underlying_type_for_vpn = ADAPTER_TYPE_UNKNOWN, |
| 599 | .network_preference = NetworkPreference::NEUTRAL, |
| 600 | .available = true}; |
| 601 | } |
| 602 | } |
| 603 |
| 604 | void BasicNetworkManager::ConvertIfAddrs( |
| 605 | struct ifaddrs* interfaces, |
| 606 | IfAddrsConverter* ifaddrs_converter, |
| 607 | bool include_ignored, |
| 608 | std::vector<std::unique_ptr<Network>>* networks) const { |
| 609 | std::map<std::string, Network*> current_networks; |
| 610 |
| 611 | for (struct ifaddrs* cursor = interfaces; cursor != nullptr; |
| 612 | cursor = cursor->ifa_next) { |
| 613 | IPAddress prefix; |
| 614 | IPAddress mask; |
| 615 | InterfaceAddress ip; |
| 616 | int scope_id = 0; |
| 617 |
| 618 | // Some interfaces may not have address assigned. |
| 619 | if (!cursor->ifa_addr || !cursor->ifa_netmask) { |
| 620 | continue; |
| 621 | } |
| 622 | // Skip unknown family. |
| 623 | if (cursor->ifa_addr->sa_family != AF_INET && |
| 624 | cursor->ifa_addr->sa_family != AF_INET6) { |
| 625 | continue; |
| 626 | } |
| 627 | // Convert to InterfaceAddress. |
| 628 | // TODO(webrtc:13114): Convert ConvertIfAddrs to use rtc::Netmask. |
| 629 | if (!ifaddrs_converter->ConvertIfAddrsToIPAddress(cursor, &ip, &mask)) { |
| 630 | continue; |
| 631 | } |
| 632 | // Skip ones which are down. |
| 633 | if (!(cursor->ifa_flags & IFF_RUNNING)) { |
| 634 | RTC_LOG(LS_INFO) << "Skip interface because of not IFF_RUNNING: " |
| 635 | << ip.ToSensitiveString(); |
| 636 | continue; |
| 637 | } |
| 638 |
| 639 | // Special case for IPv6 address. |
| 640 | if (cursor->ifa_addr->sa_family == AF_INET6) { |
| 641 | if (IsIgnoredIPv6(allow_mac_based_ipv6_, ip)) { |
| 642 | continue; |
| 643 | } |
| 644 | scope_id = |
| 645 | reinterpret_cast<sockaddr_in6*>(cursor->ifa_addr)->sin6_scope_id; |
| 646 | } |
| 647 |
| 648 | int prefix_length = CountIPMaskBits(mask); |
| 649 | prefix = TruncateIP(ip, prefix_length); |
| 650 | std::string key = |
| 651 | MakeNetworkKey(std::string(cursor->ifa_name), prefix, prefix_length); |
| 652 |
| 653 | auto iter = current_networks.find(key); |
| 654 | if (iter != current_networks.end()) { |
| 655 | // We have already added this network, simply add extra IP. |
| 656 | iter->second->AddIP(ip); |
| 657 | #if RTC_DCHECK_IS_ON |
| 658 | // Validate that different IP of same network has same properties |
| 659 | auto existing_network = iter->second; |
| 660 |
| 661 | NetworkMonitorInterface::InterfaceInfo if_info = GetInterfaceInfo(cursor); |
| 662 | if (if_info.adapter_type != ADAPTER_TYPE_VPN && |
| 663 | IsConfiguredVpn(prefix, prefix_length)) { |
| 664 | if_info.underlying_type_for_vpn = if_info.adapter_type; |
| 665 | if_info.adapter_type = ADAPTER_TYPE_VPN; |
| 666 | } |
| 667 |
| 668 | RTC_DCHECK(existing_network->type() == if_info.adapter_type); |
| 669 | RTC_DCHECK(existing_network->underlying_type_for_vpn() == |
| 670 | if_info.underlying_type_for_vpn); |
| 671 | RTC_DCHECK(existing_network->network_preference() == |
| 672 | if_info.network_preference); |
| 673 | if (!if_info.available) { |
| 674 | RTC_DCHECK(existing_network->ignored()); |
| 675 | } |
| 676 | #endif // RTC_DCHECK_IS_ON |
| 677 | continue; |
| 678 | } |
| 679 |
| 680 | // Create a new network. |
| 681 | NetworkMonitorInterface::InterfaceInfo if_info = GetInterfaceInfo(cursor); |
| 682 |
| 683 | // Check manually configured VPN override. |
| 684 | if (if_info.adapter_type != ADAPTER_TYPE_VPN && |
| 685 | IsConfiguredVpn(prefix, prefix_length)) { |
| 686 | if_info.underlying_type_for_vpn = if_info.adapter_type; |
| 687 | if_info.adapter_type = ADAPTER_TYPE_VPN; |
| 688 | } |
| 689 |
| 690 | auto network = CreateNetwork(cursor->ifa_name, cursor->ifa_name, prefix, |
| 691 | prefix_length, if_info.adapter_type); |
| 692 | network->set_default_local_address_provider(this); |
| 693 | network->set_scope_id(scope_id); |
| 694 | network->AddIP(ip); |
| 695 | if (!if_info.available) { |
| 696 | network->set_ignored(true); |
| 697 | } else { |
| 698 | network->set_ignored(IsIgnoredNetwork(*network)); |
| 699 | } |
| 700 | network->set_underlying_type_for_vpn(if_info.underlying_type_for_vpn); |
| 701 | network->set_network_preference(if_info.network_preference); |
| 702 | if (include_ignored || !network->ignored()) { |
| 703 | current_networks[key] = network.get(); |
| 704 | networks->push_back(std::move(network)); |
| 705 | } |
| 706 | } |
| 707 | } |
| 708 |
| 709 | bool BasicNetworkManager::CreateNetworks( |
| 710 | bool include_ignored, |
| 711 | std::vector<std::unique_ptr<Network>>* networks) const { |
| 712 | struct ifaddrs* interfaces; |
| 713 | int error = getifaddrs(&interfaces); |
| 714 | if (error != 0) { |
| 715 | RTC_LOG_ERR(LS_ERROR) << "getifaddrs failed to gather interface data: " |
| 716 | << error; |
| 717 | return false; |
| 718 | } |
| 719 |
| 720 | std::unique_ptr<IfAddrsConverter> ifaddrs_converter(CreateIfAddrsConverter()); |
| 721 | ConvertIfAddrs(interfaces, ifaddrs_converter.get(), include_ignored, |
| 722 | networks); |
| 723 |
| 724 | freeifaddrs(interfaces); |
| 725 | return true; |
| 726 | } |
| 727 |
| 728 | #elif defined(WEBRTC_WIN) |
| 729 |
| 730 | unsigned int GetPrefix(PIP_ADAPTER_PREFIX prefixlist, |
| 731 | const IPAddress& ip, |
| 732 | IPAddress* prefix) { |
| 733 | IPAddress current_prefix; |
| 734 | IPAddress best_prefix; |
| 735 | unsigned int best_length = 0; |
| 736 | while (prefixlist) { |
| 737 | // Look for the longest matching prefix in the prefixlist. |
| 738 | if (prefixlist->Address.lpSockaddr == nullptr || |
| 739 | prefixlist->Address.lpSockaddr->sa_family != ip.family()) { |
| 740 | prefixlist = prefixlist->Next; |
| 741 | continue; |
| 742 | } |
| 743 | switch (prefixlist->Address.lpSockaddr->sa_family) { |
| 744 | case AF_INET: { |
| 745 | sockaddr_in* v4_addr = |
| 746 | reinterpret_cast<sockaddr_in*>(prefixlist->Address.lpSockaddr); |
| 747 | current_prefix = IPAddress(v4_addr->sin_addr); |
| 748 | break; |
| 749 | } |
| 750 | case AF_INET6: { |
| 751 | sockaddr_in6* v6_addr = |
| 752 | reinterpret_cast<sockaddr_in6*>(prefixlist->Address.lpSockaddr); |
| 753 | current_prefix = IPAddress(v6_addr->sin6_addr); |
| 754 | break; |
| 755 | } |
| 756 | default: { |
| 757 | prefixlist = prefixlist->Next; |
| 758 | continue; |
| 759 | } |
| 760 | } |
| 761 | if (TruncateIP(ip, prefixlist->PrefixLength) == current_prefix && |
| 762 | prefixlist->PrefixLength > best_length) { |
| 763 | best_prefix = current_prefix; |
| 764 | best_length = prefixlist->PrefixLength; |
| 765 | } |
| 766 | prefixlist = prefixlist->Next; |
| 767 | } |
| 768 | *prefix = best_prefix; |
| 769 | return best_length; |
| 770 | } |
| 771 |
| 772 | bool BasicNetworkManager::CreateNetworks( |
| 773 | bool include_ignored, |
| 774 | std::vector<std::unique_ptr<Network>>* networks) const { |
| 775 | std::map<std::string, Network*> current_networks; |
| 776 | // MSDN recommends a 15KB buffer for the first try at GetAdaptersAddresses. |
| 777 | size_t buffer_size = 16384; |
| 778 | std::unique_ptr<char[]> adapter_info(new char[buffer_size]); |
| 779 | PIP_ADAPTER_ADDRESSES adapter_addrs = |
| 780 | reinterpret_cast<PIP_ADAPTER_ADDRESSES>(adapter_info.get()); |
| 781 | int adapter_flags = (GAA_FLAG_SKIP_DNS_SERVER | GAA_FLAG_SKIP_ANYCAST | |
| 782 | GAA_FLAG_SKIP_MULTICAST | GAA_FLAG_INCLUDE_PREFIX); |
| 783 | int ret = 0; |
| 784 | do { |
| 785 | adapter_info.reset(new char[buffer_size]); |
| 786 | adapter_addrs = reinterpret_cast<PIP_ADAPTER_ADDRESSES>(adapter_info.get()); |
| 787 | ret = GetAdaptersAddresses(AF_UNSPEC, adapter_flags, 0, adapter_addrs, |
| 788 | reinterpret_cast<PULONG>(&buffer_size)); |
| 789 | } while (ret == ERROR_BUFFER_OVERFLOW); |
| 790 | if (ret != ERROR_SUCCESS) { |
| 791 | return false; |
| 792 | } |
| 793 | int count = 0; |
| 794 | while (adapter_addrs) { |
| 795 | if (adapter_addrs->OperStatus == IfOperStatusUp) { |
| 796 | PIP_ADAPTER_UNICAST_ADDRESS address = adapter_addrs->FirstUnicastAddress; |
| 797 | PIP_ADAPTER_PREFIX prefixlist = adapter_addrs->FirstPrefix; |
| 798 | std::string description = ToUtf8(adapter_addrs->Description, |
| 799 | wcslen(adapter_addrs->Description)); |
| 800 |
| 801 | for (; address; address = address->Next) { |
| 802 | std::string name = rtc::ToString(count); |
| 803 | #if !defined(NDEBUG) |
| 804 | name = ToUtf8(adapter_addrs->FriendlyName, |
| 805 | wcslen(adapter_addrs->FriendlyName)); |
| 806 | #endif |
| 807 |
| 808 | IPAddress ip; |
| 809 | int scope_id = 0; |
| 810 | std::unique_ptr<Network> network; |
| 811 | switch (address->Address.lpSockaddr->sa_family) { |
| 812 | case AF_INET: { |
| 813 | sockaddr_in* v4_addr = |
| 814 | reinterpret_cast<sockaddr_in*>(address->Address.lpSockaddr); |
| 815 | ip = IPAddress(v4_addr->sin_addr); |
| 816 | break; |
| 817 | } |
| 818 | case AF_INET6: { |
| 819 | sockaddr_in6* v6_addr = |
| 820 | reinterpret_cast<sockaddr_in6*>(address->Address.lpSockaddr); |
| 821 | scope_id = v6_addr->sin6_scope_id; |
| 822 |
| 823 | // From http://technet.microsoft.com/en-us/ff568768(v=vs.60).aspx, |
| 824 | // the way to identify a temporary IPv6 Address is to check if |
| 825 | // PrefixOrigin is equal to IpPrefixOriginRouterAdvertisement and |
| 826 | // SuffixOrigin equal to IpSuffixOriginRandom. |
| 827 | int ip_address_attributes = IPV6_ADDRESS_FLAG_NONE; |
| 828 | if (IpAddressAttributesEnabled(field_trials_.get())) { |
| 829 | if (address->PrefixOrigin == IpPrefixOriginRouterAdvertisement && |
| 830 | address->SuffixOrigin == IpSuffixOriginRandom) { |
| 831 | ip_address_attributes |= IPV6_ADDRESS_FLAG_TEMPORARY; |
| 832 | } |
| 833 | if (address->PreferredLifetime == 0) { |
| 834 | ip_address_attributes |= IPV6_ADDRESS_FLAG_DEPRECATED; |
| 835 | } |
| 836 | } |
| 837 | if (IsIgnoredIPv6(allow_mac_based_ipv6_, |
| 838 | InterfaceAddress(v6_addr->sin6_addr, |
| 839 | ip_address_attributes))) { |
| 840 | continue; |
| 841 | } |
| 842 | ip = InterfaceAddress(v6_addr->sin6_addr, ip_address_attributes); |
| 843 | break; |
| 844 | } |
| 845 | default: { |
| 846 | continue; |
| 847 | } |
| 848 | } |
| 849 |
| 850 | IPAddress prefix; |
| 851 | int prefix_length = GetPrefix(prefixlist, ip, &prefix); |
| 852 | std::string key = MakeNetworkKey(name, prefix, prefix_length); |
| 853 | auto existing_network = current_networks.find(key); |
| 854 | if (existing_network == current_networks.end()) { |
| 855 | AdapterType adapter_type = ADAPTER_TYPE_UNKNOWN; |
| 856 | switch (adapter_addrs->IfType) { |
| 857 | case IF_TYPE_SOFTWARE_LOOPBACK: |
| 858 | adapter_type = ADAPTER_TYPE_LOOPBACK; |
| 859 | break; |
| 860 | case IF_TYPE_ETHERNET_CSMACD: |
| 861 | case IF_TYPE_ETHERNET_3MBIT: |
| 862 | case IF_TYPE_IEEE80212: |
| 863 | case IF_TYPE_FASTETHER: |
| 864 | case IF_TYPE_FASTETHER_FX: |
| 865 | case IF_TYPE_GIGABITETHERNET: |
| 866 | adapter_type = ADAPTER_TYPE_ETHERNET; |
| 867 | break; |
| 868 | case IF_TYPE_IEEE80211: |
| 869 | adapter_type = ADAPTER_TYPE_WIFI; |
| 870 | break; |
| 871 | case IF_TYPE_WWANPP: |
| 872 | case IF_TYPE_WWANPP2: |
| 873 | adapter_type = ADAPTER_TYPE_CELLULAR; |
| 874 | break; |
| 875 | default: |
| 876 | // TODO(phoglund): Need to recognize other types as well. |
| 877 | adapter_type = ADAPTER_TYPE_UNKNOWN; |
| 878 | break; |
| 879 | } |
| 880 | auto underlying_type_for_vpn = ADAPTER_TYPE_UNKNOWN; |
| 881 | if (adapter_type != ADAPTER_TYPE_VPN && |
| 882 | IsConfiguredVpn(prefix, prefix_length)) { |
| 883 | underlying_type_for_vpn = adapter_type; |
| 884 | adapter_type = ADAPTER_TYPE_VPN; |
| 885 | } |
| 886 | if (adapter_type != ADAPTER_TYPE_VPN && |
| 887 | IsVpnMacAddress(rtc::ArrayView<const uint8_t>( |
| 888 | reinterpret_cast<const uint8_t*>( |
| 889 | adapter_addrs->PhysicalAddress), |
| 890 | adapter_addrs->PhysicalAddressLength))) { |
| 891 | // With MAC-based detection we do not know the |
| 892 | // underlying adapter type. |
| 893 | underlying_type_for_vpn = ADAPTER_TYPE_UNKNOWN; |
| 894 | adapter_type = ADAPTER_TYPE_VPN; |
| 895 | } |
| 896 |
| 897 | auto network = CreateNetwork(name, description, prefix, prefix_length, |
| 898 | adapter_type); |
| 899 | network->set_underlying_type_for_vpn(underlying_type_for_vpn); |
| 900 | network->set_default_local_address_provider(this); |
| 901 | network->set_mdns_responder_provider(this); |
| 902 | network->set_scope_id(scope_id); |
| 903 | network->AddIP(ip); |
| 904 | bool ignored = IsIgnoredNetwork(*network); |
| 905 | network->set_ignored(ignored); |
| 906 | if (include_ignored || !network->ignored()) { |
| 907 | current_networks[key] = network.get(); |
| 908 | networks->push_back(std::move(network)); |
| 909 | } |
| 910 | } else { |
| 911 | (*existing_network).second->AddIP(ip); |
| 912 | } |
| 913 | } |
| 914 | // Count is per-adapter - all 'Networks' created from the same |
| 915 | // adapter need to have the same name. |
| 916 | ++count; |
| 917 | } |
| 918 | adapter_addrs = adapter_addrs->Next; |
| 919 | } |
| 920 | return true; |
| 921 | } |
| 922 | #endif // WEBRTC_WIN |
| 923 |
| 924 | bool BasicNetworkManager::IsIgnoredNetwork(const Network& network) const { |
| 925 | // Ignore networks on the explicit ignore list. |
| 926 | for (const std::string& ignored_name : network_ignore_list_) { |
| 927 | if (network.name() == ignored_name) { |
| 928 | return true; |
| 929 | } |
| 930 | } |
| 931 |
| 932 | #if defined(WEBRTC_POSIX) |
| 933 | // Filter out VMware/VirtualBox interfaces, typically named vmnet1, |
| 934 | // vmnet8, or vboxnet0. |
| 935 | if (strncmp(network.name().c_str(), "vmnet", 5) == 0 || |
| 936 | strncmp(network.name().c_str(), "vnic", 4) == 0 || |
| 937 | strncmp(network.name().c_str(), "vboxnet", 7) == 0) { |
| 938 | return true; |
| 939 | } |
| 940 | #elif defined(WEBRTC_WIN) |
| 941 | // Ignore any HOST side vmware adapters with a description like: |
| 942 | // VMware Virtual Ethernet Adapter for VMnet1 |
| 943 | // but don't ignore any GUEST side adapters with a description like: |
| 944 | // VMware Accelerated AMD PCNet Adapter #2 |
| 945 | if (strstr(network.description().c_str(), "VMnet") != nullptr) { |
| 946 | return true; |
| 947 | } |
| 948 | #endif |
| 949 |
| 950 | // Ignore any networks with a 0.x.y.z IP |
| 951 | if (network.prefix().family() == AF_INET) { |
| 952 | return (network.prefix().v4AddressAsHostOrderInteger() < 0x01000000); |
| 953 | } |
| 954 |
| 955 | return false; |
| 956 | } |
| 957 |
| 958 | void BasicNetworkManager::StartUpdating() { |
| 959 | thread_ = Thread::Current(); |
| 960 | // Redundant but necessary for thread annotations. |
| 961 | RTC_DCHECK_RUN_ON(thread_); |
| 962 | if (start_count_) { |
| 963 | // If network interfaces are already discovered and signal is sent, |
| 964 | // we should trigger network signal immediately for the new clients |
| 965 | // to start allocating ports. |
| 966 | if (sent_first_update_) |
| 967 | thread_->PostTask(SafeTask(task_safety_flag_, [this] { |
| 968 | RTC_DCHECK_RUN_ON(thread_); |
| 969 | SignalNetworksChanged(); |
| 970 | })); |
| 971 | } else { |
| 972 | RTC_DCHECK(task_safety_flag_ == nullptr); |
| 973 | task_safety_flag_ = webrtc::PendingTaskSafetyFlag::Create(); |
| 974 | thread_->PostTask(SafeTask(task_safety_flag_, [this] { |
| 975 | RTC_DCHECK_RUN_ON(thread_); |
| 976 | UpdateNetworksContinually(); |
| 977 | })); |
| 978 | StartNetworkMonitor(); |
| 979 | } |
| 980 | ++start_count_; |
| 981 | } |
| 982 |
| 983 | void BasicNetworkManager::StopUpdating() { |
| 984 | RTC_DCHECK_RUN_ON(thread_); |
| 985 | if (!start_count_) |
| 986 | return; |
| 987 |
| 988 | --start_count_; |
| 989 | if (!start_count_) { |
| 990 | task_safety_flag_->SetNotAlive(); |
| 991 | task_safety_flag_ = nullptr; |
| 992 | sent_first_update_ = false; |
| 993 | StopNetworkMonitor(); |
| 994 | } |
| 995 | } |
| 996 |
| 997 | void BasicNetworkManager::StartNetworkMonitor() { |
| 998 | if (network_monitor_factory_ == nullptr) { |
| 999 | return; |
| 1000 | } |
| 1001 | if (!network_monitor_) { |
| 1002 | network_monitor_.reset( |
| 1003 | network_monitor_factory_->CreateNetworkMonitor(*field_trials())); |
| 1004 | if (!network_monitor_) { |
| 1005 | return; |
| 1006 | } |
| 1007 | network_monitor_->SetNetworksChangedCallback( |
| 1008 | [this]() { OnNetworksChanged(); }); |
| 1009 | } |
| 1010 |
| 1011 | if (network_monitor_->SupportsBindSocketToNetwork()) { |
| 1012 | // Set NetworkBinder on SocketServer so that |
| 1013 | // PhysicalSocket::Bind will call |
| 1014 | // BasicNetworkManager::BindSocketToNetwork(), (that will lookup interface |
| 1015 | // name and then call network_monitor_->BindSocketToNetwork()). |
| 1016 | thread_->socketserver()->set_network_binder(this); |
| 1017 | } |
| 1018 |
| 1019 | network_monitor_->Start(); |
| 1020 | } |
| 1021 |
| 1022 | void BasicNetworkManager::StopNetworkMonitor() { |
| 1023 | if (!network_monitor_) { |
| 1024 | return; |
| 1025 | } |
| 1026 | network_monitor_->Stop(); |
| 1027 |
| 1028 | if (network_monitor_->SupportsBindSocketToNetwork()) { |
| 1029 | // Reset NetworkBinder on SocketServer. |
| 1030 | if (thread_->socketserver()->network_binder() == this) { |
| 1031 | thread_->socketserver()->set_network_binder(nullptr); |
| 1032 | } |
| 1033 | } |
| 1034 | } |
| 1035 |
| 1036 | IPAddress BasicNetworkManager::QueryDefaultLocalAddress(int family) const { |
| 1037 | RTC_DCHECK(family == AF_INET || family == AF_INET6); |
| 1038 |
| 1039 | std::unique_ptr<Socket> socket( |
| 1040 | socket_factory_->CreateSocket(family, SOCK_DGRAM)); |
| 1041 | if (!socket) { |
| 1042 | RTC_LOG_ERR(LS_ERROR) << "Socket creation failed"; |
| 1043 | return IPAddress(); |
| 1044 | } |
| 1045 |
| 1046 | if (socket->Connect(SocketAddress( |
| 1047 | family == AF_INET ? kPublicIPv4Host : kPublicIPv6Host, kPublicPort)) < |
| 1048 | 0) { |
| 1049 | if (socket->GetError() != ENETUNREACH && |
| 1050 | socket->GetError() != EHOSTUNREACH) { |
| 1051 | // Ignore the expected case of "host/net unreachable" - which happens if |
| 1052 | // the network is V4- or V6-only. |
| 1053 | RTC_LOG(LS_INFO) << "Connect failed with " << socket->GetError(); |
| 1054 | } |
| 1055 | return IPAddress(); |
| 1056 | } |
| 1057 | return socket->GetLocalAddress().ipaddr(); |
| 1058 | } |
| 1059 |
| 1060 | void BasicNetworkManager::UpdateNetworksOnce() { |
| 1061 | if (!start_count_) |
| 1062 | return; |
| 1063 |
| 1064 | std::vector<std::unique_ptr<Network>> list; |
| 1065 | if (!CreateNetworks(false, &list)) { |
| 1066 | SignalError(); |
| 1067 | } else { |
| 1068 | bool changed; |
| 1069 | NetworkManager::Stats stats; |
| 1070 | MergeNetworkList(std::move(list), &changed, &stats); |
| 1071 | set_default_local_addresses(QueryDefaultLocalAddress(AF_INET), |
| 1072 | QueryDefaultLocalAddress(AF_INET6)); |
| 1073 | if (changed || !sent_first_update_) { |
| 1074 | SignalNetworksChanged(); |
| 1075 | sent_first_update_ = true; |
| 1076 | } |
| 1077 | } |
| 1078 | } |
| 1079 |
| 1080 | void BasicNetworkManager::UpdateNetworksContinually() { |
| 1081 | UpdateNetworksOnce(); |
| 1082 | thread_->PostDelayedTask(SafeTask(task_safety_flag_, |
| 1083 | [this] { |
| 1084 | RTC_DCHECK_RUN_ON(thread_); |
| 1085 | UpdateNetworksContinually(); |
| 1086 | }), |
| 1087 | TimeDelta::Millis(kNetworksUpdateIntervalMs)); |
| 1088 | } |
| 1089 |
| 1090 | void BasicNetworkManager::DumpNetworks() { |
| 1091 | RTC_DCHECK_RUN_ON(thread_); |
| 1092 | std::vector<const Network*> list = GetNetworks(); |
| 1093 | RTC_LOG(LS_INFO) << "NetworkManager detected " << list.size() << " networks:"; |
| 1094 | for (const Network* network : list) { |
| 1095 | RTC_LOG(LS_INFO) << network->ToString() << ": " << network->description() |
| 1096 | << ", active ? " << network->active() |
| 1097 | << ((network->ignored()) ? ", Ignored" : ""); |
| 1098 | } |
| 1099 | } |
| 1100 |
| 1101 | NetworkBindingResult BasicNetworkManager::BindSocketToNetwork( |
| 1102 | int socket_fd, |
| 1103 | const IPAddress& address) { |
| 1104 | RTC_DCHECK_RUN_ON(thread_); |
| 1105 | std::string if_name; |
| 1106 | if (bind_using_ifname_) { |
| 1107 | Network* net = GetNetworkFromAddress(address); |
| 1108 | if (net != nullptr) { |
| 1109 | if_name = net->name(); |
| 1110 | } |
| 1111 | } |
| 1112 | return network_monitor_->BindSocketToNetwork(socket_fd, address, if_name); |
| 1113 | } |
| 1114 |
| 1115 | Network::Network(absl::string_view name, |
| 1116 | absl::string_view desc, |
| 1117 | const IPAddress& prefix, |
| 1118 | int prefix_length, |
| 1119 | AdapterType type) |
| 1120 | : name_(name), |
| 1121 | description_(desc), |
| 1122 | prefix_(prefix), |
| 1123 | prefix_length_(prefix_length), |
| 1124 | key_(MakeNetworkKey(name, prefix, prefix_length)), |
| 1125 | scope_id_(0), |
| 1126 | ignored_(false), |
| 1127 | type_(type), |
| 1128 | preference_(0) {} |
| 1129 |
| 1130 | Network::Network(const Network&) = default; |
| 1131 |
| 1132 | Network::~Network() = default; |
| 1133 |
| 1134 | // Sets the addresses of this network. Returns true if the address set changed. |
| 1135 | // Change detection is short circuited if the changed argument is true. |
| 1136 | bool Network::SetIPs(const std::vector<InterfaceAddress>& ips, bool changed) { |
| 1137 | // Detect changes with a nested loop; n-squared but we expect on the order |
| 1138 | // of 2-3 addresses per network. |
| 1139 | changed = changed || ips.size() != ips_.size(); |
| 1140 | if (!changed) { |
| 1141 | for (const InterfaceAddress& ip : ips) { |
| 1142 | if (!absl::c_linear_search(ips_, ip)) { |
| 1143 | changed = true; |
| 1144 | break; |
| 1145 | } |
| 1146 | } |
| 1147 | } |
| 1148 |
| 1149 | ips_ = ips; |
| 1150 | return changed; |
| 1151 | } |
| 1152 |
| 1153 | // Select the best IP address to use from this Network. |
| 1154 | IPAddress Network::GetBestIP() const { |
| 1155 | if (ips_.size() == 0) { |
| 1156 | return IPAddress(); |
| 1157 | } |
| 1158 |
| 1159 | if (prefix_.family() == AF_INET) { |
| 1160 | return static_cast<IPAddress>(ips_.at(0)); |
| 1161 | } |
| 1162 |
| 1163 | InterfaceAddress selected_ip, link_local_ip, ula_ip; |
| 1164 |
| 1165 | for (const InterfaceAddress& ip : ips_) { |
| 1166 | // Ignore any address which has been deprecated already. |
| 1167 | if (ip.ipv6_flags() & IPV6_ADDRESS_FLAG_DEPRECATED) |
| 1168 | continue; |
| 1169 |
| 1170 | if (IPIsLinkLocal(ip)) { |
| 1171 | link_local_ip = ip; |
| 1172 | continue; |
| 1173 | } |
| 1174 |
| 1175 | // ULA address should only be returned when we have no other |
| 1176 | // global IP. |
| 1177 | if (IPIsULA(static_cast<const IPAddress&>(ip))) { |
| 1178 | ula_ip = ip; |
| 1179 | continue; |
| 1180 | } |
| 1181 | selected_ip = ip; |
| 1182 |
| 1183 | // Search could stop once a temporary non-deprecated one is found. |
| 1184 | if (ip.ipv6_flags() & IPV6_ADDRESS_FLAG_TEMPORARY) |
| 1185 | break; |
| 1186 | } |
| 1187 |
| 1188 | if (IPIsUnspec(selected_ip)) { |
| 1189 | if (!IPIsUnspec(link_local_ip)) { |
| 1190 | // No proper global IPv6 address found, use link local address instead. |
| 1191 | selected_ip = link_local_ip; |
| 1192 | } else if (!IPIsUnspec(ula_ip)) { |
| 1193 | // No proper global and link local address found, use ULA instead. |
| 1194 | selected_ip = ula_ip; |
| 1195 | } |
| 1196 | } |
| 1197 |
| 1198 | return static_cast<IPAddress>(selected_ip); |
| 1199 | } |
| 1200 |
| 1201 | webrtc::MdnsResponderInterface* Network::GetMdnsResponder() const { |
| 1202 | if (mdns_responder_provider_ == nullptr) { |
| 1203 | return nullptr; |
| 1204 | } |
| 1205 | return mdns_responder_provider_->GetMdnsResponder(); |
| 1206 | } |
| 1207 |
| 1208 | uint16_t Network::GetCost(const webrtc::FieldTrialsView* field_trials) const { |
| 1209 | return GetCost( |
| 1210 | *webrtc::AlwaysValidPointer<const webrtc::FieldTrialsView, |
| 1211 | webrtc::FieldTrialBasedConfig>(field_trials)); |
| 1212 | } |
| 1213 |
| 1214 | uint16_t Network::GetCost(const webrtc::FieldTrialsView& field_trials) const { |
| 1215 | AdapterType type = IsVpn() ? underlying_type_for_vpn_ : type_; |
| 1216 | const bool use_differentiated_cellular_costs = |
| 1217 | field_trials.IsEnabled("WebRTC-UseDifferentiatedCellularCosts"); |
| 1218 | const bool add_network_cost_to_vpn = |
| 1219 | field_trials.IsEnabled("WebRTC-AddNetworkCostToVpn"); |
| 1220 | return ComputeNetworkCostByType(type, IsVpn(), |
| 1221 | use_differentiated_cellular_costs, |
| 1222 | add_network_cost_to_vpn); |
| 1223 | } |
| 1224 |
| 1225 | // This is the inverse of ComputeNetworkCostByType(). |
| 1226 | std::pair<rtc::AdapterType, bool /* vpn */> |
| 1227 | Network::GuessAdapterFromNetworkCost(int network_cost) { |
| 1228 | switch (network_cost) { |
| 1229 | case kNetworkCostMin: |
| 1230 | return {rtc::ADAPTER_TYPE_ETHERNET, false}; |
| 1231 | case kNetworkCostMin + kNetworkCostVpn: |
| 1232 | return {rtc::ADAPTER_TYPE_ETHERNET, true}; |
| 1233 | case kNetworkCostLow: |
| 1234 | return {rtc::ADAPTER_TYPE_WIFI, false}; |
| 1235 | case kNetworkCostLow + kNetworkCostVpn: |
| 1236 | return {rtc::ADAPTER_TYPE_WIFI, true}; |
| 1237 | case kNetworkCostCellular: |
| 1238 | return {rtc::ADAPTER_TYPE_CELLULAR, false}; |
| 1239 | case kNetworkCostCellular + kNetworkCostVpn: |
| 1240 | return {rtc::ADAPTER_TYPE_CELLULAR, true}; |
| 1241 | case kNetworkCostCellular2G: |
| 1242 | return {rtc::ADAPTER_TYPE_CELLULAR_2G, false}; |
| 1243 | case kNetworkCostCellular2G + kNetworkCostVpn: |
| 1244 | return {rtc::ADAPTER_TYPE_CELLULAR_2G, true}; |
| 1245 | case kNetworkCostCellular3G: |
| 1246 | return {rtc::ADAPTER_TYPE_CELLULAR_3G, false}; |
| 1247 | case kNetworkCostCellular3G + kNetworkCostVpn: |
| 1248 | return {rtc::ADAPTER_TYPE_CELLULAR_3G, true}; |
| 1249 | case kNetworkCostCellular4G: |
| 1250 | return {rtc::ADAPTER_TYPE_CELLULAR_4G, false}; |
| 1251 | case kNetworkCostCellular4G + kNetworkCostVpn: |
| 1252 | return {rtc::ADAPTER_TYPE_CELLULAR_4G, true}; |
| 1253 | case kNetworkCostCellular5G: |
| 1254 | return {rtc::ADAPTER_TYPE_CELLULAR_5G, false}; |
| 1255 | case kNetworkCostCellular5G + kNetworkCostVpn: |
| 1256 | return {rtc::ADAPTER_TYPE_CELLULAR_5G, true}; |
| 1257 | case kNetworkCostUnknown: |
| 1258 | return {rtc::ADAPTER_TYPE_UNKNOWN, false}; |
| 1259 | case kNetworkCostUnknown + kNetworkCostVpn: |
| 1260 | return {rtc::ADAPTER_TYPE_UNKNOWN, true}; |
| 1261 | case kNetworkCostMax: |
| 1262 | return {rtc::ADAPTER_TYPE_ANY, false}; |
| 1263 | case kNetworkCostMax + kNetworkCostVpn: |
| 1264 | return {rtc::ADAPTER_TYPE_ANY, true}; |
| 1265 | } |
| 1266 | RTC_LOG(LS_VERBOSE) << "Unknown network cost: " << network_cost; |
| 1267 | return {rtc::ADAPTER_TYPE_UNKNOWN, false}; |
| 1268 | } |
| 1269 |
| 1270 | std::string Network::ToString() const { |
| 1271 | rtc::StringBuilder ss; |
| 1272 | // Print out the first space-terminated token of the network desc, plus |
| 1273 | // the IP address. |
| 1274 | ss << "Net[" << description_.substr(0, description_.find(' ')) << ":" |
| 1275 | << prefix_.ToSensitiveString() << "/" << prefix_length_ << ":" |
| 1276 | << AdapterTypeToString(type_); |
| 1277 | if (IsVpn()) { |
| 1278 | ss << "/" << AdapterTypeToString(underlying_type_for_vpn_); |
| 1279 | } |
| 1280 | ss << ":id=" << id_ << "]"; |
| 1281 | return ss.Release(); |
| 1282 | } |
| 1283 |
| 1284 | void BasicNetworkManager::set_vpn_list(const std::vector<NetworkMask>& vpn) { |
| 1285 | if (thread_ == nullptr) { |
| 1286 | vpn_ = vpn; |
| 1287 | } else { |
| 1288 | thread_->BlockingCall([this, vpn] { vpn_ = vpn; }); |
| 1289 | } |
| 1290 | } |
| 1291 |
| 1292 | bool BasicNetworkManager::IsConfiguredVpn(IPAddress prefix, |
| 1293 | int prefix_length) const { |
| 1294 | RTC_DCHECK_RUN_ON(thread_); |
| 1295 | for (const auto& vpn : vpn_) { |
| 1296 | if (prefix_length >= vpn.prefix_length()) { |
| 1297 | auto copy = TruncateIP(prefix, vpn.prefix_length()); |
| 1298 | if (copy == vpn.address()) { |
| 1299 | return true; |
| 1300 | } |
| 1301 | } |
| 1302 | } |
| 1303 | return false; |
| 1304 | } |
| 1305 |
| 1306 | } // namespace rtc |
| 1307 |