• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 #if defined(WEBRTC_POSIX)
14 #include <net/if.h>
15 #endif  // WEBRTC_POSIX
16 
17 #if defined(WEBRTC_WIN)
18 #include <iphlpapi.h>
19 
20 #include "rtc_base/win32.h"
21 #elif !defined(__native_client__)
22 #include "rtc_base/ifaddrs_converter.h"
23 #endif
24 
25 #include <memory>
26 
27 #include "absl/algorithm/container.h"
28 #include "absl/strings/match.h"
29 #include "absl/strings/string_view.h"
30 #include "rtc_base/checks.h"
31 #include "rtc_base/logging.h"
32 #include "rtc_base/network_monitor.h"
33 #include "rtc_base/socket.h"  // includes something that makes windows happy
34 #include "rtc_base/string_encode.h"
35 #include "rtc_base/string_utils.h"
36 #include "rtc_base/strings/string_builder.h"
37 #include "rtc_base/thread.h"
38 #include "system_wrappers/include/field_trial.h"
39 
40 namespace rtc {
41 namespace {
42 
43 const uint32_t kUpdateNetworksMessage = 1;
44 const uint32_t kSignalNetworksMessage = 2;
45 
46 // Fetch list of networks every two seconds.
47 const int kNetworksUpdateIntervalMs = 2000;
48 
49 const int kHighestNetworkPreference = 127;
50 
51 typedef struct {
52   Network* net;
53   std::vector<InterfaceAddress> ips;
54 } AddressList;
55 
CompareNetworks(const Network * a,const Network * b)56 bool CompareNetworks(const Network* a, const Network* b) {
57   if (a->prefix_length() == b->prefix_length()) {
58     if (a->name() == b->name()) {
59       return a->prefix() < b->prefix();
60     }
61   }
62   return a->name() < b->name();
63 }
64 
SortNetworks(const Network * a,const Network * b)65 bool SortNetworks(const Network* a, const Network* b) {
66   // Network types will be preferred above everything else while sorting
67   // Networks.
68 
69   // Networks are sorted first by type.
70   if (a->type() != b->type()) {
71     return a->type() < b->type();
72   }
73 
74   IPAddress ip_a = a->GetBestIP();
75   IPAddress ip_b = b->GetBestIP();
76 
77   // After type, networks are sorted by IP address precedence values
78   // from RFC 3484-bis
79   if (IPAddressPrecedence(ip_a) != IPAddressPrecedence(ip_b)) {
80     return IPAddressPrecedence(ip_a) > IPAddressPrecedence(ip_b);
81   }
82 
83   // TODO(mallinath) - Add VPN and Link speed conditions while sorting.
84 
85   // Networks are sorted last by key.
86   return a->key() < b->key();
87 }
88 
ComputeNetworkCostByType(int type,bool use_differentiated_cellular_costs)89 uint16_t ComputeNetworkCostByType(int type,
90                                   bool use_differentiated_cellular_costs) {
91   // TODO(jonaso) : Rollout support for cellular network cost using A/B
92   // experiment to make sure it does not introduce regressions.
93   switch (type) {
94     case rtc::ADAPTER_TYPE_ETHERNET:
95     case rtc::ADAPTER_TYPE_LOOPBACK:
96       return kNetworkCostMin;
97     case rtc::ADAPTER_TYPE_WIFI:
98       return kNetworkCostLow;
99     case rtc::ADAPTER_TYPE_CELLULAR:
100       return kNetworkCostCellular;
101     case rtc::ADAPTER_TYPE_CELLULAR_2G:
102       return use_differentiated_cellular_costs ? kNetworkCostCellular2G
103                                                : kNetworkCostCellular;
104     case rtc::ADAPTER_TYPE_CELLULAR_3G:
105       return use_differentiated_cellular_costs ? kNetworkCostCellular3G
106                                                : kNetworkCostCellular;
107     case rtc::ADAPTER_TYPE_CELLULAR_4G:
108       return use_differentiated_cellular_costs ? kNetworkCostCellular4G
109                                                : kNetworkCostCellular;
110     case rtc::ADAPTER_TYPE_CELLULAR_5G:
111       return use_differentiated_cellular_costs ? kNetworkCostCellular5G
112                                                : kNetworkCostCellular;
113     case rtc::ADAPTER_TYPE_ANY:
114       // Candidates gathered from the any-address/wildcard ports, as backups,
115       // are given the maximum cost so that if there are other candidates with
116       // known interface types, we would not select candidate pairs using these
117       // backup candidates if other selection criteria with higher precedence
118       // (network conditions over the route) are the same. Note that setting the
119       // cost to kNetworkCostUnknown would be problematic since
120       // ADAPTER_TYPE_CELLULAR would then have a higher cost. See
121       // P2PTransportChannel::SortConnectionsAndUpdateState for how we rank and
122       // select candidate pairs, where the network cost is among the criteria.
123       return kNetworkCostMax;
124     case rtc::ADAPTER_TYPE_VPN:
125       // The cost of a VPN should be computed using its underlying network type.
126       RTC_NOTREACHED();
127       return kNetworkCostUnknown;
128     default:
129       return kNetworkCostUnknown;
130   }
131 }
132 
133 #if !defined(__native_client__)
IsIgnoredIPv6(const InterfaceAddress & ip)134 bool IsIgnoredIPv6(const InterfaceAddress& ip) {
135   if (ip.family() != AF_INET6) {
136     return false;
137   }
138 
139   // Link-local addresses require scope id to be bound successfully.
140   // However, our IPAddress structure doesn't carry that so the
141   // information is lost and causes binding failure.
142   if (IPIsLinkLocal(ip)) {
143     return true;
144   }
145 
146   // Any MAC based IPv6 should be avoided to prevent the MAC tracking.
147   if (IPIsMacBased(ip)) {
148     return true;
149   }
150 
151   // Ignore deprecated IPv6.
152   if (ip.ipv6_flags() & IPV6_ADDRESS_FLAG_DEPRECATED) {
153     return true;
154   }
155 
156   return false;
157 }
158 #endif  // !defined(__native_client__)
159 
160 // Note: consider changing to const Network* as arguments
161 // if/when considering other changes that should not trigger
162 // OnNetworksChanged.
ShouldAdapterChangeTriggerNetworkChange(rtc::AdapterType old_type,rtc::AdapterType new_type)163 bool ShouldAdapterChangeTriggerNetworkChange(rtc::AdapterType old_type,
164                                              rtc::AdapterType new_type) {
165   // skip triggering OnNetworksChanged if
166   // changing from one cellular to another.
167   if (Network::IsCellular(old_type) && Network::IsCellular(new_type))
168     return false;
169   return true;
170 }
171 
172 }  // namespace
173 
174 // These addresses are used as the targets to find out the default local address
175 // on a multi-homed endpoint. They are actually DNS servers.
176 const char kPublicIPv4Host[] = "8.8.8.8";
177 const char kPublicIPv6Host[] = "2001:4860:4860::8888";
178 const int kPublicPort = 53;  // DNS port.
179 
MakeNetworkKey(const std::string & name,const IPAddress & prefix,int prefix_length)180 std::string MakeNetworkKey(const std::string& name,
181                            const IPAddress& prefix,
182                            int prefix_length) {
183   rtc::StringBuilder ost;
184   ost << name << "%" << prefix.ToString() << "/" << prefix_length;
185   return ost.Release();
186 }
187 // Test if the network name matches the type<number> pattern, e.g. eth0. The
188 // matching is case-sensitive.
MatchTypeNameWithIndexPattern(absl::string_view network_name,absl::string_view type_name)189 bool MatchTypeNameWithIndexPattern(absl::string_view network_name,
190                                    absl::string_view type_name) {
191   if (!absl::StartsWith(network_name, type_name)) {
192     return false;
193   }
194   return absl::c_none_of(network_name.substr(type_name.size()),
195                          [](char c) { return !isdigit(c); });
196 }
197 
198 // A cautious note that this method may not provide an accurate adapter type
199 // based on the string matching. Incorrect type of adapters can affect the
200 // result of the downstream network filtering, see e.g.
201 // BasicPortAllocatorSession::GetNetworks when
202 // PORTALLOCATOR_DISABLE_COSTLY_NETWORKS is turned on.
GetAdapterTypeFromName(const char * network_name)203 AdapterType GetAdapterTypeFromName(const char* network_name) {
204   if (MatchTypeNameWithIndexPattern(network_name, "lo")) {
205     // Note that we have a more robust way to determine if a network interface
206     // is a loopback interface by checking the flag IFF_LOOPBACK in ifa_flags of
207     // an ifaddr struct. See ConvertIfAddrs in this file.
208     return ADAPTER_TYPE_LOOPBACK;
209   }
210 
211   if (MatchTypeNameWithIndexPattern(network_name, "eth")) {
212     return ADAPTER_TYPE_ETHERNET;
213   }
214 
215   if (MatchTypeNameWithIndexPattern(network_name, "wlan")) {
216     return ADAPTER_TYPE_WIFI;
217   }
218 
219   if (MatchTypeNameWithIndexPattern(network_name, "ipsec") ||
220       MatchTypeNameWithIndexPattern(network_name, "tun") ||
221       MatchTypeNameWithIndexPattern(network_name, "utun") ||
222       MatchTypeNameWithIndexPattern(network_name, "tap")) {
223     return ADAPTER_TYPE_VPN;
224   }
225 #if defined(WEBRTC_IOS)
226   // Cell networks are pdp_ipN on iOS.
227   if (MatchTypeNameWithIndexPattern(network_name, "pdp_ip")) {
228     return ADAPTER_TYPE_CELLULAR;
229   }
230   if (MatchTypeNameWithIndexPattern(network_name, "en")) {
231     // This may not be most accurate because sometimes Ethernet interface
232     // name also starts with "en" but it is better than showing it as
233     // "unknown" type.
234     // TODO(honghaiz): Write a proper IOS network manager.
235     return ADAPTER_TYPE_WIFI;
236   }
237 #elif defined(WEBRTC_ANDROID)
238   if (MatchTypeNameWithIndexPattern(network_name, "rmnet") ||
239       MatchTypeNameWithIndexPattern(network_name, "rmnet_data") ||
240       MatchTypeNameWithIndexPattern(network_name, "v4-rmnet") ||
241       MatchTypeNameWithIndexPattern(network_name, "v4-rmnet_data") ||
242       MatchTypeNameWithIndexPattern(network_name, "clat")) {
243     return ADAPTER_TYPE_CELLULAR;
244   }
245 #endif
246 
247   return ADAPTER_TYPE_UNKNOWN;
248 }
249 
NetworkManager()250 NetworkManager::NetworkManager() {}
251 
~NetworkManager()252 NetworkManager::~NetworkManager() {}
253 
enumeration_permission() const254 NetworkManager::EnumerationPermission NetworkManager::enumeration_permission()
255     const {
256   return ENUMERATION_ALLOWED;
257 }
258 
GetDefaultLocalAddress(int family,IPAddress * addr) const259 bool NetworkManager::GetDefaultLocalAddress(int family, IPAddress* addr) const {
260   return false;
261 }
262 
GetMdnsResponder() const263 webrtc::MdnsResponderInterface* NetworkManager::GetMdnsResponder() const {
264   return nullptr;
265 }
266 
NetworkManagerBase()267 NetworkManagerBase::NetworkManagerBase()
268     : enumeration_permission_(NetworkManager::ENUMERATION_ALLOWED) {}
269 
~NetworkManagerBase()270 NetworkManagerBase::~NetworkManagerBase() {
271   for (const auto& kv : networks_map_) {
272     delete kv.second;
273   }
274 }
275 
276 NetworkManager::EnumerationPermission
enumeration_permission() const277 NetworkManagerBase::enumeration_permission() const {
278   return enumeration_permission_;
279 }
280 
GetAnyAddressNetworks(NetworkList * networks)281 void NetworkManagerBase::GetAnyAddressNetworks(NetworkList* networks) {
282   if (!ipv4_any_address_network_) {
283     const rtc::IPAddress ipv4_any_address(INADDR_ANY);
284     ipv4_any_address_network_.reset(
285         new rtc::Network("any", "any", ipv4_any_address, 0, ADAPTER_TYPE_ANY));
286     ipv4_any_address_network_->set_default_local_address_provider(this);
287     ipv4_any_address_network_->set_mdns_responder_provider(this);
288     ipv4_any_address_network_->AddIP(ipv4_any_address);
289   }
290   networks->push_back(ipv4_any_address_network_.get());
291 
292   if (!ipv6_any_address_network_) {
293     const rtc::IPAddress ipv6_any_address(in6addr_any);
294     ipv6_any_address_network_.reset(
295         new rtc::Network("any", "any", ipv6_any_address, 0, ADAPTER_TYPE_ANY));
296     ipv6_any_address_network_->set_default_local_address_provider(this);
297     ipv6_any_address_network_->set_mdns_responder_provider(this);
298     ipv6_any_address_network_->AddIP(ipv6_any_address);
299   }
300   networks->push_back(ipv6_any_address_network_.get());
301 }
302 
GetNetworks(NetworkList * result) const303 void NetworkManagerBase::GetNetworks(NetworkList* result) const {
304   result->clear();
305   result->insert(result->begin(), networks_.begin(), networks_.end());
306 }
307 
MergeNetworkList(const NetworkList & new_networks,bool * changed)308 void NetworkManagerBase::MergeNetworkList(const NetworkList& new_networks,
309                                           bool* changed) {
310   NetworkManager::Stats stats;
311   MergeNetworkList(new_networks, changed, &stats);
312 }
313 
MergeNetworkList(const NetworkList & new_networks,bool * changed,NetworkManager::Stats * stats)314 void NetworkManagerBase::MergeNetworkList(const NetworkList& new_networks,
315                                           bool* changed,
316                                           NetworkManager::Stats* stats) {
317   *changed = false;
318   // AddressList in this map will track IP addresses for all Networks
319   // with the same key.
320   std::map<std::string, AddressList> consolidated_address_list;
321   NetworkList list(new_networks);
322   absl::c_sort(list, CompareNetworks);
323   // First, build a set of network-keys to the ipaddresses.
324   for (Network* network : list) {
325     bool might_add_to_merged_list = false;
326     std::string key = MakeNetworkKey(network->name(), network->prefix(),
327                                      network->prefix_length());
328     if (consolidated_address_list.find(key) ==
329         consolidated_address_list.end()) {
330       AddressList addrlist;
331       addrlist.net = network;
332       consolidated_address_list[key] = addrlist;
333       might_add_to_merged_list = true;
334     }
335     const std::vector<InterfaceAddress>& addresses = network->GetIPs();
336     AddressList& current_list = consolidated_address_list[key];
337     for (const InterfaceAddress& address : addresses) {
338       current_list.ips.push_back(address);
339     }
340     if (!might_add_to_merged_list) {
341       delete network;
342     } else {
343       if (current_list.ips[0].family() == AF_INET) {
344         stats->ipv4_network_count++;
345       } else {
346         RTC_DCHECK(current_list.ips[0].family() == AF_INET6);
347         stats->ipv6_network_count++;
348       }
349     }
350   }
351 
352   // Next, look for existing network objects to re-use.
353   // Result of Network merge. Element in this list should have unique key.
354   NetworkList merged_list;
355   for (const auto& kv : consolidated_address_list) {
356     const std::string& key = kv.first;
357     Network* net = kv.second.net;
358     auto existing = networks_map_.find(key);
359     if (existing == networks_map_.end()) {
360       // This network is new. Place it in the network map.
361       merged_list.push_back(net);
362       networks_map_[key] = net;
363       net->set_id(next_available_network_id_++);
364       // Also, we might have accumulated IPAddresses from the first
365       // step, set it here.
366       net->SetIPs(kv.second.ips, true);
367       *changed = true;
368     } else {
369       // This network exists in the map already. Reset its IP addresses.
370       Network* existing_net = existing->second;
371       *changed = existing_net->SetIPs(kv.second.ips, *changed);
372       merged_list.push_back(existing_net);
373       if (net->type() != ADAPTER_TYPE_UNKNOWN &&
374           net->type() != existing_net->type()) {
375         if (ShouldAdapterChangeTriggerNetworkChange(existing_net->type(),
376                                                     net->type())) {
377           *changed = true;
378         }
379         existing_net->set_type(net->type());
380       }
381       // If the existing network was not active, networks have changed.
382       if (!existing_net->active()) {
383         *changed = true;
384       }
385       RTC_DCHECK(net->active());
386       if (existing_net != net) {
387         delete net;
388       }
389     }
390     networks_map_[key]->set_mdns_responder_provider(this);
391   }
392   // It may still happen that the merged list is a subset of |networks_|.
393   // To detect this change, we compare their sizes.
394   if (merged_list.size() != networks_.size()) {
395     *changed = true;
396   }
397 
398   // If the network list changes, we re-assign |networks_| to the merged list
399   // and re-sort it.
400   if (*changed) {
401     networks_ = merged_list;
402     // Reset the active states of all networks.
403     for (const auto& kv : networks_map_) {
404       Network* network = kv.second;
405       // If |network| is in the newly generated |networks_|, it is active.
406       bool found = absl::c_linear_search(networks_, network);
407       network->set_active(found);
408     }
409     absl::c_sort(networks_, SortNetworks);
410     // Now network interfaces are sorted, we should set the preference value
411     // for each of the interfaces we are planning to use.
412     // Preference order of network interfaces might have changed from previous
413     // sorting due to addition of higher preference network interface.
414     // Since we have already sorted the network interfaces based on our
415     // requirements, we will just assign a preference value starting with 127,
416     // in decreasing order.
417     int pref = kHighestNetworkPreference;
418     for (Network* network : networks_) {
419       network->set_preference(pref);
420       if (pref > 0) {
421         --pref;
422       } else {
423         RTC_LOG(LS_ERROR) << "Too many network interfaces to handle!";
424         break;
425       }
426     }
427   }
428 }
429 
set_default_local_addresses(const IPAddress & ipv4,const IPAddress & ipv6)430 void NetworkManagerBase::set_default_local_addresses(const IPAddress& ipv4,
431                                                      const IPAddress& ipv6) {
432   if (ipv4.family() == AF_INET) {
433     default_local_ipv4_address_ = ipv4;
434   }
435   if (ipv6.family() == AF_INET6) {
436     default_local_ipv6_address_ = ipv6;
437   }
438 }
439 
GetDefaultLocalAddress(int family,IPAddress * ipaddr) const440 bool NetworkManagerBase::GetDefaultLocalAddress(int family,
441                                                 IPAddress* ipaddr) const {
442   if (family == AF_INET && !default_local_ipv4_address_.IsNil()) {
443     *ipaddr = default_local_ipv4_address_;
444     return true;
445   } else if (family == AF_INET6 && !default_local_ipv6_address_.IsNil()) {
446     Network* ipv6_network = GetNetworkFromAddress(default_local_ipv6_address_);
447     if (ipv6_network) {
448       // If the default ipv6 network's BestIP is different than
449       // default_local_ipv6_address_, use it instead.
450       // This is to prevent potential IP address leakage. See WebRTC bug 5376.
451       *ipaddr = ipv6_network->GetBestIP();
452     } else {
453       *ipaddr = default_local_ipv6_address_;
454     }
455     return true;
456   }
457   return false;
458 }
459 
GetNetworkFromAddress(const rtc::IPAddress & ip) const460 Network* NetworkManagerBase::GetNetworkFromAddress(
461     const rtc::IPAddress& ip) const {
462   for (Network* network : networks_) {
463     const auto& ips = network->GetIPs();
464     if (absl::c_any_of(ips, [&](const InterfaceAddress& existing_ip) {
465           return ip == static_cast<rtc::IPAddress>(existing_ip);
466         })) {
467       return network;
468     }
469   }
470   return nullptr;
471 }
472 
BasicNetworkManager()473 BasicNetworkManager::BasicNetworkManager()
474     : thread_(nullptr), sent_first_update_(false), start_count_(0) {}
475 
~BasicNetworkManager()476 BasicNetworkManager::~BasicNetworkManager() {}
477 
OnNetworksChanged()478 void BasicNetworkManager::OnNetworksChanged() {
479   RTC_LOG(LS_INFO) << "Network change was observed";
480   UpdateNetworksOnce();
481 }
482 
483 #if defined(__native_client__)
484 
CreateNetworks(bool include_ignored,NetworkList * networks) const485 bool BasicNetworkManager::CreateNetworks(bool include_ignored,
486                                          NetworkList* networks) const {
487   RTC_NOTREACHED();
488   RTC_LOG(LS_WARNING) << "BasicNetworkManager doesn't work on NaCl yet";
489   return false;
490 }
491 
492 #elif defined(WEBRTC_POSIX)
ConvertIfAddrs(struct ifaddrs * interfaces,IfAddrsConverter * ifaddrs_converter,bool include_ignored,NetworkList * networks) const493 void BasicNetworkManager::ConvertIfAddrs(struct ifaddrs* interfaces,
494                                          IfAddrsConverter* ifaddrs_converter,
495                                          bool include_ignored,
496                                          NetworkList* networks) const {
497   NetworkMap current_networks;
498 
499   for (struct ifaddrs* cursor = interfaces; cursor != nullptr;
500        cursor = cursor->ifa_next) {
501     IPAddress prefix;
502     IPAddress mask;
503     InterfaceAddress ip;
504     int scope_id = 0;
505 
506     // Some interfaces may not have address assigned.
507     if (!cursor->ifa_addr || !cursor->ifa_netmask) {
508       continue;
509     }
510     // Skip ones which are down.
511     if (!(cursor->ifa_flags & IFF_RUNNING)) {
512       continue;
513     }
514     // Skip unknown family.
515     if (cursor->ifa_addr->sa_family != AF_INET &&
516         cursor->ifa_addr->sa_family != AF_INET6) {
517       continue;
518     }
519     // Convert to InterfaceAddress.
520     if (!ifaddrs_converter->ConvertIfAddrsToIPAddress(cursor, &ip, &mask)) {
521       continue;
522     }
523 
524     // Special case for IPv6 address.
525     if (cursor->ifa_addr->sa_family == AF_INET6) {
526       if (IsIgnoredIPv6(ip)) {
527         continue;
528       }
529       scope_id =
530           reinterpret_cast<sockaddr_in6*>(cursor->ifa_addr)->sin6_scope_id;
531     }
532 
533     AdapterType adapter_type = ADAPTER_TYPE_UNKNOWN;
534     AdapterType vpn_underlying_adapter_type = ADAPTER_TYPE_UNKNOWN;
535     if (cursor->ifa_flags & IFF_LOOPBACK) {
536       adapter_type = ADAPTER_TYPE_LOOPBACK;
537     } else {
538       // If there is a network_monitor, use it to get the adapter type.
539       // Otherwise, get the adapter type based on a few name matching rules.
540       if (network_monitor_) {
541         adapter_type = network_monitor_->GetAdapterType(cursor->ifa_name);
542       }
543       if (adapter_type == ADAPTER_TYPE_UNKNOWN) {
544         adapter_type = GetAdapterTypeFromName(cursor->ifa_name);
545       }
546     }
547 
548     if (adapter_type == ADAPTER_TYPE_VPN && network_monitor_) {
549       vpn_underlying_adapter_type =
550           network_monitor_->GetVpnUnderlyingAdapterType(cursor->ifa_name);
551     }
552     int prefix_length = CountIPMaskBits(mask);
553     prefix = TruncateIP(ip, prefix_length);
554     std::string key =
555         MakeNetworkKey(std::string(cursor->ifa_name), prefix, prefix_length);
556     auto iter = current_networks.find(key);
557     if (iter == current_networks.end()) {
558       // TODO(phoglund): Need to recognize other types as well.
559       std::unique_ptr<Network> network(
560           new Network(cursor->ifa_name, cursor->ifa_name, prefix, prefix_length,
561                       adapter_type));
562       network->set_default_local_address_provider(this);
563       network->set_scope_id(scope_id);
564       network->AddIP(ip);
565       network->set_ignored(IsIgnoredNetwork(*network));
566       network->set_underlying_type_for_vpn(vpn_underlying_adapter_type);
567       if (include_ignored || !network->ignored()) {
568         current_networks[key] = network.get();
569         networks->push_back(network.release());
570       }
571     } else {
572       Network* existing_network = iter->second;
573       existing_network->AddIP(ip);
574       if (adapter_type != ADAPTER_TYPE_UNKNOWN) {
575         existing_network->set_type(adapter_type);
576         existing_network->set_underlying_type_for_vpn(
577             vpn_underlying_adapter_type);
578       }
579     }
580   }
581 }
582 
CreateNetworks(bool include_ignored,NetworkList * networks) const583 bool BasicNetworkManager::CreateNetworks(bool include_ignored,
584                                          NetworkList* networks) const {
585   struct ifaddrs* interfaces;
586   int error = getifaddrs(&interfaces);
587   if (error != 0) {
588     RTC_LOG_ERR(LERROR) << "getifaddrs failed to gather interface data: "
589                         << error;
590     return false;
591   }
592 
593   std::unique_ptr<IfAddrsConverter> ifaddrs_converter(CreateIfAddrsConverter());
594   ConvertIfAddrs(interfaces, ifaddrs_converter.get(), include_ignored,
595                  networks);
596 
597   freeifaddrs(interfaces);
598   return true;
599 }
600 
601 #elif defined(WEBRTC_WIN)
602 
GetPrefix(PIP_ADAPTER_PREFIX prefixlist,const IPAddress & ip,IPAddress * prefix)603 unsigned int GetPrefix(PIP_ADAPTER_PREFIX prefixlist,
604                        const IPAddress& ip,
605                        IPAddress* prefix) {
606   IPAddress current_prefix;
607   IPAddress best_prefix;
608   unsigned int best_length = 0;
609   while (prefixlist) {
610     // Look for the longest matching prefix in the prefixlist.
611     if (prefixlist->Address.lpSockaddr == nullptr ||
612         prefixlist->Address.lpSockaddr->sa_family != ip.family()) {
613       prefixlist = prefixlist->Next;
614       continue;
615     }
616     switch (prefixlist->Address.lpSockaddr->sa_family) {
617       case AF_INET: {
618         sockaddr_in* v4_addr =
619             reinterpret_cast<sockaddr_in*>(prefixlist->Address.lpSockaddr);
620         current_prefix = IPAddress(v4_addr->sin_addr);
621         break;
622       }
623       case AF_INET6: {
624         sockaddr_in6* v6_addr =
625             reinterpret_cast<sockaddr_in6*>(prefixlist->Address.lpSockaddr);
626         current_prefix = IPAddress(v6_addr->sin6_addr);
627         break;
628       }
629       default: {
630         prefixlist = prefixlist->Next;
631         continue;
632       }
633     }
634     if (TruncateIP(ip, prefixlist->PrefixLength) == current_prefix &&
635         prefixlist->PrefixLength > best_length) {
636       best_prefix = current_prefix;
637       best_length = prefixlist->PrefixLength;
638     }
639     prefixlist = prefixlist->Next;
640   }
641   *prefix = best_prefix;
642   return best_length;
643 }
644 
CreateNetworks(bool include_ignored,NetworkList * networks) const645 bool BasicNetworkManager::CreateNetworks(bool include_ignored,
646                                          NetworkList* networks) const {
647   NetworkMap current_networks;
648   // MSDN recommends a 15KB buffer for the first try at GetAdaptersAddresses.
649   size_t buffer_size = 16384;
650   std::unique_ptr<char[]> adapter_info(new char[buffer_size]);
651   PIP_ADAPTER_ADDRESSES adapter_addrs =
652       reinterpret_cast<PIP_ADAPTER_ADDRESSES>(adapter_info.get());
653   int adapter_flags = (GAA_FLAG_SKIP_DNS_SERVER | GAA_FLAG_SKIP_ANYCAST |
654                        GAA_FLAG_SKIP_MULTICAST | GAA_FLAG_INCLUDE_PREFIX);
655   int ret = 0;
656   do {
657     adapter_info.reset(new char[buffer_size]);
658     adapter_addrs = reinterpret_cast<PIP_ADAPTER_ADDRESSES>(adapter_info.get());
659     ret = GetAdaptersAddresses(AF_UNSPEC, adapter_flags, 0, adapter_addrs,
660                                reinterpret_cast<PULONG>(&buffer_size));
661   } while (ret == ERROR_BUFFER_OVERFLOW);
662   if (ret != ERROR_SUCCESS) {
663     return false;
664   }
665   int count = 0;
666   while (adapter_addrs) {
667     if (adapter_addrs->OperStatus == IfOperStatusUp) {
668       PIP_ADAPTER_UNICAST_ADDRESS address = adapter_addrs->FirstUnicastAddress;
669       PIP_ADAPTER_PREFIX prefixlist = adapter_addrs->FirstPrefix;
670       std::string name;
671       std::string description;
672 #if !defined(NDEBUG)
673       name = ToUtf8(adapter_addrs->FriendlyName,
674                     wcslen(adapter_addrs->FriendlyName));
675 #endif
676       description = ToUtf8(adapter_addrs->Description,
677                            wcslen(adapter_addrs->Description));
678       for (; address; address = address->Next) {
679 #if defined(NDEBUG)
680         name = rtc::ToString(count);
681 #endif
682 
683         IPAddress ip;
684         int scope_id = 0;
685         std::unique_ptr<Network> network;
686         switch (address->Address.lpSockaddr->sa_family) {
687           case AF_INET: {
688             sockaddr_in* v4_addr =
689                 reinterpret_cast<sockaddr_in*>(address->Address.lpSockaddr);
690             ip = IPAddress(v4_addr->sin_addr);
691             break;
692           }
693           case AF_INET6: {
694             sockaddr_in6* v6_addr =
695                 reinterpret_cast<sockaddr_in6*>(address->Address.lpSockaddr);
696             scope_id = v6_addr->sin6_scope_id;
697             ip = IPAddress(v6_addr->sin6_addr);
698 
699             if (IsIgnoredIPv6(InterfaceAddress(ip))) {
700               continue;
701             }
702 
703             break;
704           }
705           default: {
706             continue;
707           }
708         }
709 
710         IPAddress prefix;
711         int prefix_length = GetPrefix(prefixlist, ip, &prefix);
712         std::string key = MakeNetworkKey(name, prefix, prefix_length);
713         auto existing_network = current_networks.find(key);
714         if (existing_network == current_networks.end()) {
715           AdapterType adapter_type = ADAPTER_TYPE_UNKNOWN;
716           switch (adapter_addrs->IfType) {
717             case IF_TYPE_SOFTWARE_LOOPBACK:
718               adapter_type = ADAPTER_TYPE_LOOPBACK;
719               break;
720             case IF_TYPE_ETHERNET_CSMACD:
721             case IF_TYPE_ETHERNET_3MBIT:
722             case IF_TYPE_IEEE80212:
723             case IF_TYPE_FASTETHER:
724             case IF_TYPE_FASTETHER_FX:
725             case IF_TYPE_GIGABITETHERNET:
726               adapter_type = ADAPTER_TYPE_ETHERNET;
727               break;
728             case IF_TYPE_IEEE80211:
729               adapter_type = ADAPTER_TYPE_WIFI;
730               break;
731             case IF_TYPE_WWANPP:
732             case IF_TYPE_WWANPP2:
733               adapter_type = ADAPTER_TYPE_CELLULAR;
734               break;
735             default:
736               // TODO(phoglund): Need to recognize other types as well.
737               adapter_type = ADAPTER_TYPE_UNKNOWN;
738               break;
739           }
740           std::unique_ptr<Network> network(new Network(
741               name, description, prefix, prefix_length, adapter_type));
742           network->set_default_local_address_provider(this);
743           network->set_mdns_responder_provider(this);
744           network->set_scope_id(scope_id);
745           network->AddIP(ip);
746           bool ignored = IsIgnoredNetwork(*network);
747           network->set_ignored(ignored);
748           if (include_ignored || !network->ignored()) {
749             current_networks[key] = network.get();
750             networks->push_back(network.release());
751           }
752         } else {
753           (*existing_network).second->AddIP(ip);
754         }
755       }
756       // Count is per-adapter - all 'Networks' created from the same
757       // adapter need to have the same name.
758       ++count;
759     }
760     adapter_addrs = adapter_addrs->Next;
761   }
762   return true;
763 }
764 #endif  // WEBRTC_WIN
765 
IsIgnoredNetwork(const Network & network) const766 bool BasicNetworkManager::IsIgnoredNetwork(const Network& network) const {
767   // Ignore networks on the explicit ignore list.
768   for (const std::string& ignored_name : network_ignore_list_) {
769     if (network.name() == ignored_name) {
770       return true;
771     }
772   }
773 
774 #if defined(WEBRTC_POSIX)
775   // Filter out VMware/VirtualBox interfaces, typically named vmnet1,
776   // vmnet8, or vboxnet0.
777   if (strncmp(network.name().c_str(), "vmnet", 5) == 0 ||
778       strncmp(network.name().c_str(), "vnic", 4) == 0 ||
779       strncmp(network.name().c_str(), "vboxnet", 7) == 0) {
780     return true;
781   }
782 #elif defined(WEBRTC_WIN)
783   // Ignore any HOST side vmware adapters with a description like:
784   // VMware Virtual Ethernet Adapter for VMnet1
785   // but don't ignore any GUEST side adapters with a description like:
786   // VMware Accelerated AMD PCNet Adapter #2
787   if (strstr(network.description().c_str(), "VMnet") != nullptr) {
788     return true;
789   }
790 #endif
791 
792   // Ignore any networks with a 0.x.y.z IP
793   if (network.prefix().family() == AF_INET) {
794     return (network.prefix().v4AddressAsHostOrderInteger() < 0x01000000);
795   }
796 
797   return false;
798 }
799 
StartUpdating()800 void BasicNetworkManager::StartUpdating() {
801   thread_ = Thread::Current();
802   if (start_count_) {
803     // If network interfaces are already discovered and signal is sent,
804     // we should trigger network signal immediately for the new clients
805     // to start allocating ports.
806     if (sent_first_update_)
807       thread_->Post(RTC_FROM_HERE, this, kSignalNetworksMessage);
808   } else {
809     thread_->Post(RTC_FROM_HERE, this, kUpdateNetworksMessage);
810     StartNetworkMonitor();
811   }
812   ++start_count_;
813 }
814 
StopUpdating()815 void BasicNetworkManager::StopUpdating() {
816   RTC_DCHECK(Thread::Current() == thread_);
817   if (!start_count_)
818     return;
819 
820   --start_count_;
821   if (!start_count_) {
822     thread_->Clear(this);
823     sent_first_update_ = false;
824     StopNetworkMonitor();
825   }
826 }
827 
StartNetworkMonitor()828 void BasicNetworkManager::StartNetworkMonitor() {
829   NetworkMonitorFactory* factory = NetworkMonitorFactory::GetFactory();
830   if (factory == nullptr) {
831     return;
832   }
833   if (!network_monitor_) {
834     network_monitor_.reset(factory->CreateNetworkMonitor());
835     if (!network_monitor_) {
836       return;
837     }
838     network_monitor_->SignalNetworksChanged.connect(
839         this, &BasicNetworkManager::OnNetworksChanged);
840   }
841   network_monitor_->Start();
842 }
843 
StopNetworkMonitor()844 void BasicNetworkManager::StopNetworkMonitor() {
845   if (!network_monitor_) {
846     return;
847   }
848   network_monitor_->Stop();
849 }
850 
OnMessage(Message * msg)851 void BasicNetworkManager::OnMessage(Message* msg) {
852   switch (msg->message_id) {
853     case kUpdateNetworksMessage: {
854       UpdateNetworksContinually();
855       break;
856     }
857     case kSignalNetworksMessage: {
858       SignalNetworksChanged();
859       break;
860     }
861     default:
862       RTC_NOTREACHED();
863   }
864 }
865 
QueryDefaultLocalAddress(int family) const866 IPAddress BasicNetworkManager::QueryDefaultLocalAddress(int family) const {
867   RTC_DCHECK(thread_ == Thread::Current());
868   RTC_DCHECK(thread_->socketserver() != nullptr);
869   RTC_DCHECK(family == AF_INET || family == AF_INET6);
870 
871   std::unique_ptr<AsyncSocket> socket(
872       thread_->socketserver()->CreateAsyncSocket(family, SOCK_DGRAM));
873   if (!socket) {
874     RTC_LOG_ERR(LERROR) << "Socket creation failed";
875     return IPAddress();
876   }
877 
878   if (socket->Connect(SocketAddress(
879           family == AF_INET ? kPublicIPv4Host : kPublicIPv6Host, kPublicPort)) <
880       0) {
881     if (socket->GetError() != ENETUNREACH &&
882         socket->GetError() != EHOSTUNREACH) {
883       // Ignore the expected case of "host/net unreachable" - which happens if
884       // the network is V4- or V6-only.
885       RTC_LOG(LS_INFO) << "Connect failed with " << socket->GetError();
886     }
887     return IPAddress();
888   }
889   return socket->GetLocalAddress().ipaddr();
890 }
891 
UpdateNetworksOnce()892 void BasicNetworkManager::UpdateNetworksOnce() {
893   if (!start_count_)
894     return;
895 
896   RTC_DCHECK(Thread::Current() == thread_);
897 
898   NetworkList list;
899   if (!CreateNetworks(false, &list)) {
900     SignalError();
901   } else {
902     bool changed;
903     NetworkManager::Stats stats;
904     MergeNetworkList(list, &changed, &stats);
905     set_default_local_addresses(QueryDefaultLocalAddress(AF_INET),
906                                 QueryDefaultLocalAddress(AF_INET6));
907     if (changed || !sent_first_update_) {
908       SignalNetworksChanged();
909       sent_first_update_ = true;
910     }
911   }
912 }
913 
UpdateNetworksContinually()914 void BasicNetworkManager::UpdateNetworksContinually() {
915   UpdateNetworksOnce();
916   thread_->PostDelayed(RTC_FROM_HERE, kNetworksUpdateIntervalMs, this,
917                        kUpdateNetworksMessage);
918 }
919 
DumpNetworks()920 void BasicNetworkManager::DumpNetworks() {
921   NetworkList list;
922   GetNetworks(&list);
923   RTC_LOG(LS_INFO) << "NetworkManager detected " << list.size() << " networks:";
924   for (const Network* network : list) {
925     RTC_LOG(LS_INFO) << network->ToString() << ": " << network->description()
926                      << ", active ? " << network->active()
927                      << ((network->ignored()) ? ", Ignored" : "");
928   }
929 }
930 
Network(const std::string & name,const std::string & desc,const IPAddress & prefix,int prefix_length)931 Network::Network(const std::string& name,
932                  const std::string& desc,
933                  const IPAddress& prefix,
934                  int prefix_length)
935     : name_(name),
936       description_(desc),
937       prefix_(prefix),
938       prefix_length_(prefix_length),
939       key_(MakeNetworkKey(name, prefix, prefix_length)),
940       scope_id_(0),
941       ignored_(false),
942       type_(ADAPTER_TYPE_UNKNOWN),
943       preference_(0),
944       use_differentiated_cellular_costs_(webrtc::field_trial::IsEnabled(
945           "WebRTC-UseDifferentiatedCellularCosts")) {}
946 
Network(const std::string & name,const std::string & desc,const IPAddress & prefix,int prefix_length,AdapterType type)947 Network::Network(const std::string& name,
948                  const std::string& desc,
949                  const IPAddress& prefix,
950                  int prefix_length,
951                  AdapterType type)
952     : name_(name),
953       description_(desc),
954       prefix_(prefix),
955       prefix_length_(prefix_length),
956       key_(MakeNetworkKey(name, prefix, prefix_length)),
957       scope_id_(0),
958       ignored_(false),
959       type_(type),
960       preference_(0),
961       use_differentiated_cellular_costs_(webrtc::field_trial::IsEnabled(
962           "WebRTC-UseDifferentiatedCellularCosts")) {}
963 
964 Network::Network(const Network&) = default;
965 
966 Network::~Network() = default;
967 
968 // Sets the addresses of this network. Returns true if the address set changed.
969 // Change detection is short circuited if the changed argument is true.
SetIPs(const std::vector<InterfaceAddress> & ips,bool changed)970 bool Network::SetIPs(const std::vector<InterfaceAddress>& ips, bool changed) {
971   // Detect changes with a nested loop; n-squared but we expect on the order
972   // of 2-3 addresses per network.
973   changed = changed || ips.size() != ips_.size();
974   if (!changed) {
975     for (const InterfaceAddress& ip : ips) {
976       if (!absl::c_linear_search(ips_, ip)) {
977         changed = true;
978         break;
979       }
980     }
981   }
982 
983   ips_ = ips;
984   return changed;
985 }
986 
987 // Select the best IP address to use from this Network.
GetBestIP() const988 IPAddress Network::GetBestIP() const {
989   if (ips_.size() == 0) {
990     return IPAddress();
991   }
992 
993   if (prefix_.family() == AF_INET) {
994     return static_cast<IPAddress>(ips_.at(0));
995   }
996 
997   InterfaceAddress selected_ip, ula_ip;
998 
999   for (const InterfaceAddress& ip : ips_) {
1000     // Ignore any address which has been deprecated already.
1001     if (ip.ipv6_flags() & IPV6_ADDRESS_FLAG_DEPRECATED)
1002       continue;
1003 
1004     // ULA address should only be returned when we have no other
1005     // global IP.
1006     if (IPIsULA(static_cast<const IPAddress&>(ip))) {
1007       ula_ip = ip;
1008       continue;
1009     }
1010     selected_ip = ip;
1011 
1012     // Search could stop once a temporary non-deprecated one is found.
1013     if (ip.ipv6_flags() & IPV6_ADDRESS_FLAG_TEMPORARY)
1014       break;
1015   }
1016 
1017   // No proper global IPv6 address found, use ULA instead.
1018   if (IPIsUnspec(selected_ip) && !IPIsUnspec(ula_ip)) {
1019     selected_ip = ula_ip;
1020   }
1021 
1022   return static_cast<IPAddress>(selected_ip);
1023 }
1024 
GetMdnsResponder() const1025 webrtc::MdnsResponderInterface* Network::GetMdnsResponder() const {
1026   if (mdns_responder_provider_ == nullptr) {
1027     return nullptr;
1028   }
1029   return mdns_responder_provider_->GetMdnsResponder();
1030 }
1031 
GetCost() const1032 uint16_t Network::GetCost() const {
1033   AdapterType type = IsVpn() ? underlying_type_for_vpn_ : type_;
1034   return ComputeNetworkCostByType(type, use_differentiated_cellular_costs_);
1035 }
1036 
ToString() const1037 std::string Network::ToString() const {
1038   rtc::StringBuilder ss;
1039   // Print out the first space-terminated token of the network desc, plus
1040   // the IP address.
1041   ss << "Net[" << description_.substr(0, description_.find(' ')) << ":"
1042      << prefix_.ToSensitiveString() << "/" << prefix_length_ << ":"
1043      << AdapterTypeToString(type_);
1044   if (IsVpn()) {
1045     ss << "/" << AdapterTypeToString(underlying_type_for_vpn_);
1046   }
1047   ss << ":id=" << id_ << "]";
1048   return ss.Release();
1049 }
1050 
1051 }  // namespace rtc
1052