• 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 #include <stdlib.h>
14 
15 #include <algorithm>
16 #include <memory>
17 #include <vector>
18 
19 #include "absl/algorithm/container.h"
20 #include "absl/strings/match.h"
21 #include "absl/strings/string_view.h"
22 #include "rtc_base/checks.h"
23 #include "rtc_base/net_helpers.h"
24 #include "rtc_base/network_monitor.h"
25 #include "rtc_base/network_monitor_factory.h"
26 #include "rtc_base/physical_socket_server.h"
27 #if defined(WEBRTC_POSIX)
28 #include <net/if.h>
29 #include <sys/types.h>
30 
31 #include "rtc_base/ifaddrs_converter.h"
32 #endif  // defined(WEBRTC_POSIX)
33 #include "rtc_base/gunit.h"
34 #include "test/gmock.h"
35 #if defined(WEBRTC_WIN)
36 #include "rtc_base/logging.h"  // For RTC_LOG_GLE
37 #endif
38 #include "test/field_trial.h"
39 #include "test/scoped_key_value_config.h"
40 
41 using ::testing::Contains;
42 using ::testing::Not;
43 using ::testing::UnorderedElementsAre;
44 using ::testing::UnorderedElementsAreArray;
45 
46 namespace rtc {
47 
48 namespace {
49 
IPFromString(absl::string_view str)50 IPAddress IPFromString(absl::string_view str) {
51   IPAddress ip;
52   RTC_CHECK(IPFromString(str, &ip));
53   return ip;
54 }
55 
56 class FakeNetworkMonitor : public NetworkMonitorInterface {
57  public:
Start()58   void Start() override { started_ = true; }
Stop()59   void Stop() override { started_ = false; }
started()60   bool started() { return started_; }
GetInterfaceInfo(absl::string_view if_name)61   InterfaceInfo GetInterfaceInfo(absl::string_view if_name) override {
62     InterfaceInfo if_info = {
63         .adapter_type = ADAPTER_TYPE_UNKNOWN,
64         .available = absl::c_count(unavailable_adapters_, if_name) == 0,
65     };
66     if (absl::StartsWith(if_name, "wifi")) {
67       if_info.adapter_type = ADAPTER_TYPE_WIFI;
68     } else if (absl::StartsWith(if_name, "cellular")) {
69       if_info.adapter_type = ADAPTER_TYPE_CELLULAR;
70     }
71     return if_info;
72   }
73 
74   // Used to test IsAdapterAvailable.
set_unavailable_adapters(std::vector<std::string> unavailable_adapters)75   void set_unavailable_adapters(std::vector<std::string> unavailable_adapters) {
76     unavailable_adapters_ = unavailable_adapters;
77   }
78 
SupportsBindSocketToNetwork() const79   bool SupportsBindSocketToNetwork() const override { return true; }
80 
BindSocketToNetwork(int socket_fd,const IPAddress & address,absl::string_view if_name)81   NetworkBindingResult BindSocketToNetwork(int socket_fd,
82                                            const IPAddress& address,
83                                            absl::string_view if_name) override {
84     if (absl::c_count(addresses_, address) > 0) {
85       return NetworkBindingResult::SUCCESS;
86     }
87 
88     for (auto const& iter : adapters_) {
89       if (if_name.find(iter) != absl::string_view::npos) {
90         return NetworkBindingResult::SUCCESS;
91       }
92     }
93     return NetworkBindingResult::ADDRESS_NOT_FOUND;
94   }
95 
set_ip_addresses(std::vector<IPAddress> addresses)96   void set_ip_addresses(std::vector<IPAddress> addresses) {
97     addresses_ = addresses;
98   }
99 
set_adapters(std::vector<std::string> adapters)100   void set_adapters(std::vector<std::string> adapters) { adapters_ = adapters; }
101 
InovkeNetworksChangedCallbackForTesting()102   void InovkeNetworksChangedCallbackForTesting() {
103     InvokeNetworksChangedCallback();
104   }
105 
106  private:
107   bool started_ = false;
108   std::vector<std::string> adapters_;
109   std::vector<std::string> unavailable_adapters_;
110   std::vector<IPAddress> addresses_;
111 };
112 
113 class FakeNetworkMonitorFactory : public NetworkMonitorFactory {
114  public:
FakeNetworkMonitorFactory()115   FakeNetworkMonitorFactory() {}
CreateNetworkMonitor(const webrtc::FieldTrialsView & field_trials)116   NetworkMonitorInterface* CreateNetworkMonitor(
117       const webrtc::FieldTrialsView& field_trials) override {
118     return new FakeNetworkMonitor();
119   }
120 };
121 
SameNameAndPrefix(const rtc::Network & a,const rtc::Network & b)122 bool SameNameAndPrefix(const rtc::Network& a, const rtc::Network& b) {
123   if (a.name() != b.name()) {
124     RTC_LOG(LS_INFO) << "Different interface names.";
125     return false;
126   }
127   if (a.prefix_length() != b.prefix_length() || a.prefix() != b.prefix()) {
128     RTC_LOG(LS_INFO) << "Different IP prefixes.";
129     return false;
130   }
131   return true;
132 }
133 
CopyNetworkPointers(const std::vector<std::unique_ptr<Network>> & owning_list)134 std::vector<const Network*> CopyNetworkPointers(
135     const std::vector<std::unique_ptr<Network>>& owning_list) {
136   std::vector<const Network*> ptr_list;
137   ptr_list.reserve(owning_list.size());
138   for (const auto& network : owning_list) {
139     ptr_list.push_back(network.get());
140   }
141   return ptr_list;
142 }
143 
144 }  // namespace
145 
146 class NetworkTest : public ::testing::Test, public sigslot::has_slots<> {
147  public:
NetworkTest()148   NetworkTest() : callback_called_(false) {}
149 
OnNetworksChanged()150   void OnNetworksChanged() { callback_called_ = true; }
151 
MergeNetworkList(BasicNetworkManager & network_manager,std::vector<std::unique_ptr<Network>> list,bool * changed)152   NetworkManager::Stats MergeNetworkList(
153       BasicNetworkManager& network_manager,
154       std::vector<std::unique_ptr<Network>> list,
155       bool* changed) {
156     NetworkManager::Stats stats;
157     network_manager.MergeNetworkList(std::move(list), changed, &stats);
158     return stats;
159   }
160 
IsIgnoredNetwork(BasicNetworkManager & network_manager,const Network & network)161   bool IsIgnoredNetwork(BasicNetworkManager& network_manager,
162                         const Network& network) {
163     RTC_DCHECK_RUN_ON(network_manager.thread_);
164     return network_manager.IsIgnoredNetwork(network);
165   }
166 
QueryDefaultLocalAddress(BasicNetworkManager & network_manager,int family)167   IPAddress QueryDefaultLocalAddress(BasicNetworkManager& network_manager,
168                                      int family) {
169     RTC_DCHECK_RUN_ON(network_manager.thread_);
170     return network_manager.QueryDefaultLocalAddress(family);
171   }
172 
GetNetworks(const BasicNetworkManager & network_manager,bool include_ignored)173   std::vector<std::unique_ptr<Network>> GetNetworks(
174       const BasicNetworkManager& network_manager,
175       bool include_ignored) {
176     RTC_DCHECK_RUN_ON(network_manager.thread_);
177     std::vector<std::unique_ptr<Network>> list;
178     network_manager.CreateNetworks(include_ignored, &list);
179     return list;
180   }
181 
GetNetworkMonitor(BasicNetworkManager & network_manager)182   FakeNetworkMonitor* GetNetworkMonitor(BasicNetworkManager& network_manager) {
183     RTC_DCHECK_RUN_ON(network_manager.thread_);
184     return static_cast<FakeNetworkMonitor*>(
185         network_manager.network_monitor_.get());
186   }
ClearNetworks(BasicNetworkManager & network_manager)187   void ClearNetworks(BasicNetworkManager& network_manager) {
188     network_manager.networks_.clear();
189     network_manager.networks_map_.clear();
190   }
191 
GetAdapterType(BasicNetworkManager & network_manager)192   AdapterType GetAdapterType(BasicNetworkManager& network_manager) {
193     std::vector<const Network*> list = network_manager.GetNetworks();
194     RTC_CHECK_EQ(1, list.size());
195     return list[0]->type();
196   }
197 
198 #if defined(WEBRTC_POSIX)
199   // Separated from CreateNetworks for tests.
CallConvertIfAddrs(const BasicNetworkManager & network_manager,struct ifaddrs * interfaces,bool include_ignored,std::vector<std::unique_ptr<Network>> * networks)200   static void CallConvertIfAddrs(
201       const BasicNetworkManager& network_manager,
202       struct ifaddrs* interfaces,
203       bool include_ignored,
204       std::vector<std::unique_ptr<Network>>* networks) {
205     RTC_DCHECK_RUN_ON(network_manager.thread_);
206     // Use the base IfAddrsConverter for test cases.
207     std::unique_ptr<IfAddrsConverter> ifaddrs_converter(new IfAddrsConverter());
208     network_manager.ConvertIfAddrs(interfaces, ifaddrs_converter.get(),
209                                    include_ignored, networks);
210   }
211 
CreateIpv6Addr(absl::string_view ip_string,uint32_t scope_id)212   struct sockaddr_in6* CreateIpv6Addr(absl::string_view ip_string,
213                                       uint32_t scope_id) {
214     struct sockaddr_in6* ipv6_addr =
215         static_cast<struct sockaddr_in6*>(malloc(sizeof(struct sockaddr_in6)));
216     memset(ipv6_addr, 0, sizeof(struct sockaddr_in6));
217     ipv6_addr->sin6_family = AF_INET6;
218     ipv6_addr->sin6_scope_id = scope_id;
219     IPAddress ip;
220     IPFromString(ip_string, &ip);
221     ipv6_addr->sin6_addr = ip.ipv6_address();
222     return ipv6_addr;
223   }
224 
225   // Pointers created here need to be released via ReleaseIfAddrs.
AddIpv6Address(struct ifaddrs * list,char * if_name,absl::string_view ipv6_address,absl::string_view ipv6_netmask,uint32_t scope_id)226   struct ifaddrs* AddIpv6Address(struct ifaddrs* list,
227                                  char* if_name,
228                                  absl::string_view ipv6_address,
229                                  absl::string_view ipv6_netmask,
230                                  uint32_t scope_id) {
231     struct ifaddrs* if_addr = new struct ifaddrs;
232     memset(if_addr, 0, sizeof(struct ifaddrs));
233     if_addr->ifa_name = if_name;
234     if_addr->ifa_addr = reinterpret_cast<struct sockaddr*>(
235         CreateIpv6Addr(ipv6_address, scope_id));
236     if_addr->ifa_netmask =
237         reinterpret_cast<struct sockaddr*>(CreateIpv6Addr(ipv6_netmask, 0));
238     if_addr->ifa_next = list;
239     if_addr->ifa_flags = IFF_RUNNING;
240     return if_addr;
241   }
242 
InstallIpv6Network(char * if_name,absl::string_view ipv6_address,absl::string_view ipv6_mask,BasicNetworkManager & network_manager)243   struct ifaddrs* InstallIpv6Network(char* if_name,
244                                      absl::string_view ipv6_address,
245                                      absl::string_view ipv6_mask,
246                                      BasicNetworkManager& network_manager) {
247     ifaddrs* addr_list = nullptr;
248     addr_list = AddIpv6Address(addr_list, if_name, ipv6_address, ipv6_mask, 0);
249     std::vector<std::unique_ptr<Network>> result;
250     bool changed;
251     NetworkManager::Stats stats;
252     CallConvertIfAddrs(network_manager, addr_list, true, &result);
253     network_manager.MergeNetworkList(std::move(result), &changed, &stats);
254     return addr_list;
255   }
256 
CreateIpv4Addr(absl::string_view ip_string)257   struct sockaddr_in* CreateIpv4Addr(absl::string_view ip_string) {
258     struct sockaddr_in* ipv4_addr =
259         static_cast<struct sockaddr_in*>(malloc(sizeof(struct sockaddr_in)));
260     memset(ipv4_addr, 0, sizeof(struct sockaddr_in));
261     ipv4_addr->sin_family = AF_INET;
262     IPAddress ip;
263     IPFromString(ip_string, &ip);
264     ipv4_addr->sin_addr = ip.ipv4_address();
265     return ipv4_addr;
266   }
267 
268   // Pointers created here need to be released via ReleaseIfAddrs.
AddIpv4Address(struct ifaddrs * list,char * if_name,absl::string_view ipv4_address,absl::string_view ipv4_netmask)269   struct ifaddrs* AddIpv4Address(struct ifaddrs* list,
270                                  char* if_name,
271                                  absl::string_view ipv4_address,
272                                  absl::string_view ipv4_netmask) {
273     struct ifaddrs* if_addr = new struct ifaddrs;
274     memset(if_addr, 0, sizeof(struct ifaddrs));
275     if_addr->ifa_name = if_name;
276     if_addr->ifa_addr =
277         reinterpret_cast<struct sockaddr*>(CreateIpv4Addr(ipv4_address));
278     if_addr->ifa_netmask =
279         reinterpret_cast<struct sockaddr*>(CreateIpv4Addr(ipv4_netmask));
280     if_addr->ifa_next = list;
281     if_addr->ifa_flags = IFF_RUNNING;
282     return if_addr;
283   }
284 
InstallIpv4Network(char * if_name,absl::string_view ipv4_address,absl::string_view ipv4_mask,BasicNetworkManager & network_manager)285   struct ifaddrs* InstallIpv4Network(char* if_name,
286                                      absl::string_view ipv4_address,
287                                      absl::string_view ipv4_mask,
288                                      BasicNetworkManager& network_manager) {
289     ifaddrs* addr_list = nullptr;
290     addr_list = AddIpv4Address(addr_list, if_name, ipv4_address, ipv4_mask);
291     std::vector<std::unique_ptr<Network>> result;
292     bool changed;
293     NetworkManager::Stats stats;
294     CallConvertIfAddrs(network_manager, addr_list, true, &result);
295     network_manager.MergeNetworkList(std::move(result), &changed, &stats);
296     return addr_list;
297   }
298 
ReleaseIfAddrs(struct ifaddrs * list)299   void ReleaseIfAddrs(struct ifaddrs* list) {
300     struct ifaddrs* if_addr = list;
301     while (if_addr != nullptr) {
302       struct ifaddrs* next_addr = if_addr->ifa_next;
303       free(if_addr->ifa_addr);
304       free(if_addr->ifa_netmask);
305       delete if_addr;
306       if_addr = next_addr;
307     }
308   }
309 #endif  // defined(WEBRTC_POSIX)
310 
311  protected:
312   webrtc::test::ScopedKeyValueConfig field_trials_;
313   rtc::AutoThread main_thread_;
314   bool callback_called_;
315 };
316 
317 class TestBasicNetworkManager : public BasicNetworkManager {
318  public:
TestBasicNetworkManager(NetworkMonitorFactory * network_monitor_factory,SocketFactory * socket_factory,const webrtc::FieldTrialsView & field_trials)319   TestBasicNetworkManager(NetworkMonitorFactory* network_monitor_factory,
320                           SocketFactory* socket_factory,
321                           const webrtc::FieldTrialsView& field_trials)
322       : BasicNetworkManager(network_monitor_factory,
323                             socket_factory,
324                             &field_trials) {}
325   using BasicNetworkManager::QueryDefaultLocalAddress;
326   using BasicNetworkManager::set_default_local_addresses;
327 };
328 
329 // Test that the Network ctor works properly.
TEST_F(NetworkTest,TestNetworkConstruct)330 TEST_F(NetworkTest, TestNetworkConstruct) {
331   Network ipv4_network1("test_eth0", "Test Network Adapter 1",
332                         IPAddress(0x12345600U), 24);
333   EXPECT_EQ("test_eth0", ipv4_network1.name());
334   EXPECT_EQ("Test Network Adapter 1", ipv4_network1.description());
335   EXPECT_EQ(IPAddress(0x12345600U), ipv4_network1.prefix());
336   EXPECT_EQ(24, ipv4_network1.prefix_length());
337   EXPECT_EQ(AF_INET, ipv4_network1.family());
338   EXPECT_FALSE(ipv4_network1.ignored());
339 }
340 
TEST_F(NetworkTest,TestIsIgnoredNetworkIgnoresIPsStartingWith0)341 TEST_F(NetworkTest, TestIsIgnoredNetworkIgnoresIPsStartingWith0) {
342   Network ipv4_network1("test_eth0", "Test Network Adapter 1",
343                         IPAddress(0x12345600U), 24, ADAPTER_TYPE_ETHERNET,
344                         &field_trials_);
345   Network ipv4_network2("test_eth1", "Test Network Adapter 2",
346                         IPAddress(0x010000U), 24, ADAPTER_TYPE_ETHERNET,
347                         &field_trials_);
348   PhysicalSocketServer socket_server;
349   BasicNetworkManager network_manager(&socket_server);
350   network_manager.StartUpdating();
351   EXPECT_FALSE(IsIgnoredNetwork(network_manager, ipv4_network1));
352   EXPECT_TRUE(IsIgnoredNetwork(network_manager, ipv4_network2));
353 }
354 
355 // TODO(phoglund): Remove when ignore list goes away.
TEST_F(NetworkTest,TestIgnoreList)356 TEST_F(NetworkTest, TestIgnoreList) {
357   Network ignore_me("ignore_me", "Ignore me please!", IPAddress(0x12345600U),
358                     24);
359   Network include_me("include_me", "Include me please!", IPAddress(0x12345600U),
360                      24);
361   PhysicalSocketServer socket_server;
362   BasicNetworkManager default_network_manager(&socket_server);
363   default_network_manager.StartUpdating();
364   EXPECT_FALSE(IsIgnoredNetwork(default_network_manager, ignore_me));
365   EXPECT_FALSE(IsIgnoredNetwork(default_network_manager, include_me));
366 
367   BasicNetworkManager ignoring_network_manager(&socket_server);
368   std::vector<std::string> ignore_list;
369   ignore_list.push_back("ignore_me");
370   ignoring_network_manager.set_network_ignore_list(ignore_list);
371   ignoring_network_manager.StartUpdating();
372   EXPECT_TRUE(IsIgnoredNetwork(ignoring_network_manager, ignore_me));
373   EXPECT_FALSE(IsIgnoredNetwork(ignoring_network_manager, include_me));
374 }
375 
376 // Test is failing on Windows opt: b/11288214
TEST_F(NetworkTest,DISABLED_TestCreateNetworks)377 TEST_F(NetworkTest, DISABLED_TestCreateNetworks) {
378   PhysicalSocketServer socket_server;
379   BasicNetworkManager manager(&socket_server);
380   std::vector<std::unique_ptr<Network>> result = GetNetworks(manager, true);
381   // We should be able to bind to any addresses we find.
382   for (auto it = result.begin(); it != result.end(); ++it) {
383     sockaddr_storage storage;
384     memset(&storage, 0, sizeof(storage));
385     IPAddress ip = (*it)->GetBestIP();
386     SocketAddress bindaddress(ip, 0);
387     bindaddress.SetScopeID((*it)->scope_id());
388     // TODO(thaloun): Use rtc::Socket once it supports IPv6.
389     int fd = static_cast<int>(socket(ip.family(), SOCK_STREAM, IPPROTO_TCP));
390     if (fd > 0) {
391       size_t ipsize = bindaddress.ToSockAddrStorage(&storage);
392       EXPECT_GE(ipsize, 0U);
393       int success = ::bind(fd, reinterpret_cast<sockaddr*>(&storage),
394                            static_cast<int>(ipsize));
395 #if defined(WEBRTC_WIN)
396       if (success)
397         RTC_LOG_GLE(LS_ERROR) << "Socket bind failed.";
398 #endif
399       EXPECT_EQ(0, success);
400 #if defined(WEBRTC_WIN)
401       closesocket(fd);
402 #else
403       close(fd);
404 #endif
405     }
406   }
407 }
408 
409 // Test StartUpdating() and StopUpdating(). network_permission_state starts with
410 // ALLOWED.
TEST_F(NetworkTest,TestUpdateNetworks)411 TEST_F(NetworkTest, TestUpdateNetworks) {
412   PhysicalSocketServer socket_server;
413   BasicNetworkManager manager(nullptr, &socket_server, &field_trials_);
414   manager.SignalNetworksChanged.connect(static_cast<NetworkTest*>(this),
415                                         &NetworkTest::OnNetworksChanged);
416   EXPECT_EQ(NetworkManager::ENUMERATION_ALLOWED,
417             manager.enumeration_permission());
418   manager.StartUpdating();
419   Thread::Current()->ProcessMessages(0);
420   EXPECT_TRUE(callback_called_);
421   callback_called_ = false;
422   // Callback should be triggered immediately when StartUpdating
423   // is called, after network update signal is already sent.
424   manager.StartUpdating();
425   EXPECT_TRUE(manager.started());
426   Thread::Current()->ProcessMessages(0);
427   EXPECT_TRUE(callback_called_);
428   manager.StopUpdating();
429   EXPECT_TRUE(manager.started());
430   manager.StopUpdating();
431   EXPECT_EQ(NetworkManager::ENUMERATION_ALLOWED,
432             manager.enumeration_permission());
433   EXPECT_FALSE(manager.started());
434   manager.StopUpdating();
435   EXPECT_FALSE(manager.started());
436   callback_called_ = false;
437   // Callback should be triggered immediately after StartUpdating is called
438   // when start_count_ is reset to 0.
439   manager.StartUpdating();
440   Thread::Current()->ProcessMessages(0);
441   EXPECT_TRUE(callback_called_);
442 }
443 
444 // Verify that MergeNetworkList() merges network lists properly.
TEST_F(NetworkTest,TestBasicMergeNetworkList)445 TEST_F(NetworkTest, TestBasicMergeNetworkList) {
446   Network ipv4_network1("test_eth0", "Test Network Adapter 1",
447                         IPAddress(0x12345600U), 24);
448   Network ipv4_network2("test_eth1", "Test Network Adapter 2",
449                         IPAddress(0x00010000U), 16);
450   ipv4_network1.AddIP(IPAddress(0x12345678));
451   ipv4_network2.AddIP(IPAddress(0x00010004));
452   PhysicalSocketServer socket_server;
453   BasicNetworkManager manager(&socket_server);
454 
455   // Add ipv4_network1 to the list of networks.
456   std::vector<std::unique_ptr<Network>> list;
457   list.push_back(std::make_unique<Network>(ipv4_network1));
458   bool changed;
459   NetworkManager::Stats stats =
460       MergeNetworkList(manager, std::move(list), &changed);
461   EXPECT_TRUE(changed);
462   EXPECT_EQ(stats.ipv6_network_count, 0);
463   EXPECT_EQ(stats.ipv4_network_count, 1);
464   list.clear();  // It is fine to call .clear() on a moved-from vector.
465 
466   std::vector<const rtc::Network*> current = manager.GetNetworks();
467   EXPECT_EQ(1U, current.size());
468   EXPECT_TRUE(SameNameAndPrefix(ipv4_network1, *current[0]));
469   const Network* net1 = current[0];
470   uint16_t net_id1 = net1->id();
471   EXPECT_EQ(1, net_id1);
472 
473   // Replace ipv4_network1 with ipv4_network2.
474   list.push_back(std::make_unique<Network>(ipv4_network2));
475   stats = MergeNetworkList(manager, std::move(list), &changed);
476   EXPECT_TRUE(changed);
477   EXPECT_EQ(stats.ipv6_network_count, 0);
478   EXPECT_EQ(stats.ipv4_network_count, 1);
479   list.clear();
480 
481   current = manager.GetNetworks();
482   EXPECT_EQ(1U, current.size());
483   EXPECT_TRUE(SameNameAndPrefix(ipv4_network2, *current[0]));
484   const Network* net2 = current[0];
485   uint16_t net_id2 = net2->id();
486   // Network id will increase.
487   EXPECT_LT(net_id1, net_id2);
488 
489   // Add Network2 back.
490   list.push_back(std::make_unique<Network>(ipv4_network1));
491   list.push_back(std::make_unique<Network>(ipv4_network2));
492   stats = MergeNetworkList(manager, std::move(list), &changed);
493   EXPECT_TRUE(changed);
494   EXPECT_EQ(stats.ipv6_network_count, 0);
495   EXPECT_EQ(stats.ipv4_network_count, 2);
496   list.clear();
497 
498   // Verify that we get previous instances of Network objects.
499   current = manager.GetNetworks();
500   EXPECT_EQ(2U, current.size());
501   EXPECT_TRUE((net1 == current[0] && net2 == current[1]) ||
502               (net1 == current[1] && net2 == current[0]));
503   EXPECT_TRUE((net_id1 == current[0]->id() && net_id2 == current[1]->id()) ||
504               (net_id1 == current[1]->id() && net_id2 == current[0]->id()));
505 
506   // Call MergeNetworkList() again and verify that we don't get update
507   // notification.
508   list.push_back(std::make_unique<Network>(ipv4_network2));
509   list.push_back(std::make_unique<Network>(ipv4_network1));
510   stats = MergeNetworkList(manager, std::move(list), &changed);
511   EXPECT_FALSE(changed);
512   EXPECT_EQ(stats.ipv6_network_count, 0);
513   EXPECT_EQ(stats.ipv4_network_count, 2);
514   list.clear();
515 
516   // Verify that we get previous instances of Network objects.
517   current = manager.GetNetworks();
518   EXPECT_EQ(2U, current.size());
519   EXPECT_TRUE((net1 == current[0] && net2 == current[1]) ||
520               (net1 == current[1] && net2 == current[0]));
521   EXPECT_TRUE((net_id1 == current[0]->id() && net_id2 == current[1]->id()) ||
522               (net_id1 == current[1]->id() && net_id2 == current[0]->id()));
523 }
524 
525 // Sets up some test IPv6 networks and appends them to list.
526 // Four networks are added - public and link local, for two interfaces.
SetupNetworks(std::vector<std::unique_ptr<Network>> * list)527 void SetupNetworks(std::vector<std::unique_ptr<Network>>* list) {
528   IPAddress ip;
529   IPAddress prefix;
530   EXPECT_TRUE(IPFromString("abcd::1234:5678:abcd:ef12", &ip));
531   EXPECT_TRUE(IPFromString("abcd::", &prefix));
532   // First, fake link-locals.
533   Network ipv6_eth0_linklocalnetwork("test_eth0", "Test NetworkAdapter 1",
534                                      prefix, 64);
535   ipv6_eth0_linklocalnetwork.AddIP(ip);
536   EXPECT_TRUE(IPFromString("abcd::5678:abcd:ef12:3456", &ip));
537   Network ipv6_eth1_linklocalnetwork("test_eth1", "Test NetworkAdapter 2",
538                                      prefix, 64);
539   ipv6_eth1_linklocalnetwork.AddIP(ip);
540   // Public networks:
541   EXPECT_TRUE(IPFromString("2401:fa00:4:1000:be30:5bff:fee5:c3", &ip));
542   prefix = TruncateIP(ip, 64);
543   Network ipv6_eth0_publicnetwork1_ip1("test_eth0", "Test NetworkAdapter 1",
544                                        prefix, 64);
545   ipv6_eth0_publicnetwork1_ip1.AddIP(ip);
546   EXPECT_TRUE(IPFromString("2400:4030:1:2c00:be30:abcd:efab:cdef", &ip));
547   prefix = TruncateIP(ip, 64);
548   Network ipv6_eth1_publicnetwork1_ip1("test_eth1", "Test NetworkAdapter 1",
549                                        prefix, 64);
550   ipv6_eth1_publicnetwork1_ip1.AddIP(ip);
551   list->push_back(std::make_unique<Network>(ipv6_eth0_linklocalnetwork));
552   list->push_back(std::make_unique<Network>(ipv6_eth1_linklocalnetwork));
553   list->push_back(std::make_unique<Network>(ipv6_eth0_publicnetwork1_ip1));
554   list->push_back(std::make_unique<Network>(ipv6_eth1_publicnetwork1_ip1));
555 }
556 
557 // Test that the basic network merging case works.
TEST_F(NetworkTest,TestIPv6MergeNetworkList)558 TEST_F(NetworkTest, TestIPv6MergeNetworkList) {
559   PhysicalSocketServer socket_server;
560   BasicNetworkManager manager(&socket_server);
561   manager.SignalNetworksChanged.connect(static_cast<NetworkTest*>(this),
562                                         &NetworkTest::OnNetworksChanged);
563   std::vector<std::unique_ptr<Network>> networks;
564   SetupNetworks(&networks);
565   std::vector<const Network*> original_list = CopyNetworkPointers(networks);
566   bool changed = false;
567   NetworkManager::Stats stats =
568       MergeNetworkList(manager, std::move(networks), &changed);
569   EXPECT_TRUE(changed);
570   EXPECT_EQ(stats.ipv6_network_count, 4);
571   EXPECT_EQ(stats.ipv4_network_count, 0);
572   std::vector<const Network*> list = manager.GetNetworks();
573   // Verify that the original members are in the merged list.
574   EXPECT_THAT(list, UnorderedElementsAreArray(original_list));
575 }
576 
577 // Tests that when two network lists that describe the same set of networks are
578 // merged, that the changed callback is not called, and that the original
579 // objects remain in the result list.
TEST_F(NetworkTest,TestNoChangeMerge)580 TEST_F(NetworkTest, TestNoChangeMerge) {
581   PhysicalSocketServer socket_server;
582   BasicNetworkManager manager(&socket_server);
583   manager.SignalNetworksChanged.connect(static_cast<NetworkTest*>(this),
584                                         &NetworkTest::OnNetworksChanged);
585   std::vector<std::unique_ptr<Network>> networks;
586   SetupNetworks(&networks);
587   std::vector<const Network*> original_list = CopyNetworkPointers(networks);
588   bool changed = false;
589   MergeNetworkList(manager, std::move(networks), &changed);
590   EXPECT_TRUE(changed);
591   // Second list that describes the same networks but with new objects.
592   std::vector<std::unique_ptr<Network>> second_networks;
593   SetupNetworks(&second_networks);
594   std::vector<const Network*> second_list =
595       CopyNetworkPointers(second_networks);
596   changed = false;
597   MergeNetworkList(manager, std::move(second_networks), &changed);
598   EXPECT_FALSE(changed);
599   std::vector<const Network*> resulting_list = manager.GetNetworks();
600   // Verify that the original members are in the merged list.
601   EXPECT_THAT(resulting_list, UnorderedElementsAreArray(original_list));
602   // Doublecheck that the new networks aren't in the list.
603   for (const Network* network : second_list) {
604     EXPECT_THAT(resulting_list, Not(Contains(network)));
605   }
606 }
607 
608 // Test that we can merge a network that is the same as another network but with
609 // a different IP. The original network should remain in the list, but have its
610 // IP changed.
TEST_F(NetworkTest,MergeWithChangedIP)611 TEST_F(NetworkTest, MergeWithChangedIP) {
612   PhysicalSocketServer socket_server;
613   BasicNetworkManager manager(&socket_server);
614   manager.SignalNetworksChanged.connect(static_cast<NetworkTest*>(this),
615                                         &NetworkTest::OnNetworksChanged);
616   std::vector<std::unique_ptr<Network>> original_list;
617   SetupNetworks(&original_list);
618   // Make a network that we're going to change.
619   IPAddress ip;
620   EXPECT_TRUE(IPFromString("2401:fa01:4:1000:be30:faa:fee:faa", &ip));
621   IPAddress prefix = TruncateIP(ip, 64);
622   std::unique_ptr<Network> network_to_change = std::make_unique<Network>(
623       "test_eth0", "Test Network Adapter 1", prefix, 64);
624   std::unique_ptr<Network> changed_network =
625       std::make_unique<Network>(*network_to_change);
626   network_to_change->AddIP(ip);
627   IPAddress changed_ip;
628   EXPECT_TRUE(IPFromString("2401:fa01:4:1000:be30:f00:f00:f00", &changed_ip));
629   changed_network->AddIP(changed_ip);
630   const Network* const network_to_change_ptr = network_to_change.get();
631   original_list.push_back(std::move(network_to_change));
632   const size_t original_size = original_list.size();
633   bool changed = false;
634   MergeNetworkList(manager, std::move(original_list), &changed);
635   std::vector<std::unique_ptr<Network>> second_list;
636   SetupNetworks(&second_list);
637   second_list.push_back(std::move(changed_network));
638   changed = false;
639   MergeNetworkList(manager, std::move(second_list), &changed);
640   EXPECT_TRUE(changed);
641   std::vector<const Network*> list = manager.GetNetworks();
642   EXPECT_EQ(original_size, list.size());
643   // Make sure the original network is still in the merged list.
644   EXPECT_THAT(list, Contains(network_to_change_ptr));
645   EXPECT_EQ(changed_ip, network_to_change_ptr->GetIPs().at(0));
646 }
647 
TEST_F(NetworkTest,TestMultipleIPMergeNetworkList)648 TEST_F(NetworkTest, TestMultipleIPMergeNetworkList) {
649   PhysicalSocketServer socket_server;
650   BasicNetworkManager manager(&socket_server);
651   manager.SignalNetworksChanged.connect(static_cast<NetworkTest*>(this),
652                                         &NetworkTest::OnNetworksChanged);
653   std::vector<std::unique_ptr<Network>> original_list;
654   SetupNetworks(&original_list);
655   const Network* const network_ptr = original_list[2].get();
656   bool changed = false;
657   MergeNetworkList(manager, std::move(original_list), &changed);
658   EXPECT_TRUE(changed);
659   IPAddress ip;
660   IPAddress check_ip;
661   IPAddress prefix;
662   // Add a second IP to the public network on eth0 (2401:fa00:4:1000/64).
663   EXPECT_TRUE(IPFromString("2401:fa00:4:1000:be30:5bff:fee5:c6", &ip));
664   prefix = TruncateIP(ip, 64);
665   Network ipv6_eth0_publicnetwork1_ip2("test_eth0", "Test NetworkAdapter 1",
666                                        prefix, 64);
667   // This is the IP that already existed in the public network on eth0.
668   EXPECT_TRUE(IPFromString("2401:fa00:4:1000:be30:5bff:fee5:c3", &check_ip));
669   ipv6_eth0_publicnetwork1_ip2.AddIP(ip);
670 
671   std::vector<std::unique_ptr<Network>> second_list;
672   SetupNetworks(&second_list);
673   second_list.push_back(
674       std::make_unique<Network>(ipv6_eth0_publicnetwork1_ip2));
675   changed = false;
676   const auto network_copy = std::make_unique<Network>(*second_list[2]);
677   MergeNetworkList(manager, std::move(second_list), &changed);
678   EXPECT_TRUE(changed);
679   // There should still be four networks.
680   std::vector<const Network*> list = manager.GetNetworks();
681   EXPECT_EQ(4U, list.size());
682   // Check the gathered IPs.
683   int matchcount = 0;
684   for (const Network* network : list) {
685     if (SameNameAndPrefix(*network, *network_copy)) {
686       ++matchcount;
687       EXPECT_EQ(1, matchcount);
688       // This should be the same network object as before.
689       EXPECT_EQ(network, network_ptr);
690       // But with two addresses now.
691       EXPECT_THAT(network->GetIPs(),
692                   UnorderedElementsAre(InterfaceAddress(check_ip),
693                                        InterfaceAddress(ip)));
694     } else {
695       // Check the IP didn't get added anywhere it wasn't supposed to.
696       EXPECT_THAT(network->GetIPs(), Not(Contains(InterfaceAddress(ip))));
697     }
698   }
699 }
700 
701 // Test that merge correctly distinguishes multiple networks on an interface.
TEST_F(NetworkTest,TestMultiplePublicNetworksOnOneInterfaceMerge)702 TEST_F(NetworkTest, TestMultiplePublicNetworksOnOneInterfaceMerge) {
703   PhysicalSocketServer socket_server;
704   BasicNetworkManager manager(&socket_server);
705   manager.SignalNetworksChanged.connect(static_cast<NetworkTest*>(this),
706                                         &NetworkTest::OnNetworksChanged);
707   std::vector<std::unique_ptr<Network>> original_list;
708   SetupNetworks(&original_list);
709   bool changed = false;
710   MergeNetworkList(manager, std::move(original_list), &changed);
711   EXPECT_TRUE(changed);
712   IPAddress ip;
713   IPAddress prefix;
714   // A second network for eth0.
715   EXPECT_TRUE(IPFromString("2400:4030:1:2c00:be30:5bff:fee5:c3", &ip));
716   prefix = TruncateIP(ip, 64);
717   Network ipv6_eth0_publicnetwork2_ip1("test_eth0", "Test NetworkAdapter 1",
718                                        prefix, 64);
719   ipv6_eth0_publicnetwork2_ip1.AddIP(ip);
720   std::vector<std::unique_ptr<Network>> second_list;
721   SetupNetworks(&second_list);
722   second_list.push_back(
723       std::make_unique<Network>(ipv6_eth0_publicnetwork2_ip1));
724   changed = false;
725   MergeNetworkList(manager, std::move(second_list), &changed);
726   EXPECT_TRUE(changed);
727   // There should be five networks now.
728   std::vector<const Network*> list = manager.GetNetworks();
729   EXPECT_EQ(5U, list.size());
730   // Check the resulting addresses.
731   for (const Network* network : list) {
732     if (network->prefix() == ipv6_eth0_publicnetwork2_ip1.prefix() &&
733         network->name() == ipv6_eth0_publicnetwork2_ip1.name()) {
734       // Check the new network has 1 IP and that it's the correct one.
735       EXPECT_EQ(1U, network->GetIPs().size());
736       EXPECT_EQ(ip, network->GetIPs().at(0));
737     } else {
738       // Check the IP didn't get added anywhere it wasn't supposed to.
739       EXPECT_THAT(network->GetIPs(), Not(Contains(InterfaceAddress(ip))));
740     }
741   }
742 }
743 
744 // Test that DumpNetworks does not crash.
TEST_F(NetworkTest,TestCreateAndDumpNetworks)745 TEST_F(NetworkTest, TestCreateAndDumpNetworks) {
746   PhysicalSocketServer socket_server;
747   BasicNetworkManager manager(&socket_server);
748   manager.StartUpdating();
749   std::vector<std::unique_ptr<Network>> list = GetNetworks(manager, true);
750   bool changed;
751   MergeNetworkList(manager, std::move(list), &changed);
752   manager.DumpNetworks();
753 }
754 
TEST_F(NetworkTest,TestIPv6Toggle)755 TEST_F(NetworkTest, TestIPv6Toggle) {
756   PhysicalSocketServer socket_server;
757   BasicNetworkManager manager(&socket_server);
758   manager.StartUpdating();
759   bool ipv6_found = false;
760   for (const auto& network : GetNetworks(manager, true)) {
761     if (network->prefix().family() == AF_INET6) {
762       ipv6_found = true;
763       break;
764     }
765   }
766   EXPECT_TRUE(ipv6_found);
767 }
768 
769 // Test that when network interfaces are sorted and given preference values,
770 // IPv6 comes first.
TEST_F(NetworkTest,IPv6NetworksPreferredOverIPv4)771 TEST_F(NetworkTest, IPv6NetworksPreferredOverIPv4) {
772   PhysicalSocketServer socket_server;
773   BasicNetworkManager manager(&socket_server);
774   Network ipv4_network1("test_eth0", "Test Network Adapter 1",
775                         IPAddress(0x12345600U), 24);
776   ipv4_network1.AddIP(IPAddress(0x12345600U));
777 
778   IPAddress ip;
779   IPAddress prefix;
780   EXPECT_TRUE(IPFromString("2400:4030:1:2c00:be30:abcd:efab:cdef", &ip));
781   prefix = TruncateIP(ip, 64);
782   Network ipv6_eth1_publicnetwork1_ip1("test_eth1", "Test NetworkAdapter 2",
783                                        prefix, 64);
784   ipv6_eth1_publicnetwork1_ip1.AddIP(ip);
785 
786   std::vector<std::unique_ptr<Network>> list;
787   list.push_back(std::make_unique<Network>(ipv4_network1));
788   list.push_back(std::make_unique<Network>(ipv6_eth1_publicnetwork1_ip1));
789   const Network* net1 = list[0].get();
790   const Network* net2 = list[1].get();
791 
792   bool changed = false;
793   MergeNetworkList(manager, std::move(list), &changed);
794   ASSERT_TRUE(changed);
795   // After sorting IPv6 network should be higher order than IPv4 networks.
796   EXPECT_TRUE(net1->preference() < net2->preference());
797 }
798 
799 // When two interfaces are equivalent in everything but name, they're expected
800 // to be preference-ordered by name. For example, "eth0" before "eth1".
TEST_F(NetworkTest,NetworksSortedByInterfaceName)801 TEST_F(NetworkTest, NetworksSortedByInterfaceName) {
802   PhysicalSocketServer socket_server;
803   BasicNetworkManager manager(&socket_server, &field_trials_);
804   auto eth0 = std::make_unique<Network>("test_eth0", "Test Network Adapter 1",
805                                         IPAddress(0x65432100U), 24);
806   eth0->AddIP(IPAddress(0x65432100U));
807   auto eth1 = std::make_unique<Network>("test_eth1", "Test Network Adapter 2",
808                                         IPAddress(0x12345600U), 24);
809   eth1->AddIP(IPAddress(0x12345600U));
810   std::vector<std::unique_ptr<Network>> list;
811   const Network* eth0_ptr = eth0.get();
812   const Network* eth1_ptr = eth1.get();
813   // Add them to the list in the opposite of the expected sorted order, to
814   // ensure sorting actually occurs.
815   list.push_back(std::move(eth1));
816   list.push_back(std::move(eth0));
817 
818   bool changed = false;
819   MergeNetworkList(manager, std::move(list), &changed);
820   ASSERT_TRUE(changed);
821   // "test_eth0" should be preferred over "test_eth1".
822   EXPECT_TRUE(eth0_ptr->preference() > eth1_ptr->preference());
823 }
824 
TEST_F(NetworkTest,TestNetworkAdapterTypes)825 TEST_F(NetworkTest, TestNetworkAdapterTypes) {
826   Network wifi("wlan0", "Wireless Adapter", IPAddress(0x12345600U), 24,
827                ADAPTER_TYPE_WIFI, &field_trials_);
828   EXPECT_EQ(ADAPTER_TYPE_WIFI, wifi.type());
829   Network ethernet("eth0", "Ethernet", IPAddress(0x12345600U), 24,
830                    ADAPTER_TYPE_ETHERNET, &field_trials_);
831   EXPECT_EQ(ADAPTER_TYPE_ETHERNET, ethernet.type());
832   Network cellular("test_cell", "Cellular Adapter", IPAddress(0x12345600U), 24,
833                    ADAPTER_TYPE_CELLULAR, &field_trials_);
834   EXPECT_EQ(ADAPTER_TYPE_CELLULAR, cellular.type());
835   Network vpn("bridge_test", "VPN Adapter", IPAddress(0x12345600U), 24,
836               ADAPTER_TYPE_VPN, &field_trials_);
837   EXPECT_EQ(ADAPTER_TYPE_VPN, vpn.type());
838   Network unknown("test", "Test Adapter", IPAddress(0x12345600U), 24,
839                   ADAPTER_TYPE_UNKNOWN, &field_trials_);
840   EXPECT_EQ(ADAPTER_TYPE_UNKNOWN, unknown.type());
841 }
842 
843 #if defined(WEBRTC_POSIX)
844 // Verify that we correctly handle interfaces with no address.
TEST_F(NetworkTest,TestConvertIfAddrsNoAddress)845 TEST_F(NetworkTest, TestConvertIfAddrsNoAddress) {
846   ifaddrs list;
847   memset(&list, 0, sizeof(list));
848   list.ifa_name = const_cast<char*>("test_iface");
849 
850   std::vector<std::unique_ptr<Network>> result;
851   PhysicalSocketServer socket_server;
852   BasicNetworkManager manager(&socket_server);
853   manager.StartUpdating();
854   CallConvertIfAddrs(manager, &list, true, &result);
855   EXPECT_TRUE(result.empty());
856 }
857 
858 // Verify that if there are two addresses on one interface, only one network
859 // is generated.
TEST_F(NetworkTest,TestConvertIfAddrsMultiAddressesOnOneInterface)860 TEST_F(NetworkTest, TestConvertIfAddrsMultiAddressesOnOneInterface) {
861   char if_name[20] = "rmnet0";
862   ifaddrs* list = nullptr;
863   list = AddIpv6Address(list, if_name, "1000:2000:3000:4000:0:0:0:1",
864                         "FFFF:FFFF:FFFF:FFFF::", 0);
865   list = AddIpv6Address(list, if_name, "1000:2000:3000:4000:0:0:0:2",
866                         "FFFF:FFFF:FFFF:FFFF::", 0);
867   std::vector<std::unique_ptr<Network>> result;
868   PhysicalSocketServer socket_server;
869   BasicNetworkManager manager(&socket_server);
870   manager.StartUpdating();
871   CallConvertIfAddrs(manager, list, true, &result);
872   EXPECT_EQ(1U, result.size());
873   bool changed;
874   // This ensures we release the objects created in CallConvertIfAddrs.
875   MergeNetworkList(manager, std::move(result), &changed);
876   ReleaseIfAddrs(list);
877 }
878 
TEST_F(NetworkTest,TestConvertIfAddrsNotRunning)879 TEST_F(NetworkTest, TestConvertIfAddrsNotRunning) {
880   ifaddrs list;
881   memset(&list, 0, sizeof(list));
882   list.ifa_name = const_cast<char*>("test_iface");
883   sockaddr ifa_addr;
884   sockaddr ifa_netmask;
885   list.ifa_addr = &ifa_addr;
886   list.ifa_netmask = &ifa_netmask;
887 
888   std::vector<std::unique_ptr<Network>> result;
889   PhysicalSocketServer socket_server;
890   BasicNetworkManager manager(&socket_server);
891   manager.StartUpdating();
892   CallConvertIfAddrs(manager, &list, true, &result);
893   EXPECT_TRUE(result.empty());
894 }
895 
896 // Tests that the network type can be determined from the network monitor when
897 // it would otherwise be unknown.
TEST_F(NetworkTest,TestGetAdapterTypeFromNetworkMonitor)898 TEST_F(NetworkTest, TestGetAdapterTypeFromNetworkMonitor) {
899   char if_name[20] = "wifi0";
900   std::string ipv6_address = "1000:2000:3000:4000:0:0:0:1";
901   std::string ipv6_mask = "FFFF:FFFF:FFFF:FFFF::";
902   PhysicalSocketServer socket_server;
903   BasicNetworkManager manager_without_monitor(nullptr, &socket_server,
904                                               &field_trials_);
905   manager_without_monitor.StartUpdating();
906   // A network created without a network monitor will get UNKNOWN type.
907   ifaddrs* addr_list = InstallIpv6Network(if_name, ipv6_address, ipv6_mask,
908                                           manager_without_monitor);
909   EXPECT_EQ(ADAPTER_TYPE_UNKNOWN, GetAdapterType(manager_without_monitor));
910   ReleaseIfAddrs(addr_list);
911 
912   // With the fake network monitor the type should be correctly determined.
913   FakeNetworkMonitorFactory factory;
914   BasicNetworkManager manager_with_monitor(&factory, &socket_server,
915                                            &field_trials_);
916   manager_with_monitor.StartUpdating();
917   // Add the same ipv6 address as before but it has the right network type
918   // detected by the network monitor now.
919   addr_list = InstallIpv6Network(if_name, ipv6_address, ipv6_mask,
920                                  manager_with_monitor);
921   EXPECT_EQ(ADAPTER_TYPE_WIFI, GetAdapterType(manager_with_monitor));
922   ReleaseIfAddrs(addr_list);
923 }
924 
925 // Test that the network type can be determined based on name matching in
926 // a few cases. Note that UNKNOWN type for non-matching strings has been tested
927 // in the above test.
TEST_F(NetworkTest,TestGetAdapterTypeFromNameMatching)928 TEST_F(NetworkTest, TestGetAdapterTypeFromNameMatching) {
929   std::string ipv4_address1 = "192.0.0.121";
930   std::string ipv4_mask = "255.255.255.0";
931   std::string ipv6_address1 = "1000:2000:3000:4000:0:0:0:1";
932   std::string ipv6_address2 = "1000:2000:3000:8000:0:0:0:1";
933   std::string ipv6_mask = "FFFF:FFFF:FFFF:FFFF::";
934   PhysicalSocketServer socket_server;
935   BasicNetworkManager manager(&socket_server);
936   manager.StartUpdating();
937 
938   // IPSec interface; name is in form "ipsec<index>".
939   char if_name[20] = "ipsec11";
940   ifaddrs* addr_list =
941       InstallIpv6Network(if_name, ipv6_address1, ipv6_mask, manager);
942   EXPECT_EQ(ADAPTER_TYPE_VPN, GetAdapterType(manager));
943   ClearNetworks(manager);
944   ReleaseIfAddrs(addr_list);
945 
946   strcpy(if_name, "lo0");
947   addr_list = InstallIpv6Network(if_name, ipv6_address1, ipv6_mask, manager);
948   EXPECT_EQ(ADAPTER_TYPE_LOOPBACK, GetAdapterType(manager));
949   ClearNetworks(manager);
950   ReleaseIfAddrs(addr_list);
951 
952   strcpy(if_name, "eth0");
953   addr_list = InstallIpv4Network(if_name, ipv4_address1, ipv4_mask, manager);
954   EXPECT_EQ(ADAPTER_TYPE_ETHERNET, GetAdapterType(manager));
955   ClearNetworks(manager);
956   ReleaseIfAddrs(addr_list);
957 
958   strcpy(if_name, "wlan0");
959   addr_list = InstallIpv6Network(if_name, ipv6_address1, ipv6_mask, manager);
960   EXPECT_EQ(ADAPTER_TYPE_WIFI, GetAdapterType(manager));
961   ClearNetworks(manager);
962   ReleaseIfAddrs(addr_list);
963 
964 #if defined(WEBRTC_IOS)
965   strcpy(if_name, "pdp_ip0");
966   addr_list = InstallIpv6Network(if_name, ipv6_address1, ipv6_mask, manager);
967   EXPECT_EQ(ADAPTER_TYPE_CELLULAR, GetAdapterType(manager));
968   ClearNetworks(manager);
969   ReleaseIfAddrs(addr_list);
970 
971   strcpy(if_name, "en0");
972   addr_list = InstallIpv6Network(if_name, ipv6_address1, ipv6_mask, manager);
973   EXPECT_EQ(ADAPTER_TYPE_WIFI, GetAdapterType(manager));
974   ClearNetworks(manager);
975   ReleaseIfAddrs(addr_list);
976 
977 #elif defined(WEBRTC_ANDROID)
978   strcpy(if_name, "rmnet0");
979   addr_list = InstallIpv6Network(if_name, ipv6_address1, ipv6_mask, manager);
980   EXPECT_EQ(ADAPTER_TYPE_CELLULAR, GetAdapterType(manager));
981   ClearNetworks(manager);
982   ReleaseIfAddrs(addr_list);
983 
984   strcpy(if_name, "v4-rmnet_data0");
985   addr_list = InstallIpv6Network(if_name, ipv6_address2, ipv6_mask, manager);
986   EXPECT_EQ(ADAPTER_TYPE_CELLULAR, GetAdapterType(manager));
987   ClearNetworks(manager);
988   ReleaseIfAddrs(addr_list);
989 
990   strcpy(if_name, "clat4");
991   addr_list = InstallIpv4Network(if_name, ipv4_address1, ipv4_mask, manager);
992   EXPECT_EQ(ADAPTER_TYPE_CELLULAR, GetAdapterType(manager));
993   ClearNetworks(manager);
994   ReleaseIfAddrs(addr_list);
995 #endif
996 }
997 
998 // Test that an adapter won't be included in the network list if there's a
999 // network monitor that says it's unavailable.
TEST_F(NetworkTest,TestNetworkMonitorIsAdapterAvailable)1000 TEST_F(NetworkTest, TestNetworkMonitorIsAdapterAvailable) {
1001   char if_name1[20] = "pdp_ip0";
1002   char if_name2[20] = "pdp_ip1";
1003   ifaddrs* list = nullptr;
1004   list = AddIpv6Address(list, if_name1, "1000:2000:3000:4000:0:0:0:1",
1005                         "FFFF:FFFF:FFFF:FFFF::", 0);
1006   list = AddIpv6Address(list, if_name2, "1000:2000:3000:4000:0:0:0:2",
1007                         "FFFF:FFFF:FFFF:FFFF::", 0);
1008   std::vector<std::unique_ptr<Network>> result;
1009 
1010   // Sanity check that both interfaces are included by default.
1011   FakeNetworkMonitorFactory factory;
1012   PhysicalSocketServer socket_server;
1013   BasicNetworkManager manager(&factory, &socket_server, &field_trials_);
1014   manager.StartUpdating();
1015   CallConvertIfAddrs(manager, list, /*include_ignored=*/false, &result);
1016   EXPECT_EQ(2u, result.size());
1017   bool changed;
1018   // This ensures we release the objects created in CallConvertIfAddrs.
1019   MergeNetworkList(manager, std::move(result), &changed);
1020   result.clear();
1021 
1022   // Now simulate one interface being unavailable.
1023   FakeNetworkMonitor* network_monitor = GetNetworkMonitor(manager);
1024   network_monitor->set_unavailable_adapters({if_name1});
1025   CallConvertIfAddrs(manager, list, /*include_ignored=*/false, &result);
1026   EXPECT_EQ(1u, result.size());
1027   EXPECT_EQ(if_name2, result[0]->name());
1028 
1029   MergeNetworkList(manager, std::move(result), &changed);
1030   ReleaseIfAddrs(list);
1031 }
1032 
1033 #endif  // defined(WEBRTC_POSIX)
1034 
1035 // Test MergeNetworkList successfully combines all IPs for the same
1036 // prefix/length into a single Network.
TEST_F(NetworkTest,TestMergeNetworkList)1037 TEST_F(NetworkTest, TestMergeNetworkList) {
1038   PhysicalSocketServer socket_server;
1039   BasicNetworkManager manager(&socket_server);
1040   std::vector<std::unique_ptr<Network>> list;
1041 
1042   // Create 2 IPAddress classes with only last digit different.
1043   IPAddress ip1, ip2;
1044   EXPECT_TRUE(IPFromString("2400:4030:1:2c00:be30:0:0:1", &ip1));
1045   EXPECT_TRUE(IPFromString("2400:4030:1:2c00:be30:0:0:2", &ip2));
1046 
1047   // Create 2 networks with the same prefix and length.
1048   auto net1 = std::make_unique<Network>("em1", "em1", TruncateIP(ip1, 64), 64);
1049   auto net2 = std::make_unique<Network>("em1", "em1", TruncateIP(ip1, 64), 64);
1050 
1051   // Add different IP into each.
1052   net1->AddIP(ip1);
1053   net2->AddIP(ip2);
1054 
1055   list.push_back(std::move(net1));
1056   list.push_back(std::move(net2));
1057   bool changed;
1058   MergeNetworkList(manager, std::move(list), &changed);
1059   EXPECT_TRUE(changed);
1060 
1061   std::vector<const Network*> list2 = manager.GetNetworks();
1062 
1063   // Make sure the resulted networklist has only 1 element and 2
1064   // IPAddresses.
1065   EXPECT_EQ(list2.size(), 1uL);
1066   EXPECT_EQ(list2[0]->GetIPs().size(), 2uL);
1067   EXPECT_THAT(list2[0]->GetIPs(), UnorderedElementsAre(InterfaceAddress(ip1),
1068                                                        InterfaceAddress(ip2)));
1069 }
1070 
1071 // Test that MergeNetworkList successfully detects the change if
1072 // a network becomes inactive and then active again.
TEST_F(NetworkTest,TestMergeNetworkListWithInactiveNetworks)1073 TEST_F(NetworkTest, TestMergeNetworkListWithInactiveNetworks) {
1074   PhysicalSocketServer socket_server;
1075   BasicNetworkManager manager(&socket_server);
1076   Network network1("test_wifi", "Test Network Adapter 1",
1077                    IPAddress(0x12345600U), 24);
1078   Network network2("test_eth0", "Test Network Adapter 2",
1079                    IPAddress(0x00010000U), 16);
1080   network1.AddIP(IPAddress(0x12345678));
1081   network2.AddIP(IPAddress(0x00010004));
1082   std::vector<std::unique_ptr<Network>> list;
1083   auto net1 = std::make_unique<Network>(network1);
1084   const Network* const net1_ptr = net1.get();
1085   list.push_back(std::move(net1));
1086   bool changed;
1087   MergeNetworkList(manager, std::move(list), &changed);
1088   EXPECT_TRUE(changed);
1089   list.clear();
1090 
1091   std::vector<const Network*> current = manager.GetNetworks();
1092   ASSERT_EQ(1U, current.size());
1093   EXPECT_EQ(net1_ptr, current[0]);
1094 
1095   list.clear();
1096   auto net2 = std::make_unique<Network>(network2);
1097   const Network* const net2_ptr = net2.get();
1098   list.push_back(std::move(net2));
1099   MergeNetworkList(manager, std::move(list), &changed);
1100   EXPECT_TRUE(changed);
1101   list.clear();
1102 
1103   current = manager.GetNetworks();
1104   ASSERT_EQ(1U, current.size());
1105   EXPECT_EQ(net2_ptr, current[0]);
1106   // Now network1 is inactive. Try to merge it again.
1107   list.clear();
1108   list.push_back(std::make_unique<Network>(network1));
1109   MergeNetworkList(manager, std::move(list), &changed);
1110   EXPECT_TRUE(changed);
1111   list.clear();
1112   current = manager.GetNetworks();
1113   ASSERT_EQ(1U, current.size());
1114   EXPECT_TRUE(current[0]->active());
1115   EXPECT_EQ(net1_ptr, current[0]);
1116 }
1117 
1118 // Test that the filtering logic follows the defined ruleset in network.h.
TEST_F(NetworkTest,TestIPv6Selection)1119 TEST_F(NetworkTest, TestIPv6Selection) {
1120   InterfaceAddress ip;
1121   std::string ipstr;
1122 
1123   ipstr = "2401:fa00:4:1000:be30:5bff:fee5:c3";
1124   ASSERT_TRUE(IPFromString(ipstr, IPV6_ADDRESS_FLAG_DEPRECATED, &ip));
1125 
1126   // Create a network with this prefix.
1127   Network ipv6_network("test_eth0", "Test NetworkAdapter", TruncateIP(ip, 64),
1128                        64);
1129   EXPECT_EQ(AF_INET6, ipv6_network.family());
1130 
1131   // When there is no address added, it should return an unspecified
1132   // address.
1133   EXPECT_EQ(ipv6_network.GetBestIP(), IPAddress());
1134   EXPECT_TRUE(IPIsUnspec(ipv6_network.GetBestIP()));
1135 
1136   // Deprecated one should not be returned.
1137   ipv6_network.AddIP(ip);
1138   EXPECT_EQ(ipv6_network.GetBestIP(), IPAddress());
1139 
1140   // Add ULA one. ULA is unique local address which is starting either
1141   // with 0xfc or 0xfd.
1142   ipstr = "fd00:fa00:4:1000:be30:5bff:fee5:c4";
1143   ASSERT_TRUE(IPFromString(ipstr, IPV6_ADDRESS_FLAG_NONE, &ip));
1144   ipv6_network.AddIP(ip);
1145   EXPECT_EQ(ipv6_network.GetBestIP(), static_cast<IPAddress>(ip));
1146 
1147   // Add global one.
1148   ipstr = "2401:fa00:4:1000:be30:5bff:fee5:c5";
1149   ASSERT_TRUE(IPFromString(ipstr, IPV6_ADDRESS_FLAG_NONE, &ip));
1150   ipv6_network.AddIP(ip);
1151   EXPECT_EQ(ipv6_network.GetBestIP(), static_cast<IPAddress>(ip));
1152 
1153   // Add global dynamic temporary one.
1154   ipstr = "2401:fa00:4:1000:be30:5bff:fee5:c6";
1155   ASSERT_TRUE(IPFromString(ipstr, IPV6_ADDRESS_FLAG_TEMPORARY, &ip));
1156   ipv6_network.AddIP(ip);
1157   EXPECT_EQ(ipv6_network.GetBestIP(), static_cast<IPAddress>(ip));
1158 }
1159 
1160 // Test that the filtering logic follows the defined ruleset in network.h.
TEST_F(NetworkTest,TestGetBestIPWithPreferGlobalIPv6ToLinkLocalEnabled)1161 TEST_F(NetworkTest, TestGetBestIPWithPreferGlobalIPv6ToLinkLocalEnabled) {
1162   webrtc::test::ScopedKeyValueConfig field_trials(
1163       "WebRTC-IPv6NetworkResolutionFixes/"
1164       "Enabled,PreferGlobalIPv6Address:true/");
1165   InterfaceAddress ip, link_local;
1166   std::string ipstr;
1167 
1168   ipstr = "2401:fa00:4:1000:be30:5bff:fee5:c3";
1169   ASSERT_TRUE(IPFromString(ipstr, IPV6_ADDRESS_FLAG_DEPRECATED, &ip));
1170 
1171   // Create a network with this prefix.
1172   Network ipv6_network("test_eth0", "Test NetworkAdapter", TruncateIP(ip, 64),
1173                        64, ADAPTER_TYPE_UNKNOWN, &field_trials);
1174 
1175   // When there is no address added, it should return an unspecified
1176   // address.
1177   EXPECT_EQ(ipv6_network.GetBestIP(), IPAddress());
1178   EXPECT_TRUE(IPIsUnspec(ipv6_network.GetBestIP()));
1179 
1180   // Deprecated one should not be returned.
1181   ipv6_network.AddIP(ip);
1182   EXPECT_EQ(ipv6_network.GetBestIP(), IPAddress());
1183 
1184   // Add ULA one. ULA is unique local address which is starting either
1185   // with 0xfc or 0xfd.
1186   ipstr = "fd00:fa00:4:1000:be30:5bff:fee5:c4";
1187   ASSERT_TRUE(IPFromString(ipstr, IPV6_ADDRESS_FLAG_NONE, &ip));
1188   ipv6_network.AddIP(ip);
1189   EXPECT_EQ(ipv6_network.GetBestIP(), static_cast<IPAddress>(ip));
1190 
1191   // Add link local one.
1192   ipstr = "fe80::aabb:ccff:fedd:eeff";
1193   ASSERT_TRUE(IPFromString(ipstr, IPV6_ADDRESS_FLAG_NONE, &link_local));
1194   ipv6_network.AddIP(link_local);
1195   EXPECT_EQ(ipv6_network.GetBestIP(), static_cast<IPAddress>(link_local));
1196 
1197   // Add global one.
1198   ipstr = "2401:fa00:4:1000:be30:5bff:fee5:c5";
1199   ASSERT_TRUE(IPFromString(ipstr, IPV6_ADDRESS_FLAG_NONE, &ip));
1200   ipv6_network.AddIP(ip);
1201   EXPECT_EQ(ipv6_network.GetBestIP(), static_cast<IPAddress>(ip));
1202 
1203   // Add another link local address, then the compatible address is still global
1204   // one.
1205   ipstr = "fe80::aabb:ccff:fedd:eedd";
1206   ASSERT_TRUE(IPFromString(ipstr, IPV6_ADDRESS_FLAG_NONE, &link_local));
1207   ipv6_network.AddIP(link_local);
1208   EXPECT_EQ(ipv6_network.GetBestIP(), static_cast<IPAddress>(ip));
1209 
1210   // Add global dynamic temporary one.
1211   ipstr = "2401:fa00:4:1000:be30:5bff:fee5:c6";
1212   ASSERT_TRUE(IPFromString(ipstr, IPV6_ADDRESS_FLAG_TEMPORARY, &ip));
1213   ipv6_network.AddIP(ip);
1214   EXPECT_EQ(ipv6_network.GetBestIP(), static_cast<IPAddress>(ip));
1215 
1216   // Add another link local address, then the compatible address is still global
1217   // dynamic one.
1218   ipstr = "fe80::aabb:ccff:fedd:eedd";
1219   ASSERT_TRUE(IPFromString(ipstr, IPV6_ADDRESS_FLAG_NONE, &link_local));
1220   ipv6_network.AddIP(link_local);
1221   EXPECT_EQ(ipv6_network.GetBestIP(), static_cast<IPAddress>(ip));
1222 }
1223 
TEST_F(NetworkTest,TestNetworkMonitoring)1224 TEST_F(NetworkTest, TestNetworkMonitoring) {
1225   FakeNetworkMonitorFactory factory;
1226   PhysicalSocketServer socket_server;
1227   BasicNetworkManager manager(&factory, &socket_server, &field_trials_);
1228   manager.SignalNetworksChanged.connect(static_cast<NetworkTest*>(this),
1229                                         &NetworkTest::OnNetworksChanged);
1230   manager.StartUpdating();
1231   FakeNetworkMonitor* network_monitor = GetNetworkMonitor(manager);
1232   EXPECT_TRUE(network_monitor && network_monitor->started());
1233   EXPECT_TRUE_WAIT(callback_called_, 1000);
1234   callback_called_ = false;
1235 
1236   // Clear the networks so that there will be network changes below.
1237   ClearNetworks(manager);
1238   // Network manager is started, so the callback is called when the network
1239   // monitor fires the network-change event.
1240   network_monitor->InovkeNetworksChangedCallbackForTesting();
1241   EXPECT_TRUE_WAIT(callback_called_, 1000);
1242 
1243   // Network manager is stopped.
1244   manager.StopUpdating();
1245   EXPECT_FALSE(GetNetworkMonitor(manager)->started());
1246 }
1247 
1248 // Fails on Android: https://bugs.chromium.org/p/webrtc/issues/detail?id=4364.
1249 #if defined(WEBRTC_ANDROID)
1250 #define MAYBE_DefaultLocalAddress DISABLED_DefaultLocalAddress
1251 #else
1252 #define MAYBE_DefaultLocalAddress DefaultLocalAddress
1253 #endif
TEST_F(NetworkTest,MAYBE_DefaultLocalAddress)1254 TEST_F(NetworkTest, MAYBE_DefaultLocalAddress) {
1255   IPAddress ip;
1256   FakeNetworkMonitorFactory factory;
1257   PhysicalSocketServer socket_server;
1258   TestBasicNetworkManager manager(&factory, &socket_server, field_trials_);
1259   manager.SignalNetworksChanged.connect(static_cast<NetworkTest*>(this),
1260                                         &NetworkTest::OnNetworksChanged);
1261   manager.StartUpdating();
1262   EXPECT_TRUE_WAIT(callback_called_, 1000);
1263 
1264   // Make sure we can query default local address when an address for such
1265   // address family exists.
1266   std::vector<const Network*> networks = manager.GetNetworks();
1267   EXPECT_TRUE(!networks.empty());
1268   for (const Network* network : networks) {
1269     if (network->GetBestIP().family() == AF_INET) {
1270       EXPECT_TRUE(QueryDefaultLocalAddress(manager, AF_INET) != IPAddress());
1271     } else if (network->GetBestIP().family() == AF_INET6 &&
1272                !IPIsLoopback(network->GetBestIP())) {
1273       // Existence of an IPv6 loopback address doesn't mean it has IPv6 network
1274       // enabled.
1275       EXPECT_TRUE(QueryDefaultLocalAddress(manager, AF_INET6) != IPAddress());
1276     }
1277   }
1278 
1279   // GetDefaultLocalAddress should return the valid default address after set.
1280   manager.set_default_local_addresses(GetLoopbackIP(AF_INET),
1281                                       GetLoopbackIP(AF_INET6));
1282   EXPECT_TRUE(manager.GetDefaultLocalAddress(AF_INET, &ip));
1283   EXPECT_EQ(ip, GetLoopbackIP(AF_INET));
1284   EXPECT_TRUE(manager.GetDefaultLocalAddress(AF_INET6, &ip));
1285   EXPECT_EQ(ip, GetLoopbackIP(AF_INET6));
1286 
1287   // More tests on GetDefaultLocalAddress with ipv6 addresses where the set
1288   // default address may be different from the best IP address of any network.
1289   InterfaceAddress ip1;
1290   EXPECT_TRUE(IPFromString("abcd::1234:5678:abcd:1111",
1291                            IPV6_ADDRESS_FLAG_TEMPORARY, &ip1));
1292   // Create a network with a prefix of ip1.
1293   Network ipv6_network("test_eth0", "Test NetworkAdapter", TruncateIP(ip1, 64),
1294                        64);
1295   IPAddress ip2;
1296   EXPECT_TRUE(IPFromString("abcd::1234:5678:abcd:2222", &ip2));
1297   ipv6_network.AddIP(ip1);
1298   ipv6_network.AddIP(ip2);
1299   std::vector<std::unique_ptr<Network>> list;
1300   list.push_back(std::make_unique<Network>(ipv6_network));
1301   bool changed;
1302   MergeNetworkList(manager, std::move(list), &changed);
1303   // If the set default address is not in any network, GetDefaultLocalAddress
1304   // should return it.
1305   IPAddress ip3;
1306   EXPECT_TRUE(IPFromString("abcd::1234:5678:abcd:3333", &ip3));
1307   manager.set_default_local_addresses(GetLoopbackIP(AF_INET), ip3);
1308   EXPECT_TRUE(manager.GetDefaultLocalAddress(AF_INET6, &ip));
1309   EXPECT_EQ(ip3, ip);
1310   // If the set default address is in a network, GetDefaultLocalAddress will
1311   // return the best IP in that network.
1312   manager.set_default_local_addresses(GetLoopbackIP(AF_INET), ip2);
1313   EXPECT_TRUE(manager.GetDefaultLocalAddress(AF_INET6, &ip));
1314   EXPECT_EQ(static_cast<IPAddress>(ip1), ip);
1315 
1316   manager.StopUpdating();
1317 }
1318 
1319 // Test that MergeNetworkList does not set change = true
1320 // when changing from cellular_X to cellular_Y.
TEST_F(NetworkTest,TestWhenNetworkListChangeReturnsChangedFlag)1321 TEST_F(NetworkTest, TestWhenNetworkListChangeReturnsChangedFlag) {
1322   PhysicalSocketServer socket_server;
1323   BasicNetworkManager manager(&socket_server);
1324 
1325   IPAddress ip1;
1326   EXPECT_TRUE(IPFromString("2400:4030:1:2c00:be30:0:0:1", &ip1));
1327   auto net1 = std::make_unique<Network>("em1", "em1", TruncateIP(ip1, 64), 64);
1328   net1->set_type(ADAPTER_TYPE_CELLULAR_3G);
1329   net1->AddIP(ip1);
1330   std::vector<std::unique_ptr<Network>> list;
1331   list.push_back(std::move(net1));
1332 
1333   {
1334     bool changed;
1335     MergeNetworkList(manager, std::move(list), &changed);
1336     EXPECT_TRUE(changed);
1337     std::vector<const Network*> list2 = manager.GetNetworks();
1338     EXPECT_EQ(list2.size(), 1uL);
1339     EXPECT_EQ(ADAPTER_TYPE_CELLULAR_3G, list2[0]->type());
1340   }
1341 
1342   // Modify net1 from 3G to 4G
1343   {
1344     auto net2 =
1345         std::make_unique<Network>("em1", "em1", TruncateIP(ip1, 64), 64);
1346     net2->set_type(ADAPTER_TYPE_CELLULAR_4G);
1347     net2->AddIP(ip1);
1348     list.clear();
1349     list.push_back(std::move(net2));
1350     bool changed;
1351     MergeNetworkList(manager, std::move(list), &changed);
1352 
1353     // Change from 3G to 4G shall not trigger OnNetworksChanged,
1354     // i.e changed = false.
1355     EXPECT_FALSE(changed);
1356     std::vector<const Network*> list2 = manager.GetNetworks();
1357     ASSERT_EQ(list2.size(), 1uL);
1358     EXPECT_EQ(ADAPTER_TYPE_CELLULAR_4G, list2[0]->type());
1359   }
1360 
1361   // Don't modify.
1362   {
1363     auto net2 =
1364         std::make_unique<Network>("em1", "em1", TruncateIP(ip1, 64), 64);
1365     net2->set_type(ADAPTER_TYPE_CELLULAR_4G);
1366     net2->AddIP(ip1);
1367     list.clear();
1368     list.push_back(std::move(net2));
1369     bool changed;
1370     MergeNetworkList(manager, std::move(list), &changed);
1371 
1372     // No change.
1373     EXPECT_FALSE(changed);
1374     std::vector<const Network*> list2 = manager.GetNetworks();
1375     ASSERT_EQ(list2.size(), 1uL);
1376     EXPECT_EQ(ADAPTER_TYPE_CELLULAR_4G, list2[0]->type());
1377   }
1378 }
1379 
1380 #if defined(WEBRTC_POSIX)
TEST_F(NetworkTest,IgnoresMACBasedIPv6Address)1381 TEST_F(NetworkTest, IgnoresMACBasedIPv6Address) {
1382   std::string ipv6_address = "2607:fc20:f340:1dc8:214:22ff:fe01:2345";
1383   std::string ipv6_mask = "FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF";
1384   PhysicalSocketServer socket_server;
1385   BasicNetworkManager manager(&socket_server);
1386   manager.StartUpdating();
1387 
1388   // IPSec interface; name is in form "ipsec<index>".
1389   char if_name[20] = "ipsec11";
1390   ifaddrs* addr_list =
1391       InstallIpv6Network(if_name, ipv6_address, ipv6_mask, manager);
1392 
1393   std::vector<const Network*> list = manager.GetNetworks();
1394   EXPECT_EQ(list.size(), 0u);
1395   ReleaseIfAddrs(addr_list);
1396 }
1397 
TEST_F(NetworkTest,WebRTC_AllowMACBasedIPv6Address)1398 TEST_F(NetworkTest, WebRTC_AllowMACBasedIPv6Address) {
1399   webrtc::test::ScopedFieldTrials field_trials(
1400       "WebRTC-AllowMACBasedIPv6/Enabled/");
1401   std::string ipv6_address = "2607:fc20:f340:1dc8:214:22ff:fe01:2345";
1402   std::string ipv6_mask = "FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF";
1403   PhysicalSocketServer socket_server;
1404   BasicNetworkManager manager(&socket_server);
1405   manager.StartUpdating();
1406 
1407   // IPSec interface; name is in form "ipsec<index>".
1408   char if_name[20] = "ipsec11";
1409   ifaddrs* addr_list =
1410       InstallIpv6Network(if_name, ipv6_address, ipv6_mask, manager);
1411 
1412   std::vector<const Network*> list = manager.GetNetworks();
1413   EXPECT_EQ(list.size(), 1u);
1414   ReleaseIfAddrs(addr_list);
1415 }
1416 #endif
1417 
1418 #if defined(WEBRTC_POSIX)
TEST_F(NetworkTest,WebRTC_BindUsingInterfaceName)1419 TEST_F(NetworkTest, WebRTC_BindUsingInterfaceName) {
1420   char if_name1[20] = "wlan0";
1421   char if_name2[20] = "v4-wlan0";
1422   ifaddrs* list = nullptr;
1423   list = AddIpv6Address(list, if_name1, "1000:2000:3000:4000:0:0:0:1",
1424                         "FFFF:FFFF:FFFF:FFFF::", 0);
1425   list = AddIpv4Address(list, if_name2, "192.168.0.2", "255.255.255.255");
1426   std::vector<std::unique_ptr<Network>> result;
1427 
1428   // Sanity check that both interfaces are included by default.
1429   FakeNetworkMonitorFactory factory;
1430   PhysicalSocketServer socket_server;
1431   BasicNetworkManager manager(&factory, &socket_server, &field_trials_);
1432   manager.StartUpdating();
1433   CallConvertIfAddrs(manager, list, /*include_ignored=*/false, &result);
1434   EXPECT_EQ(2u, result.size());
1435   ReleaseIfAddrs(list);
1436   bool changed;
1437   // This ensures we release the objects created in CallConvertIfAddrs.
1438   MergeNetworkList(manager, std::move(result), &changed);
1439   result.clear();
1440 
1441   FakeNetworkMonitor* network_monitor = GetNetworkMonitor(manager);
1442 
1443   IPAddress ipv6;
1444   EXPECT_TRUE(IPFromString("1000:2000:3000:4000:0:0:0:1", &ipv6));
1445   IPAddress ipv4;
1446   EXPECT_TRUE(IPFromString("192.168.0.2", &ipv4));
1447 
1448   // The network monitor only knwos about the ipv6 address, interface.
1449   network_monitor->set_adapters({"wlan0"});
1450   network_monitor->set_ip_addresses({ipv6});
1451   EXPECT_EQ(manager.BindSocketToNetwork(/* fd */ 77, ipv6),
1452             NetworkBindingResult::SUCCESS);
1453 
1454   // But it will bind anyway using string matching...
1455   EXPECT_EQ(manager.BindSocketToNetwork(/* fd */ 77, ipv4),
1456             NetworkBindingResult::SUCCESS);
1457 }
1458 #endif
1459 
TEST_F(NetworkTest,NetworkCostVpn_Default)1460 TEST_F(NetworkTest, NetworkCostVpn_Default) {
1461   IPAddress ip1;
1462   EXPECT_TRUE(IPFromString("2400:4030:1:2c00:be30:0:0:1", &ip1));
1463   webrtc::test::ScopedKeyValueConfig field_trials;
1464 
1465   Network* net1 = new Network("em1", "em1", TruncateIP(ip1, 64), 64);
1466   net1->set_type(ADAPTER_TYPE_VPN);
1467   net1->set_underlying_type_for_vpn(ADAPTER_TYPE_ETHERNET);
1468 
1469   Network* net2 = new Network("em1", "em1", TruncateIP(ip1, 64), 64);
1470   net2->set_type(ADAPTER_TYPE_ETHERNET);
1471 
1472   EXPECT_EQ(net1->GetCost(field_trials), net2->GetCost(field_trials));
1473   delete net1;
1474   delete net2;
1475 }
1476 
TEST_F(NetworkTest,NetworkCostVpn_VpnMoreExpensive)1477 TEST_F(NetworkTest, NetworkCostVpn_VpnMoreExpensive) {
1478   webrtc::test::ScopedKeyValueConfig field_trials(
1479       "WebRTC-AddNetworkCostToVpn/Enabled/");
1480 
1481   IPAddress ip1;
1482   EXPECT_TRUE(IPFromString("2400:4030:1:2c00:be30:0:0:1", &ip1));
1483 
1484   Network* net1 = new Network("em1", "em1", TruncateIP(ip1, 64), 64);
1485   net1->set_type(ADAPTER_TYPE_VPN);
1486   net1->set_underlying_type_for_vpn(ADAPTER_TYPE_ETHERNET);
1487 
1488   Network* net2 = new Network("em1", "em1", TruncateIP(ip1, 64), 64);
1489   net2->set_type(ADAPTER_TYPE_ETHERNET);
1490 
1491   EXPECT_GT(net1->GetCost(field_trials), net2->GetCost(field_trials));
1492   delete net1;
1493   delete net2;
1494 }
1495 
TEST_F(NetworkTest,GuessAdapterFromNetworkCost)1496 TEST_F(NetworkTest, GuessAdapterFromNetworkCost) {
1497   webrtc::test::ScopedKeyValueConfig field_trials(
1498       "WebRTC-AddNetworkCostToVpn/Enabled/"
1499       "WebRTC-UseDifferentiatedCellularCosts/Enabled/");
1500 
1501   IPAddress ip1;
1502   EXPECT_TRUE(IPFromString("2400:4030:1:2c00:be30:0:0:1", &ip1));
1503 
1504   for (auto type : kAllAdapterTypes) {
1505     if (type == rtc::ADAPTER_TYPE_VPN)
1506       continue;
1507     Network net1("em1", "em1", TruncateIP(ip1, 64), 64);
1508     net1.set_type(type);
1509     auto [guess, vpn] =
1510         Network::GuessAdapterFromNetworkCost(net1.GetCost(field_trials));
1511     EXPECT_FALSE(vpn);
1512     if (type == rtc::ADAPTER_TYPE_LOOPBACK) {
1513       EXPECT_EQ(guess, rtc::ADAPTER_TYPE_ETHERNET);
1514     } else {
1515       EXPECT_EQ(type, guess);
1516     }
1517   }
1518 
1519   // VPN
1520   for (auto type : kAllAdapterTypes) {
1521     if (type == rtc::ADAPTER_TYPE_VPN)
1522       continue;
1523     Network net1("em1", "em1", TruncateIP(ip1, 64), 64);
1524     net1.set_type(rtc::ADAPTER_TYPE_VPN);
1525     net1.set_underlying_type_for_vpn(type);
1526     auto [guess, vpn] =
1527         Network::GuessAdapterFromNetworkCost(net1.GetCost(field_trials));
1528     EXPECT_TRUE(vpn);
1529     if (type == rtc::ADAPTER_TYPE_LOOPBACK) {
1530       EXPECT_EQ(guess, rtc::ADAPTER_TYPE_ETHERNET);
1531     } else {
1532       EXPECT_EQ(type, guess);
1533     }
1534   }
1535 }
1536 
TEST_F(NetworkTest,VpnList)1537 TEST_F(NetworkTest, VpnList) {
1538   PhysicalSocketServer socket_server;
1539   {
1540     BasicNetworkManager manager(&socket_server);
1541     manager.set_vpn_list({NetworkMask(IPFromString("192.168.0.0"), 16)});
1542     manager.StartUpdating();
1543     EXPECT_TRUE(manager.IsConfiguredVpn(IPFromString("192.168.1.1"), 32));
1544     EXPECT_TRUE(manager.IsConfiguredVpn(IPFromString("192.168.12.1"), 24));
1545     EXPECT_TRUE(manager.IsConfiguredVpn(IPFromString("192.168.0.0"), 16));
1546     EXPECT_TRUE(manager.IsConfiguredVpn(IPFromString("192.168.0.0"), 24));
1547     EXPECT_FALSE(manager.IsConfiguredVpn(IPFromString("192.133.1.1"), 32));
1548     EXPECT_FALSE(manager.IsConfiguredVpn(IPFromString("192.133.0.0"), 16));
1549     EXPECT_FALSE(manager.IsConfiguredVpn(IPFromString("192.168.0.0"), 15));
1550   }
1551   {
1552     BasicNetworkManager manager(&socket_server);
1553     manager.set_vpn_list({NetworkMask(IPFromString("192.168.0.0"), 24)});
1554     manager.StartUpdating();
1555     EXPECT_FALSE(manager.IsConfiguredVpn(IPFromString("192.168.1.1"), 32));
1556     EXPECT_TRUE(manager.IsConfiguredVpn(IPFromString("192.168.0.1"), 32));
1557   }
1558 }
1559 
1560 #if defined(WEBRTC_POSIX)
1561 // TODO(webrtc:13114): Implement the InstallIpv4Network for windows.
TEST_F(NetworkTest,VpnListOverrideAdapterType)1562 TEST_F(NetworkTest, VpnListOverrideAdapterType) {
1563   PhysicalSocketServer socket_server;
1564   BasicNetworkManager manager(&socket_server);
1565   manager.set_vpn_list({NetworkMask(IPFromString("192.168.0.0"), 16)});
1566   manager.StartUpdating();
1567 
1568   char if_name[20] = "eth0";
1569   auto addr_list =
1570       InstallIpv4Network(if_name, "192.168.1.23", "255.255.255.255", manager);
1571 
1572   std::vector<const Network*> list = manager.GetNetworks();
1573   ASSERT_EQ(1u, list.size());
1574   EXPECT_EQ(ADAPTER_TYPE_VPN, list[0]->type());
1575   EXPECT_EQ(ADAPTER_TYPE_ETHERNET, list[0]->underlying_type_for_vpn());
1576   ClearNetworks(manager);
1577   ReleaseIfAddrs(addr_list);
1578 }
1579 #endif  // defined(WEBRTC_POSIX)
1580 
TEST_F(NetworkTest,HardcodedVpn)1581 TEST_F(NetworkTest, HardcodedVpn) {
1582   const uint8_t cisco[] = {0x0, 0x5, 0x9A, 0x3C, 0x7A, 0x0};
1583   const uint8_t global[] = {0x2, 0x50, 0x41, 0x0, 0x0, 0x1};
1584   const uint8_t unknown[] = {0x2, 0x50, 0x41, 0x0, 0x0, 0x0};
1585   const uint8_t five_bytes[] = {0x2, 0x50, 0x41, 0x0, 0x0};
1586   EXPECT_TRUE(NetworkManagerBase::IsVpnMacAddress(cisco));
1587   EXPECT_TRUE(NetworkManagerBase::IsVpnMacAddress(global));
1588 
1589   EXPECT_FALSE(NetworkManagerBase::IsVpnMacAddress(
1590       rtc::ArrayView<const uint8_t>(cisco, 5)));
1591   EXPECT_FALSE(NetworkManagerBase::IsVpnMacAddress(five_bytes));
1592   EXPECT_FALSE(NetworkManagerBase::IsVpnMacAddress(unknown));
1593   EXPECT_FALSE(NetworkManagerBase::IsVpnMacAddress(nullptr));
1594 }
1595 
TEST(CompareNetworks,IrreflexivityTest)1596 TEST(CompareNetworks, IrreflexivityTest) {
1597   // x < x is false
1598   auto network = std::make_unique<Network>(
1599       "test_eth0", "Test Network Adapter 1", IPAddress(0x12345600U), 24);
1600   EXPECT_FALSE(webrtc_network_internal::CompareNetworks(network, network));
1601 }
1602 
TEST(CompareNetworks,AsymmetryTest)1603 TEST(CompareNetworks, AsymmetryTest) {
1604   // x < y and y < x cannot be both true
1605   auto network_a = std::make_unique<Network>(
1606       "test_eth0", "Test Network Adapter 1", IPAddress(0x12345600U), 24);
1607   auto network_b = std::make_unique<Network>(
1608       "test_eth1", "Test Network Adapter 1", IPAddress(0x12345600U), 24);
1609   EXPECT_TRUE(webrtc_network_internal::CompareNetworks(network_a, network_b));
1610   EXPECT_FALSE(webrtc_network_internal::CompareNetworks(network_b, network_a));
1611 
1612   auto network_c = std::make_unique<Network>(
1613       "test_eth0", "Test Network Adapter 1", IPAddress(0x12345500U), 24);
1614   auto network_d = std::make_unique<Network>(
1615       "test_eth0", "Test Network Adapter 1", IPAddress(0x12345600U), 24);
1616   EXPECT_TRUE(webrtc_network_internal::CompareNetworks(network_c, network_d));
1617   EXPECT_FALSE(webrtc_network_internal::CompareNetworks(network_d, network_c));
1618 }
1619 
TEST(CompareNetworks,TransitivityTest)1620 TEST(CompareNetworks, TransitivityTest) {
1621   // x < y and y < z imply x < z
1622   auto network_a = std::make_unique<Network>(
1623       "test_eth0", "Test Network Adapter 1", IPAddress(0x12345600U), 24);
1624   auto network_b = std::make_unique<Network>(
1625       "test_eth1", "Test Network Adapter 1", IPAddress(0x12345600U), 24);
1626   auto network_c = std::make_unique<Network>(
1627       "test_eth2", "Test Network Adapter 1", IPAddress(0x12345600U), 24);
1628   EXPECT_TRUE(webrtc_network_internal::CompareNetworks(network_a, network_b));
1629   EXPECT_TRUE(webrtc_network_internal::CompareNetworks(network_b, network_c));
1630 
1631   auto network_d = std::make_unique<Network>(
1632       "test_eth0", "Test Network Adapter 1", IPAddress(0x12345600U), 24);
1633   auto network_e = std::make_unique<Network>(
1634       "test_eth0", "Test Network Adapter 1", IPAddress(0x12345700U), 24);
1635   auto network_f = std::make_unique<Network>(
1636       "test_eth0", "Test Network Adapter 1", IPAddress(0x12345800U), 24);
1637   EXPECT_TRUE(webrtc_network_internal::CompareNetworks(network_d, network_e));
1638   EXPECT_TRUE(webrtc_network_internal::CompareNetworks(network_e, network_f));
1639   EXPECT_TRUE(webrtc_network_internal::CompareNetworks(network_d, network_f));
1640   EXPECT_TRUE(webrtc_network_internal::CompareNetworks(network_a, network_c));
1641 }
1642 
TEST(CompareNetworks,TransitivityOfIncomparabilityTest)1643 TEST(CompareNetworks, TransitivityOfIncomparabilityTest) {
1644   // x == y and y == z imply x == z,
1645   // where x == y means x < y and y < x are both false
1646   auto network_a = std::make_unique<Network>(
1647       "test_eth0", "Test Network Adapter 1", IPAddress(0x12345600U), 23);
1648   auto network_b = std::make_unique<Network>(
1649       "test_eth0", "Test Network Adapter 1", IPAddress(0x12345600U), 24);
1650   auto network_c = std::make_unique<Network>(
1651       "test_eth0", "Test Network Adapter 1", IPAddress(0x12345700U), 24);
1652 
1653   // network_a < network_b
1654   EXPECT_TRUE(webrtc_network_internal::CompareNetworks(network_a, network_b));
1655   EXPECT_FALSE(webrtc_network_internal::CompareNetworks(network_b, network_a));
1656 
1657   // network_b < network_c
1658   EXPECT_TRUE(webrtc_network_internal::CompareNetworks(network_b, network_c));
1659   EXPECT_FALSE(webrtc_network_internal::CompareNetworks(network_c, network_b));
1660 
1661   // network_a < network_c
1662   EXPECT_TRUE(webrtc_network_internal::CompareNetworks(network_a, network_c));
1663   EXPECT_FALSE(webrtc_network_internal::CompareNetworks(network_c, network_a));
1664 
1665   auto network_d = std::make_unique<Network>(
1666       "test_eth0", "Test Network Adapter 1", IPAddress(0x12345600U), 24);
1667   auto network_e = std::make_unique<Network>(
1668       "test_eth0", "Test Network Adapter 1", IPAddress(0x12345600U), 24);
1669   auto network_f = std::make_unique<Network>(
1670       "test_eth0", "Test Network Adapter 1", IPAddress(0x12345600U), 24);
1671 
1672   // network_d == network_e
1673   EXPECT_FALSE(webrtc_network_internal::CompareNetworks(network_d, network_e));
1674   EXPECT_FALSE(webrtc_network_internal::CompareNetworks(network_e, network_d));
1675 
1676   // network_e == network_f
1677   EXPECT_FALSE(webrtc_network_internal::CompareNetworks(network_e, network_f));
1678   EXPECT_FALSE(webrtc_network_internal::CompareNetworks(network_f, network_e));
1679 
1680   // network_d == network_f
1681   EXPECT_FALSE(webrtc_network_internal::CompareNetworks(network_d, network_f));
1682   EXPECT_FALSE(webrtc_network_internal::CompareNetworks(network_f, network_d));
1683 }
1684 
1685 }  // namespace rtc
1686