blob: 76df528e146605b85bcb0dc914e3ffa09b30be44 [file] [log] [blame]
mukesh agrawal8a3188d2011-12-01 20:56:44 +00001// Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
Paul Stewart75897df2011-04-27 09:05:53 -07002// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
Chris Masone2b105542011-06-22 10:58:09 -07005#include "shill/device.h"
6
mukesh agrawal5c4dd0b2011-09-14 13:53:14 -07007#include <netinet/in.h>
8#include <linux/if.h> // Needs definitions from netinet/in.h
Paul Stewart75897df2011-04-27 09:05:53 -07009#include <stdio.h>
mukesh agrawal5c4dd0b2011-09-14 13:53:14 -070010#include <time.h>
Chris Masoneee929b72011-05-10 10:02:18 -070011
Paul Stewart75897df2011-04-27 09:05:53 -070012#include <string>
Chris Masone8fe2c7e2011-06-09 15:51:19 -070013#include <vector>
Paul Stewart75897df2011-04-27 09:05:53 -070014
Eric Shienbrood3e20a232012-02-16 11:35:56 -050015#include <base/bind.h>
Paul Stewart2bf1d352011-12-06 15:02:55 -080016#include <base/file_util.h>
Chris Masone487b8bf2011-05-13 16:27:57 -070017#include <base/memory/ref_counted.h>
Ben Chana0ddf462014-02-06 11:32:42 -080018#include <base/strings/stringprintf.h>
Chris Masone3bd3c8c2011-06-13 08:20:26 -070019#include <chromeos/dbus/service_constants.h>
Chris Masoneee929b72011-05-10 10:02:18 -070020
Arman Ugurayf84a4242013-04-09 20:01:07 -070021#include "shill/async_connection.h"
Paul Stewarte6132022011-08-16 09:11:02 -070022#include "shill/connection.h"
Paul Stewart75897df2011-04-27 09:05:53 -070023#include "shill/control_interface.h"
Chris Masoned7732e42011-05-20 11:08:56 -070024#include "shill/device_dbus_adaptor.h"
Chris Masone2b105542011-06-22 10:58:09 -070025#include "shill/dhcp_config.h"
Darin Petkovafa6fc42011-06-21 16:21:08 -070026#include "shill/dhcp_provider.h"
Arman Ugurayf84a4242013-04-09 20:01:07 -070027#include "shill/dns_client.h"
Peter Qiub9256f32014-05-09 15:27:29 -070028#include "shill/dns_client_factory.h"
Chris Masone8fe2c7e2011-06-09 15:51:19 -070029#include "shill/error.h"
Paul Stewart26b327e2011-10-19 11:38:09 -070030#include "shill/event_dispatcher.h"
Gaurav Shah6d2c72d2012-10-16 16:30:44 -070031#include "shill/geolocation_info.h"
Paul Stewartf65320c2011-10-13 14:34:52 -070032#include "shill/http_proxy.h"
Arman Ugurayf84a4242013-04-09 20:01:07 -070033#include "shill/ip_address.h"
Paul Stewart036dba02012-08-07 12:34:41 -070034#include "shill/link_monitor.h"
Christopher Wileyb691efd2012-08-09 13:51:51 -070035#include "shill/logging.h"
Chris Masone8fe2c7e2011-06-09 15:51:19 -070036#include "shill/manager.h"
Thieu Le85e050b2012-03-13 15:04:38 -070037#include "shill/metrics.h"
Chris Masone95207da2011-06-29 16:50:49 -070038#include "shill/property_accessor.h"
Chris Masone2b105542011-06-22 10:58:09 -070039#include "shill/refptr_types.h"
Paul Stewartc39f1132011-06-22 12:02:28 -070040#include "shill/rtnl_handler.h"
Chris Masone2b105542011-06-22 10:58:09 -070041#include "shill/service.h"
Arman Ugurayf84a4242013-04-09 20:01:07 -070042#include "shill/socket_info_reader.h"
Chris Masone5dec5f42011-07-22 14:07:55 -070043#include "shill/store_interface.h"
Gaurav Shah435de2c2011-11-17 19:01:07 -080044#include "shill/technology.h"
Paul Stewartfa11e282013-12-02 22:04:25 -080045#include "shill/tethering.h"
Peter Qiudc335f82014-05-15 10:33:17 -070046#include "shill/traffic_monitor.h"
Paul Stewart75897df2011-04-27 09:05:53 -070047
Eric Shienbrood3e20a232012-02-16 11:35:56 -050048using base::Bind;
Albert Chaulk0e1cdea2013-02-27 15:32:55 -080049using base::FilePath;
Chris Masone5dec5f42011-07-22 14:07:55 -070050using base::StringPrintf;
Chris Masone8fe2c7e2011-06-09 15:51:19 -070051using std::string;
52using std::vector;
53
Paul Stewart75897df2011-04-27 09:05:53 -070054namespace shill {
Chris Masone5dec5f42011-07-22 14:07:55 -070055
56// static
Paul Stewart2bf1d352011-12-06 15:02:55 -080057const char Device::kIPFlagTemplate[] = "/proc/sys/net/%s/conf/%s/%s";
58// static
59const char Device::kIPFlagVersion4[] = "ipv4";
60// static
61const char Device::kIPFlagVersion6[] = "ipv6";
62// static
63const char Device::kIPFlagDisableIPv6[] = "disable_ipv6";
64// static
65const char Device::kIPFlagUseTempAddr[] = "use_tempaddr";
66// static
67const char Device::kIPFlagUseTempAddrUsedAndDefault[] = "2";
Paul Stewartc8f4bef2011-12-13 09:45:51 -080068// static
69const char Device::kIPFlagReversePathFilter[] = "rp_filter";
70// static
71const char Device::kIPFlagReversePathFilterEnabled[] = "1";
72// static
73const char Device::kIPFlagReversePathFilterLooseMode[] = "2";
Paul Stewart2bf1d352011-12-06 15:02:55 -080074// static
Prathmesh Prabhuba99b592013-04-17 15:13:14 -070075const char Device::kStoragePowered[] = "Powered";
76// static
Paul Stewart6ff27f52012-07-11 06:51:41 -070077const char Device::kStorageReceiveByteCount[] = "ReceiveByteCount";
78// static
79const char Device::kStorageTransmitByteCount[] = "TransmitByteCount";
Peter Qiub9256f32014-05-09 15:27:29 -070080// static
81const char Device::kFallbackDnsTestHostname[] = "www.gstatic.com";
82// static
83const char* Device::kFallbackDnsServers[] = {
84 "8.8.8.8",
85 "8.8.8.4"
86};
87
88// static
89const int Device::kDNSTimeoutMilliseconds = 5000;
Chris Masone5dec5f42011-07-22 14:07:55 -070090
Paul Stewart75897df2011-04-27 09:05:53 -070091Device::Device(ControlInterface *control_interface,
Paul Stewartb50f0b92011-05-16 16:31:42 -070092 EventDispatcher *dispatcher,
Thieu Le3426c8f2012-01-11 17:35:11 -080093 Metrics *metrics,
Paul Stewartf1ce5d22011-05-19 13:10:20 -070094 Manager *manager,
Darin Petkovafa6fc42011-06-21 16:21:08 -070095 const string &link_name,
Chris Masone626719f2011-08-18 16:58:48 -070096 const string &address,
Gaurav Shah435de2c2011-11-17 19:01:07 -080097 int interface_index,
98 Technology::Identifier technology)
Eric Shienbrood9a245532012-03-07 14:20:39 -050099 : enabled_(false),
100 enabled_persistent_(true),
101 enabled_pending_(enabled_),
Chris Masoneb925cc82011-06-22 15:39:57 -0700102 reconnect_(true),
Chris Masone626719f2011-08-18 16:58:48 -0700103 hardware_address_(address),
mukesh agrawalf60e4062011-05-27 13:13:41 -0700104 interface_index_(interface_index),
105 running_(false),
Darin Petkovafa6fc42011-06-21 16:21:08 -0700106 link_name_(link_name),
Chris Masone19e30402011-07-19 15:48:47 -0700107 unique_id_(link_name),
Darin Petkovd9661952011-08-03 16:25:42 -0700108 control_interface_(control_interface),
109 dispatcher_(dispatcher),
Thieu Le3426c8f2012-01-11 17:35:11 -0800110 metrics_(metrics),
Chris Masone7df0c672011-07-15 10:24:54 -0700111 manager_(manager),
Eric Shienbrood9a245532012-03-07 14:20:39 -0500112 weak_ptr_factory_(this),
Darin Petkov77cb6812011-08-15 16:19:41 -0700113 adaptor_(control_interface->CreateDeviceAdaptor(this)),
Peter Qiub9256f32014-05-09 15:27:29 -0700114 dns_client_factory_(DNSClientFactory::GetInstance()),
Eric Shienbrood9a245532012-03-07 14:20:39 -0500115 portal_detector_callback_(Bind(&Device::PortalDetectorCallback,
116 weak_ptr_factory_.GetWeakPtr())),
Peter Qiub9256f32014-05-09 15:27:29 -0700117 dns_client_callback_(Bind(&Device::DNSClientCallback,
118 weak_ptr_factory_.GetWeakPtr())),
Gaurav Shah435de2c2011-11-17 19:01:07 -0800119 technology_(technology),
Thieu Le85e050b2012-03-13 15:04:38 -0700120 portal_attempts_to_online_(0),
Paul Stewart6ff27f52012-07-11 06:51:41 -0700121 receive_byte_offset_(0),
122 transmit_byte_offset_(0),
mukesh agrawal5c4dd0b2011-09-14 13:53:14 -0700123 dhcp_provider_(DHCPProvider::GetInstance()),
124 rtnl_handler_(RTNLHandler::GetInstance()) {
Ben Chan923a5022013-09-20 11:23:23 -0700125 store_.RegisterConstString(kAddressProperty, &hardware_address_);
Chris Masone4d42df82011-07-02 17:09:39 -0700126
Ben Chan923a5022013-09-20 11:23:23 -0700127 // kBgscanMethodProperty: Registered in WiFi
128 // kBgscanShortIntervalProperty: Registered in WiFi
129 // kBgscanSignalThresholdProperty: Registered in WiFi
Chris Masone4d42df82011-07-02 17:09:39 -0700130
Ben Chan923a5022013-09-20 11:23:23 -0700131 // kCellularAllowRoamingProperty: Registered in Cellular
132 // kCarrierProperty: Registered in Cellular
133 // kEsnProperty: Registered in Cellular
134 // kHomeProviderProperty: Registered in Cellular
135 // kImeiProperty: Registered in Cellular
136 // kIccidProperty: Registered in Cellular
137 // kImsiProperty: Registered in Cellular
138 // kManufacturerProperty: Registered in Cellular
139 // kMdnProperty: Registered in Cellular
140 // kMeidProperty: Registered in Cellular
141 // kMinProperty: Registered in Cellular
142 // kModelIDProperty: Registered in Cellular
143 // kFirmwareRevisionProperty: Registered in Cellular
144 // kHardwareRevisionProperty: Registered in Cellular
145 // kPRLVersionProperty: Registered in Cellular
146 // kSIMLockStatusProperty: Registered in Cellular
147 // kFoundNetworksProperty: Registered in Cellular
Ben Chan923a5022013-09-20 11:23:23 -0700148 // kDBusObjectProperty: Register in Cellular
Chris Masone4d42df82011-07-02 17:09:39 -0700149
Ben Chan923a5022013-09-20 11:23:23 -0700150 store_.RegisterConstString(kInterfaceProperty, &link_name_);
151 HelpRegisterConstDerivedRpcIdentifiers(kIPConfigsProperty,
Jason Glasgow08afdff2012-04-03 10:22:26 -0400152 &Device::AvailableIPConfigs);
Ben Chan923a5022013-09-20 11:23:23 -0700153 store_.RegisterConstString(kNameProperty, &link_name_);
154 store_.RegisterConstBool(kPoweredProperty, &enabled_);
155 HelpRegisterConstDerivedString(kTypeProperty,
mukesh agrawalbebf1b82013-04-23 15:06:33 -0700156 &Device::GetTechnologyString);
Ben Chan39a7beb2013-09-21 11:28:00 -0700157 HelpRegisterConstDerivedUint64(kLinkMonitorResponseTimeProperty,
Paul Stewart036dba02012-08-07 12:34:41 -0700158 &Device::GetLinkMonitorResponseTime);
Jason Glasgowb5790052012-01-27 01:03:52 -0500159
Chris Masoneb925cc82011-06-22 15:39:57 -0700160 // TODO(cmasone): Chrome doesn't use this...does anyone?
Ben Chan923a5022013-09-20 11:23:23 -0700161 // store_.RegisterConstBool(kReconnectProperty, &reconnect_);
Chris Masoneb925cc82011-06-22 15:39:57 -0700162
Chris Masone4e851612011-07-01 10:46:53 -0700163 // TODO(cmasone): Figure out what shill concept maps to flimflam's "Network".
Ben Chan923a5022013-09-20 11:23:23 -0700164 // known_properties_.push_back(kNetworksProperty);
Chris Masoneb925cc82011-06-22 15:39:57 -0700165
Wade Guthrie227c7742013-10-10 11:06:33 -0700166 // kRoamThresholdProperty: Registered in WiFi
Ben Chan923a5022013-09-20 11:23:23 -0700167 // kScanningProperty: Registered in WiFi, Cellular
168 // kScanIntervalProperty: Registered in WiFi, Cellular
Paul Stewart6ff27f52012-07-11 06:51:41 -0700169
170 if (manager_ && manager_->device_info()) { // Unit tests may not have these.
171 manager_->device_info()->GetByteCounts(
172 interface_index_, &receive_byte_offset_, &transmit_byte_offset_);
Ben Chan39a7beb2013-09-21 11:28:00 -0700173 HelpRegisterConstDerivedUint64(kReceiveByteCountProperty,
Ben Chanb061f892013-02-27 17:46:55 -0800174 &Device::GetReceiveByteCountProperty);
Ben Chan39a7beb2013-09-21 11:28:00 -0700175 HelpRegisterConstDerivedUint64(kTransmitByteCountProperty,
Ben Chanb061f892013-02-27 17:46:55 -0800176 &Device::GetTransmitByteCountProperty);
Paul Stewart6ff27f52012-07-11 06:51:41 -0700177 }
178
Darin Petkova0a0efe2012-06-27 12:50:01 +0200179 LOG(INFO) << "Device created: " << link_name_
180 << " index " << interface_index_;
Paul Stewart75897df2011-04-27 09:05:53 -0700181}
182
183Device::~Device() {
Darin Petkova0a0efe2012-06-27 12:50:01 +0200184 LOG(INFO) << "Device destructed: " << link_name_
185 << " index " << interface_index_;
Paul Stewart75897df2011-04-27 09:05:53 -0700186}
187
Paul Stewartf1ce5d22011-05-19 13:10:20 -0700188void Device::LinkEvent(unsigned flags, unsigned change) {
Ben Chanfad4a0b2012-04-18 15:49:59 -0700189 SLOG(Device, 2) << "Device " << link_name_
190 << std::showbase << std::hex
191 << " flags " << flags << " changed " << change
192 << std::dec << std::noshowbase;
Paul Stewartf1ce5d22011-05-19 13:10:20 -0700193}
194
Wade Guthrie4823f4f2013-07-25 10:03:03 -0700195void Device::Scan(ScanType scan_type, Error *error, const string &reason) {
196 SLOG(Device, 2) << __func__ << " [Device] on " << link_name() << " from "
197 << reason;
Paul Stewartbe005172011-11-02 18:10:29 -0700198 Error::PopulateAndLog(error, Error::kNotSupported,
199 "Device doesn't support scan.");
Paul Stewartf1ce5d22011-05-19 13:10:20 -0700200}
201
Eric Shienbrood9a245532012-03-07 14:20:39 -0500202void Device::RegisterOnNetwork(const std::string &/*network_id*/, Error *error,
203 const ResultCallback &/*callback*/) {
204 Error::PopulateAndLog(error, Error::kNotSupported,
Paul Stewartbe005172011-11-02 18:10:29 -0700205 "Device doesn't support network registration.");
Darin Petkov9ae310f2011-08-30 15:41:13 -0700206}
207
Darin Petkovc64fe5e2012-01-11 12:46:13 +0100208void Device::RequirePIN(
Eric Shienbrood9a245532012-03-07 14:20:39 -0500209 const string &/*pin*/, bool /*require*/,
210 Error *error, const ResultCallback &/*callback*/) {
Ben Chanfad4a0b2012-04-18 15:49:59 -0700211 SLOG(Device, 2) << __func__;
Eric Shienbrood9a245532012-03-07 14:20:39 -0500212 Error::PopulateAndLog(error, Error::kNotSupported,
213 "Device doesn't support RequirePIN.");
Darin Petkove42e1012011-08-31 12:35:04 -0700214}
215
Eric Shienbrood9a245532012-03-07 14:20:39 -0500216void Device::EnterPIN(const string &/*pin*/,
217 Error *error, const ResultCallback &/*callback*/) {
Ben Chanfad4a0b2012-04-18 15:49:59 -0700218 SLOG(Device, 2) << __func__;
Eric Shienbrood9a245532012-03-07 14:20:39 -0500219 Error::PopulateAndLog(error, Error::kNotSupported,
220 "Device doesn't support EnterPIN.");
Darin Petkove42e1012011-08-31 12:35:04 -0700221}
222
mukesh agrawal1830fa12011-09-26 14:31:40 -0700223void Device::UnblockPIN(const string &/*unblock_code*/,
224 const string &/*pin*/,
Eric Shienbrood9a245532012-03-07 14:20:39 -0500225 Error *error, const ResultCallback &/*callback*/) {
Ben Chanfad4a0b2012-04-18 15:49:59 -0700226 SLOG(Device, 2) << __func__;
Eric Shienbrood9a245532012-03-07 14:20:39 -0500227 Error::PopulateAndLog(error, Error::kNotSupported,
228 "Device doesn't support UnblockPIN.");
Darin Petkove42e1012011-08-31 12:35:04 -0700229}
230
mukesh agrawal1830fa12011-09-26 14:31:40 -0700231void Device::ChangePIN(const string &/*old_pin*/,
232 const string &/*new_pin*/,
Eric Shienbrood9a245532012-03-07 14:20:39 -0500233 Error *error, const ResultCallback &/*callback*/) {
Ben Chanfad4a0b2012-04-18 15:49:59 -0700234 SLOG(Device, 2) << __func__;
Eric Shienbrood9a245532012-03-07 14:20:39 -0500235 Error::PopulateAndLog(error, Error::kNotSupported,
236 "Device doesn't support ChangePIN.");
Darin Petkove42e1012011-08-31 12:35:04 -0700237}
238
Ben Chanad663e12013-01-08 01:58:47 -0800239void Device::Reset(Error *error, const ResultCallback &/*callback*/) {
240 SLOG(Device, 2) << __func__;
241 Error::PopulateAndLog(error, Error::kNotSupported,
242 "Device doesn't support Reset.");
243}
244
Darin Petkovc37a9c42012-09-06 15:28:22 +0200245void Device::SetCarrier(const string &/*carrier*/,
246 Error *error, const ResultCallback &/*callback*/) {
247 SLOG(Device, 2) << __func__;
248 Error::PopulateAndLog(error, Error::kNotSupported,
249 "Device doesn't support SetCarrier.");
250}
251
Ben Chanbcc6e012013-11-04 14:28:37 -0800252bool Device::IsIPv6Allowed() const {
253 return true;
254}
255
Paul Stewart2bf1d352011-12-06 15:02:55 -0800256void Device::DisableIPv6() {
Ben Chanbcc6e012013-11-04 14:28:37 -0800257 SLOG(Device, 2) << __func__;
Paul Stewart2bf1d352011-12-06 15:02:55 -0800258 SetIPFlag(IPAddress::kFamilyIPv6, kIPFlagDisableIPv6, "1");
259}
260
261void Device::EnableIPv6() {
Ben Chanbcc6e012013-11-04 14:28:37 -0800262 SLOG(Device, 2) << __func__;
263 if (!IsIPv6Allowed()) {
264 LOG(INFO) << "Skip enabling IPv6 on " << link_name_
265 << " as it is not allowed.";
266 return;
267 }
Paul Stewart2bf1d352011-12-06 15:02:55 -0800268 SetIPFlag(IPAddress::kFamilyIPv6, kIPFlagDisableIPv6, "0");
269}
270
271void Device::EnableIPv6Privacy() {
272 SetIPFlag(IPAddress::kFamilyIPv6, kIPFlagUseTempAddr,
273 kIPFlagUseTempAddrUsedAndDefault);
274}
275
Paul Stewartc8f4bef2011-12-13 09:45:51 -0800276void Device::DisableReversePathFilter() {
277 // TODO(pstew): Current kernel doesn't offer reverse-path filtering flag
Paul Stewartee6b3d72013-07-12 16:07:51 -0700278 // for IPv6. crbug.com/207193
Paul Stewartc8f4bef2011-12-13 09:45:51 -0800279 SetIPFlag(IPAddress::kFamilyIPv4, kIPFlagReversePathFilter,
280 kIPFlagReversePathFilterLooseMode);
281}
282
283void Device::EnableReversePathFilter() {
284 SetIPFlag(IPAddress::kFamilyIPv4, kIPFlagReversePathFilter,
285 kIPFlagReversePathFilterEnabled);
286}
287
Gaurav Shah435de2c2011-11-17 19:01:07 -0800288bool Device::IsConnected() const {
289 if (selected_service_)
290 return selected_service_->IsConnected();
291 return false;
292}
293
Paul Stewartd215af62012-04-24 23:25:50 -0700294bool Device::IsConnectedToService(const ServiceRefPtr &service) const {
295 return service == selected_service_ && IsConnected();
296}
297
Paul Stewartfa11e282013-12-02 22:04:25 -0800298bool Device::IsConnectedViaTether() const {
299 return
300 ipconfig_.get() &&
301 ipconfig_->properties().vendor_encapsulated_options ==
302 Tethering::kAndroidVendorEncapsulatedOptions;
303}
304
mukesh agrawalf6b32092013-04-10 15:49:55 -0700305string Device::GetRpcIdentifier() const {
Chris Masone27c4aa52011-07-02 13:10:14 -0700306 return adaptor_->GetRpcIdentifier();
Chris Masone8fe2c7e2011-06-09 15:51:19 -0700307}
308
Chris Masone5dec5f42011-07-22 14:07:55 -0700309string Device::GetStorageIdentifier() {
310 string id = GetRpcIdentifier();
311 ControlInterface::RpcIdToStorageId(&id);
Chris Masone626719f2011-08-18 16:58:48 -0700312 size_t needle = id.find('_');
Chris Masone34af2182011-08-22 11:59:36 -0700313 DLOG_IF(ERROR, needle == string::npos) << "No _ in storage id?!?!";
Chris Masone626719f2011-08-18 16:58:48 -0700314 id.replace(id.begin() + needle + 1, id.end(), hardware_address_);
Chris Masone5dec5f42011-07-22 14:07:55 -0700315 return id;
316}
317
Gaurav Shah6d2c72d2012-10-16 16:30:44 -0700318vector<GeolocationInfo> Device::GetGeolocationObjects() const {
319 return vector<GeolocationInfo>();
Wade Guthrie227c7742013-10-10 11:06:33 -0700320}
Gaurav Shah6d2c72d2012-10-16 16:30:44 -0700321
Jason Glasgowb5790052012-01-27 01:03:52 -0500322string Device::GetTechnologyString(Error */*error*/) {
323 return Technology::NameFromIdentifier(technology());
324}
325
Chris Masone19e30402011-07-19 15:48:47 -0700326const string& Device::FriendlyName() const {
Chris Masone7df0c672011-07-15 10:24:54 -0700327 return link_name_;
Darin Petkovafa6fc42011-06-21 16:21:08 -0700328}
329
Chris Masone19e30402011-07-19 15:48:47 -0700330const string& Device::UniqueName() const {
331 return unique_id_;
332}
333
Chris Masone5dec5f42011-07-22 14:07:55 -0700334bool Device::Load(StoreInterface *storage) {
335 const string id = GetStorageIdentifier();
336 if (!storage->ContainsGroup(id)) {
337 LOG(WARNING) << "Device is not available in the persistent store: " << id;
338 return false;
339 }
Eric Shienbrood9a245532012-03-07 14:20:39 -0500340 enabled_persistent_ = true;
341 storage->GetBool(id, kStoragePowered, &enabled_persistent_);
Paul Stewart6ff27f52012-07-11 06:51:41 -0700342 uint64 rx_byte_count = 0, tx_byte_count = 0;
343
344 manager_->device_info()->GetByteCounts(
345 interface_index_, &rx_byte_count, &tx_byte_count);
346 // If there is a byte-count present in the profile, the return value
347 // of Device::Get*ByteCount() should be the this stored value plus
348 // whatever additional bytes we receive since time-of-load. We
349 // accomplish this by the subtractions below, which can validly
350 // roll over "negative" in the subtractions below and in Get*ByteCount.
351 uint64 profile_byte_count;
352 if (storage->GetUint64(id, kStorageReceiveByteCount, &profile_byte_count)) {
353 receive_byte_offset_ = rx_byte_count - profile_byte_count;
354 }
355 if (storage->GetUint64(id, kStorageTransmitByteCount, &profile_byte_count)) {
356 transmit_byte_offset_ = tx_byte_count - profile_byte_count;
357 }
358
Chris Masone5dec5f42011-07-22 14:07:55 -0700359 return true;
360}
361
362bool Device::Save(StoreInterface *storage) {
363 const string id = GetStorageIdentifier();
Eric Shienbrood9a245532012-03-07 14:20:39 -0500364 storage->SetBool(id, kStoragePowered, enabled_persistent_);
Ben Chanb061f892013-02-27 17:46:55 -0800365 storage->SetUint64(id, kStorageReceiveByteCount, GetReceiveByteCount());
366 storage->SetUint64(id, kStorageTransmitByteCount, GetTransmitByteCount());
Chris Masone5dec5f42011-07-22 14:07:55 -0700367 return true;
368}
369
mukesh agrawal784566d2012-08-08 18:32:58 -0700370void Device::OnBeforeSuspend() {
371 // Nothing to be done in the general case.
372}
373
374void Device::OnAfterResume() {
375 if (ipconfig_) {
376 SLOG(Device, 3) << "Renewing IP address on resume.";
377 ipconfig_->RenewIP();
378 }
mukesh agrawalbb2231c2013-07-17 16:32:24 -0700379 if (link_monitor_) {
380 SLOG(Device, 3) << "Informing Link Monitor of resume.";
381 link_monitor_->OnAfterResume();
382 }
mukesh agrawal784566d2012-08-08 18:32:58 -0700383}
384
Darin Petkov2b8e44e2012-06-25 15:13:26 +0200385void Device::DropConnection() {
386 SLOG(Device, 2) << __func__;
387 DestroyIPConfig();
388 SelectService(NULL);
389}
390
Darin Petkovafa6fc42011-06-21 16:21:08 -0700391void Device::DestroyIPConfig() {
Paul Stewart2bf1d352011-12-06 15:02:55 -0800392 DisableIPv6();
Darin Petkovafa6fc42011-06-21 16:21:08 -0700393 if (ipconfig_.get()) {
Paul Stewart217c61d2013-06-13 15:12:02 -0700394 ipconfig_->ReleaseIP(IPConfig::kReleaseReasonDisconnect);
Darin Petkovafa6fc42011-06-21 16:21:08 -0700395 ipconfig_ = NULL;
Paul Stewartd4f26482014-04-25 19:12:03 -0700396 UpdateIPConfigsProperty();
Darin Petkovafa6fc42011-06-21 16:21:08 -0700397 }
Paul Stewarte6132022011-08-16 09:11:02 -0700398 DestroyConnection();
Darin Petkovafa6fc42011-06-21 16:21:08 -0700399}
400
Paul Stewartd4f26482014-04-25 19:12:03 -0700401void Device::OnIPv6AddressChanged() {
402 IPAddress address(IPAddress::kFamilyIPv6);
403 if (!manager_->device_info()->GetPrimaryIPv6Address(
404 interface_index_, &address)) {
405 if (ip6config_) {
406 ip6config_ = NULL;
407 UpdateIPConfigsProperty();
408 }
409 return;
410 }
411
412 IPConfig::Properties properties;
413 if (!address.IntoString(&properties.address)) {
414 LOG(ERROR) << "Unable to convert IPv6 address into a string!";
415 return;
416 }
417 properties.subnet_prefix = address.prefix();
418
419 if (!ip6config_) {
420 ip6config_ = new IPConfig(control_interface_, link_name_);
421 } else if (properties.address == ip6config_->properties().address &&
422 properties.subnet_prefix ==
423 ip6config_->properties().subnet_prefix) {
424 SLOG(Device, 2) << __func__ << " primary address for "
425 << link_name_ << " is unchanged.";
426 return;
427 }
428
429 properties.address_family = IPAddress::kFamilyIPv6;
430 properties.method = kTypeIPv6;
431 ip6config_->set_properties(properties);
432 UpdateIPConfigsProperty();
433}
434
Arman Ugurayed8e6102012-11-29 14:47:20 -0800435bool Device::ShouldUseArpGateway() const {
436 return false;
437}
438
Paul Stewart75a68b92013-10-24 10:50:27 -0700439bool Device::ShouldUseMinimalDHCPConfig() const {
Paul Stewart7b5cee92014-06-25 02:03:34 -0700440 return false;
Paul Stewart75a68b92013-10-24 10:50:27 -0700441}
442
Paul Stewart316acef2014-05-29 18:40:48 -0700443bool Device::IsUsingStaticIP() const {
444 if (!selected_service_) {
445 return false;
446 }
447 return selected_service_->HasStaticIPAddress();
448}
449
Paul Stewart2bf1d352011-12-06 15:02:55 -0800450bool Device::AcquireIPConfig() {
Paul Stewartd408fdf2012-05-07 17:15:57 -0700451 return AcquireIPConfigWithLeaseName(string());
452}
453
454bool Device::AcquireIPConfigWithLeaseName(const string &lease_name) {
Darin Petkovafa6fc42011-06-21 16:21:08 -0700455 DestroyIPConfig();
Paul Stewart2bf1d352011-12-06 15:02:55 -0800456 EnableIPv6();
Arman Ugurayed8e6102012-11-29 14:47:20 -0800457 bool arp_gateway = manager_->GetArpGateway() && ShouldUseArpGateway();
Paul Stewartd408fdf2012-05-07 17:15:57 -0700458 ipconfig_ = dhcp_provider_->CreateConfig(link_name_,
459 manager_->GetHostName(),
460 lease_name,
Paul Stewart75a68b92013-10-24 10:50:27 -0700461 arp_gateway,
462 ShouldUseMinimalDHCPConfig());
Eric Shienbrood9a245532012-03-07 14:20:39 -0500463 ipconfig_->RegisterUpdateCallback(Bind(&Device::OnIPConfigUpdated,
464 weak_ptr_factory_.GetWeakPtr()));
Paul Stewartc5099532013-12-12 07:53:15 -0800465 ipconfig_->RegisterFailureCallback(Bind(&Device::OnIPConfigFailed,
466 weak_ptr_factory_.GetWeakPtr()));
Paul Stewart82236532013-12-10 15:33:11 -0800467 ipconfig_->RegisterRefreshCallback(Bind(&Device::OnIPConfigRefreshed,
468 weak_ptr_factory_.GetWeakPtr()));
Paul Stewart1f916e42013-12-23 09:52:54 -0800469 ipconfig_->RegisterExpireCallback(Bind(&Device::OnIPConfigExpired,
470 weak_ptr_factory_.GetWeakPtr()));
Paul Stewart1062d9d2012-04-27 10:42:27 -0700471 dispatcher_->PostTask(Bind(&Device::ConfigureStaticIPTask,
472 weak_ptr_factory_.GetWeakPtr()));
Darin Petkovafa6fc42011-06-21 16:21:08 -0700473 return ipconfig_->RequestIP();
474}
475
Ben Chan539ab022014-02-03 16:34:57 -0800476void Device::AssignIPConfig(const IPConfig::Properties &properties) {
477 DestroyIPConfig();
478 EnableIPv6();
479 ipconfig_ = new IPConfig(control_interface_, link_name_);
480 ipconfig_->set_properties(properties);
481 dispatcher_->PostTask(Bind(&Device::OnIPConfigUpdated,
482 weak_ptr_factory_.GetWeakPtr(), ipconfig_));
483}
484
Albert Chaulk0e1cdea2013-02-27 15:32:55 -0800485void Device::DestroyIPConfigLease(const string &name) {
486 dhcp_provider_->DestroyLease(name);
487}
488
mukesh agrawalbebf1b82013-04-23 15:06:33 -0700489void Device::HelpRegisterConstDerivedString(
Jason Glasgowb5790052012-01-27 01:03:52 -0500490 const string &name,
mukesh agrawalbebf1b82013-04-23 15:06:33 -0700491 string(Device::*get)(Error *error)) {
Jason Glasgowb5790052012-01-27 01:03:52 -0500492 store_.RegisterDerivedString(
493 name,
mukesh agrawalbebf1b82013-04-23 15:06:33 -0700494 StringAccessor(new CustomAccessor<Device, string>(this, get, NULL)));
Chris Masone4e851612011-07-01 10:46:53 -0700495}
496
Jason Glasgow08afdff2012-04-03 10:22:26 -0400497void Device::HelpRegisterConstDerivedRpcIdentifiers(
498 const string &name,
499 RpcIdentifiers(Device::*get)(Error *)) {
500 store_.RegisterDerivedRpcIdentifiers(
501 name,
502 RpcIdentifiersAccessor(
503 new CustomAccessor<Device, RpcIdentifiers>(this, get, NULL)));
504}
505
Paul Stewart6ff27f52012-07-11 06:51:41 -0700506void Device::HelpRegisterConstDerivedUint64(
507 const string &name,
508 uint64(Device::*get)(Error *)) {
509 store_.RegisterDerivedUint64(
510 name,
511 Uint64Accessor(
512 new CustomAccessor<Device, uint64>(this, get, NULL)));
513}
514
Paul Stewart1062d9d2012-04-27 10:42:27 -0700515void Device::ConfigureStaticIPTask() {
516 SLOG(Device, 2) << __func__ << " selected_service " << selected_service_.get()
517 << " ipconfig " << ipconfig_.get();
518
519 if (!selected_service_ || !ipconfig_) {
520 return;
521 }
522
Paul Stewart316acef2014-05-29 18:40:48 -0700523 if (IsUsingStaticIP()) {
Paul Stewart1062d9d2012-04-27 10:42:27 -0700524 SLOG(Device, 2) << __func__ << " " << " configuring static IP parameters.";
525 // If the parameters contain an IP address, apply them now and bring
526 // the interface up. When DHCP information arrives, it will supplement
527 // the static information.
Paul Stewartc5099532013-12-12 07:53:15 -0800528 OnIPConfigUpdated(ipconfig_);
Paul Stewart1062d9d2012-04-27 10:42:27 -0700529 } else {
Paul Stewart82236532013-12-10 15:33:11 -0800530 // Either |ipconfig_| has just been created in AcquireIPConfig() or
531 // we're being called by OnIPConfigRefreshed(). In either case a
532 // DHCP client has been started, and will take care of calling
533 // OnIPConfigUpdated() when it completes.
Paul Stewart1062d9d2012-04-27 10:42:27 -0700534 SLOG(Device, 2) << __func__ << " " << " no static IP address.";
535 }
536}
537
Paul Stewartc5099532013-12-12 07:53:15 -0800538void Device::OnIPConfigUpdated(const IPConfigRefPtr &ipconfig) {
539 SLOG(Device, 2) << __func__;
540 CreateConnection();
541 if (selected_service_) {
542 ipconfig->ApplyStaticIPParameters(
543 selected_service_->mutable_static_ip_parameters());
Paul Stewart316acef2014-05-29 18:40:48 -0700544 if (IsUsingStaticIP()) {
Paul Stewartc5099532013-12-12 07:53:15 -0800545 // If we are using a statically configured IP address instead
546 // of a leased IP address, release any acquired lease so it may
547 // be used by others. This allows us to merge other non-leased
548 // parameters (like DNS) when they're available from a DHCP server
549 // and not overridden by static parameters, but at the same time
550 // we avoid taking up a dynamic IP address the DHCP server could
551 // assign to someone else who might actually use it.
552 ipconfig->ReleaseIP(IPConfig::kReleaseReasonStaticIP);
Paul Stewart1062d9d2012-04-27 10:42:27 -0700553 }
Paul Stewartc39f1132011-06-22 12:02:28 -0700554 }
Paul Stewartc5099532013-12-12 07:53:15 -0800555 connection_->UpdateFromIPConfig(ipconfig);
556 // SetConnection must occur after the UpdateFromIPConfig so the
557 // service can use the values derived from the connection.
558 if (selected_service_) {
Paul Stewartc5099532013-12-12 07:53:15 -0800559 selected_service_->SetConnection(connection_);
560 }
561 // The service state change needs to happen last, so that at the
562 // time we report the state change to the manager, the service
563 // has its connection.
564 SetServiceState(Service::kStateConnected);
565 OnConnected();
566 portal_attempts_to_online_ = 0;
567 // Subtle: Start portal detection after transitioning the service
568 // to the Connected state because this call may immediately transition
569 // to the Online state.
570 if (selected_service_) {
571 StartPortalDetection();
572 }
573 StartLinkMonitor();
Peter Qiudc335f82014-05-15 10:33:17 -0700574 StartTrafficMonitor();
Paul Stewartd4f26482014-04-25 19:12:03 -0700575 UpdateIPConfigsProperty();
Paul Stewartc5099532013-12-12 07:53:15 -0800576}
577
578void Device::OnIPConfigFailed(const IPConfigRefPtr &ipconfig) {
579 SLOG(Device, 2) << __func__;
580 // TODO(pstew): This logic gets yet more complex when multiple
581 // IPConfig types are run in parallel (e.g. DHCP and DHCP6)
582 if (selected_service_) {
Paul Stewart316acef2014-05-29 18:40:48 -0700583 if (IsUsingStaticIP()) {
Paul Stewartc5099532013-12-12 07:53:15 -0800584 // Consider three cases:
585 //
586 // 1. We're here because DHCP failed while starting up. There
587 // are two subcases:
588 // a. DHCP has failed, and Static IP config has _not yet_
589 // completed. It's fine to do nothing, because we'll
590 // apply the static config shortly.
591 // b. DHCP has failed, and Static IP config has _already_
592 // completed. It's fine to do nothing, because we can
593 // continue to use the static config that's already
594 // been applied.
595 //
596 // 2. We're here because a previously valid DHCP configuration
597 // is no longer valid. There's still a static IP config,
598 // because the condition in the if clause evaluated to true.
599 // Furthermore, the static config includes an IP address for
600 // us to use.
601 //
602 // The current configuration may include some DHCP
603 // parameters, overriden by any static parameters
604 // provided. We continue to use this configuration, because
605 // the only configuration element that is leased to us (IP
606 // address) will be overriden by a static parameter.
607 return;
608 }
609 }
610
611 ipconfig->ResetProperties();
612 OnIPConfigFailure();
Paul Stewartd4f26482014-04-25 19:12:03 -0700613 UpdateIPConfigsProperty();
Paul Stewartc5099532013-12-12 07:53:15 -0800614 DestroyConnection();
Chris Masone8fe2c7e2011-06-09 15:51:19 -0700615}
616
Paul Stewart82236532013-12-10 15:33:11 -0800617void Device::OnIPConfigRefreshed(const IPConfigRefPtr &ipconfig) {
618 // Clear the previously applied static IP parameters.
619 ipconfig->RestoreSavedIPParameters(
620 selected_service_->mutable_static_ip_parameters());
621
622 dispatcher_->PostTask(Bind(&Device::ConfigureStaticIPTask,
623 weak_ptr_factory_.GetWeakPtr()));
624}
625
Paul Stewartf6f96482013-07-12 12:49:15 -0700626void Device::OnIPConfigFailure() {
627 if (selected_service_) {
628 Error error;
629 selected_service_->DisconnectWithFailure(Service::kFailureDHCP, &error);
630 }
631}
632
Paul Stewart1f916e42013-12-23 09:52:54 -0800633void Device::OnIPConfigExpired(const IPConfigRefPtr &ipconfig) {
634 metrics()->SendToUMA(
635 metrics()->GetFullMetricName(
mukesh agrawal132e96f2014-04-24 11:49:42 -0700636 Metrics::kMetricExpiredLeaseLengthSecondsSuffix, technology()),
Paul Stewart1f916e42013-12-23 09:52:54 -0800637 ipconfig->properties().lease_duration_seconds,
638 Metrics::kMetricExpiredLeaseLengthSecondsMin,
639 Metrics::kMetricExpiredLeaseLengthSecondsMax,
640 Metrics::kMetricExpiredLeaseLengthSecondsNumBuckets);
641}
642
Christopher Wiley5519e9e2013-01-08 16:55:56 -0800643void Device::OnConnected() {}
644
Paul Stewart8596f9f2013-03-14 07:58:26 -0700645void Device::OnConnectionUpdated() {
646 if (selected_service_) {
647 manager_->UpdateService(selected_service_);
648 }
649}
650
Paul Stewarte6132022011-08-16 09:11:02 -0700651void Device::CreateConnection() {
Ben Chanfad4a0b2012-04-18 15:49:59 -0700652 SLOG(Device, 2) << __func__;
Paul Stewarte6132022011-08-16 09:11:02 -0700653 if (!connection_.get()) {
mukesh agrawal23ac6b72013-01-31 18:52:37 -0800654 connection_ = new Connection(interface_index_,
655 link_name_,
656 technology_,
657 manager_->device_info());
Paul Stewarte6132022011-08-16 09:11:02 -0700658 }
659}
660
661void Device::DestroyConnection() {
mukesh agrawal6813e762013-07-10 19:05:08 -0700662 SLOG(Device, 2) << __func__ << " on " << link_name_;
Peter Qiudc335f82014-05-15 10:33:17 -0700663 StopTrafficMonitor();
Paul Stewart20088d82012-02-16 06:58:55 -0800664 StopPortalDetection();
Paul Stewart036dba02012-08-07 12:34:41 -0700665 StopLinkMonitor();
Paul Stewartbe5f5b32011-12-07 17:11:11 -0800666 if (selected_service_.get()) {
mukesh agrawal6813e762013-07-10 19:05:08 -0700667 SLOG(Device, 3) << "Clearing connection of service "
668 << selected_service_->unique_name();
Paul Stewartc1dec4d2011-12-08 15:25:28 -0800669 selected_service_->SetConnection(NULL);
Paul Stewartbe5f5b32011-12-07 17:11:11 -0800670 }
Paul Stewartc8f4bef2011-12-13 09:45:51 -0800671 connection_ = NULL;
Paul Stewarte6132022011-08-16 09:11:02 -0700672}
673
Paul Stewart03dba0b2011-08-22 16:32:45 -0700674void Device::SelectService(const ServiceRefPtr &service) {
Darin Petkov457728b2013-01-09 09:49:08 +0100675 SLOG(Device, 2) << __func__ << ": service "
mukesh agrawal6813e762013-07-10 19:05:08 -0700676 << (service ? service->unique_name() : "*reset*")
677 << " on " << link_name_;
mukesh agrawal8a3188d2011-12-01 20:56:44 +0000678
679 if (selected_service_.get() == service.get()) {
680 // No change to |selected_service_|. Return early to avoid
681 // changing its state.
682 return;
683 }
684
Paul Stewartbe5f5b32011-12-07 17:11:11 -0800685 if (selected_service_.get()) {
686 if (selected_service_->state() != Service::kStateFailure) {
687 selected_service_->SetState(Service::kStateIdle);
688 }
Paul Stewart20b0a092012-05-22 20:39:57 -0700689 // Just in case the Device subclass has not already done so, make
690 // sure the previously selected service has its connection removed.
Paul Stewartc1dec4d2011-12-08 15:25:28 -0800691 selected_service_->SetConnection(NULL);
Peter Qiudc335f82014-05-15 10:33:17 -0700692 StopTrafficMonitor();
Paul Stewartc8860612012-09-28 07:36:21 -0700693 StopLinkMonitor();
694 StopPortalDetection();
Paul Stewart03dba0b2011-08-22 16:32:45 -0700695 }
696 selected_service_ = service;
697}
698
699void Device::SetServiceState(Service::ConnectState state) {
700 if (selected_service_.get()) {
701 selected_service_->SetState(state);
702 }
703}
704
705void Device::SetServiceFailure(Service::ConnectFailure failure_state) {
706 if (selected_service_.get()) {
707 selected_service_->SetFailure(failure_state);
708 }
709}
710
Eric Shienbroodcc95c5d2012-03-30 15:25:49 -0400711void Device::SetServiceFailureSilent(Service::ConnectFailure failure_state) {
712 if (selected_service_.get()) {
713 selected_service_->SetFailureSilent(failure_state);
714 }
715}
716
Paul Stewart2bf1d352011-12-06 15:02:55 -0800717bool Device::SetIPFlag(IPAddress::Family family, const string &flag,
718 const string &value) {
719 string ip_version;
720 if (family == IPAddress::kFamilyIPv4) {
721 ip_version = kIPFlagVersion4;
722 } else if (family == IPAddress::kFamilyIPv6) {
723 ip_version = kIPFlagVersion6;
724 } else {
725 NOTIMPLEMENTED();
726 }
727 FilePath flag_file(StringPrintf(kIPFlagTemplate, ip_version.c_str(),
728 link_name_.c_str(), flag.c_str()));
Ben Chanfad4a0b2012-04-18 15:49:59 -0700729 SLOG(Device, 2) << "Writing " << value << " to flag file "
730 << flag_file.value();
Ben Chan6fbf64f2014-05-21 18:07:01 -0700731 if (base::WriteFile(flag_file, value.c_str(), value.length()) != 1) {
Paul Stewart2bf1d352011-12-06 15:02:55 -0800732 LOG(ERROR) << StringPrintf("IP flag write failed: %s to %s",
733 value.c_str(), flag_file.value().c_str());
734 return false;
735 }
736 return true;
737}
738
Paul Stewartc6fbad92013-11-13 14:50:52 -0800739string Device::PerformTDLSOperation(const string &/* operation */,
740 const string &/* peer */,
741 Error */* error */) {
742 return "";
743}
744
Paul Stewart6ff27f52012-07-11 06:51:41 -0700745void Device::ResetByteCounters() {
746 manager_->device_info()->GetByteCounts(
747 interface_index_, &receive_byte_offset_, &transmit_byte_offset_);
748 manager_->UpdateDevice(this);
749}
750
Paul Stewartd215af62012-04-24 23:25:50 -0700751bool Device::RestartPortalDetection() {
752 StopPortalDetection();
753 return StartPortalDetection();
754}
755
Paul Stewartc681fa02012-03-02 19:40:04 -0800756bool Device::RequestPortalDetection() {
757 if (!selected_service_) {
Ben Chanfad4a0b2012-04-18 15:49:59 -0700758 SLOG(Device, 2) << FriendlyName()
Paul Stewartc681fa02012-03-02 19:40:04 -0800759 << ": No selected service, so no need for portal check.";
760 return false;
761 }
762
763 if (!connection_.get()) {
Ben Chanfad4a0b2012-04-18 15:49:59 -0700764 SLOG(Device, 2) << FriendlyName()
Paul Stewartc681fa02012-03-02 19:40:04 -0800765 << ": No connection, so no need for portal check.";
766 return false;
767 }
768
769 if (selected_service_->state() != Service::kStatePortal) {
Ben Chanfad4a0b2012-04-18 15:49:59 -0700770 SLOG(Device, 2) << FriendlyName()
Paul Stewartc681fa02012-03-02 19:40:04 -0800771 << ": Service is not in portal state. No need to start check.";
772 return false;
773 }
774
775 if (!connection_->is_default()) {
Ben Chanfad4a0b2012-04-18 15:49:59 -0700776 SLOG(Device, 2) << FriendlyName()
Paul Stewartc681fa02012-03-02 19:40:04 -0800777 << ": Service is not the default connection. Don't start check.";
778 return false;
779 }
780
781 if (portal_detector_.get() && portal_detector_->IsInProgress()) {
Ben Chanfad4a0b2012-04-18 15:49:59 -0700782 SLOG(Device, 2) << FriendlyName()
783 << ": Portal detection is already running.";
Paul Stewartc681fa02012-03-02 19:40:04 -0800784 return true;
785 }
786
787 return StartPortalDetection();
788}
789
Paul Stewart20088d82012-02-16 06:58:55 -0800790bool Device::StartPortalDetection() {
Darin Petkov457728b2013-01-09 09:49:08 +0100791 DCHECK(selected_service_);
Paul Stewartd215af62012-04-24 23:25:50 -0700792 if (selected_service_->IsPortalDetectionDisabled()) {
Darin Petkov457728b2013-01-09 09:49:08 +0100793 SLOG(Device, 2) << "Service " << selected_service_->unique_name()
Paul Stewartd215af62012-04-24 23:25:50 -0700794 << ": Portal detection is disabled; "
795 << "marking service online.";
796 SetServiceConnectedState(Service::kStateOnline);
797 return false;
798 }
799
800 if (selected_service_->IsPortalDetectionAuto() &&
801 !manager_->IsPortalDetectionEnabled(technology())) {
Paul Stewart20088d82012-02-16 06:58:55 -0800802 // If portal detection is disabled for this technology, immediately set
803 // the service state to "Online".
Ben Chanfad4a0b2012-04-18 15:49:59 -0700804 SLOG(Device, 2) << "Device " << FriendlyName()
805 << ": Portal detection is disabled; "
806 << "marking service online.";
Paul Stewart20088d82012-02-16 06:58:55 -0800807 SetServiceConnectedState(Service::kStateOnline);
808 return false;
809 }
810
Paul Stewart20088d82012-02-16 06:58:55 -0800811 if (selected_service_->HasProxyConfig()) {
812 // Services with HTTP proxy configurations should not be checked by the
813 // connection manager, since we don't have the ability to evaluate
814 // arbitrary proxy configs and their possible credentials.
Ben Chanfad4a0b2012-04-18 15:49:59 -0700815 SLOG(Device, 2) << "Device " << FriendlyName()
816 << ": Service has proxy config; marking it online.";
Paul Stewart20088d82012-02-16 06:58:55 -0800817 SetServiceConnectedState(Service::kStateOnline);
818 return false;
819 }
820
821 portal_detector_.reset(new PortalDetector(connection_,
822 dispatcher_,
Eric Shienbrood3e20a232012-02-16 11:35:56 -0500823 portal_detector_callback_));
Paul Stewart20088d82012-02-16 06:58:55 -0800824 if (!portal_detector_->Start(manager_->GetPortalCheckURL())) {
825 LOG(ERROR) << "Device " << FriendlyName()
826 << ": Portal detection failed to start: likely bad URL: "
827 << manager_->GetPortalCheckURL();
828 SetServiceConnectedState(Service::kStateOnline);
829 return false;
830 }
831
Ben Chanfad4a0b2012-04-18 15:49:59 -0700832 SLOG(Device, 2) << "Device " << FriendlyName()
833 << ": Portal detection has started.";
Paul Stewart20088d82012-02-16 06:58:55 -0800834 return true;
835}
836
837void Device::StopPortalDetection() {
Ben Chanfad4a0b2012-04-18 15:49:59 -0700838 SLOG(Device, 2) << "Device " << FriendlyName()
mukesh agrawalbb2231c2013-07-17 16:32:24 -0700839 << ": Portal detection stopping.";
Paul Stewart20088d82012-02-16 06:58:55 -0800840 portal_detector_.reset();
841}
842
Paul Stewart036dba02012-08-07 12:34:41 -0700843void Device::set_link_monitor(LinkMonitor *link_monitor) {
844 link_monitor_.reset(link_monitor);
845}
846
847bool Device::StartLinkMonitor() {
848 if (!manager_->IsTechnologyLinkMonitorEnabled(technology())) {
849 SLOG(Device, 2) << "Device " << FriendlyName()
850 << ": Link Monitoring is disabled.";
851 return false;
852 }
853
854 if (!link_monitor()) {
855 set_link_monitor(
856 new LinkMonitor(
857 connection_, dispatcher_, metrics(), manager_->device_info(),
Peter Qiub5d124f2014-04-14 12:05:02 -0700858 Bind(&Device::OnLinkMonitorFailure, weak_ptr_factory_.GetWeakPtr()),
859 Bind(&Device::OnLinkMonitorGatewayChange,
860 weak_ptr_factory_.GetWeakPtr())));
Paul Stewart036dba02012-08-07 12:34:41 -0700861 }
862
863 SLOG(Device, 2) << "Device " << FriendlyName()
864 << ": Link Monitor starting.";
865 return link_monitor_->Start();
866}
867
868void Device::StopLinkMonitor() {
869 SLOG(Device, 2) << "Device " << FriendlyName()
870 << ": Link Monitor stopping.";
871 link_monitor_.reset();
872}
873
874void Device::OnLinkMonitorFailure() {
875 LOG(ERROR) << "Device " << FriendlyName()
876 << ": Link Monitor indicates failure.";
877}
878
Peter Qiu9d581932014-04-14 16:37:37 -0700879void Device::OnLinkMonitorGatewayChange() {
880 string gateway_mac = link_monitor()->gateway_mac_address().HexEncode();
881 int connection_id = manager_->CalcConnectionId(
882 ipconfig_->properties().gateway, gateway_mac);
883
884 CHECK(selected_service_);
885 selected_service_->set_connection_id(connection_id);
886
887 manager_->ReportServicesOnSameNetwork(connection_id);
888}
889
Peter Qiub9256f32014-05-09 15:27:29 -0700890void Device::PerformFallbackDNSTest() {
891 // Return if DNS client already running.
Alex Vakulenko8a532292014-06-16 17:18:44 -0700892 if (fallback_dns_test_client_.get()) {
Peter Qiub9256f32014-05-09 15:27:29 -0700893 return;
894 }
895
896 // Send DNS request to Google's DNS server.
897 vector<string> dns_servers(std::begin(kFallbackDnsServers),
898 std::end(kFallbackDnsServers));
899 fallback_dns_test_client_.reset(
900 dns_client_factory_->CreateDNSClient(IPAddress::kFamilyIPv4,
901 connection_->interface_name(),
902 dns_servers,
903 kDNSTimeoutMilliseconds,
904 dispatcher_,
905 dns_client_callback_));
906 Error error;
907 if (!fallback_dns_test_client_->Start(kFallbackDnsTestHostname, &error)) {
908 LOG(ERROR) << __func__ << ": Failed to start DNS client "
909 << error.message();
910 fallback_dns_test_client_.reset();
911 }
912}
913
914void Device::DNSClientCallback(const Error &error, const IPAddress& ip) {
Peter Qiuf18e7712014-05-20 09:59:46 -0700915 int result = Metrics::kFallbackDNSTestResultFailure;
Peter Qiub9256f32014-05-09 15:27:29 -0700916 if (error.IsSuccess()) {
Peter Qiuf18e7712014-05-20 09:59:46 -0700917 result = Metrics::kFallbackDNSTestResultSuccess;
Peter Qiub9256f32014-05-09 15:27:29 -0700918 }
Peter Qiuf18e7712014-05-20 09:59:46 -0700919 metrics()->NotifyFallbackDNSTestResult(technology_, result);
Peter Qiub9256f32014-05-09 15:27:29 -0700920 fallback_dns_test_client_.reset();
921}
922
Peter Qiudc335f82014-05-15 10:33:17 -0700923void Device::set_traffic_monitor(TrafficMonitor *traffic_monitor) {
924 traffic_monitor_.reset(traffic_monitor);
925}
926
927bool Device::IsTrafficMonitorEnabled() const {
928 return false;
929}
930
931void Device::StartTrafficMonitor() {
932 // Return if traffic monitor is not enabled for this device.
933 if (!IsTrafficMonitorEnabled()) {
934 return;
935 }
936
937 SLOG(Device, 2) << "Device " << FriendlyName()
938 << ": Traffic Monitor starting.";
939 if (!traffic_monitor_.get()) {
940 traffic_monitor_.reset(new TrafficMonitor(this, dispatcher_));
941 traffic_monitor_->set_network_problem_detected_callback(
942 Bind(&Device::OnEncounterNetworkProblem,
943 weak_ptr_factory_.GetWeakPtr()));
944 }
945 traffic_monitor_->Start();
946}
947
948void Device::StopTrafficMonitor() {
949 // Return if traffic monitor is not enabled for this device.
950 if (!IsTrafficMonitorEnabled()) {
951 return;
952 }
953
954 if (traffic_monitor_.get()) {
955 SLOG(Device, 2) << "Device " << FriendlyName()
956 << ": Traffic Monitor stopping.";
957 traffic_monitor_->Stop();
958 }
959 traffic_monitor_.reset();
960}
961
962void Device::OnEncounterNetworkProblem(int reason) {
963 int metric_code;
964 switch (reason) {
965 case TrafficMonitor::kNetworkProblemCongestedTxQueue:
966 metric_code = Metrics::kNetworkProblemCongestedTCPTxQueue;
967 break;
968 case TrafficMonitor::kNetworkProblemDNSFailure:
969 metric_code = Metrics::kNetworkProblemDNSFailure;
970 break;
971 default:
972 LOG(ERROR) << "Invalid network problem code: " << reason;
973 return;
974 }
975
976 metrics()->NotifyNetworkProblemDetected(technology_, metric_code);
977 // Stop the traffic monitor, only report the first network problem detected
978 // on the connection for now.
979 StopTrafficMonitor();
980}
981
Paul Stewart20088d82012-02-16 06:58:55 -0800982void Device::SetServiceConnectedState(Service::ConnectState state) {
983 DCHECK(selected_service_.get());
984
985 if (!selected_service_.get()) {
986 LOG(ERROR) << FriendlyName() << ": "
987 << "Portal detection completed but no selected service exists!";
988 return;
989 }
990
991 if (!selected_service_->IsConnected()) {
992 LOG(ERROR) << FriendlyName() << ": "
993 << "Portal detection completed but selected service "
Darin Petkov457728b2013-01-09 09:49:08 +0100994 << selected_service_->unique_name()
Paul Stewart20088d82012-02-16 06:58:55 -0800995 << " is in non-connected state.";
996 return;
997 }
998
Paul Stewartc681fa02012-03-02 19:40:04 -0800999 if (state == Service::kStatePortal && connection_->is_default() &&
1000 manager_->GetPortalCheckInterval() != 0) {
1001 CHECK(portal_detector_.get());
1002 if (!portal_detector_->StartAfterDelay(
1003 manager_->GetPortalCheckURL(),
1004 manager_->GetPortalCheckInterval())) {
1005 LOG(ERROR) << "Device " << FriendlyName()
1006 << ": Portal detection failed to restart: likely bad URL: "
1007 << manager_->GetPortalCheckURL();
1008 SetServiceState(Service::kStateOnline);
1009 portal_detector_.reset();
1010 return;
1011 }
Ben Chanfad4a0b2012-04-18 15:49:59 -07001012 SLOG(Device, 2) << "Device " << FriendlyName()
1013 << ": Portal detection retrying.";
Paul Stewartc681fa02012-03-02 19:40:04 -08001014 } else {
Ben Chanfad4a0b2012-04-18 15:49:59 -07001015 SLOG(Device, 2) << "Device " << FriendlyName()
1016 << ": Portal will not retry.";
Paul Stewartc681fa02012-03-02 19:40:04 -08001017 portal_detector_.reset();
1018 }
1019
Paul Stewart20088d82012-02-16 06:58:55 -08001020 SetServiceState(state);
1021}
1022
1023void Device::PortalDetectorCallback(const PortalDetector::Result &result) {
1024 if (!result.final) {
Ben Chanfad4a0b2012-04-18 15:49:59 -07001025 SLOG(Device, 2) << "Device " << FriendlyName()
1026 << ": Received non-final status: "
1027 << PortalDetector::StatusToString(result.status);
Paul Stewart20088d82012-02-16 06:58:55 -08001028 return;
1029 }
1030
Ben Chanfad4a0b2012-04-18 15:49:59 -07001031 SLOG(Device, 2) << "Device " << FriendlyName()
1032 << ": Received final status: "
1033 << PortalDetector::StatusToString(result.status);
Paul Stewart20088d82012-02-16 06:58:55 -08001034
Thieu Le85e050b2012-03-13 15:04:38 -07001035 portal_attempts_to_online_ += result.num_attempts;
1036
Peter Qiub9256f32014-05-09 15:27:29 -07001037 int portal_status = Metrics::PortalDetectionResultToEnum(result);
Thieu Le85e050b2012-03-13 15:04:38 -07001038 metrics()->SendEnumToUMA(
mukesh agrawal132e96f2014-04-24 11:49:42 -07001039 metrics()->GetFullMetricName(Metrics::kMetricPortalResultSuffix,
1040 technology()),
Peter Qiub9256f32014-05-09 15:27:29 -07001041 portal_status,
Thieu Le85e050b2012-03-13 15:04:38 -07001042 Metrics::kPortalResultMax);
1043
Paul Stewart20088d82012-02-16 06:58:55 -08001044 if (result.status == PortalDetector::kStatusSuccess) {
1045 SetServiceConnectedState(Service::kStateOnline);
Thieu Le85e050b2012-03-13 15:04:38 -07001046
1047 metrics()->SendToUMA(
1048 metrics()->GetFullMetricName(
mukesh agrawal132e96f2014-04-24 11:49:42 -07001049 Metrics::kMetricPortalAttemptsToOnlineSuffix, technology()),
Thieu Le85e050b2012-03-13 15:04:38 -07001050 portal_attempts_to_online_,
1051 Metrics::kMetricPortalAttemptsToOnlineMin,
1052 Metrics::kMetricPortalAttemptsToOnlineMax,
1053 Metrics::kMetricPortalAttemptsToOnlineNumBuckets);
Paul Stewart20088d82012-02-16 06:58:55 -08001054 } else {
1055 SetServiceConnectedState(Service::kStatePortal);
Thieu Le85e050b2012-03-13 15:04:38 -07001056
1057 metrics()->SendToUMA(
1058 metrics()->GetFullMetricName(
mukesh agrawal132e96f2014-04-24 11:49:42 -07001059 Metrics::kMetricPortalAttemptsSuffix, technology()),
Thieu Le85e050b2012-03-13 15:04:38 -07001060 result.num_attempts,
1061 Metrics::kMetricPortalAttemptsMin,
1062 Metrics::kMetricPortalAttemptsMax,
1063 Metrics::kMetricPortalAttemptsNumBuckets);
Peter Qiub9256f32014-05-09 15:27:29 -07001064
1065 // Perform fallback DNS test if the portal failure is DNS related.
1066 // The test will send a DNS request to Google's DNS server to determine
1067 // if the DNS failure is due to bad DNS server settings.
1068 if ((portal_status == Metrics::kPortalResultDNSFailure) ||
1069 (portal_status == Metrics::kPortalResultDNSTimeout)) {
1070 PerformFallbackDNSTest();
1071 }
Paul Stewart20088d82012-02-16 06:58:55 -08001072 }
1073}
1074
Gaurav Shah1b7a6162011-11-09 11:41:01 -08001075vector<string> Device::AvailableIPConfigs(Error */*error*/) {
Paul Stewartd4f26482014-04-25 19:12:03 -07001076 vector<string> ipconfigs;
1077 if (ipconfig_) {
1078 ipconfigs.push_back(ipconfig_->GetRpcIdentifier());
Jason Glasgow08afdff2012-04-03 10:22:26 -04001079 }
Paul Stewartd4f26482014-04-25 19:12:03 -07001080 if (ip6config_) {
1081 ipconfigs.push_back(ip6config_->GetRpcIdentifier());
1082 }
1083 return ipconfigs;
Chris Masone4e851612011-07-01 10:46:53 -07001084}
1085
1086string Device::GetRpcConnectionIdentifier() {
1087 return adaptor_->GetRpcConnectionIdentifier();
1088}
1089
Paul Stewart036dba02012-08-07 12:34:41 -07001090uint64 Device::GetLinkMonitorResponseTime(Error *error) {
1091 if (!link_monitor_.get()) {
1092 // It is not strictly an error that the link monitor does not
1093 // exist, but returning an error here allows the GetProperties
1094 // call in our Adaptor to omit this parameter.
1095 error->Populate(Error::kNotFound, "Device is not running LinkMonitor");
1096 return 0;
1097 }
1098 return link_monitor_->GetResponseTimeMilliseconds();
1099}
1100
Ben Chanb061f892013-02-27 17:46:55 -08001101uint64 Device::GetReceiveByteCount() {
Paul Stewart6ff27f52012-07-11 06:51:41 -07001102 uint64 rx_byte_count = 0, tx_byte_count = 0;
1103 manager_->device_info()->GetByteCounts(
1104 interface_index_, &rx_byte_count, &tx_byte_count);
1105 return rx_byte_count - receive_byte_offset_;
1106}
1107
Ben Chanb061f892013-02-27 17:46:55 -08001108uint64 Device::GetTransmitByteCount() {
Paul Stewart6ff27f52012-07-11 06:51:41 -07001109 uint64 rx_byte_count = 0, tx_byte_count = 0;
1110 manager_->device_info()->GetByteCounts(
1111 interface_index_, &rx_byte_count, &tx_byte_count);
1112 return tx_byte_count - transmit_byte_offset_;
1113}
1114
Ben Chanb061f892013-02-27 17:46:55 -08001115uint64 Device::GetReceiveByteCountProperty(Error */*error*/) {
1116 return GetReceiveByteCount();
1117}
1118
1119uint64 Device::GetTransmitByteCountProperty(Error */*error*/) {
1120 return GetTransmitByteCount();
1121}
1122
Eric Shienbrood7fce52c2012-04-13 19:11:02 -04001123bool Device::IsUnderlyingDeviceEnabled() const {
1124 return false;
1125}
1126
Eric Shienbrood9a245532012-03-07 14:20:39 -05001127// callback
1128void Device::OnEnabledStateChanged(const ResultCallback &callback,
1129 const Error &error) {
mukesh agrawal46c27cc2013-07-10 16:39:10 -07001130 SLOG(Device, 2) << __func__
1131 << " (target: " << enabled_pending_ << ","
1132 << " success: " << error.IsSuccess() << ")"
1133 << " on " << link_name_;
Eric Shienbrood9a245532012-03-07 14:20:39 -05001134 if (error.IsSuccess()) {
1135 enabled_ = enabled_pending_;
1136 manager_->UpdateEnabledTechnologies();
Ben Chan923a5022013-09-20 11:23:23 -07001137 adaptor_->EmitBoolChanged(kPoweredProperty, enabled_);
Eric Shienbrood9a245532012-03-07 14:20:39 -05001138 }
Gary Morainbaeefdf2012-04-30 14:53:35 -07001139 enabled_pending_ = enabled_;
Eric Shienbrood9a245532012-03-07 14:20:39 -05001140 if (!callback.is_null())
1141 callback.Run(error);
1142}
1143
1144void Device::SetEnabled(bool enable) {
Ben Chanfad4a0b2012-04-18 15:49:59 -07001145 SLOG(Device, 2) << __func__ << "(" << enable << ")";
Jason Glasgow4a490792012-04-10 15:02:05 -04001146 Error error;
mukesh agrawal28185512013-10-18 16:57:09 -07001147 SetEnabledChecked(enable, false, &error, ResultCallback());
Arman Uguray8bf6a5c2013-08-12 14:18:03 -07001148
1149 // SetEnabledInternal might fail here if there is an unfinished enable or
1150 // disable operation. Don't log error in this case, as this method is only
1151 // called when the underlying device is already in the target state and the
1152 // pending operation should eventually bring the device to the expected
1153 // state.
1154 LOG_IF(ERROR,
1155 error.IsFailure() &&
1156 !error.IsOngoing() &&
1157 error.type() != Error::kInProgress)
Jason Glasgow4a490792012-04-10 15:02:05 -04001158 << "Enabled failed, but no way to report the failure.";
Eric Shienbrood9a245532012-03-07 14:20:39 -05001159}
1160
Ben Chan9f3dcf82013-09-25 18:04:58 -07001161void Device::SetEnabledNonPersistent(bool enable,
1162 Error *error,
1163 const ResultCallback &callback) {
mukesh agrawal28185512013-10-18 16:57:09 -07001164 SetEnabledChecked(enable, false, error, callback);
Ben Chan9f3dcf82013-09-25 18:04:58 -07001165}
1166
Eric Shienbrood9a245532012-03-07 14:20:39 -05001167void Device::SetEnabledPersistent(bool enable,
1168 Error *error,
1169 const ResultCallback &callback) {
mukesh agrawal28185512013-10-18 16:57:09 -07001170 SetEnabledChecked(enable, true, error, callback);
Eric Shienbrood9a245532012-03-07 14:20:39 -05001171}
1172
mukesh agrawal28185512013-10-18 16:57:09 -07001173void Device::SetEnabledChecked(bool enable,
1174 bool persist,
1175 Error *error,
1176 const ResultCallback &callback) {
Jason Glasgow4a490792012-04-10 15:02:05 -04001177 DCHECK(error);
Ben Chanfad4a0b2012-04-18 15:49:59 -07001178 SLOG(Device, 2) << "Device " << link_name_ << " "
1179 << (enable ? "starting" : "stopping");
Eric Shienbrood9a245532012-03-07 14:20:39 -05001180 if (enable == enabled_) {
Arman Uguray2f352e62013-08-28 19:12:53 -07001181 if (enable != enabled_pending_ && persist) {
1182 // Return an error, as there is an ongoing operation to achieve the
1183 // opposite.
1184 Error::PopulateAndLog(
1185 error, Error::kOperationFailed,
1186 enable ? "Cannot enable while the device is disabling." :
1187 "Cannot disable while the device is enabling.");
1188 return;
1189 }
mukesh agrawal28185512013-10-18 16:57:09 -07001190 LOG(INFO) << "Already in desired enable state.";
Jason Glasgow4a490792012-04-10 15:02:05 -04001191 error->Reset();
Eric Shienbrood9a245532012-03-07 14:20:39 -05001192 return;
1193 }
1194
1195 if (enabled_pending_ == enable) {
Jason Glasgow4a490792012-04-10 15:02:05 -04001196 Error::PopulateAndLog(error, Error::kInProgress,
1197 "Enable operation already in progress");
Eric Shienbrood9a245532012-03-07 14:20:39 -05001198 return;
1199 }
1200
1201 if (persist) {
1202 enabled_persistent_ = enable;
Darin Petkove7c6ad32012-06-29 10:22:09 +02001203 manager_->UpdateDevice(this);
Eric Shienbrood9a245532012-03-07 14:20:39 -05001204 }
1205
mukesh agrawal28185512013-10-18 16:57:09 -07001206 SetEnabledUnchecked(enable, error, callback);
1207}
1208
1209void Device::SetEnabledUnchecked(bool enable, Error *error,
1210 const ResultCallback &on_enable_complete) {
Eric Shienbrood9a245532012-03-07 14:20:39 -05001211 enabled_pending_ = enable;
mukesh agrawal28185512013-10-18 16:57:09 -07001212 EnabledStateChangedCallback chained_callback =
Eric Shienbrood9a245532012-03-07 14:20:39 -05001213 Bind(&Device::OnEnabledStateChanged,
mukesh agrawal28185512013-10-18 16:57:09 -07001214 weak_ptr_factory_.GetWeakPtr(), on_enable_complete);
Eric Shienbrood9a245532012-03-07 14:20:39 -05001215 if (enable) {
1216 running_ = true;
mukesh agrawal28185512013-10-18 16:57:09 -07001217 Start(error, chained_callback);
Eric Shienbrood9a245532012-03-07 14:20:39 -05001218 } else {
1219 running_ = false;
1220 DestroyIPConfig(); // breaks a reference cycle
1221 SelectService(NULL); // breaks a reference cycle
1222 rtnl_handler_->SetInterfaceFlags(interface_index(), 0, IFF_UP);
Ben Chanfad4a0b2012-04-18 15:49:59 -07001223 SLOG(Device, 3) << "Device " << link_name_ << " ipconfig_ "
1224 << (ipconfig_ ? "is set." : "is not set.");
Paul Stewartd4f26482014-04-25 19:12:03 -07001225 SLOG(Device, 3) << "Device " << link_name_ << " ip6config_ "
1226 << (ip6config_ ? "is set." : "is not set.");
Ben Chanfad4a0b2012-04-18 15:49:59 -07001227 SLOG(Device, 3) << "Device " << link_name_ << " connection_ "
1228 << (connection_ ? "is set." : "is not set.");
1229 SLOG(Device, 3) << "Device " << link_name_ << " selected_service_ "
1230 << (selected_service_ ? "is set." : "is not set.");
mukesh agrawal28185512013-10-18 16:57:09 -07001231 Stop(error, chained_callback);
Eric Shienbrood9a245532012-03-07 14:20:39 -05001232 }
1233}
1234
Paul Stewartd4f26482014-04-25 19:12:03 -07001235void Device::UpdateIPConfigsProperty() {
1236 adaptor_->EmitRpcIdentifierArrayChanged(
1237 kIPConfigsProperty, AvailableIPConfigs(NULL));
1238}
1239
Paul Stewart75897df2011-04-27 09:05:53 -07001240} // namespace shill