1 //
2 // Copyright (C) 2012 The Android Open Source Project
3 //
4 // Licensed under the Apache License, Version 2.0 (the "License");
5 // you may not use this file except in compliance with the License.
6 // You may obtain a copy of the License at
7 //
8 // http://www.apache.org/licenses/LICENSE-2.0
9 //
10 // Unless required by applicable law or agreed to in writing, software
11 // distributed under the License is distributed on an "AS IS" BASIS,
12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 // See the License for the specific language governing permissions and
14 // limitations under the License.
15 //
16
17 #include "shill/device.h"
18
19 #include <ctype.h>
20 #include <sys/socket.h>
21 #include <linux/if.h> // NOLINT - Needs typedefs from sys/socket.h.
22
23 #include <map>
24 #include <memory>
25 #include <string>
26 #include <vector>
27
28 #include <base/bind.h>
29 #include <base/callback.h>
30 #include <base/macros.h>
31 #include <base/memory/weak_ptr.h>
32 #if defined(__ANDROID__)
33 #include <dbus/service_constants.h>
34 #else
35 #include <chromeos/dbus/service_constants.h>
36 #endif // __ANDROID__
37 #include <gmock/gmock.h>
38 #include <gtest/gtest.h>
39
40 #include "shill/connectivity_trial.h"
41 #include "shill/dhcp/dhcp_provider.h"
42 #include "shill/dhcp/mock_dhcp_config.h"
43 #include "shill/dhcp/mock_dhcp_provider.h"
44 #include "shill/event_dispatcher.h"
45 #include "shill/mock_adaptors.h"
46 #include "shill/mock_connection.h"
47 #include "shill/mock_connection_health_checker.h"
48 #include "shill/mock_control.h"
49 #include "shill/mock_dhcp_properties.h"
50 #include "shill/mock_device.h"
51 #include "shill/mock_device_info.h"
52 #include "shill/mock_dns_server_tester.h"
53 #include "shill/mock_event_dispatcher.h"
54 #include "shill/mock_ip_address_store.h"
55 #include "shill/mock_ipconfig.h"
56 #include "shill/mock_link_monitor.h"
57 #include "shill/mock_manager.h"
58 #include "shill/mock_metrics.h"
59 #include "shill/mock_portal_detector.h"
60 #include "shill/mock_service.h"
61 #include "shill/mock_store.h"
62 #include "shill/mock_traffic_monitor.h"
63 #include "shill/net/mock_rtnl_handler.h"
64 #include "shill/net/mock_time.h"
65 #include "shill/net/ndisc.h"
66 #include "shill/portal_detector.h"
67 #include "shill/property_store_unittest.h"
68 #include "shill/static_ip_parameters.h"
69 #include "shill/technology.h"
70 #include "shill/testing.h"
71 #include "shill/tethering.h"
72 #include "shill/traffic_monitor.h"
73
74 using base::Bind;
75 using base::Callback;
76 using std::map;
77 using std::string;
78 using std::vector;
79 using ::testing::_;
80 using ::testing::AnyNumber;
81 using ::testing::AtLeast;
82 using ::testing::DefaultValue;
83 using ::testing::DoAll;
84 using ::testing::HasSubstr;
85 using ::testing::Invoke;
86 using ::testing::Mock;
87 using ::testing::NiceMock;
88 using ::testing::Ref;
89 using ::testing::Return;
90 using ::testing::ReturnRef;
91 using ::testing::SetArgPointee;
92 using ::testing::StrEq;
93 using ::testing::StrictMock;
94 using ::testing::Test;
95 using ::testing::Values;
96
97 namespace shill {
98
99 class TestDevice : public Device {
100 public:
TestDevice(ControlInterface * control_interface,EventDispatcher * dispatcher,Metrics * metrics,Manager * manager,const std::string & link_name,const std::string & address,int interface_index,Technology::Identifier technology)101 TestDevice(ControlInterface* control_interface,
102 EventDispatcher* dispatcher,
103 Metrics* metrics,
104 Manager* manager,
105 const std::string& link_name,
106 const std::string& address,
107 int interface_index,
108 Technology::Identifier technology)
109 : Device(control_interface, dispatcher, metrics, manager, link_name,
110 address, interface_index, technology) {
111 ON_CALL(*this, IsIPv6Allowed())
112 .WillByDefault(Invoke(this, &TestDevice::DeviceIsIPv6Allowed));
113 ON_CALL(*this, SetIPFlag(_, _, _))
114 .WillByDefault(Invoke(this, &TestDevice::DeviceSetIPFlag));
115 ON_CALL(*this, IsTrafficMonitorEnabled())
116 .WillByDefault(Invoke(this,
117 &TestDevice::DeviceIsTrafficMonitorEnabled));
118 ON_CALL(*this, StartDNSTest(_, _, _))
119 .WillByDefault(Invoke(
120 this,
121 &TestDevice::DeviceStartDNSTest));
122 }
123
~TestDevice()124 ~TestDevice() {}
125
Start(Error * error,const EnabledStateChangedCallback & callback)126 virtual void Start(Error* error,
127 const EnabledStateChangedCallback& callback) {
128 DCHECK(error);
129 }
130
Stop(Error * error,const EnabledStateChangedCallback & callback)131 virtual void Stop(Error* error,
132 const EnabledStateChangedCallback& callback) {
133 DCHECK(error);
134 }
135
136 MOCK_CONST_METHOD0(IsIPv6Allowed, bool());
137 MOCK_CONST_METHOD0(IsTrafficMonitorEnabled, bool());
138
139 MOCK_METHOD3(SetIPFlag, bool(IPAddress::Family family,
140 const std::string& flag,
141 const std::string& value));
142
143 MOCK_METHOD3(StartDNSTest, bool(
144 const std::vector<std::string>& dns_servers,
145 const bool retry_until_success,
146 const base::Callback<void(const DNSServerTester::Status)>& callback));
147
148 MOCK_METHOD1(StartConnectionDiagnosticsAfterPortalDetection,
149 bool(const PortalDetector::Result& result));
150
DeviceIsIPv6Allowed() const151 virtual bool DeviceIsIPv6Allowed() const {
152 return Device::IsIPv6Allowed();
153 }
154
DeviceIsTrafficMonitorEnabled() const155 virtual bool DeviceIsTrafficMonitorEnabled() const {
156 return Device::IsTrafficMonitorEnabled();
157 }
158
DeviceSetIPFlag(IPAddress::Family family,const std::string & flag,const std::string & value)159 virtual bool DeviceSetIPFlag(IPAddress::Family family,
160 const std::string& flag,
161 const std::string& value) {
162 return Device::SetIPFlag(family, flag, value);
163 }
164
DeviceStartDNSTest(const std::vector<std::string> & dns_servers,const bool retry_until_success,const base::Callback<void (const DNSServerTester::Status)> & callback)165 virtual bool DeviceStartDNSTest(
166 const std::vector<std::string>& dns_servers,
167 const bool retry_until_success,
168 const base::Callback<void(const DNSServerTester::Status)>& callback) {
169 return Device::StartDNSTest(dns_servers, retry_until_success, callback);
170 }
171 };
172
173 class DeviceTest : public PropertyStoreTest {
174 public:
DeviceTest()175 DeviceTest()
176 : device_(new TestDevice(control_interface(),
177 dispatcher(),
178 nullptr,
179 manager(),
180 kDeviceName,
181 kDeviceAddress,
182 kDeviceInterfaceIndex,
183 Technology::kUnknown)),
184 device_info_(control_interface(), nullptr, nullptr, nullptr),
185 metrics_(dispatcher()) {
186 DHCPProvider::GetInstance()->control_interface_ = control_interface();
187 DHCPProvider::GetInstance()->dispatcher_ = dispatcher();
188 device_->time_ = &time_;
189 }
~DeviceTest()190 virtual ~DeviceTest() {}
191
SetUp()192 virtual void SetUp() {
193 device_->metrics_ = &metrics_;
194 device_->rtnl_handler_ = &rtnl_handler_;
195 }
196
197 protected:
198 static const char kDeviceName[];
199 static const char kDeviceAddress[];
200 static const int kDeviceInterfaceIndex;
201
OnIPConfigUpdated(const IPConfigRefPtr & ipconfig)202 void OnIPConfigUpdated(const IPConfigRefPtr& ipconfig) {
203 device_->OnIPConfigUpdated(ipconfig, true);
204 }
205
OnIPConfigFailed(const IPConfigRefPtr & ipconfig)206 void OnIPConfigFailed(const IPConfigRefPtr& ipconfig) {
207 device_->OnIPConfigFailed(ipconfig);
208 }
209
OnIPConfigExpired(const IPConfigRefPtr & ipconfig)210 void OnIPConfigExpired(const IPConfigRefPtr& ipconfig) {
211 device_->OnIPConfigExpired(ipconfig);
212 }
213
SelectService(const ServiceRefPtr service)214 void SelectService(const ServiceRefPtr service) {
215 device_->SelectService(service);
216 }
217
SetConnection(ConnectionRefPtr connection)218 void SetConnection(ConnectionRefPtr connection) {
219 device_->connection_ = connection;
220 }
221
SetLinkMonitor(LinkMonitor * link_monitor)222 void SetLinkMonitor(LinkMonitor* link_monitor) {
223 device_->set_link_monitor(link_monitor); // Passes ownership.
224 }
225
HasLinkMonitor()226 bool HasLinkMonitor() {
227 return device_->link_monitor();
228 }
229
StartLinkMonitor()230 bool StartLinkMonitor() {
231 return device_->StartLinkMonitor();
232 }
233
StopLinkMonitor()234 void StopLinkMonitor() {
235 device_->StopLinkMonitor();
236 }
237
GetLinkMonitorResponseTime(Error * error)238 uint64_t GetLinkMonitorResponseTime(Error* error) {
239 return device_->GetLinkMonitorResponseTime(error);
240 }
241
SetTrafficMonitor(TrafficMonitor * traffic_monitor)242 void SetTrafficMonitor(TrafficMonitor* traffic_monitor) {
243 device_->set_traffic_monitor(traffic_monitor); // Passes ownership.
244 }
245
StartTrafficMonitor()246 void StartTrafficMonitor() {
247 device_->StartTrafficMonitor();
248 }
249
StopTrafficMonitor()250 void StopTrafficMonitor() {
251 device_->StopTrafficMonitor();
252 }
253
NetworkProblemDetected(int reason)254 void NetworkProblemDetected(int reason) {
255 device_->OnEncounterNetworkProblem(reason);
256 }
257
GetDeviceMockAdaptor()258 DeviceMockAdaptor* GetDeviceMockAdaptor() {
259 return static_cast<DeviceMockAdaptor*>(device_->adaptor_.get());
260 }
261
SetManager(Manager * manager)262 void SetManager(Manager* manager) {
263 device_->manager_ = manager;
264 }
265
266 MOCK_METHOD0(ReliableLinkCallback, void());
SetReliableLinkCallback()267 void SetReliableLinkCallback() {
268 device_->reliable_link_callback_.Reset(
269 base::Bind(&DeviceTest::ReliableLinkCallback, base::Unretained(this)));
270 }
271
ReliableLinkCallbackIsCancelled()272 bool ReliableLinkCallbackIsCancelled() {
273 return device_->reliable_link_callback_.IsCancelled();
274 }
275
SetupIPv6Config()276 void SetupIPv6Config() {
277 const char kAddress[] = "2001:db8::1";
278 const char kDnsServer1[] = "2001:db8::2";
279 const char kDnsServer2[] = "2001:db8::3";
280 IPConfig::Properties properties;
281 properties.address = kAddress;
282 properties.dns_servers.push_back(kDnsServer1);
283 properties.dns_servers.push_back(kDnsServer2);
284
285 device_->ip6config_ = new MockIPConfig(control_interface(), kDeviceName);
286 device_->ip6config_->set_properties(properties);
287 }
288
SetHostname(const string & hostname)289 bool SetHostname(const string& hostname) {
290 return device_->SetHostname(hostname);
291 }
292
293 MockControl control_interface_;
294 scoped_refptr<TestDevice> device_;
295 MockDeviceInfo device_info_;
296 MockMetrics metrics_;
297 MockTime time_;
298 StrictMock<MockRTNLHandler> rtnl_handler_;
299 };
300
301 const char DeviceTest::kDeviceName[] = "testdevice";
302 const char DeviceTest::kDeviceAddress[] = "address";
303 const int DeviceTest::kDeviceInterfaceIndex = 0;
304
TEST_F(DeviceTest,Contains)305 TEST_F(DeviceTest, Contains) {
306 EXPECT_TRUE(device_->store().Contains(kNameProperty));
307 EXPECT_FALSE(device_->store().Contains(""));
308 }
309
TEST_F(DeviceTest,GetProperties)310 TEST_F(DeviceTest, GetProperties) {
311 brillo::VariantDictionary props;
312 Error error;
313 device_->store().GetProperties(&props, &error);
314 ASSERT_FALSE(props.find(kNameProperty) == props.end());
315 EXPECT_TRUE(props[kNameProperty].IsTypeCompatible<string>());
316 EXPECT_EQ(props[kNameProperty].Get<string>(), string(kDeviceName));
317 }
318
319 // Note: there are currently no writeable Device properties that
320 // aren't registered in a subclass.
TEST_F(DeviceTest,SetReadOnlyProperty)321 TEST_F(DeviceTest, SetReadOnlyProperty) {
322 Error error;
323 // Ensure that an attempt to write a R/O property returns InvalidArgs error.
324 EXPECT_FALSE(device_->mutable_store()->SetAnyProperty(
325 kAddressProperty, PropertyStoreTest::kStringV, &error));
326 EXPECT_EQ(Error::kInvalidArguments, error.type());
327 }
328
TEST_F(DeviceTest,ClearReadOnlyProperty)329 TEST_F(DeviceTest, ClearReadOnlyProperty) {
330 Error error;
331 EXPECT_FALSE(device_->mutable_store()->SetAnyProperty(
332 kAddressProperty, PropertyStoreTest::kStringV, &error));
333 }
334
TEST_F(DeviceTest,ClearReadOnlyDerivedProperty)335 TEST_F(DeviceTest, ClearReadOnlyDerivedProperty) {
336 Error error;
337 EXPECT_FALSE(device_->mutable_store()->SetAnyProperty(
338 kIPConfigsProperty, PropertyStoreTest::kStringsV, &error));
339 }
340
TEST_F(DeviceTest,DestroyIPConfig)341 TEST_F(DeviceTest, DestroyIPConfig) {
342 ASSERT_FALSE(device_->ipconfig_.get());
343 device_->ipconfig_ = new IPConfig(control_interface(), kDeviceName);
344 device_->ip6config_ = new IPConfig(control_interface(), kDeviceName);
345 device_->dhcpv6_config_ = new IPConfig(control_interface(), kDeviceName);
346 device_->DestroyIPConfig();
347 ASSERT_FALSE(device_->ipconfig_.get());
348 ASSERT_FALSE(device_->ip6config_.get());
349 ASSERT_FALSE(device_->dhcpv6_config_.get());
350 }
351
TEST_F(DeviceTest,DestroyIPConfigNULL)352 TEST_F(DeviceTest, DestroyIPConfigNULL) {
353 ASSERT_FALSE(device_->ipconfig_.get());
354 ASSERT_FALSE(device_->ip6config_.get());
355 ASSERT_FALSE(device_->dhcpv6_config_.get());
356 device_->DestroyIPConfig();
357 ASSERT_FALSE(device_->ipconfig_.get());
358 ASSERT_FALSE(device_->ip6config_.get());
359 ASSERT_FALSE(device_->dhcpv6_config_.get());
360 }
361
362 MATCHER_P(IsCombinedDhcpProperties, dhcp_props, "") {
363 return dhcp_props == arg.properties();
364 }
365
TEST_F(DeviceTest,AcquireIPConfigWithSelectedService)366 TEST_F(DeviceTest, AcquireIPConfigWithSelectedService) {
367 device_->ipconfig_ = new IPConfig(control_interface(), "randomname");
368 std::unique_ptr<MockDHCPProvider> dhcp_provider(new MockDHCPProvider());
369 device_->dhcp_provider_ = dhcp_provider.get();
370
371 scoped_refptr<MockDHCPConfig> dhcp_config(
372 new MockDHCPConfig(control_interface(), kDeviceName));
373 NiceMock<MockStore> storage;
374 const string service_storage_id = "service_storage_id";
375 EXPECT_CALL(storage, GetString(service_storage_id,
376 "DHCPProperty.Hostname", _))
377 .WillOnce(DoAll(SetArgPointee<2>(string("name of host")),
378 Return(true)));
379 EXPECT_CALL(storage, GetString(service_storage_id,
380 "DHCPProperty.VendorClass", _))
381 .WillOnce(Return(false));
382
383 std::unique_ptr<DhcpProperties> service_dhcp_properties(new DhcpProperties());
384 service_dhcp_properties->Load(&storage, service_storage_id);
385
386 scoped_refptr<MockService> service(
387 new NiceMock<MockService>(control_interface(),
388 dispatcher(),
389 metrics(),
390 manager()));
391 SelectService(service);
392
393 const string default_profile_storage_id = "default_profile_storage_id";
394 NiceMock<MockStore> default_profile_storage;
395 EXPECT_CALL(default_profile_storage, GetString(default_profile_storage_id,
396 "DHCPProperty.VendorClass", _))
397 .WillOnce(DoAll(SetArgPointee<2>(string("vendorclass")),
398 Return(true)));
399 EXPECT_CALL(default_profile_storage, GetString(default_profile_storage_id,
400 "DHCPProperty.Hostname", _))
401 .WillOnce(Return(false));
402
403 std::unique_ptr<DhcpProperties> manager_dhcp_properties(new DhcpProperties());
404 manager_dhcp_properties->Load(&default_profile_storage,
405 default_profile_storage_id);
406 std::unique_ptr<DhcpProperties> combined_props =
407 DhcpProperties::Combine(*manager_dhcp_properties,
408 *service_dhcp_properties);
409 service->dhcp_properties_ = std::move(service_dhcp_properties);
410 #ifndef DISABLE_DHCPV6
411 MockManager manager(control_interface(),
412 dispatcher(),
413 metrics());
414 manager.set_mock_device_info(&device_info_);
415 SetManager(&manager);
416 device_->dhcpv6_config_ = new IPConfig(control_interface(), "randomname");
417 scoped_refptr<MockDHCPConfig> dhcpv6_config(
418 new MockDHCPConfig(control_interface(), kDeviceName));
419
420 EXPECT_CALL(manager, IsDHCPv6EnabledForDevice(kDeviceName))
421 .WillOnce(Return(true));
422 EXPECT_CALL(*dhcp_provider, CreateIPv6Config(_, _))
423 .WillOnce(Return(dhcpv6_config));
424 EXPECT_CALL(*dhcpv6_config, RequestIP()).WillOnce(Return(true));
425 #endif // DISABLE_DHCPV6
426 device_->manager_->dhcp_properties_ = std::move(manager_dhcp_properties);
427 EXPECT_CALL(*dhcp_provider,
428 CreateIPv4Config(_, _, _,
429 IsCombinedDhcpProperties(
430 combined_props->properties())))
431 .WillOnce(Return(dhcp_config));
432 EXPECT_CALL(*dhcp_config, RequestIP())
433 .WillOnce(Return(true));
434 EXPECT_TRUE(device_->AcquireIPConfig());
435 ASSERT_TRUE(device_->ipconfig_.get());
436 EXPECT_EQ(kDeviceName, device_->ipconfig_->device_name());
437 EXPECT_FALSE(device_->ipconfig_->update_callback_.is_null());
438 #ifndef DISABLE_DHCPV6
439 EXPECT_EQ(kDeviceName, device_->dhcpv6_config_->device_name());
440 EXPECT_FALSE(device_->dhcpv6_config_->update_callback_.is_null());
441 #endif // DISABLE_DHCPV6
442 device_->dhcp_provider_ = nullptr;
443 }
444
TEST_F(DeviceTest,AcquireIPConfigWithoutSelectedService)445 TEST_F(DeviceTest, AcquireIPConfigWithoutSelectedService) {
446 device_->ipconfig_ = new IPConfig(control_interface(), "randomname");
447 std::unique_ptr<MockDHCPProvider> dhcp_provider(new MockDHCPProvider());
448 device_->dhcp_provider_ = dhcp_provider.get();
449 scoped_refptr<MockDHCPConfig> dhcp_config(
450 new MockDHCPConfig(control_interface(), kDeviceName));
451 std::unique_ptr<DhcpProperties> manager_dhcp_properties(new DhcpProperties());
452 device_->manager_->dhcp_properties_ = std::move(manager_dhcp_properties);
453 #ifndef DISABLE_DHCPV6
454 MockManager manager(control_interface(),
455 dispatcher(),
456 metrics());
457 manager.set_mock_device_info(&device_info_);
458 SetManager(&manager);
459 device_->dhcpv6_config_ = new IPConfig(control_interface(), "randomname");
460 scoped_refptr<MockDHCPConfig> dhcpv6_config(
461 new MockDHCPConfig(control_interface(), kDeviceName));
462
463 EXPECT_CALL(manager, IsDHCPv6EnabledForDevice(kDeviceName))
464 .WillOnce(Return(true));
465 EXPECT_CALL(*dhcp_provider, CreateIPv6Config(_, _))
466 .WillOnce(Return(dhcpv6_config));
467 EXPECT_CALL(*dhcpv6_config, RequestIP()).WillOnce(Return(true));
468 #endif // DISABLE_DHCPV6
469
470 EXPECT_CALL(*dhcp_provider,
471 CreateIPv4Config(_, _, _,
472 Ref(*(device_->manager_->dhcp_properties_))))
473 .WillOnce(Return(dhcp_config));
474 EXPECT_CALL(*dhcp_config, RequestIP())
475 .WillOnce(Return(true));
476 EXPECT_TRUE(device_->AcquireIPConfig());
477 ASSERT_TRUE(device_->ipconfig_.get());
478 EXPECT_EQ(kDeviceName, device_->ipconfig_->device_name());
479 EXPECT_FALSE(device_->ipconfig_->update_callback_.is_null());
480 #ifndef DISABLE_DHCPV6
481 EXPECT_EQ(kDeviceName, device_->dhcpv6_config_->device_name());
482 EXPECT_FALSE(device_->dhcpv6_config_->update_callback_.is_null());
483 #endif // DISABLE_DHCPV6
484 device_->dhcp_provider_ = nullptr;
485 }
486
TEST_F(DeviceTest,ConfigWithMinimumMTU)487 TEST_F(DeviceTest, ConfigWithMinimumMTU) {
488 const int minimum_mtu = 1500;
489
490 MockManager manager(control_interface(),
491 dispatcher(),
492 metrics());
493 manager.set_mock_device_info(&device_info_);
494 SetManager(&manager);
495
496 EXPECT_CALL(manager, GetMinimumMTU()).WillOnce(Return(minimum_mtu));
497
498 device_->ipconfig_ = new IPConfig(control_interface(), "anothername");
499 std::unique_ptr<MockDHCPProvider> dhcp_provider(new MockDHCPProvider());
500 device_->dhcp_provider_ = dhcp_provider.get();
501
502 scoped_refptr<MockDHCPConfig> dhcp_config(
503 new MockDHCPConfig(control_interface(), kDeviceName));
504 EXPECT_CALL(*dhcp_provider, CreateIPv4Config(_, _, _, _))
505 .WillOnce(Return(dhcp_config));
506 EXPECT_CALL(*dhcp_config, set_minimum_mtu(minimum_mtu));
507
508 device_->AcquireIPConfig();
509 }
510
TEST_F(DeviceTest,EnableIPv6)511 TEST_F(DeviceTest, EnableIPv6) {
512 EXPECT_CALL(*device_, SetIPFlag(IPAddress::kFamilyIPv6,
513 StrEq(Device::kIPFlagDisableIPv6),
514 StrEq("0")))
515 .WillOnce(Return(true));
516 device_->EnableIPv6();
517 }
518
TEST_F(DeviceTest,EnableIPv6NotAllowed)519 TEST_F(DeviceTest, EnableIPv6NotAllowed) {
520 EXPECT_CALL(*device_, IsIPv6Allowed()).WillOnce(Return(false));
521 EXPECT_CALL(*device_, SetIPFlag(_, _, _)).Times(0);
522 device_->EnableIPv6();
523 }
524
TEST_F(DeviceTest,MultiHomed)525 TEST_F(DeviceTest, MultiHomed) {
526 // Device should have multi-homing disabled by default.
527 EXPECT_CALL(*device_, SetIPFlag(_, _, _)).Times(0);
528 device_->SetIsMultiHomed(false);
529 Mock::VerifyAndClearExpectations(device_.get());
530
531 // Disabled -> enabled should change flags on the device.
532 EXPECT_CALL(*device_, SetIPFlag(IPAddress::kFamilyIPv4, StrEq("arp_announce"),
533 StrEq("2"))).WillOnce(Return(true));
534 EXPECT_CALL(*device_, SetIPFlag(IPAddress::kFamilyIPv4, StrEq("arp_ignore"),
535 StrEq("1"))).WillOnce(Return(true));
536 EXPECT_CALL(*device_, SetIPFlag(IPAddress::kFamilyIPv4, StrEq("rp_filter"),
537 StrEq("2"))).WillOnce(Return(true));
538 device_->SetIsMultiHomed(true);
539 Mock::VerifyAndClearExpectations(device_.get());
540
541 // Enabled -> enabled should be a no-op.
542 EXPECT_CALL(*device_, SetIPFlag(_, _, _)).Times(0);
543 device_->SetIsMultiHomed(true);
544
545 // Disabling or enabling reverse-path filtering should also be a no-op
546 // (since it is disabled due to multi-homing).
547 device_->SetLooseRouting(false);
548 device_->SetLooseRouting(true);
549 Mock::VerifyAndClearExpectations(device_.get());
550
551 // Enabled -> disabled should reset the flags back to the default, but
552 // because non-default routing is enabled, rp_filter will be left
553 // in loose mode.
554 EXPECT_CALL(*device_, SetIPFlag(IPAddress::kFamilyIPv4, StrEq("arp_announce"),
555 StrEq("0"))).WillOnce(Return(true));
556 EXPECT_CALL(*device_, SetIPFlag(IPAddress::kFamilyIPv4, StrEq("arp_ignore"),
557 StrEq("0"))).WillOnce(Return(true));
558 device_->SetIsMultiHomed(false);
559 Mock::VerifyAndClearExpectations(device_.get());
560
561 // Re-enable reverse-path filtering.
562 EXPECT_CALL(*device_, SetIPFlag(IPAddress::kFamilyIPv4, StrEq("rp_filter"),
563 StrEq("1"))).WillOnce(Return(true));
564 device_->SetLooseRouting(false);
565 Mock::VerifyAndClearExpectations(device_.get());
566 }
567
TEST_F(DeviceTest,Load)568 TEST_F(DeviceTest, Load) {
569 NiceMock<MockStore> storage;
570 const string id = device_->GetStorageIdentifier();
571 EXPECT_CALL(storage, ContainsGroup(id)).WillOnce(Return(true));
572 EXPECT_CALL(storage, GetBool(id, Device::kStoragePowered, _))
573 .WillOnce(Return(true));
574 EXPECT_CALL(storage, GetUint64(id, Device::kStorageReceiveByteCount, _))
575 .WillOnce(Return(true));
576 EXPECT_CALL(storage, GetUint64(id, Device::kStorageTransmitByteCount, _))
577 .WillOnce(Return(true));
578 EXPECT_TRUE(device_->Load(&storage));
579 }
580
TEST_F(DeviceTest,Save)581 TEST_F(DeviceTest, Save) {
582 NiceMock<MockStore> storage;
583 const string id = device_->GetStorageIdentifier();
584 EXPECT_CALL(storage, SetBool(id, Device::kStoragePowered, _))
585 .WillOnce(Return(true));
586 EXPECT_CALL(storage, SetUint64(id, Device::kStorageReceiveByteCount, _))
587 .WillOnce(Return(true));
588 EXPECT_CALL(storage, SetUint64(id, Device::kStorageTransmitByteCount, _))
589 .Times(AtLeast(true));
590 EXPECT_TRUE(device_->Save(&storage));
591 }
592
TEST_F(DeviceTest,StorageIdGeneration)593 TEST_F(DeviceTest, StorageIdGeneration) {
594 string to_process("/device/stuff/0");
595 ControlInterface::RpcIdToStorageId(&to_process);
596 EXPECT_TRUE(isalpha(to_process[0]));
597 EXPECT_EQ(string::npos, to_process.find('/'));
598 }
599
TEST_F(DeviceTest,SelectedService)600 TEST_F(DeviceTest, SelectedService) {
601 EXPECT_FALSE(device_->selected_service_.get());
602 device_->SetServiceState(Service::kStateAssociating);
603 scoped_refptr<MockService> service(
604 new StrictMock<MockService>(control_interface(),
605 dispatcher(),
606 metrics(),
607 manager()));
608 SelectService(service);
609 EXPECT_TRUE(device_->selected_service_.get() == service.get());
610
611 EXPECT_CALL(*service, SetState(Service::kStateConfiguring));
612 device_->SetServiceState(Service::kStateConfiguring);
613 EXPECT_CALL(*service, SetFailure(Service::kFailureOutOfRange));
614 device_->SetServiceFailure(Service::kFailureOutOfRange);
615
616 // Service should be returned to "Idle" state
617 EXPECT_CALL(*service, state())
618 .WillOnce(Return(Service::kStateUnknown));
619 EXPECT_CALL(*service, SetState(Service::kStateIdle));
620 EXPECT_CALL(*service, SetConnection(IsNullRefPtr()));
621 SelectService(nullptr);
622
623 // A service in the "Failure" state should not be reset to "Idle"
624 SelectService(service);
625 EXPECT_CALL(*service, state())
626 .WillOnce(Return(Service::kStateFailure));
627 EXPECT_CALL(*service, SetConnection(IsNullRefPtr()));
628 SelectService(nullptr);
629 }
630
TEST_F(DeviceTest,LinkMonitorFailure)631 TEST_F(DeviceTest, LinkMonitorFailure) {
632 scoped_refptr<MockService> service(
633 new StrictMock<MockService>(control_interface(),
634 dispatcher(),
635 metrics(),
636 manager()));
637 SelectService(service);
638 EXPECT_TRUE(device_->selected_service().get() == service.get());
639
640 time_t current_time = 1000;
641
642 // Initial link monitor failure.
643 EXPECT_CALL(time_, GetSecondsBoottime(_)).WillOnce(
644 DoAll(SetArgPointee<0>(current_time), Return(true)));
645 EXPECT_CALL(metrics_, NotifyUnreliableLinkSignalStrength(_, _)).Times(0);
646 device_->OnLinkMonitorFailure();
647 EXPECT_FALSE(service->unreliable());
648
649 // Another link monitor failure after 3 minutes, report signal strength.
650 current_time += 180;
651 EXPECT_CALL(time_, GetSecondsBoottime(_)).WillOnce(
652 DoAll(SetArgPointee<0>(current_time), Return(true)));
653 EXPECT_CALL(metrics_, NotifyUnreliableLinkSignalStrength(_, _)).Times(1);
654 device_->OnLinkMonitorFailure();
655 EXPECT_TRUE(service->unreliable());
656
657 // Device is connected with the reliable link callback setup, then
658 // another link monitor failure after 3 minutes, which implies link is
659 // still unreliable, reliable link callback should be cancelled.
660 current_time += 180;
661 SetReliableLinkCallback();
662 EXPECT_CALL(time_, GetSecondsBoottime(_)).WillOnce(
663 DoAll(SetArgPointee<0>(current_time), Return(true)));
664 EXPECT_CALL(metrics_, NotifyUnreliableLinkSignalStrength(_, _)).Times(1);
665 device_->OnLinkMonitorFailure();
666 EXPECT_TRUE(service->unreliable());
667 EXPECT_TRUE(ReliableLinkCallbackIsCancelled());
668
669 // Another link monitor failure after an hour, link is still reliable, signal
670 // strength not reported.
671 current_time += 3600;
672 service->set_unreliable(false);
673 EXPECT_CALL(time_, GetSecondsBoottime(_)).WillOnce(
674 DoAll(SetArgPointee<0>(current_time), Return(true)));
675 EXPECT_CALL(metrics_, NotifyUnreliableLinkSignalStrength(_, _)).Times(0);
676 device_->OnLinkMonitorFailure();
677 EXPECT_FALSE(service->unreliable());
678 }
679
TEST_F(DeviceTest,LinkStatusResetOnSelectService)680 TEST_F(DeviceTest, LinkStatusResetOnSelectService) {
681 scoped_refptr<MockService> service(
682 new StrictMock<MockService>(control_interface(),
683 dispatcher(),
684 metrics(),
685 manager()));
686 SelectService(service);
687 service->set_unreliable(true);
688 SetReliableLinkCallback();
689 EXPECT_FALSE(ReliableLinkCallbackIsCancelled());
690
691 // Service is deselected, link status of the service should be resetted.
692 EXPECT_CALL(*service, state())
693 .WillOnce(Return(Service::kStateIdle));
694 EXPECT_CALL(*service, SetState(_));
695 EXPECT_CALL(*service, SetConnection(_));
696 SelectService(nullptr);
697 EXPECT_FALSE(service->unreliable());
698 EXPECT_TRUE(ReliableLinkCallbackIsCancelled());
699 }
700
TEST_F(DeviceTest,IPConfigUpdatedFailure)701 TEST_F(DeviceTest, IPConfigUpdatedFailure) {
702 scoped_refptr<MockIPConfig> ipconfig = new MockIPConfig(control_interface(),
703 kDeviceName);
704 scoped_refptr<MockService> service(
705 new StrictMock<MockService>(control_interface(),
706 dispatcher(),
707 metrics(),
708 manager()));
709 SelectService(service);
710 EXPECT_CALL(*service, DisconnectWithFailure(Service::kFailureDHCP,
711 _,
712 HasSubstr("OnIPConfigFailure")));
713 EXPECT_CALL(*service, SetConnection(IsNullRefPtr()));
714 EXPECT_CALL(*ipconfig, ResetProperties());
715 OnIPConfigFailed(ipconfig.get());
716 }
717
TEST_F(DeviceTest,IPConfigUpdatedFailureWithIPv6Config)718 TEST_F(DeviceTest, IPConfigUpdatedFailureWithIPv6Config) {
719 // Setup IPv6 configuration.
720 SetupIPv6Config();
721 EXPECT_THAT(device_->ip6config_, NotNullRefPtr());
722
723 // IPv4 configuration failed, fallback to use IPv6 configuration.
724 scoped_refptr<MockIPConfig> ipconfig = new MockIPConfig(control_interface(),
725 kDeviceName);
726 scoped_refptr<MockService> service(
727 new StrictMock<MockService>(control_interface(),
728 dispatcher(),
729 metrics(),
730 manager()));
731 SelectService(service);
732 scoped_refptr<MockConnection> connection(
733 new StrictMock<MockConnection>(&device_info_));
734 SetConnection(connection.get());
735
736 EXPECT_CALL(*ipconfig, ResetProperties());
737 EXPECT_CALL(*connection, IsIPv6())
738 .WillRepeatedly(Return(false));
739 EXPECT_CALL(*connection, UpdateFromIPConfig(device_->ip6config_));
740 EXPECT_CALL(*service, SetState(Service::kStateConnected));
741 EXPECT_CALL(*service, IsConnected())
742 .WillRepeatedly(Return(true));
743 EXPECT_CALL(*service, IsPortalDetectionDisabled())
744 .WillRepeatedly(Return(true));
745 EXPECT_CALL(*service, SetState(Service::kStateOnline));
746 EXPECT_CALL(*service, SetConnection(NotNullRefPtr()));
747 OnIPConfigFailed(ipconfig.get());
748 }
749
750 // IPv4 configuration failed with existing IPv6 connection.
TEST_F(DeviceTest,IPConfigUpdatedFailureWithIPv6Connection)751 TEST_F(DeviceTest, IPConfigUpdatedFailureWithIPv6Connection) {
752 // Setup IPv6 configuration.
753 SetupIPv6Config();
754 EXPECT_THAT(device_->ip6config_, NotNullRefPtr());
755
756 scoped_refptr<MockIPConfig> ipconfig = new MockIPConfig(control_interface(),
757 kDeviceName);
758 scoped_refptr<MockService> service(
759 new StrictMock<MockService>(control_interface(),
760 dispatcher(),
761 metrics(),
762 manager()));
763 SelectService(service);
764 scoped_refptr<MockConnection> connection(
765 new StrictMock<MockConnection>(&device_info_));
766 SetConnection(connection.get());
767
768 EXPECT_CALL(*ipconfig, ResetProperties());
769 EXPECT_CALL(*connection, IsIPv6())
770 .WillRepeatedly(Return(true));
771 EXPECT_CALL(*service, DisconnectWithFailure(_, _, _)).Times(0);
772 EXPECT_CALL(*service, SetConnection(IsNullRefPtr())).Times(0);
773 OnIPConfigFailed(ipconfig.get());
774 // Verify connection not teardown.
775 EXPECT_THAT(device_->connection(), NotNullRefPtr());
776 }
777
TEST_F(DeviceTest,IPConfigUpdatedFailureWithStatic)778 TEST_F(DeviceTest, IPConfigUpdatedFailureWithStatic) {
779 scoped_refptr<MockIPConfig> ipconfig = new MockIPConfig(control_interface(),
780 kDeviceName);
781 scoped_refptr<MockService> service(
782 new StrictMock<MockService>(control_interface(),
783 dispatcher(),
784 metrics(),
785 manager()));
786 SelectService(service);
787 service->static_ip_parameters_.args_.SetString(kAddressProperty, "1.1.1.1");
788 service->static_ip_parameters_.args_.SetInt(kPrefixlenProperty, 16);
789 // Even though we won't call DisconnectWithFailure, we should still have
790 // the service learn from the failed DHCP attempt.
791 EXPECT_CALL(*service, DisconnectWithFailure(_, _, _)).Times(0);
792 EXPECT_CALL(*service, SetConnection(_)).Times(0);
793 // The IPConfig should retain the previous values.
794 EXPECT_CALL(*ipconfig, ResetProperties()).Times(0);
795 OnIPConfigFailed(ipconfig.get());
796 }
797
TEST_F(DeviceTest,IPConfigUpdatedSuccess)798 TEST_F(DeviceTest, IPConfigUpdatedSuccess) {
799 scoped_refptr<MockService> service(
800 new StrictMock<MockService>(control_interface(),
801 dispatcher(),
802 metrics(),
803 manager()));
804 SelectService(service);
805 scoped_refptr<MockIPConfig> ipconfig = new MockIPConfig(control_interface(),
806 kDeviceName);
807 device_->set_ipconfig(ipconfig);
808 EXPECT_CALL(*service, SetState(Service::kStateConnected));
809 EXPECT_CALL(metrics_,
810 NotifyNetworkConnectionIPType(
811 device_->technology(),
812 Metrics::kNetworkConnectionIPTypeIPv4));
813 EXPECT_CALL(metrics_,
814 NotifyIPv6ConnectivityStatus(device_->technology(), false));
815 EXPECT_CALL(*service, IsConnected())
816 .WillRepeatedly(Return(true));
817 EXPECT_CALL(*service, IsPortalDetectionDisabled())
818 .WillRepeatedly(Return(true));
819 EXPECT_CALL(*service, HasStaticNameServers())
820 .WillRepeatedly(Return(false));
821 EXPECT_CALL(*service, SetState(Service::kStateOnline));
822 EXPECT_CALL(*service, SetConnection(NotNullRefPtr()));
823 EXPECT_CALL(*GetDeviceMockAdaptor(),
824 EmitRpcIdentifierArrayChanged(
825 kIPConfigsProperty,
826 vector<string>{ IPConfigMockAdaptor::kRpcId }));
827
828 OnIPConfigUpdated(ipconfig.get());
829 }
830
TEST_F(DeviceTest,IPConfigUpdatedSuccessNoSelectedService)831 TEST_F(DeviceTest, IPConfigUpdatedSuccessNoSelectedService) {
832 // Make sure shill doesn't crash if a service is disabled immediately
833 // after receiving its IP config (selected_service_ is nullptr in this case).
834 scoped_refptr<MockIPConfig> ipconfig = new MockIPConfig(control_interface(),
835 kDeviceName);
836 SelectService(nullptr);
837 OnIPConfigUpdated(ipconfig.get());
838 }
839
TEST_F(DeviceTest,OnIPConfigExpired)840 TEST_F(DeviceTest, OnIPConfigExpired) {
841 scoped_refptr<MockIPConfig> ipconfig =
842 new MockIPConfig(control_interface(), kDeviceName);
843 const int kLeaseLength = 1234;
844 ipconfig->properties_.lease_duration_seconds = kLeaseLength;
845
846 EXPECT_CALL(metrics_,
847 SendToUMA("Network.Shill.Unknown.ExpiredLeaseLengthSeconds",
848 kLeaseLength,
849 Metrics::kMetricExpiredLeaseLengthSecondsMin,
850 Metrics::kMetricExpiredLeaseLengthSecondsMax,
851 Metrics::kMetricExpiredLeaseLengthSecondsNumBuckets));
852
853 OnIPConfigExpired(ipconfig.get());
854 }
855
TEST_F(DeviceTest,SetEnabledNonPersistent)856 TEST_F(DeviceTest, SetEnabledNonPersistent) {
857 EXPECT_FALSE(device_->enabled_);
858 EXPECT_FALSE(device_->enabled_pending_);
859 device_->enabled_persistent_ = false;
860 StrictMock<MockManager> manager(control_interface(),
861 dispatcher(),
862 metrics());
863 SetManager(&manager);
864 Error error;
865 device_->SetEnabledNonPersistent(true, &error, ResultCallback());
866 EXPECT_FALSE(device_->enabled_persistent_);
867 EXPECT_TRUE(device_->enabled_pending_);
868
869 // Enable while already enabled.
870 error.Populate(Error::kOperationInitiated);
871 device_->enabled_persistent_ = false;
872 device_->enabled_pending_ = true;
873 device_->enabled_ = true;
874 device_->SetEnabledNonPersistent(true, &error, ResultCallback());
875 EXPECT_FALSE(device_->enabled_persistent_);
876 EXPECT_TRUE(device_->enabled_pending_);
877 EXPECT_TRUE(device_->enabled_);
878 EXPECT_TRUE(error.IsSuccess());
879
880 // Enable while enabled but disabling.
881 error.Populate(Error::kOperationInitiated);
882 device_->enabled_pending_ = false;
883 device_->SetEnabledNonPersistent(true, &error, ResultCallback());
884 EXPECT_FALSE(device_->enabled_persistent_);
885 EXPECT_FALSE(device_->enabled_pending_);
886 EXPECT_TRUE(device_->enabled_);
887 EXPECT_TRUE(error.IsSuccess());
888
889 // Disable while already disabled.
890 error.Populate(Error::kOperationInitiated);
891 device_->enabled_ = false;
892 device_->SetEnabledNonPersistent(false, &error, ResultCallback());
893 EXPECT_FALSE(device_->enabled_persistent_);
894 EXPECT_FALSE(device_->enabled_pending_);
895 EXPECT_FALSE(device_->enabled_);
896 EXPECT_TRUE(error.IsSuccess());
897
898 // Disable while already enabling.
899 error.Populate(Error::kOperationInitiated);
900 device_->enabled_pending_ = true;
901 device_->SetEnabledNonPersistent(false, &error, ResultCallback());
902 EXPECT_FALSE(device_->enabled_persistent_);
903 EXPECT_TRUE(device_->enabled_pending_);
904 EXPECT_FALSE(device_->enabled_);
905 EXPECT_TRUE(error.IsSuccess());
906 }
907
TEST_F(DeviceTest,SetEnabledPersistent)908 TEST_F(DeviceTest, SetEnabledPersistent) {
909 EXPECT_FALSE(device_->enabled_);
910 EXPECT_FALSE(device_->enabled_pending_);
911 device_->enabled_persistent_ = false;
912 StrictMock<MockManager> manager(control_interface(),
913 dispatcher(),
914 metrics());
915 EXPECT_CALL(manager, UpdateDevice(_));
916 SetManager(&manager);
917 Error error;
918 device_->SetEnabledPersistent(true, &error, ResultCallback());
919 EXPECT_TRUE(device_->enabled_persistent_);
920 EXPECT_TRUE(device_->enabled_pending_);
921
922 // Enable while already enabled.
923 error.Populate(Error::kOperationInitiated);
924 device_->enabled_persistent_ = false;
925 device_->enabled_pending_ = true;
926 device_->enabled_ = true;
927 device_->SetEnabledPersistent(true, &error, ResultCallback());
928 EXPECT_FALSE(device_->enabled_persistent_);
929 EXPECT_TRUE(device_->enabled_pending_);
930 EXPECT_TRUE(device_->enabled_);
931 EXPECT_TRUE(error.IsSuccess());
932
933 // Enable while enabled but disabling.
934 error.Populate(Error::kOperationInitiated);
935 device_->enabled_pending_ = false;
936 device_->SetEnabledPersistent(true, &error, ResultCallback());
937 EXPECT_FALSE(device_->enabled_persistent_);
938 EXPECT_FALSE(device_->enabled_pending_);
939 EXPECT_TRUE(device_->enabled_);
940 EXPECT_EQ(Error::kOperationFailed, error.type());
941
942 // Disable while already disabled.
943 error.Populate(Error::kOperationInitiated);
944 device_->enabled_ = false;
945 device_->SetEnabledPersistent(false, &error, ResultCallback());
946 EXPECT_FALSE(device_->enabled_persistent_);
947 EXPECT_FALSE(device_->enabled_pending_);
948 EXPECT_FALSE(device_->enabled_);
949 EXPECT_TRUE(error.IsSuccess());
950
951 // Disable while already enabling.
952 error.Populate(Error::kOperationInitiated);
953 device_->enabled_pending_ = true;
954 device_->SetEnabledPersistent(false, &error, ResultCallback());
955 EXPECT_FALSE(device_->enabled_persistent_);
956 EXPECT_TRUE(device_->enabled_pending_);
957 EXPECT_FALSE(device_->enabled_);
958 EXPECT_EQ(Error::kOperationFailed, error.type());
959 }
960
TEST_F(DeviceTest,Start)961 TEST_F(DeviceTest, Start) {
962 EXPECT_FALSE(device_->running_);
963 EXPECT_FALSE(device_->enabled_);
964 EXPECT_FALSE(device_->enabled_pending_);
965 device_->SetEnabled(true);
966 EXPECT_TRUE(device_->running_);
967 EXPECT_TRUE(device_->enabled_pending_);
968 device_->OnEnabledStateChanged(ResultCallback(),
969 Error(Error::kOperationFailed));
970 EXPECT_FALSE(device_->enabled_pending_);
971 }
972
TEST_F(DeviceTest,Stop)973 TEST_F(DeviceTest, Stop) {
974 device_->enabled_ = true;
975 device_->enabled_pending_ = true;
976 device_->ipconfig_ = new IPConfig(&control_interface_, kDeviceName);
977 scoped_refptr<MockService> service(
978 new NiceMock<MockService>(&control_interface_,
979 dispatcher(),
980 metrics(),
981 manager()));
982 SelectService(service);
983
984 EXPECT_CALL(*service, state()).
985 WillRepeatedly(Return(Service::kStateConnected));
986 EXPECT_CALL(*GetDeviceMockAdaptor(),
987 EmitBoolChanged(kPoweredProperty, false));
988 EXPECT_CALL(rtnl_handler_, SetInterfaceFlags(_, 0, IFF_UP));
989 device_->SetEnabled(false);
990 device_->OnEnabledStateChanged(ResultCallback(), Error());
991
992 EXPECT_FALSE(device_->ipconfig_.get());
993 EXPECT_FALSE(device_->selected_service_.get());
994 }
995
TEST_F(DeviceTest,StartProhibited)996 TEST_F(DeviceTest, StartProhibited) {
997 DeviceRefPtr device(new TestDevice(control_interface(),
998 dispatcher(),
999 nullptr,
1000 manager(),
1001 kDeviceName,
1002 kDeviceAddress,
1003 kDeviceInterfaceIndex,
1004 Technology::kWifi));
1005 {
1006 Error error;
1007 manager()->SetProhibitedTechnologies("wifi", &error);
1008 EXPECT_TRUE(error.IsSuccess());
1009 }
1010
1011 device->SetEnabled(true);
1012 EXPECT_FALSE(device->running());
1013
1014 {
1015 Error error;
1016 manager()->SetProhibitedTechnologies("", &error);
1017 EXPECT_TRUE(error.IsSuccess());
1018 }
1019 device->SetEnabled(true);
1020 EXPECT_TRUE(device->running());
1021 }
1022
TEST_F(DeviceTest,Reset)1023 TEST_F(DeviceTest, Reset) {
1024 Error e;
1025 device_->Reset(&e, ResultCallback());
1026 EXPECT_EQ(Error::kNotSupported, e.type());
1027 EXPECT_EQ("Device doesn't support Reset.", e.message());
1028 }
1029
TEST_F(DeviceTest,ResumeWithIPConfig)1030 TEST_F(DeviceTest, ResumeWithIPConfig) {
1031 scoped_refptr<MockIPConfig> ipconfig =
1032 new MockIPConfig(control_interface(), kDeviceName);
1033 device_->set_ipconfig(ipconfig);
1034 EXPECT_CALL(*ipconfig, RenewIP());
1035 device_->OnAfterResume();
1036 }
1037
TEST_F(DeviceTest,ResumeWithoutIPConfig)1038 TEST_F(DeviceTest, ResumeWithoutIPConfig) {
1039 // Just test that we don't crash in this case.
1040 ASSERT_EQ(nullptr, device_->ipconfig().get());
1041 device_->OnAfterResume();
1042 }
1043
TEST_F(DeviceTest,ResumeWithLinkMonitor)1044 TEST_F(DeviceTest, ResumeWithLinkMonitor) {
1045 MockLinkMonitor* link_monitor = new StrictMock<MockLinkMonitor>();
1046 SetLinkMonitor(link_monitor); // Passes ownership.
1047 EXPECT_CALL(*link_monitor, OnAfterResume());
1048 device_->OnAfterResume();
1049 }
1050
TEST_F(DeviceTest,ResumeWithoutLinkMonitor)1051 TEST_F(DeviceTest, ResumeWithoutLinkMonitor) {
1052 // Just test that we don't crash in this case.
1053 EXPECT_FALSE(HasLinkMonitor());
1054 device_->OnAfterResume();
1055 }
1056
TEST_F(DeviceTest,ResumeWithUnreliableLink)1057 TEST_F(DeviceTest, ResumeWithUnreliableLink) {
1058 scoped_refptr<MockService> service(
1059 new StrictMock<MockService>(control_interface(),
1060 dispatcher(),
1061 metrics(),
1062 manager()));
1063 SelectService(service);
1064 service->set_unreliable(true);
1065 SetReliableLinkCallback();
1066
1067 // Link status should be resetted upon resume.
1068 device_->OnAfterResume();
1069 EXPECT_FALSE(service->unreliable());
1070 EXPECT_TRUE(ReliableLinkCallbackIsCancelled());
1071 }
1072
TEST_F(DeviceTest,OnConnected)1073 TEST_F(DeviceTest, OnConnected) {
1074 scoped_refptr<MockService> service(
1075 new StrictMock<MockService>(control_interface(),
1076 dispatcher(),
1077 metrics(),
1078 manager()));
1079 SelectService(service);
1080
1081 // Link is reliable, no need to post delayed task to reset link status.
1082 device_->OnConnected();
1083 EXPECT_TRUE(ReliableLinkCallbackIsCancelled());
1084
1085 // Link is unreliable when connected, delayed task is posted to reset the
1086 // link state.
1087 service->set_unreliable(true);
1088 device_->OnConnected();
1089 EXPECT_FALSE(ReliableLinkCallbackIsCancelled());
1090 }
1091
TEST_F(DeviceTest,LinkMonitor)1092 TEST_F(DeviceTest, LinkMonitor) {
1093 scoped_refptr<MockConnection> connection(
1094 new StrictMock<MockConnection>(&device_info_));
1095 MockManager manager(control_interface(),
1096 dispatcher(),
1097 metrics());
1098 scoped_refptr<MockService> service(
1099 new StrictMock<MockService>(control_interface(),
1100 dispatcher(),
1101 metrics(),
1102 &manager));
1103 SelectService(service);
1104 SetConnection(connection.get());
1105 MockLinkMonitor* link_monitor = new StrictMock<MockLinkMonitor>();
1106 SetLinkMonitor(link_monitor); // Passes ownership.
1107 SetManager(&manager);
1108 EXPECT_CALL(*link_monitor, Start()).Times(0);
1109 EXPECT_CALL(manager, IsTechnologyLinkMonitorEnabled(Technology::kUnknown))
1110 .WillOnce(Return(false))
1111 .WillRepeatedly(Return(true));
1112 EXPECT_FALSE(StartLinkMonitor());
1113
1114 EXPECT_CALL(*link_monitor, Start()).Times(0);
1115 EXPECT_CALL(*service, link_monitor_disabled())
1116 .WillOnce(Return(true))
1117 .WillRepeatedly(Return(false));
1118 EXPECT_FALSE(StartLinkMonitor());
1119
1120 EXPECT_CALL(*link_monitor, Start())
1121 .WillOnce(Return(false))
1122 .WillOnce(Return(true));
1123 EXPECT_FALSE(StartLinkMonitor());
1124 EXPECT_TRUE(StartLinkMonitor());
1125
1126 unsigned int kResponseTime = 123;
1127 EXPECT_CALL(*link_monitor, GetResponseTimeMilliseconds())
1128 .WillOnce(Return(kResponseTime));
1129 {
1130 Error error;
1131 EXPECT_EQ(kResponseTime, GetLinkMonitorResponseTime(&error));
1132 EXPECT_TRUE(error.IsSuccess());
1133 }
1134 StopLinkMonitor();
1135 {
1136 Error error;
1137 EXPECT_EQ(0, GetLinkMonitorResponseTime(&error));
1138 EXPECT_FALSE(error.IsSuccess());
1139 }
1140 }
1141
TEST_F(DeviceTest,LinkMonitorCancelledOnSelectService)1142 TEST_F(DeviceTest, LinkMonitorCancelledOnSelectService) {
1143 scoped_refptr<MockConnection> connection(
1144 new StrictMock<MockConnection>(&device_info_));
1145 MockManager manager(control_interface(),
1146 dispatcher(),
1147 metrics());
1148 scoped_refptr<MockService> service(
1149 new StrictMock<MockService>(control_interface(),
1150 dispatcher(),
1151 metrics(),
1152 &manager));
1153 SelectService(service);
1154 SetConnection(connection.get());
1155 MockLinkMonitor* link_monitor = new StrictMock<MockLinkMonitor>();
1156 SetLinkMonitor(link_monitor); // Passes ownership.
1157 SetManager(&manager);
1158 EXPECT_CALL(*service, state())
1159 .WillOnce(Return(Service::kStateIdle));
1160 EXPECT_CALL(*service, SetState(_));
1161 EXPECT_CALL(*service, SetConnection(_));
1162 EXPECT_TRUE(HasLinkMonitor());
1163 SelectService(nullptr);
1164 EXPECT_FALSE(HasLinkMonitor());
1165 }
1166
TEST_F(DeviceTest,TrafficMonitor)1167 TEST_F(DeviceTest, TrafficMonitor) {
1168 scoped_refptr<MockConnection> connection(
1169 new StrictMock<MockConnection>(&device_info_));
1170 MockManager manager(control_interface(),
1171 dispatcher(),
1172 metrics());
1173 scoped_refptr<MockService> service(
1174 new StrictMock<MockService>(control_interface(),
1175 dispatcher(),
1176 metrics(),
1177 &manager));
1178 SelectService(service);
1179 SetConnection(connection.get());
1180 MockTrafficMonitor* traffic_monitor = new StrictMock<MockTrafficMonitor>();
1181 SetTrafficMonitor(traffic_monitor); // Passes ownership.
1182 SetManager(&manager);
1183
1184 EXPECT_CALL(*device_, IsTrafficMonitorEnabled()).WillRepeatedly(Return(true));
1185 EXPECT_CALL(*traffic_monitor, Start());
1186 StartTrafficMonitor();
1187 EXPECT_CALL(*traffic_monitor, Stop());
1188 StopTrafficMonitor();
1189 Mock::VerifyAndClearExpectations(traffic_monitor);
1190
1191 EXPECT_CALL(metrics_, NotifyNetworkProblemDetected(_,
1192 Metrics::kNetworkProblemDNSFailure)).Times(1);
1193 NetworkProblemDetected(TrafficMonitor::kNetworkProblemDNSFailure);
1194
1195 // Verify traffic monitor not running when it is disabled.
1196 traffic_monitor = new StrictMock<MockTrafficMonitor>();
1197 SetTrafficMonitor(traffic_monitor);
1198 EXPECT_CALL(*device_, IsTrafficMonitorEnabled())
1199 .WillRepeatedly(Return(false));
1200 EXPECT_CALL(*traffic_monitor, Start()).Times(0);
1201 StartTrafficMonitor();
1202 EXPECT_CALL(*traffic_monitor, Stop()).Times(0);
1203 StopTrafficMonitor();
1204 }
1205
TEST_F(DeviceTest,TrafficMonitorCancelledOnSelectService)1206 TEST_F(DeviceTest, TrafficMonitorCancelledOnSelectService) {
1207 scoped_refptr<MockConnection> connection(
1208 new StrictMock<MockConnection>(&device_info_));
1209 MockManager manager(control_interface(),
1210 dispatcher(),
1211 metrics());
1212 scoped_refptr<MockService> service(
1213 new StrictMock<MockService>(control_interface(),
1214 dispatcher(),
1215 metrics(),
1216 &manager));
1217 SelectService(service);
1218 SetConnection(connection.get());
1219 MockTrafficMonitor* traffic_monitor = new StrictMock<MockTrafficMonitor>();
1220 SetTrafficMonitor(traffic_monitor); // Passes ownership.
1221 EXPECT_CALL(*device_, IsTrafficMonitorEnabled()).WillRepeatedly(Return(true));
1222 SetManager(&manager);
1223 EXPECT_CALL(*service, state())
1224 .WillOnce(Return(Service::kStateIdle));
1225 EXPECT_CALL(*service, SetState(_));
1226 EXPECT_CALL(*service, SetConnection(_));
1227 EXPECT_CALL(*traffic_monitor, Stop());
1228 SelectService(nullptr);
1229 }
1230
TEST_F(DeviceTest,ShouldUseArpGateway)1231 TEST_F(DeviceTest, ShouldUseArpGateway) {
1232 EXPECT_FALSE(device_->ShouldUseArpGateway());
1233 }
1234
TEST_F(DeviceTest,PerformTDLSOperation)1235 TEST_F(DeviceTest, PerformTDLSOperation) {
1236 EXPECT_EQ(
1237 "", device_->PerformTDLSOperation("do something", "to someone", nullptr));
1238 }
1239
TEST_F(DeviceTest,IsConnectedViaTether)1240 TEST_F(DeviceTest, IsConnectedViaTether) {
1241 EXPECT_FALSE(device_->IsConnectedViaTether());
1242
1243 // An empty ipconfig doesn't mean we're tethered.
1244 device_->ipconfig_ = new IPConfig(control_interface(), kDeviceName);
1245 EXPECT_FALSE(device_->IsConnectedViaTether());
1246
1247 // Add an ipconfig property that indicates this is an Android tether.
1248 IPConfig::Properties properties;
1249 properties.vendor_encapsulated_options = ByteArray(
1250 Tethering::kAndroidVendorEncapsulatedOptions,
1251 Tethering::kAndroidVendorEncapsulatedOptions +
1252 strlen(Tethering::kAndroidVendorEncapsulatedOptions)
1253 );
1254 device_->ipconfig_->UpdateProperties(properties, true);
1255 EXPECT_TRUE(device_->IsConnectedViaTether());
1256
1257 const char kTestVendorEncapsulatedOptions[] = "Some other non-empty value";
1258 properties.vendor_encapsulated_options = ByteArray(
1259 kTestVendorEncapsulatedOptions,
1260 kTestVendorEncapsulatedOptions + sizeof(kTestVendorEncapsulatedOptions)
1261 );
1262 device_->ipconfig_->UpdateProperties(properties, true);
1263 EXPECT_FALSE(device_->IsConnectedViaTether());
1264 }
1265
TEST_F(DeviceTest,AvailableIPConfigs)1266 TEST_F(DeviceTest, AvailableIPConfigs) {
1267 EXPECT_EQ(vector<string>(), device_->AvailableIPConfigs(nullptr));
1268 device_->ipconfig_ = new IPConfig(control_interface(), kDeviceName);
1269 EXPECT_EQ(vector<string> { IPConfigMockAdaptor::kRpcId },
1270 device_->AvailableIPConfigs(nullptr));
1271 device_->ip6config_ = new IPConfig(control_interface(), kDeviceName);
1272
1273 // We don't really care that the RPC IDs for all IPConfig mock adaptors
1274 // are the same, or their ordering. We just need to see that there are two
1275 // of them when both IPv6 and IPv4 IPConfigs are available.
1276 EXPECT_EQ(2, device_->AvailableIPConfigs(nullptr).size());
1277
1278 device_->dhcpv6_config_ = new IPConfig(control_interface(), kDeviceName);
1279 EXPECT_EQ(3, device_->AvailableIPConfigs(nullptr).size());
1280
1281 device_->dhcpv6_config_ = nullptr;
1282 EXPECT_EQ(2, device_->AvailableIPConfigs(nullptr).size());
1283
1284 device_->ipconfig_ = nullptr;
1285 EXPECT_EQ(vector<string> { IPConfigMockAdaptor::kRpcId },
1286 device_->AvailableIPConfigs(nullptr));
1287
1288 device_->ip6config_ = nullptr;
1289 EXPECT_EQ(vector<string>(), device_->AvailableIPConfigs(nullptr));
1290 }
1291
TEST_F(DeviceTest,OnIPv6AddressChanged)1292 TEST_F(DeviceTest, OnIPv6AddressChanged) {
1293 StrictMock<MockManager> manager(control_interface(),
1294 dispatcher(),
1295 metrics());
1296 manager.set_mock_device_info(&device_info_);
1297 EXPECT_CALL(manager, FilterPrependDNSServersByFamily(_))
1298 .WillRepeatedly(Return(vector<string>()));
1299 SetManager(&manager);
1300
1301 // An IPv6 clear while ip6config_ is nullptr will not emit a change.
1302 EXPECT_CALL(device_info_, GetPrimaryIPv6Address(kDeviceInterfaceIndex, _))
1303 .WillOnce(Return(false));
1304 EXPECT_CALL(*GetDeviceMockAdaptor(),
1305 EmitRpcIdentifierArrayChanged(kIPConfigsProperty, _)).Times(0);
1306 device_->OnIPv6AddressChanged();
1307 EXPECT_THAT(device_->ip6config_, IsNullRefPtr());
1308 Mock::VerifyAndClearExpectations(GetDeviceMockAdaptor());
1309 Mock::VerifyAndClearExpectations(&device_info_);
1310
1311 IPAddress address0(IPAddress::kFamilyIPv6);
1312 const char kAddress0[] = "fe80::1aa9:5ff:abcd:1234";
1313 ASSERT_TRUE(address0.SetAddressFromString(kAddress0));
1314
1315 // Add an IPv6 address while ip6config_ is nullptr.
1316 EXPECT_CALL(device_info_, GetPrimaryIPv6Address(kDeviceInterfaceIndex, _))
1317 .WillOnce(DoAll(SetArgPointee<1>(address0), Return(true)));
1318 EXPECT_CALL(*GetDeviceMockAdaptor(),
1319 EmitRpcIdentifierArrayChanged(
1320 kIPConfigsProperty,
1321 vector<string> { IPConfigMockAdaptor::kRpcId }));
1322 device_->OnIPv6AddressChanged();
1323 EXPECT_THAT(device_->ip6config_, NotNullRefPtr());
1324 EXPECT_EQ(kAddress0, device_->ip6config_->properties().address);
1325 Mock::VerifyAndClearExpectations(GetDeviceMockAdaptor());
1326 Mock::VerifyAndClearExpectations(&device_info_);
1327
1328 // If the IPv6 address does not change, no signal is emitted.
1329 EXPECT_CALL(device_info_, GetPrimaryIPv6Address(kDeviceInterfaceIndex, _))
1330 .WillOnce(DoAll(SetArgPointee<1>(address0), Return(true)));
1331 EXPECT_CALL(*GetDeviceMockAdaptor(),
1332 EmitRpcIdentifierArrayChanged(kIPConfigsProperty, _)).Times(0);
1333 device_->OnIPv6AddressChanged();
1334 EXPECT_EQ(kAddress0, device_->ip6config_->properties().address);
1335 Mock::VerifyAndClearExpectations(GetDeviceMockAdaptor());
1336 Mock::VerifyAndClearExpectations(&device_info_);
1337
1338 IPAddress address1(IPAddress::kFamilyIPv6);
1339 const char kAddress1[] = "fe80::1aa9:5ff:abcd:5678";
1340 ASSERT_TRUE(address1.SetAddressFromString(kAddress1));
1341
1342 // If the IPv6 address changes, a signal is emitted.
1343 EXPECT_CALL(device_info_, GetPrimaryIPv6Address(kDeviceInterfaceIndex, _))
1344 .WillOnce(DoAll(SetArgPointee<1>(address1), Return(true)));
1345 EXPECT_CALL(*GetDeviceMockAdaptor(),
1346 EmitRpcIdentifierArrayChanged(
1347 kIPConfigsProperty,
1348 vector<string> { IPConfigMockAdaptor::kRpcId }));
1349 device_->OnIPv6AddressChanged();
1350 EXPECT_EQ(kAddress1, device_->ip6config_->properties().address);
1351 Mock::VerifyAndClearExpectations(GetDeviceMockAdaptor());
1352 Mock::VerifyAndClearExpectations(&device_info_);
1353
1354 // If the IPv6 prefix changes, a signal is emitted.
1355 address1.set_prefix(64);
1356 EXPECT_CALL(device_info_, GetPrimaryIPv6Address(kDeviceInterfaceIndex, _))
1357 .WillOnce(DoAll(SetArgPointee<1>(address1), Return(true)));
1358 EXPECT_CALL(*GetDeviceMockAdaptor(),
1359 EmitRpcIdentifierArrayChanged(
1360 kIPConfigsProperty,
1361 vector<string> { IPConfigMockAdaptor::kRpcId }));
1362 device_->OnIPv6AddressChanged();
1363 EXPECT_EQ(kAddress1, device_->ip6config_->properties().address);
1364
1365 // Return the IPv6 address to nullptr.
1366 EXPECT_CALL(device_info_, GetPrimaryIPv6Address(kDeviceInterfaceIndex, _))
1367 .WillOnce(Return(false));
1368 EXPECT_CALL(*GetDeviceMockAdaptor(),
1369 EmitRpcIdentifierArrayChanged(kIPConfigsProperty,
1370 vector<string>()));
1371 device_->OnIPv6AddressChanged();
1372 EXPECT_THAT(device_->ip6config_, IsNullRefPtr());
1373 Mock::VerifyAndClearExpectations(GetDeviceMockAdaptor());
1374 Mock::VerifyAndClearExpectations(&device_info_);
1375 }
1376
TEST_F(DeviceTest,OnIPv6DnsServerAddressesChanged_LeaseExpirationUpdated)1377 TEST_F(DeviceTest, OnIPv6DnsServerAddressesChanged_LeaseExpirationUpdated) {
1378 MockManager manager(control_interface(),
1379 dispatcher(),
1380 metrics());
1381 manager.set_mock_device_info(&device_info_);
1382 EXPECT_CALL(manager, FilterPrependDNSServersByFamily(_))
1383 .WillRepeatedly(Return(vector<string>()));
1384 SetManager(&manager);
1385
1386 scoped_refptr<MockIPConfig> ip6config =
1387 new MockIPConfig(control_interface(), kDeviceName);
1388 device_->ip6config_ = ip6config;
1389
1390 // Non-infinite lifetime should trigger an update of the current lease
1391 // expiration time.
1392 const uint32_t kExpiredLifetime = 1;
1393 EXPECT_CALL(device_info_,
1394 GetIPv6DnsServerAddresses(kDeviceInterfaceIndex, _, _))
1395 .WillOnce(DoAll(SetArgPointee<2>(kExpiredLifetime),
1396 Return(true)));
1397 EXPECT_CALL(*ip6config, UpdateLeaseExpirationTime(_)).Times(1);
1398 EXPECT_CALL(*ip6config, ResetLeaseExpirationTime()).Times(0);
1399 device_->OnIPv6DnsServerAddressesChanged();
1400
1401 // Infinite lifetime should cause a reset of the current lease expiration
1402 // time to its default value.
1403 const uint32_t kExpiredLifetimeInfinity = ND_OPT_LIFETIME_INFINITY;
1404 EXPECT_CALL(device_info_,
1405 GetIPv6DnsServerAddresses(kDeviceInterfaceIndex, _, _))
1406 .WillOnce(DoAll(SetArgPointee<2>(kExpiredLifetimeInfinity),
1407 Return(true)));
1408 EXPECT_CALL(*ip6config, UpdateLeaseExpirationTime(_)).Times(0);
1409 EXPECT_CALL(*ip6config, ResetLeaseExpirationTime()).Times(1);
1410 device_->OnIPv6DnsServerAddressesChanged();
1411 }
1412
TEST_F(DeviceTest,OnIPv6DnsServerAddressesChanged)1413 TEST_F(DeviceTest, OnIPv6DnsServerAddressesChanged) {
1414 StrictMock<MockManager> manager(control_interface(),
1415 dispatcher(),
1416 metrics());
1417 manager.set_mock_device_info(&device_info_);
1418 EXPECT_CALL(manager, FilterPrependDNSServersByFamily(_))
1419 .WillRepeatedly(Return(vector<string>()));
1420 SetManager(&manager);
1421
1422 // With existing IPv4 connection, so no attempt to setup IPv6 connection.
1423 // IPv6 connection is being tested in OnIPv6ConfigurationCompleted test.
1424 scoped_refptr<MockConnection> connection(
1425 new StrictMock<MockConnection>(&device_info_));
1426 SetConnection(connection.get());
1427 EXPECT_CALL(*connection, IsIPv6())
1428 .WillRepeatedly(Return(false));
1429
1430 // IPv6 DNS server addresses are not provided will not emit a change.
1431 EXPECT_CALL(device_info_,
1432 GetIPv6DnsServerAddresses(kDeviceInterfaceIndex, _, _))
1433 .WillOnce(Return(false));
1434 EXPECT_CALL(*GetDeviceMockAdaptor(),
1435 EmitRpcIdentifierArrayChanged(kIPConfigsProperty, _)).Times(0);
1436 device_->OnIPv6DnsServerAddressesChanged();
1437 EXPECT_THAT(device_->ip6config_, IsNullRefPtr());
1438 Mock::VerifyAndClearExpectations(GetDeviceMockAdaptor());
1439 Mock::VerifyAndClearExpectations(&device_info_);
1440
1441 const char kAddress1[] = "fe80::1aa9:5ff:abcd:1234";
1442 const char kAddress2[] = "fe80::1aa9:5ff:abcd:1235";
1443 const uint32_t kInfiniteLifetime = 0xffffffff;
1444 IPAddress ipv6_address1(IPAddress::kFamilyIPv6);
1445 IPAddress ipv6_address2(IPAddress::kFamilyIPv6);
1446 ASSERT_TRUE(ipv6_address1.SetAddressFromString(kAddress1));
1447 ASSERT_TRUE(ipv6_address2.SetAddressFromString(kAddress2));
1448 vector<IPAddress> dns_server_addresses;
1449 dns_server_addresses.push_back(ipv6_address1);
1450 dns_server_addresses.push_back(ipv6_address2);
1451 vector<string> dns_server_addresses_str;
1452 dns_server_addresses_str.push_back(kAddress1);
1453 dns_server_addresses_str.push_back(kAddress2);
1454
1455 // Add IPv6 DNS server addresses while ip6config_ is nullptr.
1456 EXPECT_CALL(device_info_,
1457 GetIPv6DnsServerAddresses(kDeviceInterfaceIndex, _, _))
1458 .WillOnce(DoAll(SetArgPointee<1>(dns_server_addresses),
1459 SetArgPointee<2>(kInfiniteLifetime),
1460 Return(true)));
1461 EXPECT_CALL(*GetDeviceMockAdaptor(),
1462 EmitRpcIdentifierArrayChanged(
1463 kIPConfigsProperty,
1464 vector<string> { IPConfigMockAdaptor::kRpcId }));
1465 device_->OnIPv6DnsServerAddressesChanged();
1466 EXPECT_THAT(device_->ip6config_, NotNullRefPtr());
1467 EXPECT_EQ(dns_server_addresses_str,
1468 device_->ip6config_->properties().dns_servers);
1469 Mock::VerifyAndClearExpectations(GetDeviceMockAdaptor());
1470 Mock::VerifyAndClearExpectations(&device_info_);
1471
1472 // Add an IPv6 address while IPv6 DNS server addresses already existed.
1473 IPAddress address3(IPAddress::kFamilyIPv6);
1474 const char kAddress3[] = "fe80::1aa9:5ff:abcd:1236";
1475 ASSERT_TRUE(address3.SetAddressFromString(kAddress3));
1476 EXPECT_CALL(device_info_, GetPrimaryIPv6Address(kDeviceInterfaceIndex, _))
1477 .WillOnce(DoAll(SetArgPointee<1>(address3), Return(true)));
1478 EXPECT_CALL(*GetDeviceMockAdaptor(),
1479 EmitRpcIdentifierArrayChanged(
1480 kIPConfigsProperty,
1481 vector<string> { IPConfigMockAdaptor::kRpcId }));
1482 device_->OnIPv6AddressChanged();
1483 EXPECT_THAT(device_->ip6config_, NotNullRefPtr());
1484 EXPECT_EQ(kAddress3, device_->ip6config_->properties().address);
1485 EXPECT_EQ(dns_server_addresses_str,
1486 device_->ip6config_->properties().dns_servers);
1487 Mock::VerifyAndClearExpectations(GetDeviceMockAdaptor());
1488 Mock::VerifyAndClearExpectations(&device_info_);
1489
1490 // If the IPv6 DNS server addresses does not change, no signal is emitted.
1491 EXPECT_CALL(device_info_,
1492 GetIPv6DnsServerAddresses(kDeviceInterfaceIndex, _, _))
1493 .WillOnce(DoAll(SetArgPointee<1>(dns_server_addresses),
1494 SetArgPointee<2>(kInfiniteLifetime),
1495 Return(true)));
1496 EXPECT_CALL(*GetDeviceMockAdaptor(),
1497 EmitRpcIdentifierArrayChanged(kIPConfigsProperty, _)).Times(0);
1498 device_->OnIPv6DnsServerAddressesChanged();
1499 EXPECT_EQ(dns_server_addresses_str,
1500 device_->ip6config_->properties().dns_servers);
1501 Mock::VerifyAndClearExpectations(GetDeviceMockAdaptor());
1502 Mock::VerifyAndClearExpectations(&device_info_);
1503
1504 // Setting lifetime to 0 should expire and clear out the DNS server.
1505 const uint32_t kExpiredLifetime = 0;
1506 vector<string> empty_dns_server;
1507 EXPECT_CALL(device_info_,
1508 GetIPv6DnsServerAddresses(kDeviceInterfaceIndex, _, _))
1509 .WillOnce(DoAll(SetArgPointee<1>(dns_server_addresses),
1510 SetArgPointee<2>(kExpiredLifetime),
1511 Return(true)));
1512 EXPECT_CALL(*GetDeviceMockAdaptor(),
1513 EmitRpcIdentifierArrayChanged(
1514 kIPConfigsProperty,
1515 vector<string> { IPConfigMockAdaptor::kRpcId }));
1516 device_->OnIPv6DnsServerAddressesChanged();
1517 EXPECT_EQ(empty_dns_server, device_->ip6config_->properties().dns_servers);
1518 Mock::VerifyAndClearExpectations(GetDeviceMockAdaptor());
1519 Mock::VerifyAndClearExpectations(&device_info_);
1520
1521 // Set DNS server with lifetime of 1 hour.
1522 const uint32_t kLifetimeOneHr = 3600;
1523 EXPECT_CALL(device_info_,
1524 GetIPv6DnsServerAddresses(kDeviceInterfaceIndex, _, _))
1525 .WillOnce(DoAll(SetArgPointee<1>(dns_server_addresses),
1526 SetArgPointee<2>(kLifetimeOneHr),
1527 Return(true)));
1528 EXPECT_CALL(*GetDeviceMockAdaptor(),
1529 EmitRpcIdentifierArrayChanged(
1530 kIPConfigsProperty,
1531 vector<string> { IPConfigMockAdaptor::kRpcId }));
1532 device_->OnIPv6DnsServerAddressesChanged();
1533 EXPECT_EQ(dns_server_addresses_str,
1534 device_->ip6config_->properties().dns_servers);
1535 Mock::VerifyAndClearExpectations(GetDeviceMockAdaptor());
1536 Mock::VerifyAndClearExpectations(&device_info_);
1537
1538 // Return the DNS server addresses to nullptr.
1539 EXPECT_CALL(device_info_,
1540 GetIPv6DnsServerAddresses(kDeviceInterfaceIndex, _, _))
1541 .WillOnce(Return(false));
1542 EXPECT_CALL(*GetDeviceMockAdaptor(),
1543 EmitRpcIdentifierArrayChanged(
1544 kIPConfigsProperty,
1545 vector<string> { IPConfigMockAdaptor::kRpcId }));
1546 device_->OnIPv6DnsServerAddressesChanged();
1547 EXPECT_EQ(empty_dns_server, device_->ip6config_->properties().dns_servers);
1548 Mock::VerifyAndClearExpectations(GetDeviceMockAdaptor());
1549 Mock::VerifyAndClearExpectations(&device_info_);
1550 }
1551
TEST_F(DeviceTest,OnIPv6ConfigurationCompleted)1552 TEST_F(DeviceTest, OnIPv6ConfigurationCompleted) {
1553 StrictMock<MockManager> manager(control_interface(),
1554 dispatcher(),
1555 metrics());
1556 manager.set_mock_device_info(&device_info_);
1557 EXPECT_CALL(manager, FilterPrependDNSServersByFamily(_))
1558 .WillRepeatedly(Return(vector<string>()));
1559 SetManager(&manager);
1560 scoped_refptr<MockService> service(
1561 new StrictMock<MockService>(control_interface(),
1562 dispatcher(),
1563 metrics(),
1564 &manager));
1565 SelectService(service);
1566 scoped_refptr<MockConnection> connection(
1567 new StrictMock<MockConnection>(&device_info_));
1568 SetConnection(connection.get());
1569
1570 // Setup initial IPv6 configuration.
1571 SetupIPv6Config();
1572 EXPECT_THAT(device_->ip6config_, NotNullRefPtr());
1573
1574 // IPv6 configuration update with non-IPv6 connection, no connection update.
1575 EXPECT_THAT(device_->connection(), NotNullRefPtr());
1576 IPAddress address1(IPAddress::kFamilyIPv6);
1577 const char kAddress1[] = "fe80::1aa9:5ff:abcd:1231";
1578 ASSERT_TRUE(address1.SetAddressFromString(kAddress1));
1579 EXPECT_CALL(device_info_, GetPrimaryIPv6Address(kDeviceInterfaceIndex, _))
1580 .WillOnce(DoAll(SetArgPointee<1>(address1), Return(true)));
1581 EXPECT_CALL(*GetDeviceMockAdaptor(),
1582 EmitRpcIdentifierArrayChanged(
1583 kIPConfigsProperty,
1584 vector<string> { IPConfigMockAdaptor::kRpcId }));
1585 EXPECT_CALL(*connection, IsIPv6())
1586 .WillRepeatedly(Return(false));
1587 EXPECT_CALL(*service, SetConnection(_)).Times(0);
1588 device_->OnIPv6AddressChanged();
1589 Mock::VerifyAndClearExpectations(GetDeviceMockAdaptor());
1590 Mock::VerifyAndClearExpectations(&device_info_);
1591 Mock::VerifyAndClearExpectations(service.get());
1592 Mock::VerifyAndClearExpectations(connection.get());
1593
1594 // IPv6 configuration update with IPv6 connection, connection update.
1595 IPAddress address2(IPAddress::kFamilyIPv6);
1596 const char kAddress2[] = "fe80::1aa9:5ff:abcd:1232";
1597 ASSERT_TRUE(address2.SetAddressFromString(kAddress2));
1598 EXPECT_CALL(device_info_, GetPrimaryIPv6Address(kDeviceInterfaceIndex, _))
1599 .WillOnce(DoAll(SetArgPointee<1>(address2), Return(true)));
1600 EXPECT_CALL(*GetDeviceMockAdaptor(),
1601 EmitRpcIdentifierArrayChanged(
1602 kIPConfigsProperty,
1603 vector<string> { IPConfigMockAdaptor::kRpcId }));
1604 EXPECT_CALL(*connection, IsIPv6())
1605 .WillRepeatedly(Return(true));
1606 EXPECT_CALL(*connection, UpdateFromIPConfig(device_->ip6config_));
1607 EXPECT_CALL(metrics_,
1608 NotifyNetworkConnectionIPType(
1609 device_->technology(),
1610 Metrics::kNetworkConnectionIPTypeIPv6));
1611 EXPECT_CALL(metrics_,
1612 NotifyIPv6ConnectivityStatus(device_->technology(), true));
1613 EXPECT_CALL(*service, SetState(Service::kStateConnected));
1614 EXPECT_CALL(*service, IsConnected())
1615 .WillRepeatedly(Return(true));
1616 EXPECT_CALL(*service, IsPortalDetectionDisabled())
1617 .WillRepeatedly(Return(true));
1618 EXPECT_CALL(*service, SetState(Service::kStateOnline));
1619 EXPECT_CALL(*service, SetConnection(NotNullRefPtr()));
1620 EXPECT_CALL(manager, IsTechnologyLinkMonitorEnabled(_))
1621 .WillRepeatedly(Return(false));
1622 device_->OnIPv6AddressChanged();
1623 Mock::VerifyAndClearExpectations(GetDeviceMockAdaptor());
1624 Mock::VerifyAndClearExpectations(&device_info_);
1625 Mock::VerifyAndClearExpectations(service.get());
1626 Mock::VerifyAndClearExpectations(connection.get());
1627 }
1628
TEST_F(DeviceTest,OnDHCPv6ConfigUpdated)1629 TEST_F(DeviceTest, OnDHCPv6ConfigUpdated) {
1630 device_->dhcpv6_config_ = new IPConfig(control_interface(), kDeviceName);
1631 EXPECT_CALL(*GetDeviceMockAdaptor(),
1632 EmitRpcIdentifierArrayChanged(
1633 kIPConfigsProperty,
1634 vector<string> { IPConfigMockAdaptor::kRpcId }));
1635 device_->OnDHCPv6ConfigUpdated(device_->dhcpv6_config_.get(), true);
1636 }
1637
TEST_F(DeviceTest,OnDHCPv6ConfigFailed)1638 TEST_F(DeviceTest, OnDHCPv6ConfigFailed) {
1639 device_->dhcpv6_config_ = new IPConfig(control_interface(), kDeviceName);
1640 IPConfig::Properties properties;
1641 properties.address = "2001:db8:0:1::1";
1642 properties.delegated_prefix = "2001:db8:0:100::";
1643 properties.lease_duration_seconds = 1;
1644 device_->dhcpv6_config_->set_properties(properties);
1645 EXPECT_CALL(*GetDeviceMockAdaptor(),
1646 EmitRpcIdentifierArrayChanged(
1647 kIPConfigsProperty,
1648 vector<string> { IPConfigMockAdaptor::kRpcId }));
1649 device_->OnDHCPv6ConfigFailed(device_->dhcpv6_config_.get());
1650 EXPECT_TRUE(device_->dhcpv6_config_->properties().address.empty());
1651 EXPECT_TRUE(device_->dhcpv6_config_->properties().delegated_prefix.empty());
1652 EXPECT_EQ(0, device_->dhcpv6_config_->properties().lease_duration_seconds);
1653 }
1654
TEST_F(DeviceTest,OnDHCPv6ConfigExpired)1655 TEST_F(DeviceTest, OnDHCPv6ConfigExpired) {
1656 device_->dhcpv6_config_ = new IPConfig(control_interface(), kDeviceName);
1657 IPConfig::Properties properties;
1658 properties.address = "2001:db8:0:1::1";
1659 properties.delegated_prefix = "2001:db8:0:100::";
1660 properties.lease_duration_seconds = 1;
1661 device_->dhcpv6_config_->set_properties(properties);
1662 EXPECT_CALL(*GetDeviceMockAdaptor(),
1663 EmitRpcIdentifierArrayChanged(
1664 kIPConfigsProperty,
1665 vector<string> { IPConfigMockAdaptor::kRpcId }));
1666 device_->OnDHCPv6ConfigExpired(device_->dhcpv6_config_.get());
1667 EXPECT_TRUE(device_->dhcpv6_config_->properties().address.empty());
1668 EXPECT_TRUE(device_->dhcpv6_config_->properties().delegated_prefix.empty());
1669 EXPECT_EQ(0, device_->dhcpv6_config_->properties().lease_duration_seconds);
1670 }
1671
TEST_F(DeviceTest,PrependIPv4DNSServers)1672 TEST_F(DeviceTest, PrependIPv4DNSServers) {
1673 MockManager manager(control_interface(), dispatcher(), metrics());
1674 manager.set_mock_device_info(&device_info_);
1675 SetManager(&manager);
1676
1677 const struct {
1678 vector<string> ipconfig_servers;
1679 vector<string> prepend_servers;
1680 vector<string> expected_servers;
1681 } expectations[] = {
1682 {{}, {"8.8.8.8"}, {"8.8.8.8"}},
1683 {{"8.8.8.8"}, {}, {"8.8.8.8"}},
1684 {{"8.8.8.8"}, {"10.10.10.10"}, {"10.10.10.10", "8.8.8.8"}},
1685 {{"8.8.8.8", "10.10.10.10"}, {"10.10.10.10"}, {"10.10.10.10", "8.8.8.8"}},
1686 {{"8.8.8.8", "10.10.10.10"}, {"8.8.8.8"}, {"8.8.8.8", "10.10.10.10"}},
1687 {{"8.8.8.8", "9.9.9.9", "10.10.10.10"}, {"9.9.9.9"},
1688 {"9.9.9.9", "8.8.8.8", "10.10.10.10"}},
1689 };
1690
1691 for (const auto& expectation : expectations) {
1692 scoped_refptr<IPConfig> ipconfig =
1693 new IPConfig(control_interface(), kDeviceName);
1694
1695 EXPECT_CALL(manager, FilterPrependDNSServersByFamily(
1696 IPAddress::kFamilyIPv4)).WillOnce(Return(expectation.prepend_servers));
1697 IPConfig::Properties properties;
1698 properties.dns_servers = expectation.ipconfig_servers;
1699 properties.address_family = IPAddress::kFamilyIPv4;
1700 ipconfig->set_properties(properties);
1701
1702 device_->set_ipconfig(ipconfig);
1703 OnIPConfigUpdated(ipconfig.get());
1704 EXPECT_EQ(expectation.expected_servers,
1705 device_->ipconfig()->properties().dns_servers);
1706 }
1707 }
1708
TEST_F(DeviceTest,PrependIPv6DNSServers)1709 TEST_F(DeviceTest, PrependIPv6DNSServers) {
1710 MockManager manager(control_interface(), dispatcher(), metrics());
1711 manager.set_mock_device_info(&device_info_);
1712 SetManager(&manager);
1713
1714 vector<IPAddress> dns_server_addresses = {
1715 IPAddress("2001:4860:4860::8888"),
1716 IPAddress("2001:4860:4860::8844")
1717 };
1718
1719 const uint32_t kAddressLifetime = 1000;
1720 EXPECT_CALL(device_info_, GetIPv6DnsServerAddresses(_, _, _))
1721 .WillRepeatedly(DoAll(SetArgPointee<1>(dns_server_addresses),
1722 SetArgPointee<2>(kAddressLifetime),
1723 Return(true)));
1724 const vector<string> kOutputServers {"2001:4860:4860::8899"};
1725 EXPECT_CALL(manager, FilterPrependDNSServersByFamily(
1726 IPAddress::kFamilyIPv6)).WillOnce(Return(kOutputServers));
1727 device_->OnIPv6DnsServerAddressesChanged();
1728
1729 const vector<string> kExpectedServers
1730 {"2001:4860:4860::8899", "2001:4860:4860::8888", "2001:4860:4860::8844"};
1731 EXPECT_EQ(kExpectedServers, device_->ip6config()->properties().dns_servers);
1732 }
1733
TEST_F(DeviceTest,PrependWithStaticConfiguration)1734 TEST_F(DeviceTest, PrependWithStaticConfiguration) {
1735 MockManager manager(control_interface(), dispatcher(), metrics());
1736 manager.set_mock_device_info(&device_info_);
1737 SetManager(&manager);
1738
1739 scoped_refptr<IPConfig> ipconfig =
1740 new IPConfig(control_interface(), kDeviceName);
1741
1742 device_->set_ipconfig(ipconfig);
1743
1744 scoped_refptr<MockService> service = new MockService(control_interface(),
1745 dispatcher(),
1746 metrics(),
1747 &manager);
1748 EXPECT_CALL(*service, IsPortalDetectionDisabled())
1749 .WillRepeatedly(Return(true));
1750 SelectService(service);
1751
1752 auto parameters = service->mutable_static_ip_parameters();
1753 parameters->args_.SetString(kAddressProperty, "1.1.1.1");
1754 parameters->args_.SetInt(kPrefixlenProperty, 16);
1755
1756 scoped_refptr<MockConnection> connection = new MockConnection(&device_info_);
1757 SetConnection(connection);
1758
1759 // Ensure that in the absence of statically configured nameservers that the
1760 // prepend DNS servers are still prepended.
1761 EXPECT_CALL(*service, HasStaticNameServers()).WillOnce(Return(false));
1762 const vector<string> kOutputServers {"8.8.8.8"};
1763 EXPECT_CALL(manager, FilterPrependDNSServersByFamily(
1764 IPAddress::kFamilyIPv4)).WillRepeatedly(Return(kOutputServers));
1765 OnIPConfigUpdated(ipconfig.get());
1766 EXPECT_EQ(kOutputServers, device_->ipconfig()->properties().dns_servers);
1767
1768 // Ensure that when nameservers are statically configured that the prepend DNS
1769 // servers are not used.
1770 const vector<string> static_servers = {"4.4.4.4", "5.5.5.5"};
1771 parameters->args_.SetStrings(kNameServersProperty, static_servers);
1772 EXPECT_CALL(*service, HasStaticNameServers()).WillOnce(Return(true));
1773 OnIPConfigUpdated(ipconfig.get());
1774 EXPECT_EQ(static_servers, device_->ipconfig()->properties().dns_servers);
1775 }
1776
TEST_F(DeviceTest,ResolvePeerMacAddress)1777 TEST_F(DeviceTest, ResolvePeerMacAddress) {
1778 MockManager manager(control_interface(),
1779 dispatcher(),
1780 metrics());
1781 manager.set_mock_device_info(&device_info_);
1782 SetManager(&manager);
1783
1784 // Invalid peer address (not a valid IP address nor MAC address).
1785 Error error;
1786 string result;
1787 const char kInvalidPeer[] = "peer";
1788 EXPECT_FALSE(device_->ResolvePeerMacAddress(kInvalidPeer, &result, &error));
1789 EXPECT_EQ(Error::kInvalidArguments, error.type());
1790
1791 // No direct connectivity to the peer.
1792 const char kPeerIp[] = "192.168.1.1";
1793 error.Reset();
1794 EXPECT_CALL(device_info_,
1795 HasDirectConnectivityTo(device_->interface_index(), _))
1796 .WillOnce(Return(false));
1797 EXPECT_FALSE(device_->ResolvePeerMacAddress(kPeerIp, &result, &error));
1798 EXPECT_EQ(Error::kInvalidArguments, error.type());
1799 Mock::VerifyAndClearExpectations(&device_info_);
1800
1801 // Provided IP address is in the ARP cache, return the resolved MAC address.
1802 const char kResolvedMac[] = "00:11:22:33:44:55";
1803 const ByteString kMacBytes(
1804 Device::MakeHardwareAddressFromString(kResolvedMac));
1805 error.Reset();
1806 EXPECT_CALL(device_info_,
1807 HasDirectConnectivityTo(device_->interface_index(), _))
1808 .WillOnce(Return(true));
1809 EXPECT_CALL(device_info_,
1810 GetMACAddressOfPeer(device_->interface_index(), _, _))
1811 .WillOnce(DoAll(SetArgPointee<2>(kMacBytes), Return(true)));
1812 EXPECT_TRUE(device_->ResolvePeerMacAddress(kPeerIp, &result, &error));
1813 EXPECT_EQ(kResolvedMac, result);
1814 }
1815
TEST_F(DeviceTest,SetHostnameWithEmptyHostname)1816 TEST_F(DeviceTest, SetHostnameWithEmptyHostname) {
1817 MockManager manager(control_interface(),
1818 dispatcher(),
1819 metrics());
1820 manager.set_mock_device_info(&device_info_);
1821 SetManager(&manager);
1822
1823 EXPECT_CALL(manager, ShouldAcceptHostnameFrom(_)).Times(0);
1824 EXPECT_CALL(device_info_, SetHostname(_)).Times(0);
1825 EXPECT_FALSE(SetHostname(""));
1826 }
1827
TEST_F(DeviceTest,SetHostnameForDisallowedDevice)1828 TEST_F(DeviceTest, SetHostnameForDisallowedDevice) {
1829 MockManager manager(control_interface(),
1830 dispatcher(),
1831 metrics());
1832 manager.set_mock_device_info(&device_info_);
1833 SetManager(&manager);
1834
1835 EXPECT_CALL(manager, ShouldAcceptHostnameFrom(kDeviceName))
1836 .WillOnce(Return(false));
1837 EXPECT_CALL(device_info_, SetHostname(_)).Times(0);
1838 EXPECT_FALSE(SetHostname("wilson"));
1839 }
1840
TEST_F(DeviceTest,SetHostnameWithFailingDeviceInfo)1841 TEST_F(DeviceTest, SetHostnameWithFailingDeviceInfo) {
1842 MockManager manager(control_interface(),
1843 dispatcher(),
1844 metrics());
1845 manager.set_mock_device_info(&device_info_);
1846 SetManager(&manager);
1847
1848 EXPECT_CALL(manager, ShouldAcceptHostnameFrom(kDeviceName))
1849 .WillOnce(Return(true));
1850 EXPECT_CALL(device_info_, SetHostname("wilson"))
1851 .WillOnce(Return(false));
1852 EXPECT_FALSE(SetHostname("wilson"));
1853 }
1854
TEST_F(DeviceTest,SetHostnameMaximumHostnameLength)1855 TEST_F(DeviceTest, SetHostnameMaximumHostnameLength) {
1856 MockManager manager(control_interface(),
1857 dispatcher(),
1858 metrics());
1859 manager.set_mock_device_info(&device_info_);
1860 SetManager(&manager);
1861
1862 EXPECT_CALL(manager, ShouldAcceptHostnameFrom(kDeviceName))
1863 .WillOnce(Return(true));
1864 EXPECT_CALL(device_info_, SetHostname(
1865 "wilson.was-a-good-ball.and-was.an-excellent-swimmer.in-high-seas"))
1866 .WillOnce(Return(true));
1867 EXPECT_TRUE(SetHostname(
1868 "wilson.was-a-good-ball.and-was.an-excellent-swimmer.in-high-seas"));
1869 }
1870
TEST_F(DeviceTest,SetHostnameTruncateDomainName)1871 TEST_F(DeviceTest, SetHostnameTruncateDomainName) {
1872 MockManager manager(control_interface(),
1873 dispatcher(),
1874 metrics());
1875 manager.set_mock_device_info(&device_info_);
1876 SetManager(&manager);
1877
1878 EXPECT_CALL(manager, ShouldAcceptHostnameFrom(kDeviceName))
1879 .WillOnce(Return(true));
1880 EXPECT_CALL(device_info_, SetHostname("wilson"))
1881 .WillOnce(Return(false));
1882 EXPECT_FALSE(SetHostname(
1883 "wilson.was-a-great-ball.and-was.an-excellent-swimmer.in-high-seas"));
1884 }
1885
TEST_F(DeviceTest,SetHostnameTruncateHostname)1886 TEST_F(DeviceTest, SetHostnameTruncateHostname) {
1887 MockManager manager(control_interface(),
1888 dispatcher(),
1889 metrics());
1890 manager.set_mock_device_info(&device_info_);
1891 SetManager(&manager);
1892
1893 EXPECT_CALL(manager, ShouldAcceptHostnameFrom(kDeviceName))
1894 .WillOnce(Return(true));
1895 EXPECT_CALL(device_info_, SetHostname(
1896 "wilson-was-a-great-ball-and-was-an-excellent-swimmer-in-high-sea"))
1897 .WillOnce(Return(true));
1898 EXPECT_TRUE(SetHostname(
1899 "wilson-was-a-great-ball-and-was-an-excellent-swimmer-in-high-sea-chop"));
1900 }
1901
1902 class DevicePortalDetectionTest : public DeviceTest {
1903 public:
DevicePortalDetectionTest()1904 DevicePortalDetectionTest()
1905 : connection_(new StrictMock<MockConnection>(&device_info_)),
1906 manager_(control_interface(),
1907 dispatcher(),
1908 metrics()),
1909 service_(new StrictMock<MockService>(control_interface(),
1910 dispatcher(),
1911 metrics(),
1912 &manager_)),
1913 portal_detector_(new StrictMock<MockPortalDetector>(connection_)) {}
~DevicePortalDetectionTest()1914 virtual ~DevicePortalDetectionTest() {}
SetUp()1915 virtual void SetUp() {
1916 DeviceTest::SetUp();
1917 SelectService(service_);
1918 SetConnection(connection_.get());
1919 device_->portal_detector_.reset(portal_detector_); // Passes ownership.
1920 SetManager(&manager_);
1921 }
1922
1923 protected:
1924 static const int kPortalAttempts;
1925
StartPortalDetection()1926 bool StartPortalDetection() { return device_->StartPortalDetection(); }
StopPortalDetection()1927 void StopPortalDetection() { device_->StopPortalDetection(); }
1928
PortalDetectorCallback(const PortalDetector::Result & result)1929 void PortalDetectorCallback(const PortalDetector::Result& result) {
1930 device_->PortalDetectorCallback(result);
1931 }
RequestPortalDetection()1932 bool RequestPortalDetection() {
1933 return device_->RequestPortalDetection();
1934 }
SetServiceConnectedState(Service::ConnectState state)1935 void SetServiceConnectedState(Service::ConnectState state) {
1936 device_->SetServiceConnectedState(state);
1937 }
ExpectPortalDetectorReset()1938 void ExpectPortalDetectorReset() {
1939 EXPECT_FALSE(device_->portal_detector_.get());
1940 }
ExpectPortalDetectorSet()1941 void ExpectPortalDetectorSet() {
1942 EXPECT_TRUE(device_->portal_detector_.get());
1943 }
ExpectPortalDetectorIsMock()1944 void ExpectPortalDetectorIsMock() {
1945 EXPECT_EQ(portal_detector_, device_->portal_detector_.get());
1946 }
InvokeFallbackDNSResultCallback(DNSServerTester::Status status)1947 void InvokeFallbackDNSResultCallback(DNSServerTester::Status status) {
1948 device_->FallbackDNSResultCallback(status);
1949 }
InvokeConfigDNSResultCallback(DNSServerTester::Status status)1950 void InvokeConfigDNSResultCallback(DNSServerTester::Status status) {
1951 device_->ConfigDNSResultCallback(status);
1952 }
DestroyConnection()1953 void DestroyConnection() { device_->DestroyConnection(); }
1954 scoped_refptr<MockConnection> connection_;
1955 StrictMock<MockManager> manager_;
1956 scoped_refptr<MockService> service_;
1957
1958 // Used only for EXPECT_CALL(). Object is owned by device.
1959 MockPortalDetector* portal_detector_;
1960 };
1961
1962 const int DevicePortalDetectionTest::kPortalAttempts = 2;
1963
TEST_F(DevicePortalDetectionTest,ServicePortalDetectionDisabled)1964 TEST_F(DevicePortalDetectionTest, ServicePortalDetectionDisabled) {
1965 EXPECT_CALL(*service_.get(), IsPortalDetectionDisabled())
1966 .WillOnce(Return(true));
1967 EXPECT_CALL(*service_.get(), IsConnected())
1968 .WillRepeatedly(Return(true));
1969 EXPECT_CALL(*service_.get(), SetState(Service::kStateOnline));
1970 EXPECT_FALSE(StartPortalDetection());
1971 }
1972
TEST_F(DevicePortalDetectionTest,TechnologyPortalDetectionDisabled)1973 TEST_F(DevicePortalDetectionTest, TechnologyPortalDetectionDisabled) {
1974 EXPECT_CALL(*service_.get(), IsPortalDetectionDisabled())
1975 .WillOnce(Return(false));
1976 EXPECT_CALL(*service_.get(), IsConnected())
1977 .WillRepeatedly(Return(true));
1978 EXPECT_CALL(*service_.get(), IsPortalDetectionAuto())
1979 .WillOnce(Return(true));
1980 EXPECT_CALL(manager_, IsPortalDetectionEnabled(device_->technology()))
1981 .WillOnce(Return(false));
1982 EXPECT_CALL(*service_.get(), SetState(Service::kStateOnline));
1983 EXPECT_FALSE(StartPortalDetection());
1984 }
1985
TEST_F(DevicePortalDetectionTest,PortalDetectionProxyConfig)1986 TEST_F(DevicePortalDetectionTest, PortalDetectionProxyConfig) {
1987 EXPECT_CALL(*service_.get(), IsPortalDetectionDisabled())
1988 .WillOnce(Return(false));
1989 EXPECT_CALL(*service_.get(), IsConnected())
1990 .WillRepeatedly(Return(true));
1991 EXPECT_CALL(*service_.get(), HasProxyConfig())
1992 .WillOnce(Return(true));
1993 EXPECT_CALL(*service_.get(), IsPortalDetectionAuto())
1994 .WillOnce(Return(true));
1995 EXPECT_CALL(manager_, IsPortalDetectionEnabled(device_->technology()))
1996 .WillOnce(Return(true));
1997 EXPECT_CALL(*service_.get(), SetState(Service::kStateOnline));
1998 EXPECT_FALSE(StartPortalDetection());
1999 }
2000
TEST_F(DevicePortalDetectionTest,PortalDetectionBadUrl)2001 TEST_F(DevicePortalDetectionTest, PortalDetectionBadUrl) {
2002 EXPECT_CALL(*service_.get(), IsPortalDetectionDisabled())
2003 .WillOnce(Return(false));
2004 EXPECT_CALL(*service_.get(), IsConnected())
2005 .WillRepeatedly(Return(true));
2006 EXPECT_CALL(*service_.get(), HasProxyConfig())
2007 .WillOnce(Return(false));
2008 EXPECT_CALL(*service_.get(), IsPortalDetectionAuto())
2009 .WillOnce(Return(true));
2010 EXPECT_CALL(manager_, IsPortalDetectionEnabled(device_->technology()))
2011 .WillOnce(Return(true));
2012 const string portal_url;
2013 EXPECT_CALL(manager_, GetPortalCheckURL())
2014 .WillRepeatedly(ReturnRef(portal_url));
2015 EXPECT_CALL(*service_.get(), SetState(Service::kStateOnline));
2016 EXPECT_FALSE(StartPortalDetection());
2017 }
2018
TEST_F(DevicePortalDetectionTest,PortalDetectionStart)2019 TEST_F(DevicePortalDetectionTest, PortalDetectionStart) {
2020 EXPECT_CALL(*service_.get(), IsPortalDetectionDisabled())
2021 .WillOnce(Return(false));
2022 EXPECT_CALL(*service_.get(), IsConnected())
2023 .WillRepeatedly(Return(true));
2024 EXPECT_CALL(*service_.get(), HasProxyConfig())
2025 .WillOnce(Return(false));
2026 EXPECT_CALL(*service_.get(), IsPortalDetectionAuto())
2027 .WillOnce(Return(true));
2028 EXPECT_CALL(manager_, IsPortalDetectionEnabled(device_->technology()))
2029 .WillOnce(Return(true));
2030 const string portal_url(ConnectivityTrial::kDefaultURL);
2031 EXPECT_CALL(manager_, GetPortalCheckURL())
2032 .WillRepeatedly(ReturnRef(portal_url));
2033 EXPECT_CALL(*service_.get(), SetState(Service::kStateOnline))
2034 .Times(0);
2035 const string kInterfaceName("int0");
2036 EXPECT_CALL(*connection_.get(), interface_name())
2037 .WillRepeatedly(ReturnRef(kInterfaceName));
2038 EXPECT_CALL(*connection_.get(), IsIPv6())
2039 .WillRepeatedly(Return(false));
2040 const vector<string> kDNSServers;
2041 EXPECT_CALL(*connection_.get(), dns_servers())
2042 .WillRepeatedly(ReturnRef(kDNSServers));
2043 EXPECT_TRUE(StartPortalDetection());
2044
2045 // Drop all references to device_info before it falls out of scope.
2046 SetConnection(nullptr);
2047 StopPortalDetection();
2048 }
2049
TEST_F(DevicePortalDetectionTest,PortalDetectionStartIPv6)2050 TEST_F(DevicePortalDetectionTest, PortalDetectionStartIPv6) {
2051 EXPECT_CALL(*service_.get(), IsPortalDetectionDisabled())
2052 .WillOnce(Return(false));
2053 EXPECT_CALL(*service_.get(), IsConnected())
2054 .WillRepeatedly(Return(true));
2055 EXPECT_CALL(*service_.get(), HasProxyConfig())
2056 .WillOnce(Return(false));
2057 EXPECT_CALL(*service_.get(), IsPortalDetectionAuto())
2058 .WillOnce(Return(true));
2059 EXPECT_CALL(manager_, IsPortalDetectionEnabled(device_->technology()))
2060 .WillOnce(Return(true));
2061 const string portal_url(ConnectivityTrial::kDefaultURL);
2062 EXPECT_CALL(manager_, GetPortalCheckURL())
2063 .WillRepeatedly(ReturnRef(portal_url));
2064 EXPECT_CALL(*service_.get(), SetState(Service::kStateOnline))
2065 .Times(0);
2066 const string kInterfaceName("int0");
2067 EXPECT_CALL(*connection_.get(), interface_name())
2068 .WillRepeatedly(ReturnRef(kInterfaceName));
2069 EXPECT_CALL(*connection_.get(), IsIPv6())
2070 .WillRepeatedly(Return(true));
2071 const vector<string> kDNSServers;
2072 EXPECT_CALL(*connection_.get(), dns_servers())
2073 .WillRepeatedly(ReturnRef(kDNSServers));
2074 EXPECT_TRUE(StartPortalDetection());
2075
2076 // Drop all references to device_info before it falls out of scope.
2077 SetConnection(nullptr);
2078 StopPortalDetection();
2079 }
2080
TEST_F(DevicePortalDetectionTest,PortalDetectionNonFinal)2081 TEST_F(DevicePortalDetectionTest, PortalDetectionNonFinal) {
2082 EXPECT_CALL(*service_.get(), IsConnected())
2083 .Times(0);
2084 EXPECT_CALL(*service_.get(), SetState(_))
2085 .Times(0);
2086 PortalDetectorCallback(
2087 PortalDetector::Result(
2088 ConnectivityTrial::Result(
2089 ConnectivityTrial::kPhaseUnknown,
2090 ConnectivityTrial::kStatusFailure),
2091 kPortalAttempts,
2092 false));
2093 }
2094
2095 MATCHER_P(IsPortalDetectorResult, result, "") {
2096 return (result.num_attempts == arg.num_attempts &&
2097 result.final == arg.final &&
2098 result.trial_result.phase == arg.trial_result.phase &&
2099 result.trial_result.status == arg.trial_result.status);
2100 }
2101
TEST_F(DevicePortalDetectionTest,PortalDetectionFailure)2102 TEST_F(DevicePortalDetectionTest, PortalDetectionFailure) {
2103 PortalDetector::Result result(
2104 ConnectivityTrial::Result(ConnectivityTrial::kPhaseConnection,
2105 ConnectivityTrial::kStatusFailure),
2106 kPortalAttempts, true);
2107 EXPECT_CALL(*service_.get(), IsConnected())
2108 .WillOnce(Return(true));
2109 EXPECT_CALL(*service_.get(),
2110 SetPortalDetectionFailure(kPortalDetectionPhaseConnection,
2111 kPortalDetectionStatusFailure));
2112 EXPECT_CALL(*service_.get(), SetState(Service::kStatePortal));
2113 EXPECT_CALL(metrics_,
2114 SendEnumToUMA("Network.Shill.Unknown.PortalResult",
2115 Metrics::kPortalResultConnectionFailure,
2116 Metrics::kPortalResultMax));
2117 EXPECT_CALL(metrics_,
2118 SendToUMA("Network.Shill.Unknown.PortalAttemptsToOnline",
2119 _, _, _, _)).Times(0);
2120 EXPECT_CALL(metrics_,
2121 SendToUMA("Network.Shill.Unknown.PortalAttempts",
2122 kPortalAttempts,
2123 Metrics::kMetricPortalAttemptsMin,
2124 Metrics::kMetricPortalAttemptsMax,
2125 Metrics::kMetricPortalAttemptsNumBuckets));
2126 EXPECT_CALL(*connection_.get(), is_default())
2127 .WillOnce(Return(false));
2128 EXPECT_CALL(*connection_.get(), IsIPv6())
2129 .WillOnce(Return(false));
2130 EXPECT_CALL(*device_, StartConnectionDiagnosticsAfterPortalDetection(
2131 IsPortalDetectorResult(result)));
2132 PortalDetectorCallback(result);
2133 }
2134
TEST_F(DevicePortalDetectionTest,PortalDetectionSuccess)2135 TEST_F(DevicePortalDetectionTest, PortalDetectionSuccess) {
2136 EXPECT_CALL(*service_.get(), IsConnected())
2137 .WillOnce(Return(true));
2138 EXPECT_CALL(*service_.get(), SetPortalDetectionFailure(_, _)).Times(0);
2139 EXPECT_CALL(*service_.get(), SetState(Service::kStateOnline));
2140 EXPECT_CALL(metrics_,
2141 SendEnumToUMA("Network.Shill.Unknown.PortalResult",
2142 Metrics::kPortalResultSuccess,
2143 Metrics::kPortalResultMax));
2144 EXPECT_CALL(metrics_,
2145 SendToUMA("Network.Shill.Unknown.PortalAttemptsToOnline",
2146 kPortalAttempts,
2147 Metrics::kMetricPortalAttemptsToOnlineMin,
2148 Metrics::kMetricPortalAttemptsToOnlineMax,
2149 Metrics::kMetricPortalAttemptsToOnlineNumBuckets));
2150 EXPECT_CALL(metrics_,
2151 SendToUMA("Network.Shill.Unknown.PortalAttempts",
2152 _, _, _, _)).Times(0);
2153 PortalDetectorCallback(
2154 PortalDetector::Result(
2155 ConnectivityTrial::Result(
2156 ConnectivityTrial::kPhaseContent,
2157 ConnectivityTrial::kStatusSuccess),
2158 kPortalAttempts,
2159 true));
2160 }
2161
TEST_F(DevicePortalDetectionTest,PortalDetectionSuccessAfterFailure)2162 TEST_F(DevicePortalDetectionTest, PortalDetectionSuccessAfterFailure) {
2163 EXPECT_CALL(*service_.get(), IsConnected())
2164 .WillRepeatedly(Return(true));
2165 EXPECT_CALL(*service_.get(),
2166 SetPortalDetectionFailure(kPortalDetectionPhaseConnection,
2167 kPortalDetectionStatusFailure));
2168 EXPECT_CALL(*service_.get(), SetState(Service::kStatePortal));
2169 EXPECT_CALL(metrics_,
2170 SendEnumToUMA("Network.Shill.Unknown.PortalResult",
2171 Metrics::kPortalResultConnectionFailure,
2172 Metrics::kPortalResultMax));
2173 EXPECT_CALL(metrics_,
2174 SendToUMA("Network.Shill.Unknown.PortalAttemptsToOnline",
2175 _, _, _, _)).Times(0);
2176 EXPECT_CALL(metrics_,
2177 SendToUMA("Network.Shill.Unknown.PortalAttempts",
2178 kPortalAttempts,
2179 Metrics::kMetricPortalAttemptsMin,
2180 Metrics::kMetricPortalAttemptsMax,
2181 Metrics::kMetricPortalAttemptsNumBuckets));
2182 EXPECT_CALL(*connection_.get(), is_default())
2183 .WillOnce(Return(false));
2184 EXPECT_CALL(*connection_.get(), IsIPv6())
2185 .WillOnce(Return(false));
2186 PortalDetectorCallback(
2187 PortalDetector::Result(
2188 ConnectivityTrial::Result(
2189 ConnectivityTrial::kPhaseConnection,
2190 ConnectivityTrial::kStatusFailure),
2191 kPortalAttempts,
2192 true));
2193 Mock::VerifyAndClearExpectations(&metrics_);
2194 EXPECT_CALL(*service_.get(), SetPortalDetectionFailure(_, _)).Times(0);
2195 EXPECT_CALL(*service_.get(), SetState(Service::kStateOnline));
2196 EXPECT_CALL(metrics_,
2197 SendEnumToUMA("Network.Shill.Unknown.PortalResult",
2198 Metrics::kPortalResultSuccess,
2199 Metrics::kPortalResultMax));
2200 EXPECT_CALL(metrics_,
2201 SendToUMA("Network.Shill.Unknown.PortalAttemptsToOnline",
2202 kPortalAttempts * 2,
2203 Metrics::kMetricPortalAttemptsToOnlineMin,
2204 Metrics::kMetricPortalAttemptsToOnlineMax,
2205 Metrics::kMetricPortalAttemptsToOnlineNumBuckets));
2206 EXPECT_CALL(metrics_,
2207 SendToUMA("Network.Shill.Unknown.PortalAttempts",
2208 _, _, _, _)).Times(0);
2209 PortalDetectorCallback(
2210 PortalDetector::Result(
2211 ConnectivityTrial::Result(
2212 ConnectivityTrial::kPhaseContent,
2213 ConnectivityTrial::kStatusSuccess),
2214 kPortalAttempts,
2215 true));
2216 }
2217
TEST_F(DevicePortalDetectionTest,RequestPortalDetection)2218 TEST_F(DevicePortalDetectionTest, RequestPortalDetection) {
2219 EXPECT_CALL(*service_.get(), state())
2220 .WillOnce(Return(Service::kStateOnline))
2221 .WillRepeatedly(Return(Service::kStatePortal));
2222 EXPECT_FALSE(RequestPortalDetection());
2223
2224 EXPECT_CALL(*connection_.get(), is_default())
2225 .WillOnce(Return(false))
2226 .WillRepeatedly(Return(true));
2227 EXPECT_FALSE(RequestPortalDetection());
2228
2229 EXPECT_CALL(*portal_detector_, IsInProgress())
2230 .WillOnce(Return(true));
2231 // Portal detection already running.
2232 EXPECT_TRUE(RequestPortalDetection());
2233
2234 // Make sure our running mock portal detector was not replaced.
2235 ExpectPortalDetectorIsMock();
2236
2237 // Throw away our pre-fabricated portal detector, and have the device create
2238 // a new one.
2239 StopPortalDetection();
2240 EXPECT_CALL(*service_.get(), IsPortalDetectionDisabled())
2241 .WillRepeatedly(Return(false));
2242 EXPECT_CALL(*service_.get(), IsPortalDetectionAuto())
2243 .WillRepeatedly(Return(true));
2244 EXPECT_CALL(manager_, IsPortalDetectionEnabled(device_->technology()))
2245 .WillRepeatedly(Return(true));
2246 EXPECT_CALL(*service_.get(), HasProxyConfig())
2247 .WillRepeatedly(Return(false));
2248 const string kPortalCheckURL("http://portal");
2249 EXPECT_CALL(manager_, GetPortalCheckURL())
2250 .WillOnce(ReturnRef(kPortalCheckURL));
2251 const string kInterfaceName("int0");
2252 EXPECT_CALL(*connection_.get(), IsIPv6())
2253 .WillRepeatedly(Return(false));
2254 EXPECT_CALL(*connection_.get(), interface_name())
2255 .WillRepeatedly(ReturnRef(kInterfaceName));
2256 const vector<string> kDNSServers;
2257 EXPECT_CALL(*connection_.get(), dns_servers())
2258 .WillRepeatedly(ReturnRef(kDNSServers));
2259 EXPECT_TRUE(RequestPortalDetection());
2260 }
2261
TEST_F(DevicePortalDetectionTest,RequestStartConnectivityTest)2262 TEST_F(DevicePortalDetectionTest, RequestStartConnectivityTest) {
2263 const string kInterfaceName("int0");
2264 EXPECT_CALL(*connection_.get(), interface_name())
2265 .WillRepeatedly(ReturnRef(kInterfaceName));
2266 EXPECT_CALL(*connection_.get(), IsIPv6())
2267 .WillRepeatedly(Return(false));
2268 const vector<string> kDNSServers;
2269 EXPECT_CALL(*connection_.get(), dns_servers())
2270 .WillRepeatedly(ReturnRef(kDNSServers));
2271
2272 EXPECT_EQ(nullptr, device_->connection_tester_);
2273 EXPECT_TRUE(device_->StartConnectivityTest());
2274 EXPECT_NE(nullptr, device_->connection_tester_);
2275 }
2276
TEST_F(DevicePortalDetectionTest,NotConnected)2277 TEST_F(DevicePortalDetectionTest, NotConnected) {
2278 EXPECT_CALL(*service_.get(), IsConnected())
2279 .WillOnce(Return(false));
2280 SetServiceConnectedState(Service::kStatePortal);
2281 // We don't check for the portal detector to be reset here, because
2282 // it would have been reset as a part of disconnection.
2283 }
2284
TEST_F(DevicePortalDetectionTest,NotPortal)2285 TEST_F(DevicePortalDetectionTest, NotPortal) {
2286 EXPECT_CALL(*service_.get(), IsConnected())
2287 .WillOnce(Return(true));
2288 EXPECT_CALL(*service_.get(), SetState(Service::kStateOnline));
2289 SetServiceConnectedState(Service::kStateOnline);
2290 ExpectPortalDetectorReset();
2291 }
2292
TEST_F(DevicePortalDetectionTest,NotDefault)2293 TEST_F(DevicePortalDetectionTest, NotDefault) {
2294 EXPECT_CALL(*service_.get(), IsConnected())
2295 .WillOnce(Return(true));
2296 EXPECT_CALL(*connection_.get(), is_default())
2297 .WillOnce(Return(false));
2298 EXPECT_CALL(*service_.get(), SetState(Service::kStatePortal));
2299 SetServiceConnectedState(Service::kStatePortal);
2300 ExpectPortalDetectorReset();
2301 }
2302
TEST_F(DevicePortalDetectionTest,PortalIntervalIsZero)2303 TEST_F(DevicePortalDetectionTest, PortalIntervalIsZero) {
2304 EXPECT_CALL(*service_.get(), IsConnected())
2305 .WillOnce(Return(true));
2306 EXPECT_CALL(*connection_.get(), is_default())
2307 .WillOnce(Return(true));
2308 EXPECT_CALL(manager_, GetPortalCheckInterval())
2309 .WillOnce(Return(0));
2310 EXPECT_CALL(*service_.get(), SetState(Service::kStatePortal));
2311 SetServiceConnectedState(Service::kStatePortal);
2312 ExpectPortalDetectorReset();
2313 }
2314
TEST_F(DevicePortalDetectionTest,RestartPortalDetection)2315 TEST_F(DevicePortalDetectionTest, RestartPortalDetection) {
2316 EXPECT_CALL(*service_.get(), IsConnected())
2317 .WillOnce(Return(true));
2318 EXPECT_CALL(*connection_.get(), is_default())
2319 .WillOnce(Return(true));
2320 const int kPortalDetectionInterval = 10;
2321 EXPECT_CALL(manager_, GetPortalCheckInterval())
2322 .Times(AtLeast(1))
2323 .WillRepeatedly(Return(kPortalDetectionInterval));
2324 const string kPortalCheckURL("http://portal");
2325 EXPECT_CALL(manager_, GetPortalCheckURL())
2326 .WillOnce(ReturnRef(kPortalCheckURL));
2327 EXPECT_CALL(*portal_detector_, StartAfterDelay(kPortalCheckURL,
2328 kPortalDetectionInterval))
2329 .WillOnce(Return(true));
2330 EXPECT_CALL(*service_.get(), SetState(Service::kStatePortal));
2331 SetServiceConnectedState(Service::kStatePortal);
2332 ExpectPortalDetectorSet();
2333 }
2334
TEST_F(DevicePortalDetectionTest,CancelledOnSelectService)2335 TEST_F(DevicePortalDetectionTest, CancelledOnSelectService) {
2336 ExpectPortalDetectorSet();
2337 EXPECT_CALL(*service_.get(), state())
2338 .WillOnce(Return(Service::kStateIdle));
2339 EXPECT_CALL(*service_.get(), SetState(_));
2340 EXPECT_CALL(*service_.get(), SetConnection(_));
2341 SelectService(nullptr);
2342 ExpectPortalDetectorReset();
2343 }
2344
TEST_F(DevicePortalDetectionTest,PortalDetectionDNSFailure)2345 TEST_F(DevicePortalDetectionTest, PortalDetectionDNSFailure) {
2346 const char* kGoogleDNSServers[] = { "8.8.8.8", "8.8.4.4" };
2347 vector<string> fallback_dns_servers(kGoogleDNSServers, kGoogleDNSServers + 2);
2348 const string kInterfaceName("int0");
2349 EXPECT_CALL(*connection_.get(), interface_name())
2350 .WillRepeatedly(ReturnRef(kInterfaceName));
2351
2352 // DNS Failure, start DNS test for fallback DNS servers.
2353 PortalDetector::Result result_dns_failure(
2354 ConnectivityTrial::Result(ConnectivityTrial::kPhaseDNS,
2355 ConnectivityTrial::kStatusFailure),
2356 kPortalAttempts, true);
2357 EXPECT_CALL(*service_.get(), IsConnected())
2358 .WillOnce(Return(true));
2359 EXPECT_CALL(*service_.get(),
2360 SetPortalDetectionFailure(kPortalDetectionPhaseDns,
2361 kPortalDetectionStatusFailure));
2362 EXPECT_CALL(*service_.get(), SetState(Service::kStatePortal));
2363 EXPECT_CALL(*connection_.get(), is_default())
2364 .WillOnce(Return(false));
2365 EXPECT_CALL(*connection_.get(), IsIPv6())
2366 .WillOnce(Return(false));
2367 EXPECT_CALL(*device_, StartConnectionDiagnosticsAfterPortalDetection(
2368 IsPortalDetectorResult(result_dns_failure)));
2369 EXPECT_CALL(*device_, StartDNSTest(fallback_dns_servers, false, _)).Times(1);
2370 PortalDetectorCallback(result_dns_failure);
2371 Mock::VerifyAndClearExpectations(device_.get());
2372
2373 // DNS Timeout, start DNS test for fallback DNS servers.
2374 PortalDetector::Result result_dns_timeout(
2375 ConnectivityTrial::Result(ConnectivityTrial::kPhaseDNS,
2376 ConnectivityTrial::kStatusTimeout),
2377 kPortalAttempts, true);
2378 EXPECT_CALL(*service_.get(), IsConnected())
2379 .WillOnce(Return(true));
2380 EXPECT_CALL(*service_.get(),
2381 SetPortalDetectionFailure(kPortalDetectionPhaseDns,
2382 kPortalDetectionStatusTimeout));
2383 EXPECT_CALL(*service_.get(), SetState(Service::kStatePortal));
2384 EXPECT_CALL(*connection_.get(), is_default())
2385 .WillOnce(Return(false));
2386 EXPECT_CALL(*connection_.get(), IsIPv6()).WillOnce(Return(false));
2387 EXPECT_CALL(*device_, StartConnectionDiagnosticsAfterPortalDetection(
2388 IsPortalDetectorResult(result_dns_timeout)));
2389 EXPECT_CALL(*device_, StartDNSTest(fallback_dns_servers, false, _)).Times(1);
2390 PortalDetectorCallback(result_dns_timeout);
2391 Mock::VerifyAndClearExpectations(device_.get());
2392
2393 // Other Failure, DNS server tester not started.
2394 PortalDetector::Result result_connection_failure(
2395 ConnectivityTrial::Result(ConnectivityTrial::kPhaseConnection,
2396 ConnectivityTrial::kStatusFailure),
2397 kPortalAttempts, true);
2398 EXPECT_CALL(*service_.get(), IsConnected())
2399 .WillOnce(Return(true));
2400 EXPECT_CALL(*service_.get(),
2401 SetPortalDetectionFailure(kPortalDetectionPhaseConnection,
2402 kPortalDetectionStatusFailure));
2403 EXPECT_CALL(*service_.get(), SetState(Service::kStatePortal));
2404 EXPECT_CALL(*connection_.get(), is_default())
2405 .WillOnce(Return(false));
2406 EXPECT_CALL(*connection_.get(), IsIPv6())
2407 .WillOnce(Return(false));
2408 EXPECT_CALL(*device_, StartConnectionDiagnosticsAfterPortalDetection(
2409 IsPortalDetectorResult(result_connection_failure)));
2410 EXPECT_CALL(*device_, StartDNSTest(_, _, _)).Times(0);
2411 PortalDetectorCallback(result_connection_failure);
2412 Mock::VerifyAndClearExpectations(device_.get());
2413 }
2414
TEST_F(DevicePortalDetectionTest,FallbackDNSResultCallback)2415 TEST_F(DevicePortalDetectionTest, FallbackDNSResultCallback) {
2416 scoped_refptr<MockIPConfig> ipconfig =
2417 new MockIPConfig(control_interface(), kDeviceName);
2418 device_->set_ipconfig(ipconfig);
2419
2420 // Fallback DNS test failed.
2421 EXPECT_CALL(*connection_.get(), UpdateDNSServers(_)).Times(0);
2422 EXPECT_CALL(*ipconfig, UpdateDNSServers(_)).Times(0);
2423 EXPECT_CALL(*device_, StartDNSTest(_, _, _)).Times(0);
2424 EXPECT_CALL(metrics_,
2425 NotifyFallbackDNSTestResult(_, Metrics::kFallbackDNSTestResultFailure))
2426 .Times(1);
2427 InvokeFallbackDNSResultCallback(DNSServerTester::kStatusFailure);
2428 Mock::VerifyAndClearExpectations(connection_.get());
2429 Mock::VerifyAndClearExpectations(ipconfig.get());
2430 Mock::VerifyAndClearExpectations(&metrics_);
2431
2432 // Fallback DNS test succeed with auto fallback disabled.
2433 EXPECT_CALL(*service_.get(), is_dns_auto_fallback_allowed())
2434 .WillOnce(Return(false));
2435 EXPECT_CALL(*connection_.get(), UpdateDNSServers(_)).Times(0);
2436 EXPECT_CALL(*ipconfig, UpdateDNSServers(_)).Times(0);
2437 EXPECT_CALL(*service_.get(), NotifyIPConfigChanges()).Times(0);
2438 EXPECT_CALL(*device_, StartDNSTest(_, _, _)).Times(0);
2439 EXPECT_CALL(metrics_,
2440 NotifyFallbackDNSTestResult(_, Metrics::kFallbackDNSTestResultSuccess))
2441 .Times(1);
2442 InvokeFallbackDNSResultCallback(DNSServerTester::kStatusSuccess);
2443 Mock::VerifyAndClearExpectations(service_.get());
2444 Mock::VerifyAndClearExpectations(connection_.get());
2445 Mock::VerifyAndClearExpectations(ipconfig.get());
2446 Mock::VerifyAndClearExpectations(&metrics_);
2447
2448 // Fallback DNS test succeed with auto fallback enabled.
2449 EXPECT_CALL(*service_.get(), is_dns_auto_fallback_allowed())
2450 .WillOnce(Return(true));
2451 EXPECT_CALL(*service_.get(), IsPortalDetectionDisabled())
2452 .WillRepeatedly(Return(false));
2453 EXPECT_CALL(*service_.get(), IsPortalDetectionAuto())
2454 .WillRepeatedly(Return(true));
2455 EXPECT_CALL(manager_, IsPortalDetectionEnabled(device_->technology()))
2456 .WillRepeatedly(Return(true));
2457 EXPECT_CALL(*service_.get(), HasProxyConfig())
2458 .WillRepeatedly(Return(false));
2459 const string kPortalCheckURL("http://portal");
2460 EXPECT_CALL(manager_, GetPortalCheckURL())
2461 .WillOnce(ReturnRef(kPortalCheckURL));
2462 const string kInterfaceName("int0");
2463 EXPECT_CALL(*connection_.get(), IsIPv6())
2464 .WillRepeatedly(Return(false));
2465 EXPECT_CALL(*connection_.get(), interface_name())
2466 .WillRepeatedly(ReturnRef(kInterfaceName));
2467 const vector<string> kDNSServers;
2468 EXPECT_CALL(*connection_.get(), dns_servers())
2469 .WillRepeatedly(ReturnRef(kDNSServers));
2470
2471 EXPECT_CALL(*ipconfig, UpdateDNSServers(_)).Times(1);
2472 EXPECT_CALL(*connection_.get(), UpdateDNSServers(_)).Times(1);
2473 EXPECT_CALL(*service_.get(), NotifyIPConfigChanges()).Times(1);
2474 EXPECT_CALL(*device_, StartDNSTest(_, true, _)).Times(1);
2475 EXPECT_CALL(metrics_,
2476 NotifyFallbackDNSTestResult(_, Metrics::kFallbackDNSTestResultSuccess))
2477 .Times(1);
2478 InvokeFallbackDNSResultCallback(DNSServerTester::kStatusSuccess);
2479 Mock::VerifyAndClearExpectations(service_.get());
2480 Mock::VerifyAndClearExpectations(connection_.get());
2481 Mock::VerifyAndClearExpectations(ipconfig.get());
2482 Mock::VerifyAndClearExpectations(&metrics_);
2483 }
2484
TEST_F(DevicePortalDetectionTest,ConfigDNSResultCallback)2485 TEST_F(DevicePortalDetectionTest, ConfigDNSResultCallback) {
2486 scoped_refptr<MockIPConfig> ipconfig =
2487 new MockIPConfig(control_interface(), kDeviceName);
2488 device_->set_ipconfig(ipconfig);
2489
2490 // DNS test failed for configured DNS servers.
2491 EXPECT_CALL(*connection_.get(), UpdateDNSServers(_)).Times(0);
2492 EXPECT_CALL(*ipconfig, UpdateDNSServers(_)).Times(0);
2493 InvokeConfigDNSResultCallback(DNSServerTester::kStatusFailure);
2494 Mock::VerifyAndClearExpectations(connection_.get());
2495 Mock::VerifyAndClearExpectations(ipconfig.get());
2496
2497 // DNS test succeed for configured DNS servers.
2498 EXPECT_CALL(*service_.get(), IsPortalDetectionDisabled())
2499 .WillRepeatedly(Return(false));
2500 EXPECT_CALL(*service_.get(), IsPortalDetectionAuto())
2501 .WillRepeatedly(Return(true));
2502 EXPECT_CALL(manager_, IsPortalDetectionEnabled(device_->technology()))
2503 .WillRepeatedly(Return(true));
2504 EXPECT_CALL(*service_.get(), HasProxyConfig())
2505 .WillRepeatedly(Return(false));
2506 const string kPortalCheckURL("http://portal");
2507 EXPECT_CALL(manager_, GetPortalCheckURL())
2508 .WillOnce(ReturnRef(kPortalCheckURL));
2509 const string kInterfaceName("int0");
2510 EXPECT_CALL(*connection_.get(), IsIPv6())
2511 .WillRepeatedly(Return(false));
2512 EXPECT_CALL(*connection_.get(), interface_name())
2513 .WillRepeatedly(ReturnRef(kInterfaceName));
2514 const vector<string> kDNSServers;
2515 EXPECT_CALL(*connection_.get(), dns_servers())
2516 .WillRepeatedly(ReturnRef(kDNSServers));
2517 EXPECT_CALL(*connection_.get(), UpdateDNSServers(_)).Times(1);
2518 EXPECT_CALL(*ipconfig, UpdateDNSServers(_)).Times(1);
2519 EXPECT_CALL(*service_.get(), NotifyIPConfigChanges()).Times(1);
2520 InvokeConfigDNSResultCallback(DNSServerTester::kStatusSuccess);
2521 Mock::VerifyAndClearExpectations(service_.get());
2522 Mock::VerifyAndClearExpectations(connection_.get());
2523 Mock::VerifyAndClearExpectations(ipconfig.get());
2524 }
2525
TEST_F(DevicePortalDetectionTest,DestroyConnection)2526 TEST_F(DevicePortalDetectionTest, DestroyConnection) {
2527 scoped_refptr<MockConnection> connection =
2528 new NiceMock<MockConnection>(&device_info_);
2529 // This test holds a single reference to the mock connection.
2530 EXPECT_TRUE(connection->HasOneRef());
2531
2532 SetConnection(connection);
2533
2534 EXPECT_CALL(*service_.get(), IsPortalDetectionDisabled())
2535 .WillOnce(Return(false));
2536 EXPECT_CALL(*service_.get(), IsConnected())
2537 .WillRepeatedly(Return(true));
2538 EXPECT_CALL(*service_.get(), HasProxyConfig())
2539 .WillOnce(Return(false));
2540 EXPECT_CALL(*service_.get(), IsPortalDetectionAuto())
2541 .WillOnce(Return(true));
2542 EXPECT_CALL(manager_, IsPortalDetectionEnabled(device_->technology()))
2543 .WillOnce(Return(true));
2544 const string portal_url(ConnectivityTrial::kDefaultURL);
2545 EXPECT_CALL(manager_, GetPortalCheckURL())
2546 .WillRepeatedly(ReturnRef(portal_url));
2547 const string kInterfaceName("int0");
2548 EXPECT_CALL(*connection.get(), interface_name())
2549 .WillRepeatedly(ReturnRef(kInterfaceName));
2550 EXPECT_CALL(*connection.get(), IsIPv6())
2551 .WillRepeatedly(Return(false));
2552 const vector<string> kDNSServers;
2553 EXPECT_CALL(*connection.get(), dns_servers())
2554 .WillRepeatedly(ReturnRef(kDNSServers));
2555
2556 EXPECT_TRUE(device_->StartConnectivityTest());
2557 EXPECT_TRUE(StartPortalDetection());
2558
2559 // Ensure that the DestroyConnection method removes all connection references
2560 // except the one left in this scope.
2561 EXPECT_CALL(*service_.get(), SetConnection(IsNullRefPtr()));
2562 DestroyConnection();
2563 EXPECT_TRUE(connection->HasOneRef());
2564 }
2565
2566 class DeviceByteCountTest : public DeviceTest {
2567 public:
DeviceByteCountTest()2568 DeviceByteCountTest()
2569 : manager_(control_interface(),
2570 dispatcher(),
2571 metrics()),
2572 rx_byte_count_(0),
2573 tx_byte_count_(0),
2574 rx_stored_byte_count_(0),
2575 tx_stored_byte_count_(0) {}
~DeviceByteCountTest()2576 virtual ~DeviceByteCountTest() {}
2577
SetUp()2578 virtual void SetUp() {
2579 DeviceTest::SetUp();
2580 EXPECT_CALL(manager_, device_info()).WillRepeatedly(Return(&device_info_));
2581 EXPECT_CALL(device_info_, GetByteCounts(kDeviceInterfaceIndex, _, _))
2582 .WillRepeatedly(Invoke(this, &DeviceByteCountTest::ReturnByteCounts));
2583 const string id = device_->GetStorageIdentifier();
2584 EXPECT_CALL(storage_, ContainsGroup(id)).WillRepeatedly(Return(true));
2585 EXPECT_CALL(storage_, GetUint64(id, Device::kStorageReceiveByteCount, _))
2586 .WillRepeatedly(
2587 Invoke(this, &DeviceByteCountTest::GetStoredReceiveCount));
2588 EXPECT_CALL(storage_, GetUint64(id, Device::kStorageTransmitByteCount, _))
2589 .WillRepeatedly(
2590 Invoke(this, &DeviceByteCountTest::GetStoredTransmitCount));
2591 }
2592
ReturnByteCounts(int interface_index,uint64_t * rx,uint64_t * tx)2593 bool ReturnByteCounts(int interface_index, uint64_t* rx, uint64_t* tx) {
2594 *rx = rx_byte_count_;
2595 *tx = tx_byte_count_;
2596 return true;
2597 }
2598
ExpectByteCounts(DeviceRefPtr device,int64_t expected_rx,int64_t expected_tx)2599 bool ExpectByteCounts(DeviceRefPtr device,
2600 int64_t expected_rx, int64_t expected_tx) {
2601 int64_t actual_rx = device->GetReceiveByteCount();
2602 int64_t actual_tx = device->GetTransmitByteCount();
2603 EXPECT_EQ(expected_rx, actual_rx);
2604 EXPECT_EQ(expected_tx, actual_tx);
2605 return expected_rx == actual_rx && expected_tx == actual_tx;
2606 }
2607
ExpectSavedCounts(DeviceRefPtr device,int64_t expected_rx,int64_t expected_tx)2608 void ExpectSavedCounts(DeviceRefPtr device,
2609 int64_t expected_rx, int64_t expected_tx) {
2610 EXPECT_CALL(storage_,
2611 SetUint64(_, Device::kStorageReceiveByteCount, expected_rx))
2612 .WillOnce(Return(true));
2613 EXPECT_CALL(storage_,
2614 SetUint64(_, Device::kStorageTransmitByteCount, expected_tx))
2615 .WillOnce(Return(true));
2616 EXPECT_TRUE(device->Save(&storage_));
2617 }
2618
2619
GetStoredReceiveCount(const string & group,const string & key,uint64_t * value)2620 bool GetStoredReceiveCount(const string& group, const string& key,
2621 uint64_t* value) {
2622 if (!rx_stored_byte_count_) {
2623 return false;
2624 }
2625 *value = rx_stored_byte_count_;
2626 return true;
2627 }
2628
GetStoredTransmitCount(const string & group,const string & key,uint64_t * value)2629 bool GetStoredTransmitCount(const string& group, const string& key,
2630 uint64_t* value) {
2631 if (!tx_stored_byte_count_) {
2632 return false;
2633 }
2634 *value = tx_stored_byte_count_;
2635 return true;
2636 }
2637
2638 protected:
2639 NiceMock<MockManager> manager_;
2640 NiceMock<MockStore> storage_;
2641 uint64_t rx_byte_count_;
2642 uint64_t tx_byte_count_;
2643 uint64_t rx_stored_byte_count_;
2644 uint64_t tx_stored_byte_count_;
2645 };
2646
2647
TEST_F(DeviceByteCountTest,GetByteCounts)2648 TEST_F(DeviceByteCountTest, GetByteCounts) {
2649 // On Device initialization, byte counts should be zero, independent of
2650 // the byte counts reported by the interface.
2651 rx_byte_count_ = 123;
2652 tx_byte_count_ = 456;
2653 DeviceRefPtr device(new TestDevice(control_interface(),
2654 dispatcher(),
2655 nullptr,
2656 &manager_,
2657 kDeviceName,
2658 kDeviceAddress,
2659 kDeviceInterfaceIndex,
2660 Technology::kUnknown));
2661 EXPECT_TRUE(ExpectByteCounts(device, 0, 0));
2662
2663 // Device should report any increase in the byte counts reported in the
2664 // interface.
2665 const int64_t delta_rx_count = 789;
2666 const int64_t delta_tx_count = 12;
2667 rx_byte_count_ += delta_rx_count;
2668 tx_byte_count_ += delta_tx_count;
2669 EXPECT_TRUE(ExpectByteCounts(device, delta_rx_count, delta_tx_count));
2670
2671 // Expect the correct values to be saved to the profile.
2672 ExpectSavedCounts(device, delta_rx_count, delta_tx_count);
2673
2674 // If Device is loaded from a profile that does not contain stored byte
2675 // counts, the byte counts reported should remain unchanged.
2676 EXPECT_TRUE(device->Load(&storage_));
2677 EXPECT_TRUE(ExpectByteCounts(device, delta_rx_count, delta_tx_count));
2678
2679 // If Device is loaded from a profile that contains stored byte
2680 // counts, the byte counts reported should now reflect the stored values.
2681 rx_stored_byte_count_ = 345;
2682 tx_stored_byte_count_ = 678;
2683 EXPECT_TRUE(device->Load(&storage_));
2684 EXPECT_TRUE(ExpectByteCounts(
2685 device, rx_stored_byte_count_, tx_stored_byte_count_));
2686
2687 // Increases to the interface receive count should be reflected as offsets
2688 // to the stored byte counts.
2689 rx_byte_count_ += delta_rx_count;
2690 tx_byte_count_ += delta_tx_count;
2691 EXPECT_TRUE(ExpectByteCounts(device,
2692 rx_stored_byte_count_ + delta_rx_count,
2693 tx_stored_byte_count_ + delta_tx_count));
2694
2695 // Expect the correct values to be saved to the profile.
2696 ExpectSavedCounts(device,
2697 rx_stored_byte_count_ + delta_rx_count,
2698 tx_stored_byte_count_ + delta_tx_count);
2699
2700 // Expect that after resetting byte counts, read-back values return to zero,
2701 // and that the device requests this information to be persisted.
2702 EXPECT_CALL(manager_, UpdateDevice(device));
2703 device->ResetByteCounters();
2704 EXPECT_TRUE(ExpectByteCounts(device, 0, 0));
2705 }
2706
2707 } // namespace shill
2708