blob: 9111f9d85ef4419af5fb35ca651de18d336838bc [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 Stewartdded0072013-10-24 12:38:54 -0700440 return selected_service_ && selected_service_->ShouldUseMinimalDHCPConfig();
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_) {
559 selected_service_->OnDHCPSuccess();
560 selected_service_->SetConnection(connection_);
561 }
562 // The service state change needs to happen last, so that at the
563 // time we report the state change to the manager, the service
564 // has its connection.
565 SetServiceState(Service::kStateConnected);
566 OnConnected();
567 portal_attempts_to_online_ = 0;
568 // Subtle: Start portal detection after transitioning the service
569 // to the Connected state because this call may immediately transition
570 // to the Online state.
571 if (selected_service_) {
572 StartPortalDetection();
573 }
574 StartLinkMonitor();
Peter Qiudc335f82014-05-15 10:33:17 -0700575 StartTrafficMonitor();
Paul Stewartd4f26482014-04-25 19:12:03 -0700576 UpdateIPConfigsProperty();
Paul Stewartc5099532013-12-12 07:53:15 -0800577}
578
579void Device::OnIPConfigFailed(const IPConfigRefPtr &ipconfig) {
580 SLOG(Device, 2) << __func__;
581 // TODO(pstew): This logic gets yet more complex when multiple
582 // IPConfig types are run in parallel (e.g. DHCP and DHCP6)
583 if (selected_service_) {
584 selected_service_->OnDHCPFailure();
585
Paul Stewart316acef2014-05-29 18:40:48 -0700586 if (IsUsingStaticIP()) {
Paul Stewartc5099532013-12-12 07:53:15 -0800587 // Consider three cases:
588 //
589 // 1. We're here because DHCP failed while starting up. There
590 // are two subcases:
591 // a. DHCP has failed, and Static IP config has _not yet_
592 // completed. It's fine to do nothing, because we'll
593 // apply the static config shortly.
594 // b. DHCP has failed, and Static IP config has _already_
595 // completed. It's fine to do nothing, because we can
596 // continue to use the static config that's already
597 // been applied.
598 //
599 // 2. We're here because a previously valid DHCP configuration
600 // is no longer valid. There's still a static IP config,
601 // because the condition in the if clause evaluated to true.
602 // Furthermore, the static config includes an IP address for
603 // us to use.
604 //
605 // The current configuration may include some DHCP
606 // parameters, overriden by any static parameters
607 // provided. We continue to use this configuration, because
608 // the only configuration element that is leased to us (IP
609 // address) will be overriden by a static parameter.
610 return;
611 }
612 }
613
614 ipconfig->ResetProperties();
615 OnIPConfigFailure();
Paul Stewartd4f26482014-04-25 19:12:03 -0700616 UpdateIPConfigsProperty();
Paul Stewartc5099532013-12-12 07:53:15 -0800617 DestroyConnection();
Chris Masone8fe2c7e2011-06-09 15:51:19 -0700618}
619
Paul Stewart82236532013-12-10 15:33:11 -0800620void Device::OnIPConfigRefreshed(const IPConfigRefPtr &ipconfig) {
621 // Clear the previously applied static IP parameters.
622 ipconfig->RestoreSavedIPParameters(
623 selected_service_->mutable_static_ip_parameters());
624
625 dispatcher_->PostTask(Bind(&Device::ConfigureStaticIPTask,
626 weak_ptr_factory_.GetWeakPtr()));
627}
628
Paul Stewartf6f96482013-07-12 12:49:15 -0700629void Device::OnIPConfigFailure() {
630 if (selected_service_) {
631 Error error;
632 selected_service_->DisconnectWithFailure(Service::kFailureDHCP, &error);
633 }
634}
635
Paul Stewart1f916e42013-12-23 09:52:54 -0800636void Device::OnIPConfigExpired(const IPConfigRefPtr &ipconfig) {
637 metrics()->SendToUMA(
638 metrics()->GetFullMetricName(
mukesh agrawal132e96f2014-04-24 11:49:42 -0700639 Metrics::kMetricExpiredLeaseLengthSecondsSuffix, technology()),
Paul Stewart1f916e42013-12-23 09:52:54 -0800640 ipconfig->properties().lease_duration_seconds,
641 Metrics::kMetricExpiredLeaseLengthSecondsMin,
642 Metrics::kMetricExpiredLeaseLengthSecondsMax,
643 Metrics::kMetricExpiredLeaseLengthSecondsNumBuckets);
644}
645
Christopher Wiley5519e9e2013-01-08 16:55:56 -0800646void Device::OnConnected() {}
647
Paul Stewart8596f9f2013-03-14 07:58:26 -0700648void Device::OnConnectionUpdated() {
649 if (selected_service_) {
650 manager_->UpdateService(selected_service_);
651 }
652}
653
Paul Stewarte6132022011-08-16 09:11:02 -0700654void Device::CreateConnection() {
Ben Chanfad4a0b2012-04-18 15:49:59 -0700655 SLOG(Device, 2) << __func__;
Paul Stewarte6132022011-08-16 09:11:02 -0700656 if (!connection_.get()) {
mukesh agrawal23ac6b72013-01-31 18:52:37 -0800657 connection_ = new Connection(interface_index_,
658 link_name_,
659 technology_,
660 manager_->device_info());
Paul Stewarte6132022011-08-16 09:11:02 -0700661 }
662}
663
664void Device::DestroyConnection() {
mukesh agrawal6813e762013-07-10 19:05:08 -0700665 SLOG(Device, 2) << __func__ << " on " << link_name_;
Peter Qiudc335f82014-05-15 10:33:17 -0700666 StopTrafficMonitor();
Paul Stewart20088d82012-02-16 06:58:55 -0800667 StopPortalDetection();
Paul Stewart036dba02012-08-07 12:34:41 -0700668 StopLinkMonitor();
Paul Stewartbe5f5b32011-12-07 17:11:11 -0800669 if (selected_service_.get()) {
mukesh agrawal6813e762013-07-10 19:05:08 -0700670 SLOG(Device, 3) << "Clearing connection of service "
671 << selected_service_->unique_name();
Paul Stewartc1dec4d2011-12-08 15:25:28 -0800672 selected_service_->SetConnection(NULL);
Paul Stewartbe5f5b32011-12-07 17:11:11 -0800673 }
Paul Stewartc8f4bef2011-12-13 09:45:51 -0800674 connection_ = NULL;
Paul Stewarte6132022011-08-16 09:11:02 -0700675}
676
Paul Stewart03dba0b2011-08-22 16:32:45 -0700677void Device::SelectService(const ServiceRefPtr &service) {
Darin Petkov457728b2013-01-09 09:49:08 +0100678 SLOG(Device, 2) << __func__ << ": service "
mukesh agrawal6813e762013-07-10 19:05:08 -0700679 << (service ? service->unique_name() : "*reset*")
680 << " on " << link_name_;
mukesh agrawal8a3188d2011-12-01 20:56:44 +0000681
682 if (selected_service_.get() == service.get()) {
683 // No change to |selected_service_|. Return early to avoid
684 // changing its state.
685 return;
686 }
687
Paul Stewartbe5f5b32011-12-07 17:11:11 -0800688 if (selected_service_.get()) {
689 if (selected_service_->state() != Service::kStateFailure) {
690 selected_service_->SetState(Service::kStateIdle);
691 }
Paul Stewart20b0a092012-05-22 20:39:57 -0700692 // Just in case the Device subclass has not already done so, make
693 // sure the previously selected service has its connection removed.
Paul Stewartc1dec4d2011-12-08 15:25:28 -0800694 selected_service_->SetConnection(NULL);
Peter Qiudc335f82014-05-15 10:33:17 -0700695 StopTrafficMonitor();
Paul Stewartc8860612012-09-28 07:36:21 -0700696 StopLinkMonitor();
697 StopPortalDetection();
Paul Stewart03dba0b2011-08-22 16:32:45 -0700698 }
699 selected_service_ = service;
700}
701
702void Device::SetServiceState(Service::ConnectState state) {
703 if (selected_service_.get()) {
704 selected_service_->SetState(state);
705 }
706}
707
708void Device::SetServiceFailure(Service::ConnectFailure failure_state) {
709 if (selected_service_.get()) {
710 selected_service_->SetFailure(failure_state);
711 }
712}
713
Eric Shienbroodcc95c5d2012-03-30 15:25:49 -0400714void Device::SetServiceFailureSilent(Service::ConnectFailure failure_state) {
715 if (selected_service_.get()) {
716 selected_service_->SetFailureSilent(failure_state);
717 }
718}
719
Paul Stewart2bf1d352011-12-06 15:02:55 -0800720bool Device::SetIPFlag(IPAddress::Family family, const string &flag,
721 const string &value) {
722 string ip_version;
723 if (family == IPAddress::kFamilyIPv4) {
724 ip_version = kIPFlagVersion4;
725 } else if (family == IPAddress::kFamilyIPv6) {
726 ip_version = kIPFlagVersion6;
727 } else {
728 NOTIMPLEMENTED();
729 }
730 FilePath flag_file(StringPrintf(kIPFlagTemplate, ip_version.c_str(),
731 link_name_.c_str(), flag.c_str()));
Ben Chanfad4a0b2012-04-18 15:49:59 -0700732 SLOG(Device, 2) << "Writing " << value << " to flag file "
733 << flag_file.value();
Ben Chan6fbf64f2014-05-21 18:07:01 -0700734 if (base::WriteFile(flag_file, value.c_str(), value.length()) != 1) {
Paul Stewart2bf1d352011-12-06 15:02:55 -0800735 LOG(ERROR) << StringPrintf("IP flag write failed: %s to %s",
736 value.c_str(), flag_file.value().c_str());
737 return false;
738 }
739 return true;
740}
741
Paul Stewartc6fbad92013-11-13 14:50:52 -0800742string Device::PerformTDLSOperation(const string &/* operation */,
743 const string &/* peer */,
744 Error */* error */) {
745 return "";
746}
747
Paul Stewart6ff27f52012-07-11 06:51:41 -0700748void Device::ResetByteCounters() {
749 manager_->device_info()->GetByteCounts(
750 interface_index_, &receive_byte_offset_, &transmit_byte_offset_);
751 manager_->UpdateDevice(this);
752}
753
Paul Stewartd215af62012-04-24 23:25:50 -0700754bool Device::RestartPortalDetection() {
755 StopPortalDetection();
756 return StartPortalDetection();
757}
758
Paul Stewartc681fa02012-03-02 19:40:04 -0800759bool Device::RequestPortalDetection() {
760 if (!selected_service_) {
Ben Chanfad4a0b2012-04-18 15:49:59 -0700761 SLOG(Device, 2) << FriendlyName()
Paul Stewartc681fa02012-03-02 19:40:04 -0800762 << ": No selected service, so no need for portal check.";
763 return false;
764 }
765
766 if (!connection_.get()) {
Ben Chanfad4a0b2012-04-18 15:49:59 -0700767 SLOG(Device, 2) << FriendlyName()
Paul Stewartc681fa02012-03-02 19:40:04 -0800768 << ": No connection, so no need for portal check.";
769 return false;
770 }
771
772 if (selected_service_->state() != Service::kStatePortal) {
Ben Chanfad4a0b2012-04-18 15:49:59 -0700773 SLOG(Device, 2) << FriendlyName()
Paul Stewartc681fa02012-03-02 19:40:04 -0800774 << ": Service is not in portal state. No need to start check.";
775 return false;
776 }
777
778 if (!connection_->is_default()) {
Ben Chanfad4a0b2012-04-18 15:49:59 -0700779 SLOG(Device, 2) << FriendlyName()
Paul Stewartc681fa02012-03-02 19:40:04 -0800780 << ": Service is not the default connection. Don't start check.";
781 return false;
782 }
783
784 if (portal_detector_.get() && portal_detector_->IsInProgress()) {
Ben Chanfad4a0b2012-04-18 15:49:59 -0700785 SLOG(Device, 2) << FriendlyName()
786 << ": Portal detection is already running.";
Paul Stewartc681fa02012-03-02 19:40:04 -0800787 return true;
788 }
789
790 return StartPortalDetection();
791}
792
Paul Stewart20088d82012-02-16 06:58:55 -0800793bool Device::StartPortalDetection() {
Darin Petkov457728b2013-01-09 09:49:08 +0100794 DCHECK(selected_service_);
Paul Stewartd215af62012-04-24 23:25:50 -0700795 if (selected_service_->IsPortalDetectionDisabled()) {
Darin Petkov457728b2013-01-09 09:49:08 +0100796 SLOG(Device, 2) << "Service " << selected_service_->unique_name()
Paul Stewartd215af62012-04-24 23:25:50 -0700797 << ": Portal detection is disabled; "
798 << "marking service online.";
799 SetServiceConnectedState(Service::kStateOnline);
800 return false;
801 }
802
803 if (selected_service_->IsPortalDetectionAuto() &&
804 !manager_->IsPortalDetectionEnabled(technology())) {
Paul Stewart20088d82012-02-16 06:58:55 -0800805 // If portal detection is disabled for this technology, immediately set
806 // the service state to "Online".
Ben Chanfad4a0b2012-04-18 15:49:59 -0700807 SLOG(Device, 2) << "Device " << FriendlyName()
808 << ": Portal detection is disabled; "
809 << "marking service online.";
Paul Stewart20088d82012-02-16 06:58:55 -0800810 SetServiceConnectedState(Service::kStateOnline);
811 return false;
812 }
813
Paul Stewart20088d82012-02-16 06:58:55 -0800814 if (selected_service_->HasProxyConfig()) {
815 // Services with HTTP proxy configurations should not be checked by the
816 // connection manager, since we don't have the ability to evaluate
817 // arbitrary proxy configs and their possible credentials.
Ben Chanfad4a0b2012-04-18 15:49:59 -0700818 SLOG(Device, 2) << "Device " << FriendlyName()
819 << ": Service has proxy config; marking it online.";
Paul Stewart20088d82012-02-16 06:58:55 -0800820 SetServiceConnectedState(Service::kStateOnline);
821 return false;
822 }
823
824 portal_detector_.reset(new PortalDetector(connection_,
825 dispatcher_,
Eric Shienbrood3e20a232012-02-16 11:35:56 -0500826 portal_detector_callback_));
Paul Stewart20088d82012-02-16 06:58:55 -0800827 if (!portal_detector_->Start(manager_->GetPortalCheckURL())) {
828 LOG(ERROR) << "Device " << FriendlyName()
829 << ": Portal detection failed to start: likely bad URL: "
830 << manager_->GetPortalCheckURL();
831 SetServiceConnectedState(Service::kStateOnline);
832 return false;
833 }
834
Ben Chanfad4a0b2012-04-18 15:49:59 -0700835 SLOG(Device, 2) << "Device " << FriendlyName()
836 << ": Portal detection has started.";
Paul Stewart20088d82012-02-16 06:58:55 -0800837 return true;
838}
839
840void Device::StopPortalDetection() {
Ben Chanfad4a0b2012-04-18 15:49:59 -0700841 SLOG(Device, 2) << "Device " << FriendlyName()
mukesh agrawalbb2231c2013-07-17 16:32:24 -0700842 << ": Portal detection stopping.";
Paul Stewart20088d82012-02-16 06:58:55 -0800843 portal_detector_.reset();
844}
845
Paul Stewart036dba02012-08-07 12:34:41 -0700846void Device::set_link_monitor(LinkMonitor *link_monitor) {
847 link_monitor_.reset(link_monitor);
848}
849
850bool Device::StartLinkMonitor() {
851 if (!manager_->IsTechnologyLinkMonitorEnabled(technology())) {
852 SLOG(Device, 2) << "Device " << FriendlyName()
853 << ": Link Monitoring is disabled.";
854 return false;
855 }
856
857 if (!link_monitor()) {
858 set_link_monitor(
859 new LinkMonitor(
860 connection_, dispatcher_, metrics(), manager_->device_info(),
Peter Qiub5d124f2014-04-14 12:05:02 -0700861 Bind(&Device::OnLinkMonitorFailure, weak_ptr_factory_.GetWeakPtr()),
862 Bind(&Device::OnLinkMonitorGatewayChange,
863 weak_ptr_factory_.GetWeakPtr())));
Paul Stewart036dba02012-08-07 12:34:41 -0700864 }
865
866 SLOG(Device, 2) << "Device " << FriendlyName()
867 << ": Link Monitor starting.";
868 return link_monitor_->Start();
869}
870
871void Device::StopLinkMonitor() {
872 SLOG(Device, 2) << "Device " << FriendlyName()
873 << ": Link Monitor stopping.";
874 link_monitor_.reset();
875}
876
877void Device::OnLinkMonitorFailure() {
878 LOG(ERROR) << "Device " << FriendlyName()
879 << ": Link Monitor indicates failure.";
880}
881
Peter Qiu9d581932014-04-14 16:37:37 -0700882void Device::OnLinkMonitorGatewayChange() {
883 string gateway_mac = link_monitor()->gateway_mac_address().HexEncode();
884 int connection_id = manager_->CalcConnectionId(
885 ipconfig_->properties().gateway, gateway_mac);
886
887 CHECK(selected_service_);
888 selected_service_->set_connection_id(connection_id);
889
890 manager_->ReportServicesOnSameNetwork(connection_id);
891}
892
Peter Qiub9256f32014-05-09 15:27:29 -0700893void Device::PerformFallbackDNSTest() {
894 // Return if DNS client already running.
Alex Vakulenko8a532292014-06-16 17:18:44 -0700895 if (fallback_dns_test_client_.get()) {
Peter Qiub9256f32014-05-09 15:27:29 -0700896 return;
897 }
898
899 // Send DNS request to Google's DNS server.
900 vector<string> dns_servers(std::begin(kFallbackDnsServers),
901 std::end(kFallbackDnsServers));
902 fallback_dns_test_client_.reset(
903 dns_client_factory_->CreateDNSClient(IPAddress::kFamilyIPv4,
904 connection_->interface_name(),
905 dns_servers,
906 kDNSTimeoutMilliseconds,
907 dispatcher_,
908 dns_client_callback_));
909 Error error;
910 if (!fallback_dns_test_client_->Start(kFallbackDnsTestHostname, &error)) {
911 LOG(ERROR) << __func__ << ": Failed to start DNS client "
912 << error.message();
913 fallback_dns_test_client_.reset();
914 }
915}
916
917void Device::DNSClientCallback(const Error &error, const IPAddress& ip) {
Peter Qiuf18e7712014-05-20 09:59:46 -0700918 int result = Metrics::kFallbackDNSTestResultFailure;
Peter Qiub9256f32014-05-09 15:27:29 -0700919 if (error.IsSuccess()) {
Peter Qiuf18e7712014-05-20 09:59:46 -0700920 result = Metrics::kFallbackDNSTestResultSuccess;
Peter Qiub9256f32014-05-09 15:27:29 -0700921 }
Peter Qiuf18e7712014-05-20 09:59:46 -0700922 metrics()->NotifyFallbackDNSTestResult(technology_, result);
Peter Qiub9256f32014-05-09 15:27:29 -0700923 fallback_dns_test_client_.reset();
924}
925
Peter Qiudc335f82014-05-15 10:33:17 -0700926void Device::set_traffic_monitor(TrafficMonitor *traffic_monitor) {
927 traffic_monitor_.reset(traffic_monitor);
928}
929
930bool Device::IsTrafficMonitorEnabled() const {
931 return false;
932}
933
934void Device::StartTrafficMonitor() {
935 // Return if traffic monitor is not enabled for this device.
936 if (!IsTrafficMonitorEnabled()) {
937 return;
938 }
939
940 SLOG(Device, 2) << "Device " << FriendlyName()
941 << ": Traffic Monitor starting.";
942 if (!traffic_monitor_.get()) {
943 traffic_monitor_.reset(new TrafficMonitor(this, dispatcher_));
944 traffic_monitor_->set_network_problem_detected_callback(
945 Bind(&Device::OnEncounterNetworkProblem,
946 weak_ptr_factory_.GetWeakPtr()));
947 }
948 traffic_monitor_->Start();
949}
950
951void Device::StopTrafficMonitor() {
952 // Return if traffic monitor is not enabled for this device.
953 if (!IsTrafficMonitorEnabled()) {
954 return;
955 }
956
957 if (traffic_monitor_.get()) {
958 SLOG(Device, 2) << "Device " << FriendlyName()
959 << ": Traffic Monitor stopping.";
960 traffic_monitor_->Stop();
961 }
962 traffic_monitor_.reset();
963}
964
965void Device::OnEncounterNetworkProblem(int reason) {
966 int metric_code;
967 switch (reason) {
968 case TrafficMonitor::kNetworkProblemCongestedTxQueue:
969 metric_code = Metrics::kNetworkProblemCongestedTCPTxQueue;
970 break;
971 case TrafficMonitor::kNetworkProblemDNSFailure:
972 metric_code = Metrics::kNetworkProblemDNSFailure;
973 break;
974 default:
975 LOG(ERROR) << "Invalid network problem code: " << reason;
976 return;
977 }
978
979 metrics()->NotifyNetworkProblemDetected(technology_, metric_code);
980 // Stop the traffic monitor, only report the first network problem detected
981 // on the connection for now.
982 StopTrafficMonitor();
983}
984
Paul Stewart20088d82012-02-16 06:58:55 -0800985void Device::SetServiceConnectedState(Service::ConnectState state) {
986 DCHECK(selected_service_.get());
987
988 if (!selected_service_.get()) {
989 LOG(ERROR) << FriendlyName() << ": "
990 << "Portal detection completed but no selected service exists!";
991 return;
992 }
993
994 if (!selected_service_->IsConnected()) {
995 LOG(ERROR) << FriendlyName() << ": "
996 << "Portal detection completed but selected service "
Darin Petkov457728b2013-01-09 09:49:08 +0100997 << selected_service_->unique_name()
Paul Stewart20088d82012-02-16 06:58:55 -0800998 << " is in non-connected state.";
999 return;
1000 }
1001
Paul Stewartc681fa02012-03-02 19:40:04 -08001002 if (state == Service::kStatePortal && connection_->is_default() &&
1003 manager_->GetPortalCheckInterval() != 0) {
1004 CHECK(portal_detector_.get());
1005 if (!portal_detector_->StartAfterDelay(
1006 manager_->GetPortalCheckURL(),
1007 manager_->GetPortalCheckInterval())) {
1008 LOG(ERROR) << "Device " << FriendlyName()
1009 << ": Portal detection failed to restart: likely bad URL: "
1010 << manager_->GetPortalCheckURL();
1011 SetServiceState(Service::kStateOnline);
1012 portal_detector_.reset();
1013 return;
1014 }
Ben Chanfad4a0b2012-04-18 15:49:59 -07001015 SLOG(Device, 2) << "Device " << FriendlyName()
1016 << ": Portal detection retrying.";
Paul Stewartc681fa02012-03-02 19:40:04 -08001017 } else {
Ben Chanfad4a0b2012-04-18 15:49:59 -07001018 SLOG(Device, 2) << "Device " << FriendlyName()
1019 << ": Portal will not retry.";
Paul Stewartc681fa02012-03-02 19:40:04 -08001020 portal_detector_.reset();
1021 }
1022
Paul Stewart20088d82012-02-16 06:58:55 -08001023 SetServiceState(state);
1024}
1025
1026void Device::PortalDetectorCallback(const PortalDetector::Result &result) {
1027 if (!result.final) {
Ben Chanfad4a0b2012-04-18 15:49:59 -07001028 SLOG(Device, 2) << "Device " << FriendlyName()
1029 << ": Received non-final status: "
1030 << PortalDetector::StatusToString(result.status);
Paul Stewart20088d82012-02-16 06:58:55 -08001031 return;
1032 }
1033
Ben Chanfad4a0b2012-04-18 15:49:59 -07001034 SLOG(Device, 2) << "Device " << FriendlyName()
1035 << ": Received final status: "
1036 << PortalDetector::StatusToString(result.status);
Paul Stewart20088d82012-02-16 06:58:55 -08001037
Thieu Le85e050b2012-03-13 15:04:38 -07001038 portal_attempts_to_online_ += result.num_attempts;
1039
Peter Qiub9256f32014-05-09 15:27:29 -07001040 int portal_status = Metrics::PortalDetectionResultToEnum(result);
Thieu Le85e050b2012-03-13 15:04:38 -07001041 metrics()->SendEnumToUMA(
mukesh agrawal132e96f2014-04-24 11:49:42 -07001042 metrics()->GetFullMetricName(Metrics::kMetricPortalResultSuffix,
1043 technology()),
Peter Qiub9256f32014-05-09 15:27:29 -07001044 portal_status,
Thieu Le85e050b2012-03-13 15:04:38 -07001045 Metrics::kPortalResultMax);
1046
Paul Stewart20088d82012-02-16 06:58:55 -08001047 if (result.status == PortalDetector::kStatusSuccess) {
1048 SetServiceConnectedState(Service::kStateOnline);
Thieu Le85e050b2012-03-13 15:04:38 -07001049
1050 metrics()->SendToUMA(
1051 metrics()->GetFullMetricName(
mukesh agrawal132e96f2014-04-24 11:49:42 -07001052 Metrics::kMetricPortalAttemptsToOnlineSuffix, technology()),
Thieu Le85e050b2012-03-13 15:04:38 -07001053 portal_attempts_to_online_,
1054 Metrics::kMetricPortalAttemptsToOnlineMin,
1055 Metrics::kMetricPortalAttemptsToOnlineMax,
1056 Metrics::kMetricPortalAttemptsToOnlineNumBuckets);
Paul Stewart20088d82012-02-16 06:58:55 -08001057 } else {
1058 SetServiceConnectedState(Service::kStatePortal);
Thieu Le85e050b2012-03-13 15:04:38 -07001059
1060 metrics()->SendToUMA(
1061 metrics()->GetFullMetricName(
mukesh agrawal132e96f2014-04-24 11:49:42 -07001062 Metrics::kMetricPortalAttemptsSuffix, technology()),
Thieu Le85e050b2012-03-13 15:04:38 -07001063 result.num_attempts,
1064 Metrics::kMetricPortalAttemptsMin,
1065 Metrics::kMetricPortalAttemptsMax,
1066 Metrics::kMetricPortalAttemptsNumBuckets);
Peter Qiub9256f32014-05-09 15:27:29 -07001067
1068 // Perform fallback DNS test if the portal failure is DNS related.
1069 // The test will send a DNS request to Google's DNS server to determine
1070 // if the DNS failure is due to bad DNS server settings.
1071 if ((portal_status == Metrics::kPortalResultDNSFailure) ||
1072 (portal_status == Metrics::kPortalResultDNSTimeout)) {
1073 PerformFallbackDNSTest();
1074 }
Paul Stewart20088d82012-02-16 06:58:55 -08001075 }
1076}
1077
Gaurav Shah1b7a6162011-11-09 11:41:01 -08001078vector<string> Device::AvailableIPConfigs(Error */*error*/) {
Paul Stewartd4f26482014-04-25 19:12:03 -07001079 vector<string> ipconfigs;
1080 if (ipconfig_) {
1081 ipconfigs.push_back(ipconfig_->GetRpcIdentifier());
Jason Glasgow08afdff2012-04-03 10:22:26 -04001082 }
Paul Stewartd4f26482014-04-25 19:12:03 -07001083 if (ip6config_) {
1084 ipconfigs.push_back(ip6config_->GetRpcIdentifier());
1085 }
1086 return ipconfigs;
Chris Masone4e851612011-07-01 10:46:53 -07001087}
1088
1089string Device::GetRpcConnectionIdentifier() {
1090 return adaptor_->GetRpcConnectionIdentifier();
1091}
1092
Paul Stewart036dba02012-08-07 12:34:41 -07001093uint64 Device::GetLinkMonitorResponseTime(Error *error) {
1094 if (!link_monitor_.get()) {
1095 // It is not strictly an error that the link monitor does not
1096 // exist, but returning an error here allows the GetProperties
1097 // call in our Adaptor to omit this parameter.
1098 error->Populate(Error::kNotFound, "Device is not running LinkMonitor");
1099 return 0;
1100 }
1101 return link_monitor_->GetResponseTimeMilliseconds();
1102}
1103
Ben Chanb061f892013-02-27 17:46:55 -08001104uint64 Device::GetReceiveByteCount() {
Paul Stewart6ff27f52012-07-11 06:51:41 -07001105 uint64 rx_byte_count = 0, tx_byte_count = 0;
1106 manager_->device_info()->GetByteCounts(
1107 interface_index_, &rx_byte_count, &tx_byte_count);
1108 return rx_byte_count - receive_byte_offset_;
1109}
1110
Ben Chanb061f892013-02-27 17:46:55 -08001111uint64 Device::GetTransmitByteCount() {
Paul Stewart6ff27f52012-07-11 06:51:41 -07001112 uint64 rx_byte_count = 0, tx_byte_count = 0;
1113 manager_->device_info()->GetByteCounts(
1114 interface_index_, &rx_byte_count, &tx_byte_count);
1115 return tx_byte_count - transmit_byte_offset_;
1116}
1117
Ben Chanb061f892013-02-27 17:46:55 -08001118uint64 Device::GetReceiveByteCountProperty(Error */*error*/) {
1119 return GetReceiveByteCount();
1120}
1121
1122uint64 Device::GetTransmitByteCountProperty(Error */*error*/) {
1123 return GetTransmitByteCount();
1124}
1125
Eric Shienbrood7fce52c2012-04-13 19:11:02 -04001126bool Device::IsUnderlyingDeviceEnabled() const {
1127 return false;
1128}
1129
Eric Shienbrood9a245532012-03-07 14:20:39 -05001130// callback
1131void Device::OnEnabledStateChanged(const ResultCallback &callback,
1132 const Error &error) {
mukesh agrawal46c27cc2013-07-10 16:39:10 -07001133 SLOG(Device, 2) << __func__
1134 << " (target: " << enabled_pending_ << ","
1135 << " success: " << error.IsSuccess() << ")"
1136 << " on " << link_name_;
Eric Shienbrood9a245532012-03-07 14:20:39 -05001137 if (error.IsSuccess()) {
1138 enabled_ = enabled_pending_;
1139 manager_->UpdateEnabledTechnologies();
Ben Chan923a5022013-09-20 11:23:23 -07001140 adaptor_->EmitBoolChanged(kPoweredProperty, enabled_);
Eric Shienbrood9a245532012-03-07 14:20:39 -05001141 }
Gary Morainbaeefdf2012-04-30 14:53:35 -07001142 enabled_pending_ = enabled_;
Eric Shienbrood9a245532012-03-07 14:20:39 -05001143 if (!callback.is_null())
1144 callback.Run(error);
1145}
1146
1147void Device::SetEnabled(bool enable) {
Ben Chanfad4a0b2012-04-18 15:49:59 -07001148 SLOG(Device, 2) << __func__ << "(" << enable << ")";
Jason Glasgow4a490792012-04-10 15:02:05 -04001149 Error error;
mukesh agrawal28185512013-10-18 16:57:09 -07001150 SetEnabledChecked(enable, false, &error, ResultCallback());
Arman Uguray8bf6a5c2013-08-12 14:18:03 -07001151
1152 // SetEnabledInternal might fail here if there is an unfinished enable or
1153 // disable operation. Don't log error in this case, as this method is only
1154 // called when the underlying device is already in the target state and the
1155 // pending operation should eventually bring the device to the expected
1156 // state.
1157 LOG_IF(ERROR,
1158 error.IsFailure() &&
1159 !error.IsOngoing() &&
1160 error.type() != Error::kInProgress)
Jason Glasgow4a490792012-04-10 15:02:05 -04001161 << "Enabled failed, but no way to report the failure.";
Eric Shienbrood9a245532012-03-07 14:20:39 -05001162}
1163
Ben Chan9f3dcf82013-09-25 18:04:58 -07001164void Device::SetEnabledNonPersistent(bool enable,
1165 Error *error,
1166 const ResultCallback &callback) {
mukesh agrawal28185512013-10-18 16:57:09 -07001167 SetEnabledChecked(enable, false, error, callback);
Ben Chan9f3dcf82013-09-25 18:04:58 -07001168}
1169
Eric Shienbrood9a245532012-03-07 14:20:39 -05001170void Device::SetEnabledPersistent(bool enable,
1171 Error *error,
1172 const ResultCallback &callback) {
mukesh agrawal28185512013-10-18 16:57:09 -07001173 SetEnabledChecked(enable, true, error, callback);
Eric Shienbrood9a245532012-03-07 14:20:39 -05001174}
1175
mukesh agrawal28185512013-10-18 16:57:09 -07001176void Device::SetEnabledChecked(bool enable,
1177 bool persist,
1178 Error *error,
1179 const ResultCallback &callback) {
Jason Glasgow4a490792012-04-10 15:02:05 -04001180 DCHECK(error);
Ben Chanfad4a0b2012-04-18 15:49:59 -07001181 SLOG(Device, 2) << "Device " << link_name_ << " "
1182 << (enable ? "starting" : "stopping");
Eric Shienbrood9a245532012-03-07 14:20:39 -05001183 if (enable == enabled_) {
Arman Uguray2f352e62013-08-28 19:12:53 -07001184 if (enable != enabled_pending_ && persist) {
1185 // Return an error, as there is an ongoing operation to achieve the
1186 // opposite.
1187 Error::PopulateAndLog(
1188 error, Error::kOperationFailed,
1189 enable ? "Cannot enable while the device is disabling." :
1190 "Cannot disable while the device is enabling.");
1191 return;
1192 }
mukesh agrawal28185512013-10-18 16:57:09 -07001193 LOG(INFO) << "Already in desired enable state.";
Jason Glasgow4a490792012-04-10 15:02:05 -04001194 error->Reset();
Eric Shienbrood9a245532012-03-07 14:20:39 -05001195 return;
1196 }
1197
1198 if (enabled_pending_ == enable) {
Jason Glasgow4a490792012-04-10 15:02:05 -04001199 Error::PopulateAndLog(error, Error::kInProgress,
1200 "Enable operation already in progress");
Eric Shienbrood9a245532012-03-07 14:20:39 -05001201 return;
1202 }
1203
1204 if (persist) {
1205 enabled_persistent_ = enable;
Darin Petkove7c6ad32012-06-29 10:22:09 +02001206 manager_->UpdateDevice(this);
Eric Shienbrood9a245532012-03-07 14:20:39 -05001207 }
1208
mukesh agrawal28185512013-10-18 16:57:09 -07001209 SetEnabledUnchecked(enable, error, callback);
1210}
1211
1212void Device::SetEnabledUnchecked(bool enable, Error *error,
1213 const ResultCallback &on_enable_complete) {
Eric Shienbrood9a245532012-03-07 14:20:39 -05001214 enabled_pending_ = enable;
mukesh agrawal28185512013-10-18 16:57:09 -07001215 EnabledStateChangedCallback chained_callback =
Eric Shienbrood9a245532012-03-07 14:20:39 -05001216 Bind(&Device::OnEnabledStateChanged,
mukesh agrawal28185512013-10-18 16:57:09 -07001217 weak_ptr_factory_.GetWeakPtr(), on_enable_complete);
Eric Shienbrood9a245532012-03-07 14:20:39 -05001218 if (enable) {
1219 running_ = true;
mukesh agrawal28185512013-10-18 16:57:09 -07001220 Start(error, chained_callback);
Eric Shienbrood9a245532012-03-07 14:20:39 -05001221 } else {
1222 running_ = false;
1223 DestroyIPConfig(); // breaks a reference cycle
1224 SelectService(NULL); // breaks a reference cycle
1225 rtnl_handler_->SetInterfaceFlags(interface_index(), 0, IFF_UP);
Ben Chanfad4a0b2012-04-18 15:49:59 -07001226 SLOG(Device, 3) << "Device " << link_name_ << " ipconfig_ "
1227 << (ipconfig_ ? "is set." : "is not set.");
Paul Stewartd4f26482014-04-25 19:12:03 -07001228 SLOG(Device, 3) << "Device " << link_name_ << " ip6config_ "
1229 << (ip6config_ ? "is set." : "is not set.");
Ben Chanfad4a0b2012-04-18 15:49:59 -07001230 SLOG(Device, 3) << "Device " << link_name_ << " connection_ "
1231 << (connection_ ? "is set." : "is not set.");
1232 SLOG(Device, 3) << "Device " << link_name_ << " selected_service_ "
1233 << (selected_service_ ? "is set." : "is not set.");
mukesh agrawal28185512013-10-18 16:57:09 -07001234 Stop(error, chained_callback);
Eric Shienbrood9a245532012-03-07 14:20:39 -05001235 }
1236}
1237
Paul Stewartd4f26482014-04-25 19:12:03 -07001238void Device::UpdateIPConfigsProperty() {
1239 adaptor_->EmitRpcIdentifierArrayChanged(
1240 kIPConfigsProperty, AvailableIPConfigs(NULL));
1241}
1242
Paul Stewart75897df2011-04-27 09:05:53 -07001243} // namespace shill