blob: c62c3ce483be0e2bb20c32f8bef383fbea081058 [file] [log] [blame]
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001/*
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
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020011#include "rtc_base/network.h"
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000012
13#if defined(WEBRTC_POSIX)
14// linux/if.h can't be included at the same time as the posix sys/if.h, and
15// it's transitively required by linux/route.h, so include that version on
16// linux instead of the standard posix one.
17#if defined(WEBRTC_LINUX)
18#include <linux/if.h>
19#include <linux/route.h>
20#elif !defined(__native_client__)
21#include <net/if.h>
22#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000023#endif // WEBRTC_POSIX
24
25#if defined(WEBRTC_WIN)
Mirko Bonadei01914412018-03-23 16:30:58 +010026#include <iphlpapi.h>
Yves Gerey665174f2018-06-19 15:03:05 +020027#include "rtc_base/win32.h"
Guo-wei Shieh9faf1542015-12-28 14:06:55 -080028#elif !defined(__native_client__)
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020029#include "rtc_base/ifaddrs_converter.h"
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000030#endif
31
32#include <stdio.h>
33
34#include <algorithm>
jbauch555604a2016-04-26 03:13:22 -070035#include <memory>
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000036
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020037#include "rtc_base/checks.h"
38#include "rtc_base/logging.h"
Steve Anton10542f22019-01-11 09:11:00 -080039#include "rtc_base/network_monitor.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020040#include "rtc_base/socket.h" // includes something that makes windows happy
Steve Anton10542f22019-01-11 09:11:00 -080041#include "rtc_base/string_encode.h"
42#include "rtc_base/string_utils.h"
Jonas Olsson366a50c2018-09-06 13:41:30 +020043#include "rtc_base/strings/string_builder.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020044#include "rtc_base/thread.h"
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000045
46namespace rtc {
47namespace {
48
Peter Boström0c4e06b2015-10-07 12:23:21 +020049const uint32_t kUpdateNetworksMessage = 1;
50const uint32_t kSignalNetworksMessage = 2;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000051
52// Fetch list of networks every two seconds.
53const int kNetworksUpdateIntervalMs = 2000;
54
55const int kHighestNetworkPreference = 127;
56
guoweis@webrtc.org4bbd3c82014-09-09 13:54:45 +000057typedef struct {
58 Network* net;
guoweis@webrtc.orgfa603982014-09-09 23:42:40 +000059 std::vector<InterfaceAddress> ips;
guoweis@webrtc.org4bbd3c82014-09-09 13:54:45 +000060} AddressList;
61
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000062bool CompareNetworks(const Network* a, const Network* b) {
63 if (a->prefix_length() == b->prefix_length()) {
64 if (a->name() == b->name()) {
65 return a->prefix() < b->prefix();
66 }
67 }
68 return a->name() < b->name();
69}
70
71bool SortNetworks(const Network* a, const Network* b) {
72 // Network types will be preferred above everything else while sorting
73 // Networks.
74
75 // Networks are sorted first by type.
76 if (a->type() != b->type()) {
77 return a->type() < b->type();
78 }
79
guoweis@webrtc.org369a6372014-09-17 22:37:29 +000080 IPAddress ip_a = a->GetBestIP();
81 IPAddress ip_b = b->GetBestIP();
82
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000083 // After type, networks are sorted by IP address precedence values
84 // from RFC 3484-bis
guoweis@webrtc.org369a6372014-09-17 22:37:29 +000085 if (IPAddressPrecedence(ip_a) != IPAddressPrecedence(ip_b)) {
86 return IPAddressPrecedence(ip_a) > IPAddressPrecedence(ip_b);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000087 }
88
89 // TODO(mallinath) - Add VPN and Link speed conditions while sorting.
90
91 // Networks are sorted last by key.
deadbeef3427f532017-07-26 16:09:33 -070092 return a->key() < b->key();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000093}
94
95std::string AdapterTypeToString(AdapterType type) {
96 switch (type) {
Qingsi Wang9f1de692018-06-28 15:38:09 -070097 case ADAPTER_TYPE_ANY:
Qingsi Wang01560de2018-07-26 10:44:02 -070098 return "Wildcard";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000099 case ADAPTER_TYPE_UNKNOWN:
100 return "Unknown";
101 case ADAPTER_TYPE_ETHERNET:
102 return "Ethernet";
103 case ADAPTER_TYPE_WIFI:
104 return "Wifi";
105 case ADAPTER_TYPE_CELLULAR:
106 return "Cellular";
107 case ADAPTER_TYPE_VPN:
108 return "VPN";
phoglund@webrtc.org006521d2015-02-12 09:23:59 +0000109 case ADAPTER_TYPE_LOOPBACK:
110 return "Loopback";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000111 default:
nisseeb4ca4e2017-01-12 02:24:27 -0800112 RTC_NOTREACHED() << "Invalid type " << type;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000113 return std::string();
114 }
115}
116
Qingsi Wangde2ed7d2018-04-27 14:25:37 -0700117uint16_t ComputeNetworkCostByType(int type) {
118 switch (type) {
119 case rtc::ADAPTER_TYPE_ETHERNET:
120 case rtc::ADAPTER_TYPE_LOOPBACK:
121 return kNetworkCostMin;
122 case rtc::ADAPTER_TYPE_WIFI:
123 return kNetworkCostLow;
124 case rtc::ADAPTER_TYPE_CELLULAR:
125 return kNetworkCostHigh;
Qingsi Wang9f1de692018-06-28 15:38:09 -0700126 case rtc::ADAPTER_TYPE_ANY:
127 // Candidates gathered from the any-address/wildcard ports, as backups,
128 // are given the maximum cost so that if there are other candidates with
129 // known interface types, we would not select candidate pairs using these
130 // backup candidates if other selection criteria with higher precedence
131 // (network conditions over the route) are the same. Note that setting the
132 // cost to kNetworkCostUnknown would be problematic since
133 // ADAPTER_TYPE_CELLULAR would then have a higher cost. See
134 // P2PTransportChannel::SortConnectionsAndUpdateState for how we rank and
135 // select candidate pairs, where the network cost is among the criteria.
136 return kNetworkCostMax;
Qingsi Wangde2ed7d2018-04-27 14:25:37 -0700137 case rtc::ADAPTER_TYPE_VPN:
138 // The cost of a VPN should be computed using its underlying network type.
139 RTC_NOTREACHED();
140 return kNetworkCostUnknown;
141 default:
142 return kNetworkCostUnknown;
143 }
144}
145
thakis06689a12015-12-30 15:05:30 -0800146#if !defined(__native_client__)
Guo-wei Shieh9faf1542015-12-28 14:06:55 -0800147bool IsIgnoredIPv6(const InterfaceAddress& ip) {
guoweis@webrtc.orgb91d0f52015-03-17 14:43:20 +0000148 if (ip.family() != AF_INET6) {
149 return false;
150 }
151
152 // Link-local addresses require scope id to be bound successfully.
153 // However, our IPAddress structure doesn't carry that so the
154 // information is lost and causes binding failure.
155 if (IPIsLinkLocal(ip)) {
156 return true;
157 }
158
159 // Any MAC based IPv6 should be avoided to prevent the MAC tracking.
160 if (IPIsMacBased(ip)) {
161 return true;
162 }
163
Guo-wei Shieh9faf1542015-12-28 14:06:55 -0800164 // Ignore deprecated IPv6.
165 if (ip.ipv6_flags() & IPV6_ADDRESS_FLAG_DEPRECATED) {
166 return true;
167 }
168
guoweis@webrtc.orgb91d0f52015-03-17 14:43:20 +0000169 return false;
170}
thakis06689a12015-12-30 15:05:30 -0800171#endif // !defined(__native_client__)
guoweis@webrtc.orgb91d0f52015-03-17 14:43:20 +0000172
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000173} // namespace
174
Guo-wei Shieh9af97f82015-11-10 14:47:39 -0800175// These addresses are used as the targets to find out the default local address
176// on a multi-homed endpoint. They are actually DNS servers.
177const char kPublicIPv4Host[] = "8.8.8.8";
178const char kPublicIPv6Host[] = "2001:4860:4860::8888";
179const int kPublicPort = 53; // DNS port.
180
Yves Gerey665174f2018-06-19 15:03:05 +0200181std::string MakeNetworkKey(const std::string& name,
182 const IPAddress& prefix,
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000183 int prefix_length) {
Jonas Olsson366a50c2018-09-06 13:41:30 +0200184 rtc::StringBuilder ost;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000185 ost << name << "%" << prefix.ToString() << "/" << prefix_length;
Jonas Olsson84df1c72018-09-14 16:59:32 +0200186 return ost.Release();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000187}
Qingsi Wange53ac042018-05-08 11:55:07 -0700188// Test if the network name matches the type<number> pattern, e.g. eth0. The
189// matching is case-sensitive.
190bool MatchTypeNameWithIndexPattern(const std::string& network_name,
191 const std::string& type_name) {
192 if (network_name.find(type_name) != 0) {
193 return false;
194 }
195 return std::find_if(network_name.begin() + type_name.size(),
196 network_name.end(),
197 [](char c) { return !isdigit(c); }) == network_name.end();
198}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000199
Qingsi Wange53ac042018-05-08 11:55:07 -0700200// A cautious note that this method may not provide an accurate adapter type
201// based on the string matching. Incorrect type of adapters can affect the
202// result of the downstream network filtering, see e.g.
203// BasicPortAllocatorSession::GetNetworks when
204// PORTALLOCATOR_DISABLE_COSTLY_NETWORKS is turned on.
Taylor Brandstetter8bac1d92018-01-24 17:38:00 -0800205AdapterType GetAdapterTypeFromName(const char* network_name) {
Qingsi Wange53ac042018-05-08 11:55:07 -0700206 if (MatchTypeNameWithIndexPattern(network_name, "lo")) {
207 // Note that we have a more robust way to determine if a network interface
208 // is a loopback interface by checking the flag IFF_LOOPBACK in ifa_flags of
209 // an ifaddr struct. See ConvertIfAddrs in this file.
210 return ADAPTER_TYPE_LOOPBACK;
211 }
212 if (MatchTypeNameWithIndexPattern(network_name, "eth")) {
213 return ADAPTER_TYPE_ETHERNET;
214 }
215
216 if (MatchTypeNameWithIndexPattern(network_name, "ipsec") ||
217 MatchTypeNameWithIndexPattern(network_name, "tun") ||
218 MatchTypeNameWithIndexPattern(network_name, "utun") ||
219 MatchTypeNameWithIndexPattern(network_name, "tap")) {
Taylor Brandstetter8bac1d92018-01-24 17:38:00 -0800220 return ADAPTER_TYPE_VPN;
221 }
222#if defined(WEBRTC_IOS)
223 // Cell networks are pdp_ipN on iOS.
Qingsi Wange53ac042018-05-08 11:55:07 -0700224 if (MatchTypeNameWithIndexPattern(network_name, "pdp_ip")) {
Taylor Brandstetter8bac1d92018-01-24 17:38:00 -0800225 return ADAPTER_TYPE_CELLULAR;
226 }
Qingsi Wange53ac042018-05-08 11:55:07 -0700227 if (MatchTypeNameWithIndexPattern(network_name, "en")) {
Taylor Brandstetter8bac1d92018-01-24 17:38:00 -0800228 // This may not be most accurate because sometimes Ethernet interface
229 // name also starts with "en" but it is better than showing it as
230 // "unknown" type.
231 // TODO(honghaiz): Write a proper IOS network manager.
232 return ADAPTER_TYPE_WIFI;
233 }
234#elif defined(WEBRTC_ANDROID)
Qingsi Wange53ac042018-05-08 11:55:07 -0700235 if (MatchTypeNameWithIndexPattern(network_name, "rmnet") ||
236 MatchTypeNameWithIndexPattern(network_name, "rmnet_data") ||
237 MatchTypeNameWithIndexPattern(network_name, "v4-rmnet") ||
238 MatchTypeNameWithIndexPattern(network_name, "v4-rmnet_data")) {
Taylor Brandstetter8bac1d92018-01-24 17:38:00 -0800239 return ADAPTER_TYPE_CELLULAR;
240 }
Qingsi Wange53ac042018-05-08 11:55:07 -0700241 if (MatchTypeNameWithIndexPattern(network_name, "wlan")) {
Taylor Brandstetter8bac1d92018-01-24 17:38:00 -0800242 return ADAPTER_TYPE_WIFI;
243 }
244#endif
245
246 return ADAPTER_TYPE_UNKNOWN;
247}
248
Yves Gerey665174f2018-06-19 15:03:05 +0200249NetworkManager::NetworkManager() {}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000250
Yves Gerey665174f2018-06-19 15:03:05 +0200251NetworkManager::~NetworkManager() {}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000252
Guo-wei Shieh86cb9232015-08-19 10:57:53 -0700253NetworkManager::EnumerationPermission NetworkManager::enumeration_permission()
254 const {
guoweisea1012b2015-08-21 09:06:28 -0700255 return ENUMERATION_ALLOWED;
Guo-wei Shieh86cb9232015-08-19 10:57:53 -0700256}
257
Guo-wei Shieh9af97f82015-11-10 14:47:39 -0800258bool NetworkManager::GetDefaultLocalAddress(int family, IPAddress* addr) const {
259 return false;
260}
261
Qingsi Wang7852d292018-10-31 11:17:07 -0700262webrtc::MdnsResponderInterface* NetworkManager::GetMdnsResponder() const {
Qingsi Wang09619332018-09-12 22:51:55 -0700263 return nullptr;
264}
265
guoweis@webrtc.org2444d962015-01-30 00:09:28 +0000266NetworkManagerBase::NetworkManagerBase()
guoweisea1012b2015-08-21 09:06:28 -0700267 : enumeration_permission_(NetworkManager::ENUMERATION_ALLOWED),
Yves Gerey665174f2018-06-19 15:03:05 +0200268 ipv6_enabled_(true) {}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000269
270NetworkManagerBase::~NetworkManagerBase() {
pthatcher@webrtc.org5950b642014-12-01 23:18:27 +0000271 for (const auto& kv : networks_map_) {
272 delete kv.second;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000273 }
274}
275
Guo-wei Shieh47872ec2015-08-19 10:32:46 -0700276NetworkManager::EnumerationPermission
277NetworkManagerBase::enumeration_permission() const {
278 return enumeration_permission_;
279}
280
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000281void 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(
Qingsi Wang9f1de692018-06-28 15:38:09 -0700285 new rtc::Network("any", "any", ipv4_any_address, 0, ADAPTER_TYPE_ANY));
Guo-wei Shieh9af97f82015-11-10 14:47:39 -0800286 ipv4_any_address_network_->set_default_local_address_provider(this);
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000287 ipv4_any_address_network_->AddIP(ipv4_any_address);
Qingsi Wang7852d292018-10-31 11:17:07 -0700288 ipv4_any_address_network_->SetMdnsResponder(GetMdnsResponder());
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000289 }
290 networks->push_back(ipv4_any_address_network_.get());
291
292 if (ipv6_enabled()) {
293 if (!ipv6_any_address_network_) {
294 const rtc::IPAddress ipv6_any_address(in6addr_any);
Qingsi Wang9f1de692018-06-28 15:38:09 -0700295 ipv6_any_address_network_.reset(new rtc::Network(
296 "any", "any", ipv6_any_address, 0, ADAPTER_TYPE_ANY));
Guo-wei Shieh9af97f82015-11-10 14:47:39 -0800297 ipv6_any_address_network_->set_default_local_address_provider(this);
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000298 ipv6_any_address_network_->AddIP(ipv6_any_address);
Qingsi Wang7852d292018-10-31 11:17:07 -0700299 ipv6_any_address_network_->SetMdnsResponder(GetMdnsResponder());
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000300 }
301 networks->push_back(ipv6_any_address_network_.get());
302 }
303}
304
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000305void NetworkManagerBase::GetNetworks(NetworkList* result) const {
guoweis@webrtc.org2444d962015-01-30 00:09:28 +0000306 result->clear();
deadbeef3427f532017-07-26 16:09:33 -0700307 result->insert(result->begin(), networks_.begin(), networks_.end());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000308}
309
310void NetworkManagerBase::MergeNetworkList(const NetworkList& new_networks,
311 bool* changed) {
guoweis@webrtc.orga094cac2015-01-28 19:34:05 +0000312 NetworkManager::Stats stats;
313 MergeNetworkList(new_networks, changed, &stats);
314}
315
316void NetworkManagerBase::MergeNetworkList(const NetworkList& new_networks,
317 bool* changed,
318 NetworkManager::Stats* stats) {
honghaizdb8cf502015-12-21 13:08:46 -0800319 *changed = false;
guoweis@webrtc.org4bbd3c82014-09-09 13:54:45 +0000320 // AddressList in this map will track IP addresses for all Networks
321 // with the same key.
322 std::map<std::string, AddressList> consolidated_address_list;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000323 NetworkList list(new_networks);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000324 std::sort(list.begin(), list.end(), CompareNetworks);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000325 // First, build a set of network-keys to the ipaddresses.
pthatcher@webrtc.org5950b642014-12-01 23:18:27 +0000326 for (Network* network : list) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000327 bool might_add_to_merged_list = false;
Yves Gerey665174f2018-06-19 15:03:05 +0200328 std::string key = MakeNetworkKey(network->name(), network->prefix(),
pthatcher@webrtc.org5950b642014-12-01 23:18:27 +0000329 network->prefix_length());
guoweis@webrtc.org4bbd3c82014-09-09 13:54:45 +0000330 if (consolidated_address_list.find(key) ==
331 consolidated_address_list.end()) {
332 AddressList addrlist;
pthatcher@webrtc.org5950b642014-12-01 23:18:27 +0000333 addrlist.net = network;
guoweis@webrtc.org4bbd3c82014-09-09 13:54:45 +0000334 consolidated_address_list[key] = addrlist;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000335 might_add_to_merged_list = true;
336 }
pthatcher@webrtc.org5950b642014-12-01 23:18:27 +0000337 const std::vector<InterfaceAddress>& addresses = network->GetIPs();
guoweis@webrtc.org4bbd3c82014-09-09 13:54:45 +0000338 AddressList& current_list = consolidated_address_list[key];
pthatcher@webrtc.org5950b642014-12-01 23:18:27 +0000339 for (const InterfaceAddress& address : addresses) {
340 current_list.ips.push_back(address);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000341 }
342 if (!might_add_to_merged_list) {
pthatcher@webrtc.org5950b642014-12-01 23:18:27 +0000343 delete network;
guoweis@webrtc.orga094cac2015-01-28 19:34:05 +0000344 } else {
345 if (current_list.ips[0].family() == AF_INET) {
346 stats->ipv4_network_count++;
347 } else {
nisseede5da42017-01-12 05:15:36 -0800348 RTC_DCHECK(current_list.ips[0].family() == AF_INET6);
guoweis@webrtc.orga094cac2015-01-28 19:34:05 +0000349 stats->ipv6_network_count++;
350 }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000351 }
352 }
353
354 // Next, look for existing network objects to re-use.
honghaizdb8cf502015-12-21 13:08:46 -0800355 // Result of Network merge. Element in this list should have unique key.
356 NetworkList merged_list;
pthatcher@webrtc.org5950b642014-12-01 23:18:27 +0000357 for (const auto& kv : consolidated_address_list) {
358 const std::string& key = kv.first;
359 Network* net = kv.second.net;
360 auto existing = networks_map_.find(key);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000361 if (existing == networks_map_.end()) {
362 // This network is new. Place it in the network map.
363 merged_list.push_back(net);
364 networks_map_[key] = net;
honghaiza0c44ea2016-03-23 16:07:48 -0700365 net->set_id(next_available_network_id_++);
guoweis@webrtc.org4bbd3c82014-09-09 13:54:45 +0000366 // Also, we might have accumulated IPAddresses from the first
367 // step, set it here.
pthatcher@webrtc.org5950b642014-12-01 23:18:27 +0000368 net->SetIPs(kv.second.ips, true);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000369 *changed = true;
370 } else {
371 // This network exists in the map already. Reset its IP addresses.
honghaizdb8cf502015-12-21 13:08:46 -0800372 Network* existing_net = existing->second;
373 *changed = existing_net->SetIPs(kv.second.ips, *changed);
374 merged_list.push_back(existing_net);
Honghai Zhang351d77b2016-05-20 15:08:29 -0700375 if (net->type() != ADAPTER_TYPE_UNKNOWN &&
376 net->type() != existing_net->type()) {
377 existing_net->set_type(net->type());
378 *changed = true;
379 }
honghaizdb8cf502015-12-21 13:08:46 -0800380 // If the existing network was not active, networks have changed.
381 if (!existing_net->active()) {
382 *changed = true;
383 }
nisseede5da42017-01-12 05:15:36 -0800384 RTC_DCHECK(net->active());
honghaizdb8cf502015-12-21 13:08:46 -0800385 if (existing_net != net) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000386 delete net;
387 }
388 }
Qingsi Wang7852d292018-10-31 11:17:07 -0700389 networks_map_[key]->SetMdnsResponder(GetMdnsResponder());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000390 }
honghaizdb8cf502015-12-21 13:08:46 -0800391 // It may still happen that the merged list is a subset of |networks_|.
392 // To detect this change, we compare their sizes.
393 if (merged_list.size() != networks_.size()) {
394 *changed = true;
395 }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000396
honghaizdb8cf502015-12-21 13:08:46 -0800397 // If the network list changes, we re-assign |networks_| to the merged list
398 // and re-sort it.
guoweis@webrtc.orga094cac2015-01-28 19:34:05 +0000399 if (*changed) {
honghaizdb8cf502015-12-21 13:08:46 -0800400 networks_ = merged_list;
401 // Reset the active states of all networks.
402 for (const auto& kv : networks_map_) {
honghaize3c6c822016-02-17 13:00:28 -0800403 Network* network = kv.second;
404 // If |network| is in the newly generated |networks_|, it is active.
405 bool found = std::find(networks_.begin(), networks_.end(), network) !=
406 networks_.end();
407 network->set_active(found);
honghaizdb8cf502015-12-21 13:08:46 -0800408 }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000409 std::sort(networks_.begin(), networks_.end(), 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;
pthatcher@webrtc.org5950b642014-12-01 23:18:27 +0000418 for (Network* network : networks_) {
419 network->set_preference(pref);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000420 if (pref > 0) {
421 --pref;
422 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100423 RTC_LOG(LS_ERROR) << "Too many network interfaces to handle!";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000424 break;
425 }
426 }
427 }
428}
429
Guo-wei Shieh9af97f82015-11-10 14:47:39 -0800430void 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
440bool NetworkManagerBase::GetDefaultLocalAddress(int family,
441 IPAddress* ipaddr) const {
Guo-wei Shieha34c39e2015-11-25 13:12:26 -0800442 if (family == AF_INET && !default_local_ipv4_address_.IsNil()) {
Guo-wei Shieh9af97f82015-11-10 14:47:39 -0800443 *ipaddr = default_local_ipv4_address_;
444 return true;
Guo-wei Shieha34c39e2015-11-25 13:12:26 -0800445 } else if (family == AF_INET6 && !default_local_ipv6_address_.IsNil()) {
honghaizaf83fe62016-04-18 14:50:44 -0700446 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 }
Guo-wei Shieh9af97f82015-11-10 14:47:39 -0800455 return true;
456 }
457 return false;
458}
459
honghaizaf83fe62016-04-18 14:50:44 -0700460Network* NetworkManagerBase::GetNetworkFromAddress(
461 const rtc::IPAddress& ip) const {
462 for (Network* network : networks_) {
463 const auto& ips = network->GetIPs();
464 if (std::find_if(ips.begin(), ips.end(),
465 [ip](const InterfaceAddress& existing_ip) {
466 return ip == static_cast<rtc::IPAddress>(existing_ip);
467 }) != ips.end()) {
468 return network;
469 }
470 }
471 return nullptr;
472}
473
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000474BasicNetworkManager::BasicNetworkManager()
deadbeef37f5ecf2017-02-27 14:06:41 -0800475 : thread_(nullptr),
476 sent_first_update_(false),
477 start_count_(0),
478 ignore_non_default_routes_(false) {}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000479
Yves Gerey665174f2018-06-19 15:03:05 +0200480BasicNetworkManager::~BasicNetworkManager() {}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000481
honghaiz023f3ef2015-10-19 09:39:32 -0700482void BasicNetworkManager::OnNetworksChanged() {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100483 RTC_LOG(LS_INFO) << "Network change was observed";
honghaiz023f3ef2015-10-19 09:39:32 -0700484 UpdateNetworksOnce();
485}
486
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000487#if defined(__native_client__)
488
489bool BasicNetworkManager::CreateNetworks(bool include_ignored,
490 NetworkList* networks) const {
nissec80e7412017-01-11 05:56:46 -0800491 RTC_NOTREACHED();
Mirko Bonadei675513b2017-11-09 11:09:25 +0100492 RTC_LOG(LS_WARNING) << "BasicNetworkManager doesn't work on NaCl yet";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000493 return false;
494}
495
496#elif defined(WEBRTC_POSIX)
497void BasicNetworkManager::ConvertIfAddrs(struct ifaddrs* interfaces,
Guo-wei Shieh9faf1542015-12-28 14:06:55 -0800498 IfAddrsConverter* ifaddrs_converter,
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000499 bool include_ignored,
500 NetworkList* networks) const {
501 NetworkMap current_networks;
Guo-wei Shieh9faf1542015-12-28 14:06:55 -0800502
deadbeef37f5ecf2017-02-27 14:06:41 -0800503 for (struct ifaddrs* cursor = interfaces; cursor != nullptr;
504 cursor = cursor->ifa_next) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000505 IPAddress prefix;
506 IPAddress mask;
Guo-wei Shieh9faf1542015-12-28 14:06:55 -0800507 InterfaceAddress ip;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000508 int scope_id = 0;
509
510 // Some interfaces may not have address assigned.
Guo-wei Shieh9faf1542015-12-28 14:06:55 -0800511 if (!cursor->ifa_addr || !cursor->ifa_netmask) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000512 continue;
Guo-wei Shieh9faf1542015-12-28 14:06:55 -0800513 }
514 // Skip ones which are down.
515 if (!(cursor->ifa_flags & IFF_RUNNING)) {
516 continue;
517 }
518 // Skip unknown family.
519 if (cursor->ifa_addr->sa_family != AF_INET &&
520 cursor->ifa_addr->sa_family != AF_INET6) {
521 continue;
522 }
523 // Skip IPv6 if not enabled.
524 if (cursor->ifa_addr->sa_family == AF_INET6 && !ipv6_enabled()) {
525 continue;
526 }
527 // Convert to InterfaceAddress.
528 if (!ifaddrs_converter->ConvertIfAddrsToIPAddress(cursor, &ip, &mask)) {
529 continue;
530 }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000531
Guo-wei Shieh9faf1542015-12-28 14:06:55 -0800532 // Special case for IPv6 address.
533 if (cursor->ifa_addr->sa_family == AF_INET6) {
534 if (IsIgnoredIPv6(ip)) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000535 continue;
536 }
Guo-wei Shieh9faf1542015-12-28 14:06:55 -0800537 scope_id =
538 reinterpret_cast<sockaddr_in6*>(cursor->ifa_addr)->sin6_scope_id;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000539 }
540
Honghai Zhang351d77b2016-05-20 15:08:29 -0700541 AdapterType adapter_type = ADAPTER_TYPE_UNKNOWN;
Qingsi Wangde2ed7d2018-04-27 14:25:37 -0700542 AdapterType vpn_underlying_adapter_type = ADAPTER_TYPE_UNKNOWN;
Honghai Zhang351d77b2016-05-20 15:08:29 -0700543 if (cursor->ifa_flags & IFF_LOOPBACK) {
544 adapter_type = ADAPTER_TYPE_LOOPBACK;
545 } else {
Taylor Brandstetter8bac1d92018-01-24 17:38:00 -0800546 // If there is a network_monitor, use it to get the adapter type.
547 // Otherwise, get the adapter type based on a few name matching rules.
548 if (network_monitor_) {
549 adapter_type = network_monitor_->GetAdapterType(cursor->ifa_name);
550 }
551 if (adapter_type == ADAPTER_TYPE_UNKNOWN) {
552 adapter_type = GetAdapterTypeFromName(cursor->ifa_name);
553 }
Honghai Zhang351d77b2016-05-20 15:08:29 -0700554 }
Qingsi Wangde2ed7d2018-04-27 14:25:37 -0700555
556 if (adapter_type == ADAPTER_TYPE_VPN && network_monitor_) {
557 vpn_underlying_adapter_type =
558 network_monitor_->GetVpnUnderlyingAdapterType(cursor->ifa_name);
559 }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000560 int prefix_length = CountIPMaskBits(mask);
561 prefix = TruncateIP(ip, prefix_length);
Yves Gerey665174f2018-06-19 15:03:05 +0200562 std::string key =
563 MakeNetworkKey(std::string(cursor->ifa_name), prefix, prefix_length);
Honghai Zhang351d77b2016-05-20 15:08:29 -0700564 auto iter = current_networks.find(key);
565 if (iter == current_networks.end()) {
Noah Richards2e266e92015-04-07 11:51:56 -0700566 // TODO(phoglund): Need to recognize other types as well.
jbauch555604a2016-04-26 03:13:22 -0700567 std::unique_ptr<Network> network(
568 new Network(cursor->ifa_name, cursor->ifa_name, prefix, prefix_length,
569 adapter_type));
Guo-wei Shieh9af97f82015-11-10 14:47:39 -0800570 network->set_default_local_address_provider(this);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000571 network->set_scope_id(scope_id);
572 network->AddIP(ip);
phoglund@webrtc.org006521d2015-02-12 09:23:59 +0000573 network->set_ignored(IsIgnoredNetwork(*network));
Qingsi Wangde2ed7d2018-04-27 14:25:37 -0700574 network->set_underlying_type_for_vpn(vpn_underlying_adapter_type);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000575 if (include_ignored || !network->ignored()) {
honghaizdb8cf502015-12-21 13:08:46 -0800576 current_networks[key] = network.get();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000577 networks->push_back(network.release());
578 }
579 } else {
Honghai Zhang351d77b2016-05-20 15:08:29 -0700580 Network* existing_network = iter->second;
581 existing_network->AddIP(ip);
582 if (adapter_type != ADAPTER_TYPE_UNKNOWN) {
583 existing_network->set_type(adapter_type);
Qingsi Wangde2ed7d2018-04-27 14:25:37 -0700584 existing_network->set_underlying_type_for_vpn(
585 vpn_underlying_adapter_type);
Honghai Zhang351d77b2016-05-20 15:08:29 -0700586 }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000587 }
588 }
589}
590
591bool BasicNetworkManager::CreateNetworks(bool include_ignored,
592 NetworkList* networks) const {
593 struct ifaddrs* interfaces;
594 int error = getifaddrs(&interfaces);
595 if (error != 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100596 RTC_LOG_ERR(LERROR) << "getifaddrs failed to gather interface data: "
597 << error;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000598 return false;
599 }
600
jbauch555604a2016-04-26 03:13:22 -0700601 std::unique_ptr<IfAddrsConverter> ifaddrs_converter(CreateIfAddrsConverter());
Guo-wei Shieh9faf1542015-12-28 14:06:55 -0800602 ConvertIfAddrs(interfaces, ifaddrs_converter.get(), include_ignored,
603 networks);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000604
605 freeifaddrs(interfaces);
606 return true;
607}
608
609#elif defined(WEBRTC_WIN)
610
611unsigned int GetPrefix(PIP_ADAPTER_PREFIX prefixlist,
Yves Gerey665174f2018-06-19 15:03:05 +0200612 const IPAddress& ip,
613 IPAddress* prefix) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000614 IPAddress current_prefix;
615 IPAddress best_prefix;
616 unsigned int best_length = 0;
617 while (prefixlist) {
618 // Look for the longest matching prefix in the prefixlist.
deadbeef37f5ecf2017-02-27 14:06:41 -0800619 if (prefixlist->Address.lpSockaddr == nullptr ||
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000620 prefixlist->Address.lpSockaddr->sa_family != ip.family()) {
621 prefixlist = prefixlist->Next;
622 continue;
623 }
624 switch (prefixlist->Address.lpSockaddr->sa_family) {
625 case AF_INET: {
626 sockaddr_in* v4_addr =
627 reinterpret_cast<sockaddr_in*>(prefixlist->Address.lpSockaddr);
628 current_prefix = IPAddress(v4_addr->sin_addr);
629 break;
630 }
631 case AF_INET6: {
Yves Gerey665174f2018-06-19 15:03:05 +0200632 sockaddr_in6* v6_addr =
633 reinterpret_cast<sockaddr_in6*>(prefixlist->Address.lpSockaddr);
634 current_prefix = IPAddress(v6_addr->sin6_addr);
635 break;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000636 }
637 default: {
638 prefixlist = prefixlist->Next;
639 continue;
640 }
641 }
642 if (TruncateIP(ip, prefixlist->PrefixLength) == current_prefix &&
643 prefixlist->PrefixLength > best_length) {
644 best_prefix = current_prefix;
645 best_length = prefixlist->PrefixLength;
646 }
647 prefixlist = prefixlist->Next;
648 }
649 *prefix = best_prefix;
650 return best_length;
651}
652
653bool BasicNetworkManager::CreateNetworks(bool include_ignored,
654 NetworkList* networks) const {
655 NetworkMap current_networks;
656 // MSDN recommends a 15KB buffer for the first try at GetAdaptersAddresses.
657 size_t buffer_size = 16384;
jbauch555604a2016-04-26 03:13:22 -0700658 std::unique_ptr<char[]> adapter_info(new char[buffer_size]);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000659 PIP_ADAPTER_ADDRESSES adapter_addrs =
660 reinterpret_cast<PIP_ADAPTER_ADDRESSES>(adapter_info.get());
661 int adapter_flags = (GAA_FLAG_SKIP_DNS_SERVER | GAA_FLAG_SKIP_ANYCAST |
662 GAA_FLAG_SKIP_MULTICAST | GAA_FLAG_INCLUDE_PREFIX);
663 int ret = 0;
664 do {
665 adapter_info.reset(new char[buffer_size]);
666 adapter_addrs = reinterpret_cast<PIP_ADAPTER_ADDRESSES>(adapter_info.get());
Yves Gerey665174f2018-06-19 15:03:05 +0200667 ret = GetAdaptersAddresses(AF_UNSPEC, adapter_flags, 0, adapter_addrs,
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000668 reinterpret_cast<PULONG>(&buffer_size));
669 } while (ret == ERROR_BUFFER_OVERFLOW);
670 if (ret != ERROR_SUCCESS) {
671 return false;
672 }
673 int count = 0;
674 while (adapter_addrs) {
675 if (adapter_addrs->OperStatus == IfOperStatusUp) {
676 PIP_ADAPTER_UNICAST_ADDRESS address = adapter_addrs->FirstUnicastAddress;
677 PIP_ADAPTER_PREFIX prefixlist = adapter_addrs->FirstPrefix;
678 std::string name;
679 std::string description;
tfarinaa41ab932015-10-30 16:08:48 -0700680#if !defined(NDEBUG)
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000681 name = ToUtf8(adapter_addrs->FriendlyName,
682 wcslen(adapter_addrs->FriendlyName));
683#endif
684 description = ToUtf8(adapter_addrs->Description,
685 wcslen(adapter_addrs->Description));
686 for (; address; address = address->Next) {
tfarinaa41ab932015-10-30 16:08:48 -0700687#if defined(NDEBUG)
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000688 name = rtc::ToString(count);
689#endif
690
691 IPAddress ip;
692 int scope_id = 0;
jbauch555604a2016-04-26 03:13:22 -0700693 std::unique_ptr<Network> network;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000694 switch (address->Address.lpSockaddr->sa_family) {
695 case AF_INET: {
696 sockaddr_in* v4_addr =
697 reinterpret_cast<sockaddr_in*>(address->Address.lpSockaddr);
698 ip = IPAddress(v4_addr->sin_addr);
699 break;
700 }
701 case AF_INET6: {
702 if (ipv6_enabled()) {
703 sockaddr_in6* v6_addr =
704 reinterpret_cast<sockaddr_in6*>(address->Address.lpSockaddr);
705 scope_id = v6_addr->sin6_scope_id;
706 ip = IPAddress(v6_addr->sin6_addr);
guoweis@webrtc.orgb91d0f52015-03-17 14:43:20 +0000707
Taylor Brandstetter01cb5f22018-03-07 15:49:32 -0800708 if (IsIgnoredIPv6(InterfaceAddress(ip))) {
guoweis@webrtc.orgb91d0f52015-03-17 14:43:20 +0000709 continue;
710 }
711
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000712 break;
713 } else {
714 continue;
715 }
716 }
Yves Gerey665174f2018-06-19 15:03:05 +0200717 default: { continue; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000718 }
719
720 IPAddress prefix;
721 int prefix_length = GetPrefix(prefixlist, ip, &prefix);
722 std::string key = MakeNetworkKey(name, prefix, prefix_length);
pthatcher@webrtc.org5950b642014-12-01 23:18:27 +0000723 auto existing_network = current_networks.find(key);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000724 if (existing_network == current_networks.end()) {
phoglund@webrtc.org006521d2015-02-12 09:23:59 +0000725 AdapterType adapter_type = ADAPTER_TYPE_UNKNOWN;
Yura Yaroshevich0ce868c2018-05-15 11:15:32 +0300726 switch (adapter_addrs->IfType) {
727 case IF_TYPE_SOFTWARE_LOOPBACK:
728 adapter_type = ADAPTER_TYPE_LOOPBACK;
729 break;
730 case IF_TYPE_ETHERNET_CSMACD:
731 case IF_TYPE_ETHERNET_3MBIT:
732 case IF_TYPE_IEEE80212:
733 case IF_TYPE_FASTETHER:
734 case IF_TYPE_FASTETHER_FX:
735 case IF_TYPE_GIGABITETHERNET:
736 adapter_type = ADAPTER_TYPE_ETHERNET;
737 break;
738 case IF_TYPE_IEEE80211:
739 adapter_type = ADAPTER_TYPE_WIFI;
740 break;
741 case IF_TYPE_WWANPP:
742 case IF_TYPE_WWANPP2:
743 adapter_type = ADAPTER_TYPE_CELLULAR;
744 break;
745 default:
746 // TODO(phoglund): Need to recognize other types as well.
747 adapter_type = ADAPTER_TYPE_UNKNOWN;
748 break;
phoglund@webrtc.org006521d2015-02-12 09:23:59 +0000749 }
jbauch555604a2016-04-26 03:13:22 -0700750 std::unique_ptr<Network> network(new Network(
751 name, description, prefix, prefix_length, adapter_type));
Guo-wei Shieh9af97f82015-11-10 14:47:39 -0800752 network->set_default_local_address_provider(this);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000753 network->set_scope_id(scope_id);
754 network->AddIP(ip);
phoglund@webrtc.org006521d2015-02-12 09:23:59 +0000755 bool ignored = IsIgnoredNetwork(*network);
756 network->set_ignored(ignored);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000757 if (include_ignored || !network->ignored()) {
honghaizdb8cf502015-12-21 13:08:46 -0800758 current_networks[key] = network.get();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000759 networks->push_back(network.release());
760 }
761 } else {
762 (*existing_network).second->AddIP(ip);
763 }
764 }
765 // Count is per-adapter - all 'Networks' created from the same
766 // adapter need to have the same name.
767 ++count;
768 }
769 adapter_addrs = adapter_addrs->Next;
770 }
771 return true;
772}
guoweis@webrtc.org369a6372014-09-17 22:37:29 +0000773#endif // WEBRTC_WIN
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000774
775#if defined(WEBRTC_LINUX)
776bool IsDefaultRoute(const std::string& network_name) {
Niels Möllera2e133d2018-10-30 13:04:33 +0100777 FILE* f = fopen("/proc/net/route", "r");
778 if (!f) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100779 RTC_LOG(LS_WARNING)
780 << "Couldn't read /proc/net/route, skipping default "
781 << "route check (assuming everything is a default route).";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000782 return true;
Niels Möllera2e133d2018-10-30 13:04:33 +0100783 }
784 bool is_default_route = false;
785 char line[500];
786 while (fgets(line, sizeof(line), f)) {
787 char iface_name[256];
788 unsigned int iface_ip, iface_gw, iface_mask, iface_flags;
789 if (sscanf(line, "%255s %8X %8X %4X %*d %*u %*d %8X", iface_name, &iface_ip,
790 &iface_gw, &iface_flags, &iface_mask) == 5 &&
791 network_name == iface_name && iface_mask == 0 &&
792 (iface_flags & (RTF_UP | RTF_HOST)) == RTF_UP) {
793 is_default_route = true;
794 break;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000795 }
796 }
Niels Möllera2e133d2018-10-30 13:04:33 +0100797 fclose(f);
798 return is_default_route;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000799}
800#endif
801
802bool BasicNetworkManager::IsIgnoredNetwork(const Network& network) const {
803 // Ignore networks on the explicit ignore list.
pthatcher@webrtc.org5950b642014-12-01 23:18:27 +0000804 for (const std::string& ignored_name : network_ignore_list_) {
805 if (network.name() == ignored_name) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000806 return true;
807 }
808 }
phoglund@webrtc.org006521d2015-02-12 09:23:59 +0000809
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000810#if defined(WEBRTC_POSIX)
pthatcher@webrtc.orgdfef0282015-01-07 17:20:52 +0000811 // Filter out VMware/VirtualBox interfaces, typically named vmnet1,
812 // vmnet8, or vboxnet0.
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000813 if (strncmp(network.name().c_str(), "vmnet", 5) == 0 ||
pthatcher@webrtc.orgdfef0282015-01-07 17:20:52 +0000814 strncmp(network.name().c_str(), "vnic", 4) == 0 ||
815 strncmp(network.name().c_str(), "vboxnet", 7) == 0) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000816 return true;
817 }
818#if defined(WEBRTC_LINUX)
819 // Make sure this is a default route, if we're ignoring non-defaults.
820 if (ignore_non_default_routes_ && !IsDefaultRoute(network.name())) {
821 return true;
822 }
823#endif
824#elif defined(WEBRTC_WIN)
825 // Ignore any HOST side vmware adapters with a description like:
826 // VMware Virtual Ethernet Adapter for VMnet1
827 // but don't ignore any GUEST side adapters with a description like:
828 // VMware Accelerated AMD PCNet Adapter #2
deadbeef37f5ecf2017-02-27 14:06:41 -0800829 if (strstr(network.description().c_str(), "VMnet") != nullptr) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000830 return true;
831 }
832#endif
833
834 // Ignore any networks with a 0.x.y.z IP
835 if (network.prefix().family() == AF_INET) {
836 return (network.prefix().v4AddressAsHostOrderInteger() < 0x01000000);
837 }
guoweis@webrtc.orgbbce5ef2015-03-05 04:38:29 +0000838
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000839 return false;
840}
841
842void BasicNetworkManager::StartUpdating() {
843 thread_ = Thread::Current();
844 if (start_count_) {
845 // If network interfaces are already discovered and signal is sent,
846 // we should trigger network signal immediately for the new clients
847 // to start allocating ports.
848 if (sent_first_update_)
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700849 thread_->Post(RTC_FROM_HERE, this, kSignalNetworksMessage);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000850 } else {
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700851 thread_->Post(RTC_FROM_HERE, this, kUpdateNetworksMessage);
honghaiz023f3ef2015-10-19 09:39:32 -0700852 StartNetworkMonitor();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000853 }
854 ++start_count_;
855}
856
857void BasicNetworkManager::StopUpdating() {
nisseede5da42017-01-12 05:15:36 -0800858 RTC_DCHECK(Thread::Current() == thread_);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000859 if (!start_count_)
860 return;
861
862 --start_count_;
863 if (!start_count_) {
864 thread_->Clear(this);
865 sent_first_update_ = false;
honghaiz023f3ef2015-10-19 09:39:32 -0700866 StopNetworkMonitor();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000867 }
868}
869
honghaiz023f3ef2015-10-19 09:39:32 -0700870void BasicNetworkManager::StartNetworkMonitor() {
871 NetworkMonitorFactory* factory = NetworkMonitorFactory::GetFactory();
872 if (factory == nullptr) {
873 return;
874 }
honghaiz023f3ef2015-10-19 09:39:32 -0700875 if (!network_monitor_) {
honghaizcec0a082016-01-15 14:49:09 -0800876 network_monitor_.reset(factory->CreateNetworkMonitor());
877 if (!network_monitor_) {
878 return;
879 }
skvlad979c2682016-06-10 15:24:13 -0700880 network_monitor_->SignalNetworksChanged.connect(
881 this, &BasicNetworkManager::OnNetworksChanged);
honghaiz023f3ef2015-10-19 09:39:32 -0700882 }
honghaiz023f3ef2015-10-19 09:39:32 -0700883 network_monitor_->Start();
884}
885
886void BasicNetworkManager::StopNetworkMonitor() {
887 if (!network_monitor_) {
888 return;
889 }
890 network_monitor_->Stop();
honghaiz023f3ef2015-10-19 09:39:32 -0700891}
892
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000893void BasicNetworkManager::OnMessage(Message* msg) {
894 switch (msg->message_id) {
honghaiz023f3ef2015-10-19 09:39:32 -0700895 case kUpdateNetworksMessage: {
896 UpdateNetworksContinually();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000897 break;
898 }
Yves Gerey665174f2018-06-19 15:03:05 +0200899 case kSignalNetworksMessage: {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000900 SignalNetworksChanged();
901 break;
902 }
903 default:
nissec80e7412017-01-11 05:56:46 -0800904 RTC_NOTREACHED();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000905 }
906}
907
Guo-wei Shieh9af97f82015-11-10 14:47:39 -0800908IPAddress BasicNetworkManager::QueryDefaultLocalAddress(int family) const {
nisseede5da42017-01-12 05:15:36 -0800909 RTC_DCHECK(thread_ == Thread::Current());
910 RTC_DCHECK(thread_->socketserver() != nullptr);
911 RTC_DCHECK(family == AF_INET || family == AF_INET6);
Guo-wei Shieh9af97f82015-11-10 14:47:39 -0800912
jbauch555604a2016-04-26 03:13:22 -0700913 std::unique_ptr<AsyncSocket> socket(
Guo-wei Shieh9af97f82015-11-10 14:47:39 -0800914 thread_->socketserver()->CreateAsyncSocket(family, SOCK_DGRAM));
915 if (!socket) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100916 RTC_LOG_ERR(LERROR) << "Socket creation failed";
Guo-wei Shieh9af97f82015-11-10 14:47:39 -0800917 return IPAddress();
918 }
919
guoweis56271ed2016-01-15 14:45:06 -0800920 if (socket->Connect(SocketAddress(
921 family == AF_INET ? kPublicIPv4Host : kPublicIPv6Host, kPublicPort)) <
922 0) {
Yves Gerey665174f2018-06-19 15:03:05 +0200923 if (socket->GetError() != ENETUNREACH &&
924 socket->GetError() != EHOSTUNREACH) {
skvlad75024012016-09-29 12:59:35 -0700925 // Ignore the expected case of "host/net unreachable" - which happens if
926 // the network is V4- or V6-only.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100927 RTC_LOG(LS_INFO) << "Connect failed with " << socket->GetError();
skvlad75024012016-09-29 12:59:35 -0700928 }
Guo-wei Shieh9af97f82015-11-10 14:47:39 -0800929 return IPAddress();
930 }
931 return socket->GetLocalAddress().ipaddr();
932}
933
honghaiz023f3ef2015-10-19 09:39:32 -0700934void BasicNetworkManager::UpdateNetworksOnce() {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000935 if (!start_count_)
936 return;
937
nisseede5da42017-01-12 05:15:36 -0800938 RTC_DCHECK(Thread::Current() == thread_);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000939
940 NetworkList list;
941 if (!CreateNetworks(false, &list)) {
942 SignalError();
943 } else {
944 bool changed;
Guo-wei Shieh9af97f82015-11-10 14:47:39 -0800945 NetworkManager::Stats stats;
946 MergeNetworkList(list, &changed, &stats);
947 set_default_local_addresses(QueryDefaultLocalAddress(AF_INET),
948 QueryDefaultLocalAddress(AF_INET6));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000949 if (changed || !sent_first_update_) {
950 SignalNetworksChanged();
951 sent_first_update_ = true;
952 }
953 }
honghaiz023f3ef2015-10-19 09:39:32 -0700954}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000955
honghaiz023f3ef2015-10-19 09:39:32 -0700956void BasicNetworkManager::UpdateNetworksContinually() {
957 UpdateNetworksOnce();
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700958 thread_->PostDelayed(RTC_FROM_HERE, kNetworksUpdateIntervalMs, this,
959 kUpdateNetworksMessage);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000960}
961
honghaizdb8cf502015-12-21 13:08:46 -0800962void BasicNetworkManager::DumpNetworks() {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000963 NetworkList list;
honghaizdb8cf502015-12-21 13:08:46 -0800964 GetNetworks(&list);
Mirko Bonadei675513b2017-11-09 11:09:25 +0100965 RTC_LOG(LS_INFO) << "NetworkManager detected " << list.size() << " networks:";
pthatcher@webrtc.org5950b642014-12-01 23:18:27 +0000966 for (const Network* network : list) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100967 RTC_LOG(LS_INFO) << network->ToString() << ": " << network->description()
968 << ", active ? " << network->active()
969 << ((network->ignored()) ? ", Ignored" : "");
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000970 }
971}
972
Guo-wei Shieh9af97f82015-11-10 14:47:39 -0800973Network::Network(const std::string& name,
974 const std::string& desc,
975 const IPAddress& prefix,
976 int prefix_length)
977 : name_(name),
978 description_(desc),
979 prefix_(prefix),
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000980 prefix_length_(prefix_length),
Guo-wei Shieh9af97f82015-11-10 14:47:39 -0800981 key_(MakeNetworkKey(name, prefix, prefix_length)),
982 scope_id_(0),
983 ignored_(false),
984 type_(ADAPTER_TYPE_UNKNOWN),
985 preference_(0) {}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000986
Guo-wei Shieh9af97f82015-11-10 14:47:39 -0800987Network::Network(const std::string& name,
988 const std::string& desc,
989 const IPAddress& prefix,
990 int prefix_length,
991 AdapterType type)
992 : name_(name),
993 description_(desc),
994 prefix_(prefix),
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000995 prefix_length_(prefix_length),
Guo-wei Shieh9af97f82015-11-10 14:47:39 -0800996 key_(MakeNetworkKey(name, prefix, prefix_length)),
997 scope_id_(0),
998 ignored_(false),
999 type_(type),
1000 preference_(0) {}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001001
Steve Anton9de3aac2017-10-24 10:08:26 -07001002Network::Network(const Network&) = default;
1003
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +00001004Network::~Network() = default;
1005
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001006// Sets the addresses of this network. Returns true if the address set changed.
1007// Change detection is short circuited if the changed argument is true.
guoweis@webrtc.orgfa603982014-09-09 23:42:40 +00001008bool Network::SetIPs(const std::vector<InterfaceAddress>& ips, bool changed) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001009 // Detect changes with a nested loop; n-squared but we expect on the order
1010 // of 2-3 addresses per network.
pthatcher@webrtc.org5950b642014-12-01 23:18:27 +00001011 changed = changed || ips.size() != ips_.size();
1012 if (!changed) {
1013 for (const InterfaceAddress& ip : ips) {
1014 if (std::find(ips_.begin(), ips_.end(), ip) == ips_.end()) {
1015 changed = true;
1016 break;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001017 }
1018 }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001019 }
pthatcher@webrtc.org5950b642014-12-01 23:18:27 +00001020
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001021 ips_ = ips;
1022 return changed;
1023}
1024
aluebs@webrtc.org07dcf602015-02-27 18:42:22 +00001025// Select the best IP address to use from this Network.
guoweis@webrtc.org369a6372014-09-17 22:37:29 +00001026IPAddress Network::GetBestIP() const {
guoweis@webrtc.orgfa603982014-09-09 23:42:40 +00001027 if (ips_.size() == 0) {
1028 return IPAddress();
1029 }
guoweis@webrtc.org369a6372014-09-17 22:37:29 +00001030
1031 if (prefix_.family() == AF_INET) {
1032 return static_cast<IPAddress>(ips_.at(0));
1033 }
1034
aluebs@webrtc.org07dcf602015-02-27 18:42:22 +00001035 InterfaceAddress selected_ip, ula_ip;
1036
pthatcher@webrtc.org5950b642014-12-01 23:18:27 +00001037 for (const InterfaceAddress& ip : ips_) {
aluebs@webrtc.org07dcf602015-02-27 18:42:22 +00001038 // Ignore any address which has been deprecated already.
1039 if (ip.ipv6_flags() & IPV6_ADDRESS_FLAG_DEPRECATED)
1040 continue;
1041
1042 // ULA address should only be returned when we have no other
1043 // global IP.
1044 if (IPIsULA(static_cast<const IPAddress&>(ip))) {
1045 ula_ip = ip;
guoweis@webrtc.org369a6372014-09-17 22:37:29 +00001046 continue;
1047 }
aluebs@webrtc.org07dcf602015-02-27 18:42:22 +00001048 selected_ip = ip;
guoweis@webrtc.org369a6372014-09-17 22:37:29 +00001049
aluebs@webrtc.org07dcf602015-02-27 18:42:22 +00001050 // Search could stop once a temporary non-deprecated one is found.
1051 if (ip.ipv6_flags() & IPV6_ADDRESS_FLAG_TEMPORARY)
1052 break;
guoweis@webrtc.org369a6372014-09-17 22:37:29 +00001053 }
1054
aluebs@webrtc.org07dcf602015-02-27 18:42:22 +00001055 // No proper global IPv6 address found, use ULA instead.
1056 if (IPIsUnspec(selected_ip) && !IPIsUnspec(ula_ip)) {
1057 selected_ip = ula_ip;
1058 }
1059
1060 return static_cast<IPAddress>(selected_ip);
guoweis@webrtc.org369a6372014-09-17 22:37:29 +00001061}
1062
Qingsi Wangde2ed7d2018-04-27 14:25:37 -07001063uint16_t Network::GetCost() const {
1064 AdapterType type = IsVpn() ? underlying_type_for_vpn_ : type_;
1065 return ComputeNetworkCostByType(type);
1066}
1067
guoweis@webrtc.org369a6372014-09-17 22:37:29 +00001068std::string Network::ToString() const {
Jonas Olsson366a50c2018-09-06 13:41:30 +02001069 rtc::StringBuilder ss;
guoweis@webrtc.org369a6372014-09-17 22:37:29 +00001070 // Print out the first space-terminated token of the network desc, plus
1071 // the IP address.
Qingsi Wangde2ed7d2018-04-27 14:25:37 -07001072 ss << "Net[" << description_.substr(0, description_.find(' ')) << ":"
1073 << prefix_.ToSensitiveString() << "/" << prefix_length_ << ":"
1074 << AdapterTypeToString(type_);
1075 if (IsVpn()) {
1076 ss << "/" << AdapterTypeToString(underlying_type_for_vpn_);
1077 }
Qingsi Wang10a0e512018-05-16 13:37:03 -07001078 ss << ":id=" << id_ << "]";
Jonas Olsson84df1c72018-09-14 16:59:32 +02001079 return ss.Release();
guoweis@webrtc.orgfa603982014-09-09 23:42:40 +00001080}
1081
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001082} // namespace rtc