• 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 "webrtc/base/network.h"
12 
13 #include "webrtc/base/nethelpers.h"
14 #include "webrtc/base/networkmonitor.h"
15 #include <vector>
16 #if defined(WEBRTC_POSIX)
17 #include <sys/types.h>
18 #include <net/if.h>
19 #include "webrtc/base/ifaddrs_converter.h"
20 #endif  // defined(WEBRTC_POSIX)
21 #include "webrtc/base/gunit.h"
22 #if defined(WEBRTC_WIN)
23 #include "webrtc/base/logging.h"  // For LOG_GLE
24 #endif
25 
26 namespace rtc {
27 
28 namespace {
29 
30 class FakeNetworkMonitor : public NetworkMonitorBase {
31  public:
Start()32   void Start() override {}
Stop()33   void Stop() override {}
34 };
35 
36 class FakeNetworkMonitorFactory : public NetworkMonitorFactory {
37  public:
FakeNetworkMonitorFactory()38   FakeNetworkMonitorFactory() {}
CreateNetworkMonitor()39   NetworkMonitorInterface* CreateNetworkMonitor() {
40     return new FakeNetworkMonitor();
41   }
42 };
43 
44 }  // namespace
45 
46 class NetworkTest : public testing::Test, public sigslot::has_slots<>  {
47  public:
NetworkTest()48   NetworkTest() : callback_called_(false) {}
49 
OnNetworksChanged()50   void OnNetworksChanged() {
51     callback_called_ = true;
52   }
53 
MergeNetworkList(BasicNetworkManager & network_manager,const NetworkManager::NetworkList & list,bool * changed)54   NetworkManager::Stats MergeNetworkList(
55       BasicNetworkManager& network_manager,
56       const NetworkManager::NetworkList& list,
57       bool* changed) {
58     NetworkManager::Stats stats;
59     network_manager.MergeNetworkList(list, changed, &stats);
60     return stats;
61   }
62 
IsIgnoredNetwork(BasicNetworkManager & network_manager,const Network & network)63   bool IsIgnoredNetwork(BasicNetworkManager& network_manager,
64                         const Network& network) {
65     return network_manager.IsIgnoredNetwork(network);
66   }
67 
GetNetworks(const BasicNetworkManager & network_manager,bool include_ignored)68   NetworkManager::NetworkList GetNetworks(
69       const BasicNetworkManager& network_manager, bool include_ignored) {
70     NetworkManager::NetworkList list;
71     network_manager.CreateNetworks(include_ignored, &list);
72     return list;
73   }
74 
GetNetworkMonitor(BasicNetworkManager & network_manager)75   NetworkMonitorInterface* GetNetworkMonitor(
76       BasicNetworkManager& network_manager) {
77     return network_manager.network_monitor_.get();
78   }
ClearNetworks(BasicNetworkManager & network_manager)79   void ClearNetworks(BasicNetworkManager& network_manager) {
80     for (const auto& kv : network_manager.networks_map_) {
81       delete kv.second;
82     }
83     network_manager.networks_.clear();
84     network_manager.networks_map_.clear();
85   }
86 
87 #if defined(WEBRTC_POSIX)
88   // Separated from CreateNetworks for tests.
CallConvertIfAddrs(const BasicNetworkManager & network_manager,struct ifaddrs * interfaces,bool include_ignored,NetworkManager::NetworkList * networks)89   static void CallConvertIfAddrs(const BasicNetworkManager& network_manager,
90                                  struct ifaddrs* interfaces,
91                                  bool include_ignored,
92                                  NetworkManager::NetworkList* networks) {
93     // Use the base IfAddrsConverter for test cases.
94     rtc::scoped_ptr<IfAddrsConverter> ifaddrs_converter(new IfAddrsConverter());
95     network_manager.ConvertIfAddrs(interfaces, ifaddrs_converter.get(),
96                                    include_ignored, networks);
97   }
98 
CreateIpv6Addr(const std::string & ip_string,uint32_t scope_id)99   struct sockaddr_in6* CreateIpv6Addr(const std::string& ip_string,
100                                       uint32_t scope_id) {
101     struct sockaddr_in6* ipv6_addr = new struct sockaddr_in6;
102     memset(ipv6_addr, 0, sizeof(struct sockaddr_in6));
103     ipv6_addr->sin6_family = AF_INET6;
104     ipv6_addr->sin6_scope_id = scope_id;
105     IPAddress ip;
106     IPFromString(ip_string, &ip);
107     ipv6_addr->sin6_addr = ip.ipv6_address();
108     return ipv6_addr;
109   }
110 
111   // Pointers created here need to be released via ReleaseIfAddrs.
AddIpv6Address(struct ifaddrs * list,char * if_name,const std::string & ipv6_address,const std::string & ipv6_netmask,uint32_t scope_id)112   struct ifaddrs* AddIpv6Address(struct ifaddrs* list,
113                                  char* if_name,
114                                  const std::string& ipv6_address,
115                                  const std::string& ipv6_netmask,
116                                  uint32_t scope_id) {
117     struct ifaddrs* if_addr = new struct ifaddrs;
118     memset(if_addr, 0, sizeof(struct ifaddrs));
119     if_addr->ifa_name = if_name;
120     if_addr->ifa_addr = reinterpret_cast<struct sockaddr*>(
121         CreateIpv6Addr(ipv6_address, scope_id));
122     if_addr->ifa_netmask =
123         reinterpret_cast<struct sockaddr*>(CreateIpv6Addr(ipv6_netmask, 0));
124     if_addr->ifa_next = list;
125     if_addr->ifa_flags = IFF_RUNNING;
126     return if_addr;
127   }
128 
ReleaseIfAddrs(struct ifaddrs * list)129   void ReleaseIfAddrs(struct ifaddrs* list) {
130     struct ifaddrs* if_addr = list;
131     while (if_addr != nullptr) {
132       struct ifaddrs* next_addr = if_addr->ifa_next;
133       delete if_addr->ifa_addr;
134       delete if_addr->ifa_netmask;
135       delete if_addr;
136       if_addr = next_addr;
137     }
138   }
139 #endif  // defined(WEBRTC_POSIX)
140 
141  protected:
142   bool callback_called_;
143 };
144 
145 class TestBasicNetworkManager : public BasicNetworkManager {
146  public:
147   using BasicNetworkManager::QueryDefaultLocalAddress;
148   using BasicNetworkManager::set_default_local_addresses;
149 };
150 
151 // Test that the Network ctor works properly.
TEST_F(NetworkTest,TestNetworkConstruct)152 TEST_F(NetworkTest, TestNetworkConstruct) {
153   Network ipv4_network1("test_eth0", "Test Network Adapter 1",
154                         IPAddress(0x12345600U), 24);
155   EXPECT_EQ("test_eth0", ipv4_network1.name());
156   EXPECT_EQ("Test Network Adapter 1", ipv4_network1.description());
157   EXPECT_EQ(IPAddress(0x12345600U), ipv4_network1.prefix());
158   EXPECT_EQ(24, ipv4_network1.prefix_length());
159   EXPECT_FALSE(ipv4_network1.ignored());
160 }
161 
TEST_F(NetworkTest,TestIsIgnoredNetworkIgnoresIPsStartingWith0)162 TEST_F(NetworkTest, TestIsIgnoredNetworkIgnoresIPsStartingWith0) {
163   Network ipv4_network1("test_eth0", "Test Network Adapter 1",
164                         IPAddress(0x12345600U), 24, ADAPTER_TYPE_ETHERNET);
165   Network ipv4_network2("test_eth1", "Test Network Adapter 2",
166                         IPAddress(0x010000U), 24, ADAPTER_TYPE_ETHERNET);
167   BasicNetworkManager network_manager;
168   EXPECT_FALSE(IsIgnoredNetwork(network_manager, ipv4_network1));
169   EXPECT_TRUE(IsIgnoredNetwork(network_manager, ipv4_network2));
170 }
171 
172 // TODO(phoglund): Remove when ignore list goes away.
TEST_F(NetworkTest,TestIgnoreList)173 TEST_F(NetworkTest, TestIgnoreList) {
174   Network ignore_me("ignore_me", "Ignore me please!",
175                     IPAddress(0x12345600U), 24);
176   Network include_me("include_me", "Include me please!",
177                      IPAddress(0x12345600U), 24);
178   BasicNetworkManager network_manager;
179   EXPECT_FALSE(IsIgnoredNetwork(network_manager, ignore_me));
180   EXPECT_FALSE(IsIgnoredNetwork(network_manager, include_me));
181   std::vector<std::string> ignore_list;
182   ignore_list.push_back("ignore_me");
183   network_manager.set_network_ignore_list(ignore_list);
184   EXPECT_TRUE(IsIgnoredNetwork(network_manager, ignore_me));
185   EXPECT_FALSE(IsIgnoredNetwork(network_manager, include_me));
186 }
187 
188 // Test is failing on Windows opt: b/11288214
TEST_F(NetworkTest,DISABLED_TestCreateNetworks)189 TEST_F(NetworkTest, DISABLED_TestCreateNetworks) {
190   BasicNetworkManager manager;
191   NetworkManager::NetworkList result = GetNetworks(manager, true);
192   // We should be able to bind to any addresses we find.
193   NetworkManager::NetworkList::iterator it;
194   for (it = result.begin();
195        it != result.end();
196        ++it) {
197     sockaddr_storage storage;
198     memset(&storage, 0, sizeof(storage));
199     IPAddress ip = (*it)->GetBestIP();
200     SocketAddress bindaddress(ip, 0);
201     bindaddress.SetScopeID((*it)->scope_id());
202     // TODO(thaloun): Use rtc::AsyncSocket once it supports IPv6.
203     int fd = static_cast<int>(socket(ip.family(), SOCK_STREAM, IPPROTO_TCP));
204     if (fd > 0) {
205       size_t ipsize = bindaddress.ToSockAddrStorage(&storage);
206       EXPECT_GE(ipsize, 0U);
207       int success = ::bind(fd,
208                            reinterpret_cast<sockaddr*>(&storage),
209                            static_cast<int>(ipsize));
210 #if defined(WEBRTC_WIN)
211       if (success) LOG_GLE(LS_ERROR) << "Socket bind failed.";
212 #endif
213       EXPECT_EQ(0, success);
214 #if defined(WEBRTC_WIN)
215       closesocket(fd);
216 #else
217       close(fd);
218 #endif
219     }
220     delete (*it);
221   }
222 }
223 
224 // Test StartUpdating() and StopUpdating(). network_permission_state starts with
225 // ALLOWED.
TEST_F(NetworkTest,TestUpdateNetworks)226 TEST_F(NetworkTest, TestUpdateNetworks) {
227   BasicNetworkManager manager;
228   manager.SignalNetworksChanged.connect(
229       static_cast<NetworkTest*>(this), &NetworkTest::OnNetworksChanged);
230   EXPECT_EQ(NetworkManager::ENUMERATION_ALLOWED,
231             manager.enumeration_permission());
232   manager.StartUpdating();
233   Thread::Current()->ProcessMessages(0);
234   EXPECT_TRUE(callback_called_);
235   callback_called_ = false;
236   // Callback should be triggered immediately when StartUpdating
237   // is called, after network update signal is already sent.
238   manager.StartUpdating();
239   EXPECT_TRUE(manager.started());
240   Thread::Current()->ProcessMessages(0);
241   EXPECT_TRUE(callback_called_);
242   manager.StopUpdating();
243   EXPECT_TRUE(manager.started());
244   manager.StopUpdating();
245   EXPECT_EQ(NetworkManager::ENUMERATION_ALLOWED,
246             manager.enumeration_permission());
247   EXPECT_FALSE(manager.started());
248   manager.StopUpdating();
249   EXPECT_FALSE(manager.started());
250   callback_called_ = false;
251   // Callback should be triggered immediately after StartUpdating is called
252   // when start_count_ is reset to 0.
253   manager.StartUpdating();
254   Thread::Current()->ProcessMessages(0);
255   EXPECT_TRUE(callback_called_);
256 }
257 
258 // Verify that MergeNetworkList() merges network lists properly.
TEST_F(NetworkTest,TestBasicMergeNetworkList)259 TEST_F(NetworkTest, TestBasicMergeNetworkList) {
260   Network ipv4_network1("test_eth0", "Test Network Adapter 1",
261                         IPAddress(0x12345600U), 24);
262   Network ipv4_network2("test_eth1", "Test Network Adapter 2",
263                         IPAddress(0x00010000U), 16);
264   ipv4_network1.AddIP(IPAddress(0x12345678));
265   ipv4_network2.AddIP(IPAddress(0x00010004));
266   BasicNetworkManager manager;
267 
268   // Add ipv4_network1 to the list of networks.
269   NetworkManager::NetworkList list;
270   list.push_back(new Network(ipv4_network1));
271   bool changed;
272   NetworkManager::Stats stats = MergeNetworkList(manager, list, &changed);
273   EXPECT_TRUE(changed);
274   EXPECT_EQ(stats.ipv6_network_count, 0);
275   EXPECT_EQ(stats.ipv4_network_count, 1);
276   list.clear();
277 
278   manager.GetNetworks(&list);
279   EXPECT_EQ(1U, list.size());
280   EXPECT_EQ(ipv4_network1.ToString(), list[0]->ToString());
281   Network* net1 = list[0];
282   list.clear();
283 
284   // Replace ipv4_network1 with ipv4_network2.
285   list.push_back(new Network(ipv4_network2));
286   stats = MergeNetworkList(manager, list, &changed);
287   EXPECT_TRUE(changed);
288   EXPECT_EQ(stats.ipv6_network_count, 0);
289   EXPECT_EQ(stats.ipv4_network_count, 1);
290   list.clear();
291 
292   manager.GetNetworks(&list);
293   EXPECT_EQ(1U, list.size());
294   EXPECT_EQ(ipv4_network2.ToString(), list[0]->ToString());
295   Network* net2 = list[0];
296   list.clear();
297 
298   // Add Network2 back.
299   list.push_back(new Network(ipv4_network1));
300   list.push_back(new Network(ipv4_network2));
301   stats = MergeNetworkList(manager, list, &changed);
302   EXPECT_TRUE(changed);
303   EXPECT_EQ(stats.ipv6_network_count, 0);
304   EXPECT_EQ(stats.ipv4_network_count, 2);
305   list.clear();
306 
307   // Verify that we get previous instances of Network objects.
308   manager.GetNetworks(&list);
309   EXPECT_EQ(2U, list.size());
310   EXPECT_TRUE((net1 == list[0] && net2 == list[1]) ||
311               (net1 == list[1] && net2 == list[0]));
312   list.clear();
313 
314   // Call MergeNetworkList() again and verify that we don't get update
315   // notification.
316   list.push_back(new Network(ipv4_network2));
317   list.push_back(new Network(ipv4_network1));
318   stats = MergeNetworkList(manager, list, &changed);
319   EXPECT_FALSE(changed);
320   EXPECT_EQ(stats.ipv6_network_count, 0);
321   EXPECT_EQ(stats.ipv4_network_count, 2);
322   list.clear();
323 
324   // Verify that we get previous instances of Network objects.
325   manager.GetNetworks(&list);
326   EXPECT_EQ(2U, list.size());
327   EXPECT_TRUE((net1 == list[0] && net2 == list[1]) ||
328               (net1 == list[1] && net2 == list[0]));
329   list.clear();
330 }
331 
332 // Sets up some test IPv6 networks and appends them to list.
333 // Four networks are added - public and link local, for two interfaces.
SetupNetworks(NetworkManager::NetworkList * list)334 void SetupNetworks(NetworkManager::NetworkList* list) {
335   IPAddress ip;
336   IPAddress prefix;
337   EXPECT_TRUE(IPFromString("abcd::1234:5678:abcd:ef12", &ip));
338   EXPECT_TRUE(IPFromString("abcd::", &prefix));
339   // First, fake link-locals.
340   Network ipv6_eth0_linklocalnetwork("test_eth0", "Test NetworkAdapter 1",
341                                      prefix, 64);
342   ipv6_eth0_linklocalnetwork.AddIP(ip);
343   EXPECT_TRUE(IPFromString("abcd::5678:abcd:ef12:3456", &ip));
344   Network ipv6_eth1_linklocalnetwork("test_eth1", "Test NetworkAdapter 2",
345                                      prefix, 64);
346   ipv6_eth1_linklocalnetwork.AddIP(ip);
347   // Public networks:
348   EXPECT_TRUE(IPFromString("2401:fa00:4:1000:be30:5bff:fee5:c3", &ip));
349   prefix = TruncateIP(ip, 64);
350   Network ipv6_eth0_publicnetwork1_ip1("test_eth0", "Test NetworkAdapter 1",
351                                        prefix, 64);
352   ipv6_eth0_publicnetwork1_ip1.AddIP(ip);
353   EXPECT_TRUE(IPFromString("2400:4030:1:2c00:be30:abcd:efab:cdef", &ip));
354   prefix = TruncateIP(ip, 64);
355   Network ipv6_eth1_publicnetwork1_ip1("test_eth1", "Test NetworkAdapter 1",
356                                        prefix, 64);
357   ipv6_eth1_publicnetwork1_ip1.AddIP(ip);
358   list->push_back(new Network(ipv6_eth0_linklocalnetwork));
359   list->push_back(new Network(ipv6_eth1_linklocalnetwork));
360   list->push_back(new Network(ipv6_eth0_publicnetwork1_ip1));
361   list->push_back(new Network(ipv6_eth1_publicnetwork1_ip1));
362 }
363 
364 // Test that the basic network merging case works.
TEST_F(NetworkTest,TestIPv6MergeNetworkList)365 TEST_F(NetworkTest, TestIPv6MergeNetworkList) {
366   BasicNetworkManager manager;
367   manager.SignalNetworksChanged.connect(
368       static_cast<NetworkTest*>(this), &NetworkTest::OnNetworksChanged);
369   NetworkManager::NetworkList original_list;
370   SetupNetworks(&original_list);
371   bool changed = false;
372   NetworkManager::Stats stats =
373       MergeNetworkList(manager, original_list, &changed);
374   EXPECT_TRUE(changed);
375   EXPECT_EQ(stats.ipv6_network_count, 4);
376   EXPECT_EQ(stats.ipv4_network_count, 0);
377   NetworkManager::NetworkList list;
378   manager.GetNetworks(&list);
379   EXPECT_EQ(original_list.size(), list.size());
380   // Verify that the original members are in the merged list.
381   for (NetworkManager::NetworkList::iterator it = original_list.begin();
382        it != original_list.end(); ++it) {
383     EXPECT_NE(list.end(), std::find(list.begin(), list.end(), *it));
384   }
385 }
386 
387 // Test that no more than manager.max_ipv6_networks() IPv6 networks get
388 // returned.
TEST_F(NetworkTest,TestIPv6MergeNetworkListTrimExcessive)389 TEST_F(NetworkTest, TestIPv6MergeNetworkListTrimExcessive) {
390   BasicNetworkManager manager;
391   manager.SignalNetworksChanged.connect(static_cast<NetworkTest*>(this),
392                                         &NetworkTest::OnNetworksChanged);
393   NetworkManager::NetworkList original_list;
394 
395   // Add twice the allowed number of IPv6 networks.
396   for (int i = 0; i < 2 * manager.max_ipv6_networks(); i++) {
397     // Make a network with different prefix length.
398     IPAddress ip;
399     EXPECT_TRUE(IPFromString("2401:fa01:4:1000:be30:faa:fee:faa", &ip));
400     IPAddress prefix = TruncateIP(ip, 64 - i);
401     Network* ipv6_network =
402         new Network("test_eth0", "Test Network Adapter 1", prefix, 64 - i);
403     ipv6_network->AddIP(ip);
404     original_list.push_back(ipv6_network);
405   }
406 
407   // Add one IPv4 network.
408   Network* ipv4_network = new Network("test_eth0", "Test Network Adapter 1",
409                                       IPAddress(0x12345600U), 24);
410   ipv4_network->AddIP(IPAddress(0x12345600U));
411   original_list.push_back(ipv4_network);
412 
413   bool changed = false;
414   MergeNetworkList(manager, original_list, &changed);
415   EXPECT_TRUE(changed);
416   NetworkManager::NetworkList list;
417   manager.GetNetworks(&list);
418 
419   // List size should be the max allowed IPv6 networks plus one IPv4 network.
420   EXPECT_EQ(manager.max_ipv6_networks() + 1, (int)list.size());
421 
422   // Verify that the IPv4 network is in the list.
423   EXPECT_NE(list.end(), std::find(list.begin(), list.end(), ipv4_network));
424 }
425 
426 // Tests that when two network lists that describe the same set of networks are
427 // merged, that the changed callback is not called, and that the original
428 // objects remain in the result list.
TEST_F(NetworkTest,TestNoChangeMerge)429 TEST_F(NetworkTest, TestNoChangeMerge) {
430   BasicNetworkManager manager;
431   manager.SignalNetworksChanged.connect(
432       static_cast<NetworkTest*>(this), &NetworkTest::OnNetworksChanged);
433   NetworkManager::NetworkList original_list;
434   SetupNetworks(&original_list);
435   bool changed = false;
436   MergeNetworkList(manager, original_list, &changed);
437   EXPECT_TRUE(changed);
438   // Second list that describes the same networks but with new objects.
439   NetworkManager::NetworkList second_list;
440   SetupNetworks(&second_list);
441   changed = false;
442   MergeNetworkList(manager, second_list, &changed);
443   EXPECT_FALSE(changed);
444   NetworkManager::NetworkList resulting_list;
445   manager.GetNetworks(&resulting_list);
446   EXPECT_EQ(original_list.size(), resulting_list.size());
447   // Verify that the original members are in the merged list.
448   for (NetworkManager::NetworkList::iterator it = original_list.begin();
449        it != original_list.end(); ++it) {
450     EXPECT_NE(resulting_list.end(),
451               std::find(resulting_list.begin(), resulting_list.end(), *it));
452   }
453   // Doublecheck that the new networks aren't in the list.
454   for (NetworkManager::NetworkList::iterator it = second_list.begin();
455        it != second_list.end(); ++it) {
456     EXPECT_EQ(resulting_list.end(),
457               std::find(resulting_list.begin(), resulting_list.end(), *it));
458   }
459 }
460 
461 // Test that we can merge a network that is the same as another network but with
462 // a different IP. The original network should remain in the list, but have its
463 // IP changed.
TEST_F(NetworkTest,MergeWithChangedIP)464 TEST_F(NetworkTest, MergeWithChangedIP) {
465   BasicNetworkManager manager;
466   manager.SignalNetworksChanged.connect(
467       static_cast<NetworkTest*>(this), &NetworkTest::OnNetworksChanged);
468   NetworkManager::NetworkList original_list;
469   SetupNetworks(&original_list);
470   // Make a network that we're going to change.
471   IPAddress ip;
472   EXPECT_TRUE(IPFromString("2401:fa01:4:1000:be30:faa:fee:faa", &ip));
473   IPAddress prefix = TruncateIP(ip, 64);
474   Network* network_to_change = new Network("test_eth0",
475                                           "Test Network Adapter 1",
476                                           prefix, 64);
477   Network* changed_network = new Network(*network_to_change);
478   network_to_change->AddIP(ip);
479   IPAddress changed_ip;
480   EXPECT_TRUE(IPFromString("2401:fa01:4:1000:be30:f00:f00:f00", &changed_ip));
481   changed_network->AddIP(changed_ip);
482   original_list.push_back(network_to_change);
483   bool changed = false;
484   MergeNetworkList(manager, original_list, &changed);
485   NetworkManager::NetworkList second_list;
486   SetupNetworks(&second_list);
487   second_list.push_back(changed_network);
488   changed = false;
489   MergeNetworkList(manager, second_list, &changed);
490   EXPECT_TRUE(changed);
491   NetworkManager::NetworkList list;
492   manager.GetNetworks(&list);
493   EXPECT_EQ(original_list.size(), list.size());
494   // Make sure the original network is still in the merged list.
495   EXPECT_NE(list.end(),
496             std::find(list.begin(), list.end(), network_to_change));
497   EXPECT_EQ(changed_ip, network_to_change->GetIPs().at(0));
498 }
499 
500 // Testing a similar case to above, but checking that a network can be updated
501 // with additional IPs (not just a replacement).
TEST_F(NetworkTest,TestMultipleIPMergeNetworkList)502 TEST_F(NetworkTest, TestMultipleIPMergeNetworkList) {
503   BasicNetworkManager manager;
504   manager.SignalNetworksChanged.connect(
505       static_cast<NetworkTest*>(this), &NetworkTest::OnNetworksChanged);
506   NetworkManager::NetworkList original_list;
507   SetupNetworks(&original_list);
508   bool changed = false;
509   MergeNetworkList(manager, original_list, &changed);
510   EXPECT_TRUE(changed);
511   IPAddress ip;
512   IPAddress check_ip;
513   IPAddress prefix;
514   // Add a second IP to the public network on eth0 (2401:fa00:4:1000/64).
515   EXPECT_TRUE(IPFromString("2401:fa00:4:1000:be30:5bff:fee5:c6", &ip));
516   prefix = TruncateIP(ip, 64);
517   Network ipv6_eth0_publicnetwork1_ip2("test_eth0", "Test NetworkAdapter 1",
518                                        prefix, 64);
519   // This is the IP that already existed in the public network on eth0.
520   EXPECT_TRUE(IPFromString("2401:fa00:4:1000:be30:5bff:fee5:c3", &check_ip));
521   ipv6_eth0_publicnetwork1_ip2.AddIP(ip);
522   original_list.push_back(new Network(ipv6_eth0_publicnetwork1_ip2));
523   changed = false;
524   MergeNetworkList(manager, original_list, &changed);
525   EXPECT_TRUE(changed);
526   // There should still be four networks.
527   NetworkManager::NetworkList list;
528   manager.GetNetworks(&list);
529   EXPECT_EQ(4U, list.size());
530   // Check the gathered IPs.
531   int matchcount = 0;
532   for (NetworkManager::NetworkList::iterator it = list.begin();
533        it != list.end(); ++it) {
534     if ((*it)->ToString() == original_list[2]->ToString()) {
535       ++matchcount;
536       EXPECT_EQ(1, matchcount);
537       // This should be the same network object as before.
538       EXPECT_EQ((*it), original_list[2]);
539       // But with two addresses now.
540       EXPECT_EQ(2U, (*it)->GetIPs().size());
541       EXPECT_NE((*it)->GetIPs().end(),
542                 std::find((*it)->GetIPs().begin(),
543                           (*it)->GetIPs().end(),
544                           check_ip));
545       EXPECT_NE((*it)->GetIPs().end(),
546                 std::find((*it)->GetIPs().begin(),
547                           (*it)->GetIPs().end(),
548                           ip));
549     } else {
550       // Check the IP didn't get added anywhere it wasn't supposed to.
551       EXPECT_EQ((*it)->GetIPs().end(),
552                 std::find((*it)->GetIPs().begin(),
553                           (*it)->GetIPs().end(),
554                           ip));
555     }
556   }
557 }
558 
559 // Test that merge correctly distinguishes multiple networks on an interface.
TEST_F(NetworkTest,TestMultiplePublicNetworksOnOneInterfaceMerge)560 TEST_F(NetworkTest, TestMultiplePublicNetworksOnOneInterfaceMerge) {
561   BasicNetworkManager manager;
562   manager.SignalNetworksChanged.connect(
563       static_cast<NetworkTest*>(this), &NetworkTest::OnNetworksChanged);
564   NetworkManager::NetworkList original_list;
565   SetupNetworks(&original_list);
566   bool changed = false;
567   MergeNetworkList(manager, original_list, &changed);
568   EXPECT_TRUE(changed);
569   IPAddress ip;
570   IPAddress prefix;
571   // A second network for eth0.
572   EXPECT_TRUE(IPFromString("2400:4030:1:2c00:be30:5bff:fee5:c3", &ip));
573   prefix = TruncateIP(ip, 64);
574   Network ipv6_eth0_publicnetwork2_ip1("test_eth0", "Test NetworkAdapter 1",
575                                        prefix, 64);
576   ipv6_eth0_publicnetwork2_ip1.AddIP(ip);
577   original_list.push_back(new Network(ipv6_eth0_publicnetwork2_ip1));
578   changed = false;
579   MergeNetworkList(manager, original_list, &changed);
580   EXPECT_TRUE(changed);
581   // There should be five networks now.
582   NetworkManager::NetworkList list;
583   manager.GetNetworks(&list);
584   EXPECT_EQ(5U, list.size());
585   // Check the resulting addresses.
586   for (NetworkManager::NetworkList::iterator it = list.begin();
587        it != list.end(); ++it) {
588     if ((*it)->prefix() == ipv6_eth0_publicnetwork2_ip1.prefix() &&
589         (*it)->name() == ipv6_eth0_publicnetwork2_ip1.name()) {
590       // Check the new network has 1 IP and that it's the correct one.
591       EXPECT_EQ(1U, (*it)->GetIPs().size());
592       EXPECT_EQ(ip, (*it)->GetIPs().at(0));
593     } else {
594       // Check the IP didn't get added anywhere it wasn't supposed to.
595       EXPECT_EQ((*it)->GetIPs().end(),
596                 std::find((*it)->GetIPs().begin(),
597                           (*it)->GetIPs().end(),
598                           ip));
599     }
600   }
601 }
602 
603 // Test that DumpNetworks does not crash.
TEST_F(NetworkTest,TestCreateAndDumpNetworks)604 TEST_F(NetworkTest, TestCreateAndDumpNetworks) {
605   BasicNetworkManager manager;
606   NetworkManager::NetworkList list = GetNetworks(manager, true);
607   bool changed;
608   MergeNetworkList(manager, list, &changed);
609   manager.DumpNetworks();
610 }
611 
612 // Test that we can toggle IPv6 on and off.
613 // Crashes on Linux. See webrtc:4923.
614 #if defined(WEBRTC_LINUX)
615 #define MAYBE_TestIPv6Toggle DISABLED_TestIPv6Toggle
616 #else
617 #define MAYBE_TestIPv6Toggle TestIPv6Toggle
618 #endif
TEST_F(NetworkTest,MAYBE_TestIPv6Toggle)619 TEST_F(NetworkTest, MAYBE_TestIPv6Toggle) {
620   BasicNetworkManager manager;
621   bool ipv6_found = false;
622   NetworkManager::NetworkList list;
623 #if !defined(WEBRTC_WIN)
624   // There should be at least one IPv6 network (fe80::/64 should be in there).
625   // TODO(thaloun): Disabling this test on windows for the moment as the test
626   // machines don't seem to have IPv6 installed on them at all.
627   manager.set_ipv6_enabled(true);
628   list = GetNetworks(manager, true);
629   for (NetworkManager::NetworkList::iterator it = list.begin();
630        it != list.end(); ++it) {
631     if ((*it)->prefix().family() == AF_INET6) {
632       ipv6_found = true;
633       break;
634     }
635   }
636   EXPECT_TRUE(ipv6_found);
637   for (NetworkManager::NetworkList::iterator it = list.begin();
638        it != list.end(); ++it) {
639     delete (*it);
640   }
641 #endif
642   ipv6_found = false;
643   manager.set_ipv6_enabled(false);
644   list = GetNetworks(manager, true);
645   for (NetworkManager::NetworkList::iterator it = list.begin();
646        it != list.end(); ++it) {
647     if ((*it)->prefix().family() == AF_INET6) {
648       ipv6_found = true;
649       break;
650     }
651   }
652   EXPECT_FALSE(ipv6_found);
653   for (NetworkManager::NetworkList::iterator it = list.begin();
654        it != list.end(); ++it) {
655     delete (*it);
656   }
657 }
658 
TEST_F(NetworkTest,TestNetworkListSorting)659 TEST_F(NetworkTest, TestNetworkListSorting) {
660   BasicNetworkManager manager;
661   Network ipv4_network1("test_eth0", "Test Network Adapter 1",
662                         IPAddress(0x12345600U), 24);
663   ipv4_network1.AddIP(IPAddress(0x12345600U));
664 
665   IPAddress ip;
666   IPAddress prefix;
667   EXPECT_TRUE(IPFromString("2400:4030:1:2c00:be30:abcd:efab:cdef", &ip));
668   prefix = TruncateIP(ip, 64);
669   Network ipv6_eth1_publicnetwork1_ip1("test_eth1", "Test NetworkAdapter 2",
670                                        prefix, 64);
671   ipv6_eth1_publicnetwork1_ip1.AddIP(ip);
672 
673   NetworkManager::NetworkList list;
674   list.push_back(new Network(ipv4_network1));
675   list.push_back(new Network(ipv6_eth1_publicnetwork1_ip1));
676   Network* net1 = list[0];
677   Network* net2 = list[1];
678 
679   bool changed = false;
680   MergeNetworkList(manager, list, &changed);
681   ASSERT_TRUE(changed);
682   // After sorting IPv6 network should be higher order than IPv4 networks.
683   EXPECT_TRUE(net1->preference() < net2->preference());
684 }
685 
TEST_F(NetworkTest,TestNetworkAdapterTypes)686 TEST_F(NetworkTest, TestNetworkAdapterTypes) {
687   Network wifi("wlan0", "Wireless Adapter", IPAddress(0x12345600U), 24,
688                ADAPTER_TYPE_WIFI);
689   EXPECT_EQ(ADAPTER_TYPE_WIFI, wifi.type());
690   Network ethernet("eth0", "Ethernet", IPAddress(0x12345600U), 24,
691                    ADAPTER_TYPE_ETHERNET);
692   EXPECT_EQ(ADAPTER_TYPE_ETHERNET, ethernet.type());
693   Network cellular("test_cell", "Cellular Adapter", IPAddress(0x12345600U), 24,
694                    ADAPTER_TYPE_CELLULAR);
695   EXPECT_EQ(ADAPTER_TYPE_CELLULAR, cellular.type());
696   Network vpn("bridge_test", "VPN Adapter", IPAddress(0x12345600U), 24,
697               ADAPTER_TYPE_VPN);
698   EXPECT_EQ(ADAPTER_TYPE_VPN, vpn.type());
699   Network unknown("test", "Test Adapter", IPAddress(0x12345600U), 24,
700                   ADAPTER_TYPE_UNKNOWN);
701   EXPECT_EQ(ADAPTER_TYPE_UNKNOWN, unknown.type());
702 }
703 
704 #if defined(WEBRTC_POSIX)
705 // Verify that we correctly handle interfaces with no address.
TEST_F(NetworkTest,TestConvertIfAddrsNoAddress)706 TEST_F(NetworkTest, TestConvertIfAddrsNoAddress) {
707   ifaddrs list;
708   memset(&list, 0, sizeof(list));
709   list.ifa_name = const_cast<char*>("test_iface");
710 
711   NetworkManager::NetworkList result;
712   BasicNetworkManager manager;
713   CallConvertIfAddrs(manager, &list, true, &result);
714   EXPECT_TRUE(result.empty());
715 }
716 
717 // Verify that if there are two addresses on one interface, only one network
718 // is generated.
TEST_F(NetworkTest,TestConvertIfAddrsMultiAddressesOnOneInterface)719 TEST_F(NetworkTest, TestConvertIfAddrsMultiAddressesOnOneInterface) {
720   char if_name[20] = "rmnet0";
721   ifaddrs* list = nullptr;
722   list = AddIpv6Address(list, if_name, "1000:2000:3000:4000:0:0:0:1",
723                         "FFFF:FFFF:FFFF:FFFF::", 0);
724   list = AddIpv6Address(list, if_name, "1000:2000:3000:4000:0:0:0:2",
725                         "FFFF:FFFF:FFFF:FFFF::", 0);
726   NetworkManager::NetworkList result;
727   BasicNetworkManager manager;
728   CallConvertIfAddrs(manager, list, true, &result);
729   EXPECT_EQ(1U, result.size());
730   bool changed;
731   // This ensures we release the objects created in CallConvertIfAddrs.
732   MergeNetworkList(manager, result, &changed);
733   ReleaseIfAddrs(list);
734 }
735 
TEST_F(NetworkTest,TestConvertIfAddrsNotRunning)736 TEST_F(NetworkTest, TestConvertIfAddrsNotRunning) {
737   ifaddrs list;
738   memset(&list, 0, sizeof(list));
739   list.ifa_name = const_cast<char*>("test_iface");
740   sockaddr ifa_addr;
741   sockaddr ifa_netmask;
742   list.ifa_addr = &ifa_addr;
743   list.ifa_netmask = &ifa_netmask;
744 
745   NetworkManager::NetworkList result;
746   BasicNetworkManager manager;
747   CallConvertIfAddrs(manager, &list, true, &result);
748   EXPECT_TRUE(result.empty());
749 }
750 #endif  // defined(WEBRTC_POSIX)
751 
752 #if defined(WEBRTC_LINUX) && !defined(WEBRTC_ANDROID)
753 // If you want to test non-default routes, you can do the following on a linux
754 // machine:
755 // 1) Load the dummy network driver:
756 // sudo modprobe dummy
757 // sudo ifconfig dummy0 127.0.0.1
758 // 2) Run this test and confirm the output says it found a dummy route (and
759 // passes).
760 // 3) When done:
761 // sudo rmmmod dummy
TEST_F(NetworkTest,TestIgnoreNonDefaultRoutes)762 TEST_F(NetworkTest, TestIgnoreNonDefaultRoutes) {
763   BasicNetworkManager manager;
764   NetworkManager::NetworkList list;
765   list = GetNetworks(manager, false);
766   bool found_dummy = false;
767   LOG(LS_INFO) << "Looking for dummy network: ";
768   for (NetworkManager::NetworkList::iterator it = list.begin();
769        it != list.end(); ++it) {
770     LOG(LS_INFO) << "  Network name: " << (*it)->name();
771     found_dummy |= (*it)->name().find("dummy0") != std::string::npos;
772   }
773   for (NetworkManager::NetworkList::iterator it = list.begin();
774        it != list.end(); ++it) {
775     delete (*it);
776   }
777   if (!found_dummy) {
778     LOG(LS_INFO) << "No dummy found, quitting.";
779     return;
780   }
781   LOG(LS_INFO) << "Found dummy, running again while ignoring non-default "
782                << "routes.";
783   manager.set_ignore_non_default_routes(true);
784   list = GetNetworks(manager, false);
785   for (NetworkManager::NetworkList::iterator it = list.begin();
786        it != list.end(); ++it) {
787     LOG(LS_INFO) << "  Network name: " << (*it)->name();
788     EXPECT_TRUE((*it)->name().find("dummy0") == std::string::npos);
789   }
790   for (NetworkManager::NetworkList::iterator it = list.begin();
791        it != list.end(); ++it) {
792     delete (*it);
793   }
794 }
795 #endif
796 
797 // Test MergeNetworkList successfully combines all IPs for the same
798 // prefix/length into a single Network.
TEST_F(NetworkTest,TestMergeNetworkList)799 TEST_F(NetworkTest, TestMergeNetworkList) {
800   BasicNetworkManager manager;
801   NetworkManager::NetworkList list;
802 
803   // Create 2 IPAddress classes with only last digit different.
804   IPAddress ip1, ip2;
805   EXPECT_TRUE(IPFromString("2400:4030:1:2c00:be30:0:0:1", &ip1));
806   EXPECT_TRUE(IPFromString("2400:4030:1:2c00:be30:0:0:2", &ip2));
807 
808   // Create 2 networks with the same prefix and length.
809   Network* net1 = new Network("em1", "em1", TruncateIP(ip1, 64), 64);
810   Network* net2 = new Network("em1", "em1", TruncateIP(ip1, 64), 64);
811 
812   // Add different IP into each.
813   net1->AddIP(ip1);
814   net2->AddIP(ip2);
815 
816   list.push_back(net1);
817   list.push_back(net2);
818   bool changed;
819   MergeNetworkList(manager, list, &changed);
820   EXPECT_TRUE(changed);
821 
822   NetworkManager::NetworkList list2;
823   manager.GetNetworks(&list2);
824 
825   // Make sure the resulted networklist has only 1 element and 2
826   // IPAddresses.
827   EXPECT_EQ(list2.size(), 1uL);
828   EXPECT_EQ(list2[0]->GetIPs().size(), 2uL);
829   EXPECT_EQ(list2[0]->GetIPs()[0], ip1);
830   EXPECT_EQ(list2[0]->GetIPs()[1], ip2);
831 }
832 
833 // Test that MergeNetworkList successfully detects the change if
834 // a network becomes inactive and then active again.
TEST_F(NetworkTest,TestMergeNetworkListWithInactiveNetworks)835 TEST_F(NetworkTest, TestMergeNetworkListWithInactiveNetworks) {
836   BasicNetworkManager manager;
837   Network network1("test_wifi", "Test Network Adapter 1",
838                    IPAddress(0x12345600U), 24);
839   Network network2("test_eth0", "Test Network Adapter 2",
840                    IPAddress(0x00010000U), 16);
841   network1.AddIP(IPAddress(0x12345678));
842   network2.AddIP(IPAddress(0x00010004));
843   NetworkManager::NetworkList list;
844   Network* net1 = new Network(network1);
845   list.push_back(net1);
846   bool changed;
847   MergeNetworkList(manager, list, &changed);
848   EXPECT_TRUE(changed);
849   list.clear();
850   manager.GetNetworks(&list);
851   ASSERT_EQ(1U, list.size());
852   EXPECT_EQ(net1, list[0]);
853 
854   list.clear();
855   Network* net2 = new Network(network2);
856   list.push_back(net2);
857   MergeNetworkList(manager, list, &changed);
858   EXPECT_TRUE(changed);
859   list.clear();
860   manager.GetNetworks(&list);
861   ASSERT_EQ(1U, list.size());
862   EXPECT_EQ(net2, list[0]);
863 
864   // Now network1 is inactive. Try to merge it again.
865   list.clear();
866   list.push_back(new Network(network1));
867   MergeNetworkList(manager, list, &changed);
868   EXPECT_TRUE(changed);
869   list.clear();
870   manager.GetNetworks(&list);
871   ASSERT_EQ(1U, list.size());
872   EXPECT_TRUE(list[0]->active());
873   EXPECT_EQ(net1, list[0]);
874 }
875 
876 // Test that the filtering logic follows the defined ruleset in network.h.
TEST_F(NetworkTest,TestIPv6Selection)877 TEST_F(NetworkTest, TestIPv6Selection) {
878   InterfaceAddress ip;
879   std::string ipstr;
880 
881   ipstr = "2401:fa00:4:1000:be30:5bff:fee5:c3";
882   ASSERT_TRUE(IPFromString(ipstr, IPV6_ADDRESS_FLAG_DEPRECATED, &ip));
883 
884   // Create a network with this prefix.
885   Network ipv6_network(
886       "test_eth0", "Test NetworkAdapter", TruncateIP(ip, 64), 64);
887 
888   // When there is no address added, it should return an unspecified
889   // address.
890   EXPECT_EQ(ipv6_network.GetBestIP(), IPAddress());
891   EXPECT_TRUE(IPIsUnspec(ipv6_network.GetBestIP()));
892 
893   // Deprecated one should not be returned.
894   ipv6_network.AddIP(ip);
895   EXPECT_EQ(ipv6_network.GetBestIP(), IPAddress());
896 
897   // Add ULA one. ULA is unique local address which is starting either
898   // with 0xfc or 0xfd.
899   ipstr = "fd00:fa00:4:1000:be30:5bff:fee5:c4";
900   ASSERT_TRUE(IPFromString(ipstr, IPV6_ADDRESS_FLAG_NONE, &ip));
901   ipv6_network.AddIP(ip);
902   EXPECT_EQ(ipv6_network.GetBestIP(), static_cast<IPAddress>(ip));
903 
904   // Add global one.
905   ipstr = "2401:fa00:4:1000:be30:5bff:fee5:c5";
906   ASSERT_TRUE(IPFromString(ipstr, IPV6_ADDRESS_FLAG_NONE, &ip));
907   ipv6_network.AddIP(ip);
908   EXPECT_EQ(ipv6_network.GetBestIP(), static_cast<IPAddress>(ip));
909 
910   // Add global dynamic temporary one.
911   ipstr = "2401:fa00:4:1000:be30:5bff:fee5:c6";
912   ASSERT_TRUE(IPFromString(ipstr, IPV6_ADDRESS_FLAG_TEMPORARY, &ip));
913   ipv6_network.AddIP(ip);
914   EXPECT_EQ(ipv6_network.GetBestIP(), static_cast<IPAddress>(ip));
915 }
916 
TEST_F(NetworkTest,TestNetworkMonitoring)917 TEST_F(NetworkTest, TestNetworkMonitoring) {
918   BasicNetworkManager manager;
919   manager.SignalNetworksChanged.connect(static_cast<NetworkTest*>(this),
920                                         &NetworkTest::OnNetworksChanged);
921   FakeNetworkMonitorFactory* factory = new FakeNetworkMonitorFactory();
922   NetworkMonitorFactory::SetFactory(factory);
923   manager.StartUpdating();
924   NetworkMonitorInterface* network_monitor = GetNetworkMonitor(manager);
925   EXPECT_TRUE_WAIT(callback_called_, 1000);
926   callback_called_ = false;
927 
928   // Clear the networks so that there will be network changes below.
929   ClearNetworks(manager);
930   // Network manager is started, so the callback is called when the network
931   // monitor fires the network-change event.
932   network_monitor->OnNetworksChanged();
933   EXPECT_TRUE_WAIT(callback_called_, 1000);
934 
935   // Network manager is stopped; the network monitor is removed.
936   manager.StopUpdating();
937   EXPECT_TRUE(GetNetworkMonitor(manager) == nullptr);
938 
939   NetworkMonitorFactory::ReleaseFactory(factory);
940 }
941 
TEST_F(NetworkTest,DefaultLocalAddress)942 TEST_F(NetworkTest, DefaultLocalAddress) {
943   TestBasicNetworkManager manager;
944   manager.StartUpdating();
945   IPAddress ip;
946 
947   // GetDefaultLocalAddress should return false when not set.
948   EXPECT_FALSE(manager.GetDefaultLocalAddress(AF_INET, &ip));
949   EXPECT_FALSE(manager.GetDefaultLocalAddress(AF_INET6, &ip));
950 
951   // Make sure we can query default local address when an address for such
952   // address family exists.
953   std::vector<Network*> networks;
954   manager.GetNetworks(&networks);
955   for (auto& network : networks) {
956     if (network->GetBestIP().family() == AF_INET) {
957       EXPECT_TRUE(manager.QueryDefaultLocalAddress(AF_INET) != IPAddress());
958     } else if (network->GetBestIP().family() == AF_INET6) {
959       EXPECT_TRUE(manager.QueryDefaultLocalAddress(AF_INET6) != IPAddress());
960     }
961   }
962 
963   // GetDefaultLocalAddress should return the valid default address after set.
964   manager.set_default_local_addresses(GetLoopbackIP(AF_INET),
965                                       GetLoopbackIP(AF_INET6));
966   EXPECT_TRUE(manager.GetDefaultLocalAddress(AF_INET, &ip));
967   EXPECT_EQ(ip, GetLoopbackIP(AF_INET));
968   EXPECT_TRUE(manager.GetDefaultLocalAddress(AF_INET6, &ip));
969   EXPECT_EQ(ip, GetLoopbackIP(AF_INET6));
970   manager.StopUpdating();
971 }
972 
973 }  // namespace rtc
974