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