blob: 5a3d17a448b6e3597ddeb1128d9dd39ae4e40d0c [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>
Chris Masone5dec5f42011-07-22 14:07:55 -070018#include <base/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"
Arman Ugurayf84a4242013-04-09 20:01:07 -070023#include "shill/connection_health_checker.h"
Paul Stewart75897df2011-04-27 09:05:53 -070024#include "shill/control_interface.h"
Chris Masoned7732e42011-05-20 11:08:56 -070025#include "shill/device_dbus_adaptor.h"
Chris Masone2b105542011-06-22 10:58:09 -070026#include "shill/dhcp_config.h"
Darin Petkovafa6fc42011-06-21 16:21:08 -070027#include "shill/dhcp_provider.h"
Arman Ugurayf84a4242013-04-09 20:01:07 -070028#include "shill/dns_client.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"
Ben Chanb061f892013-02-27 17:46:55 -080045#include "shill/traffic_monitor.h"
Paul Stewart75897df2011-04-27 09:05:53 -070046
Eric Shienbrood3e20a232012-02-16 11:35:56 -050047using base::Bind;
Albert Chaulk0e1cdea2013-02-27 15:32:55 -080048using base::FilePath;
Chris Masone5dec5f42011-07-22 14:07:55 -070049using base::StringPrintf;
Chris Masone8fe2c7e2011-06-09 15:51:19 -070050using std::string;
51using std::vector;
52
Paul Stewart75897df2011-04-27 09:05:53 -070053namespace shill {
Chris Masone5dec5f42011-07-22 14:07:55 -070054
55// static
Paul Stewart2bf1d352011-12-06 15:02:55 -080056const char Device::kIPFlagTemplate[] = "/proc/sys/net/%s/conf/%s/%s";
57// static
58const char Device::kIPFlagVersion4[] = "ipv4";
59// static
60const char Device::kIPFlagVersion6[] = "ipv6";
61// static
62const char Device::kIPFlagDisableIPv6[] = "disable_ipv6";
63// static
64const char Device::kIPFlagUseTempAddr[] = "use_tempaddr";
65// static
66const char Device::kIPFlagUseTempAddrUsedAndDefault[] = "2";
Paul Stewartc8f4bef2011-12-13 09:45:51 -080067// static
68const char Device::kIPFlagReversePathFilter[] = "rp_filter";
69// static
70const char Device::kIPFlagReversePathFilterEnabled[] = "1";
71// static
72const char Device::kIPFlagReversePathFilterLooseMode[] = "2";
Paul Stewart2bf1d352011-12-06 15:02:55 -080073// static
Paul Stewart41a071e2013-04-26 07:56:04 -070074const char Device::kStorageIPConfigs[] = "IPConfigs";
75// static
Prathmesh Prabhuba99b592013-04-17 15:13:14 -070076const char Device::kStoragePowered[] = "Powered";
77// static
Paul Stewart6ff27f52012-07-11 06:51:41 -070078const char Device::kStorageReceiveByteCount[] = "ReceiveByteCount";
79// static
80const char Device::kStorageTransmitByteCount[] = "TransmitByteCount";
Chris Masone5dec5f42011-07-22 14:07:55 -070081
Paul Stewart75897df2011-04-27 09:05:53 -070082Device::Device(ControlInterface *control_interface,
Paul Stewartb50f0b92011-05-16 16:31:42 -070083 EventDispatcher *dispatcher,
Thieu Le3426c8f2012-01-11 17:35:11 -080084 Metrics *metrics,
Paul Stewartf1ce5d22011-05-19 13:10:20 -070085 Manager *manager,
Darin Petkovafa6fc42011-06-21 16:21:08 -070086 const string &link_name,
Chris Masone626719f2011-08-18 16:58:48 -070087 const string &address,
Gaurav Shah435de2c2011-11-17 19:01:07 -080088 int interface_index,
89 Technology::Identifier technology)
Eric Shienbrood9a245532012-03-07 14:20:39 -050090 : enabled_(false),
91 enabled_persistent_(true),
92 enabled_pending_(enabled_),
Chris Masoneb925cc82011-06-22 15:39:57 -070093 reconnect_(true),
Chris Masone626719f2011-08-18 16:58:48 -070094 hardware_address_(address),
mukesh agrawalf60e4062011-05-27 13:13:41 -070095 interface_index_(interface_index),
96 running_(false),
Darin Petkovafa6fc42011-06-21 16:21:08 -070097 link_name_(link_name),
Chris Masone19e30402011-07-19 15:48:47 -070098 unique_id_(link_name),
Darin Petkovd9661952011-08-03 16:25:42 -070099 control_interface_(control_interface),
100 dispatcher_(dispatcher),
Thieu Le3426c8f2012-01-11 17:35:11 -0800101 metrics_(metrics),
Chris Masone7df0c672011-07-15 10:24:54 -0700102 manager_(manager),
Eric Shienbrood9a245532012-03-07 14:20:39 -0500103 weak_ptr_factory_(this),
Darin Petkov77cb6812011-08-15 16:19:41 -0700104 adaptor_(control_interface->CreateDeviceAdaptor(this)),
Ben Chanb061f892013-02-27 17:46:55 -0800105 traffic_monitor_enabled_(false),
Eric Shienbrood9a245532012-03-07 14:20:39 -0500106 portal_detector_callback_(Bind(&Device::PortalDetectorCallback,
107 weak_ptr_factory_.GetWeakPtr())),
Gaurav Shah435de2c2011-11-17 19:01:07 -0800108 technology_(technology),
Thieu Le85e050b2012-03-13 15:04:38 -0700109 portal_attempts_to_online_(0),
Paul Stewart6ff27f52012-07-11 06:51:41 -0700110 receive_byte_offset_(0),
111 transmit_byte_offset_(0),
mukesh agrawal5c4dd0b2011-09-14 13:53:14 -0700112 dhcp_provider_(DHCPProvider::GetInstance()),
113 rtnl_handler_(RTNLHandler::GetInstance()) {
Chris Masone27c4aa52011-07-02 13:10:14 -0700114 store_.RegisterConstString(flimflam::kAddressProperty, &hardware_address_);
Chris Masone4d42df82011-07-02 17:09:39 -0700115
116 // flimflam::kBgscanMethodProperty: Registered in WiFi
117 // flimflam::kBgscanShortIntervalProperty: Registered in WiFi
118 // flimflam::kBgscanSignalThresholdProperty: Registered in WiFi
119
120 // flimflam::kCellularAllowRoamingProperty: Registered in Cellular
121 // flimflam::kCarrierProperty: Registered in Cellular
122 // flimflam::kEsnProperty: Registered in Cellular
Darin Petkov3335b372011-08-22 11:05:32 -0700123 // flimflam::kHomeProviderProperty: Registered in Cellular
Chris Masone4d42df82011-07-02 17:09:39 -0700124 // flimflam::kImeiProperty: Registered in Cellular
Ben Chana5e27082012-07-31 14:30:28 -0700125 // flimflam::kIccidProperty: Registered in Cellular
Chris Masone4d42df82011-07-02 17:09:39 -0700126 // flimflam::kImsiProperty: Registered in Cellular
127 // flimflam::kManufacturerProperty: Registered in Cellular
128 // flimflam::kMdnProperty: Registered in Cellular
129 // flimflam::kMeidProperty: Registered in Cellular
130 // flimflam::kMinProperty: Registered in Cellular
131 // flimflam::kModelIDProperty: Registered in Cellular
132 // flimflam::kFirmwareRevisionProperty: Registered in Cellular
133 // flimflam::kHardwareRevisionProperty: Registered in Cellular
134 // flimflam::kPRLVersionProperty: Registered in Cellular
135 // flimflam::kSIMLockStatusProperty: Registered in Cellular
136 // flimflam::kFoundNetworksProperty: Registered in Cellular
Darin Petkove9d12e02011-07-27 15:09:37 -0700137 // flimflam::kDBusConnectionProperty: Registered in Cellular
138 // flimflam::kDBusObjectProperty: Register in Cellular
Chris Masone4d42df82011-07-02 17:09:39 -0700139
Jason Glasgowe8334fd2012-03-30 16:02:37 -0400140 store_.RegisterConstString(flimflam::kInterfaceProperty, &link_name_);
Jason Glasgow08afdff2012-04-03 10:22:26 -0400141 HelpRegisterConstDerivedRpcIdentifiers(flimflam::kIPConfigsProperty,
142 &Device::AvailableIPConfigs);
Chris Masone27c4aa52011-07-02 13:10:14 -0700143 store_.RegisterConstString(flimflam::kNameProperty, &link_name_);
Eric Shienbrood9a245532012-03-07 14:20:39 -0500144 store_.RegisterConstBool(flimflam::kPoweredProperty, &enabled_);
mukesh agrawalbebf1b82013-04-23 15:06:33 -0700145 HelpRegisterConstDerivedString(flimflam::kTypeProperty,
146 &Device::GetTechnologyString);
Paul Stewart036dba02012-08-07 12:34:41 -0700147 HelpRegisterConstDerivedUint64(shill::kLinkMonitorResponseTimeProperty,
148 &Device::GetLinkMonitorResponseTime);
Jason Glasgowb5790052012-01-27 01:03:52 -0500149
Chris Masoneb925cc82011-06-22 15:39:57 -0700150 // TODO(cmasone): Chrome doesn't use this...does anyone?
Chris Masone27c4aa52011-07-02 13:10:14 -0700151 // store_.RegisterConstBool(flimflam::kReconnectProperty, &reconnect_);
Chris Masoneb925cc82011-06-22 15:39:57 -0700152
Chris Masone4e851612011-07-01 10:46:53 -0700153 // TODO(cmasone): Figure out what shill concept maps to flimflam's "Network".
Chris Masoneb925cc82011-06-22 15:39:57 -0700154 // known_properties_.push_back(flimflam::kNetworksProperty);
155
Chris Masone4d42df82011-07-02 17:09:39 -0700156 // flimflam::kScanningProperty: Registered in WiFi, Cellular
157 // flimflam::kScanIntervalProperty: Registered in WiFi, Cellular
Paul Stewart6ff27f52012-07-11 06:51:41 -0700158
159 if (manager_ && manager_->device_info()) { // Unit tests may not have these.
160 manager_->device_info()->GetByteCounts(
161 interface_index_, &receive_byte_offset_, &transmit_byte_offset_);
162 HelpRegisterConstDerivedUint64(shill::kReceiveByteCountProperty,
Ben Chanb061f892013-02-27 17:46:55 -0800163 &Device::GetReceiveByteCountProperty);
Paul Stewart6ff27f52012-07-11 06:51:41 -0700164 HelpRegisterConstDerivedUint64(shill::kTransmitByteCountProperty,
Ben Chanb061f892013-02-27 17:46:55 -0800165 &Device::GetTransmitByteCountProperty);
Paul Stewart6ff27f52012-07-11 06:51:41 -0700166 }
167
Darin Petkova0a0efe2012-06-27 12:50:01 +0200168 LOG(INFO) << "Device created: " << link_name_
169 << " index " << interface_index_;
Paul Stewart75897df2011-04-27 09:05:53 -0700170}
171
172Device::~Device() {
Darin Petkova0a0efe2012-06-27 12:50:01 +0200173 LOG(INFO) << "Device destructed: " << link_name_
174 << " index " << interface_index_;
Paul Stewart75897df2011-04-27 09:05:53 -0700175}
176
Paul Stewartf1ce5d22011-05-19 13:10:20 -0700177void Device::LinkEvent(unsigned flags, unsigned change) {
Ben Chanfad4a0b2012-04-18 15:49:59 -0700178 SLOG(Device, 2) << "Device " << link_name_
179 << std::showbase << std::hex
180 << " flags " << flags << " changed " << change
181 << std::dec << std::noshowbase;
Paul Stewartf1ce5d22011-05-19 13:10:20 -0700182}
183
Wade Guthrie68d41092013-04-02 12:56:02 -0700184void Device::Scan(ScanType scan_type, Error *error) {
Ben Chanfad4a0b2012-04-18 15:49:59 -0700185 SLOG(Device, 2) << "Device " << link_name_ << " scan requested.";
Paul Stewartbe005172011-11-02 18:10:29 -0700186 Error::PopulateAndLog(error, Error::kNotSupported,
187 "Device doesn't support scan.");
Paul Stewartf1ce5d22011-05-19 13:10:20 -0700188}
189
Eric Shienbrood9a245532012-03-07 14:20:39 -0500190void Device::RegisterOnNetwork(const std::string &/*network_id*/, Error *error,
191 const ResultCallback &/*callback*/) {
192 Error::PopulateAndLog(error, Error::kNotSupported,
Paul Stewartbe005172011-11-02 18:10:29 -0700193 "Device doesn't support network registration.");
Darin Petkov9ae310f2011-08-30 15:41:13 -0700194}
195
Darin Petkovc64fe5e2012-01-11 12:46:13 +0100196void Device::RequirePIN(
Eric Shienbrood9a245532012-03-07 14:20:39 -0500197 const string &/*pin*/, bool /*require*/,
198 Error *error, const ResultCallback &/*callback*/) {
Ben Chanfad4a0b2012-04-18 15:49:59 -0700199 SLOG(Device, 2) << __func__;
Eric Shienbrood9a245532012-03-07 14:20:39 -0500200 Error::PopulateAndLog(error, Error::kNotSupported,
201 "Device doesn't support RequirePIN.");
Darin Petkove42e1012011-08-31 12:35:04 -0700202}
203
Eric Shienbrood9a245532012-03-07 14:20:39 -0500204void Device::EnterPIN(const string &/*pin*/,
205 Error *error, const ResultCallback &/*callback*/) {
Ben Chanfad4a0b2012-04-18 15:49:59 -0700206 SLOG(Device, 2) << __func__;
Eric Shienbrood9a245532012-03-07 14:20:39 -0500207 Error::PopulateAndLog(error, Error::kNotSupported,
208 "Device doesn't support EnterPIN.");
Darin Petkove42e1012011-08-31 12:35:04 -0700209}
210
mukesh agrawal1830fa12011-09-26 14:31:40 -0700211void Device::UnblockPIN(const string &/*unblock_code*/,
212 const string &/*pin*/,
Eric Shienbrood9a245532012-03-07 14:20:39 -0500213 Error *error, const ResultCallback &/*callback*/) {
Ben Chanfad4a0b2012-04-18 15:49:59 -0700214 SLOG(Device, 2) << __func__;
Eric Shienbrood9a245532012-03-07 14:20:39 -0500215 Error::PopulateAndLog(error, Error::kNotSupported,
216 "Device doesn't support UnblockPIN.");
Darin Petkove42e1012011-08-31 12:35:04 -0700217}
218
mukesh agrawal1830fa12011-09-26 14:31:40 -0700219void Device::ChangePIN(const string &/*old_pin*/,
220 const string &/*new_pin*/,
Eric Shienbrood9a245532012-03-07 14:20:39 -0500221 Error *error, const ResultCallback &/*callback*/) {
Ben Chanfad4a0b2012-04-18 15:49:59 -0700222 SLOG(Device, 2) << __func__;
Eric Shienbrood9a245532012-03-07 14:20:39 -0500223 Error::PopulateAndLog(error, Error::kNotSupported,
224 "Device doesn't support ChangePIN.");
Darin Petkove42e1012011-08-31 12:35:04 -0700225}
226
Ben Chanad663e12013-01-08 01:58:47 -0800227void Device::Reset(Error *error, const ResultCallback &/*callback*/) {
228 SLOG(Device, 2) << __func__;
229 Error::PopulateAndLog(error, Error::kNotSupported,
230 "Device doesn't support Reset.");
231}
232
Darin Petkovc37a9c42012-09-06 15:28:22 +0200233void Device::SetCarrier(const string &/*carrier*/,
234 Error *error, const ResultCallback &/*callback*/) {
235 SLOG(Device, 2) << __func__;
236 Error::PopulateAndLog(error, Error::kNotSupported,
237 "Device doesn't support SetCarrier.");
238}
239
Paul Stewart2bf1d352011-12-06 15:02:55 -0800240void Device::DisableIPv6() {
241 SetIPFlag(IPAddress::kFamilyIPv6, kIPFlagDisableIPv6, "1");
242}
243
244void Device::EnableIPv6() {
245 SetIPFlag(IPAddress::kFamilyIPv6, kIPFlagDisableIPv6, "0");
246}
247
248void Device::EnableIPv6Privacy() {
249 SetIPFlag(IPAddress::kFamilyIPv6, kIPFlagUseTempAddr,
250 kIPFlagUseTempAddrUsedAndDefault);
251}
252
Paul Stewartc8f4bef2011-12-13 09:45:51 -0800253void Device::DisableReversePathFilter() {
254 // TODO(pstew): Current kernel doesn't offer reverse-path filtering flag
255 // for IPv6. crosbug.com/24228
256 SetIPFlag(IPAddress::kFamilyIPv4, kIPFlagReversePathFilter,
257 kIPFlagReversePathFilterLooseMode);
258}
259
260void Device::EnableReversePathFilter() {
261 SetIPFlag(IPAddress::kFamilyIPv4, kIPFlagReversePathFilter,
262 kIPFlagReversePathFilterEnabled);
263}
264
Gaurav Shah435de2c2011-11-17 19:01:07 -0800265bool Device::IsConnected() const {
266 if (selected_service_)
267 return selected_service_->IsConnected();
268 return false;
269}
270
Paul Stewartd215af62012-04-24 23:25:50 -0700271bool Device::IsConnectedToService(const ServiceRefPtr &service) const {
272 return service == selected_service_ && IsConnected();
273}
274
mukesh agrawalf6b32092013-04-10 15:49:55 -0700275string Device::GetRpcIdentifier() const {
Chris Masone27c4aa52011-07-02 13:10:14 -0700276 return adaptor_->GetRpcIdentifier();
Chris Masone8fe2c7e2011-06-09 15:51:19 -0700277}
278
Chris Masone5dec5f42011-07-22 14:07:55 -0700279string Device::GetStorageIdentifier() {
280 string id = GetRpcIdentifier();
281 ControlInterface::RpcIdToStorageId(&id);
Chris Masone626719f2011-08-18 16:58:48 -0700282 size_t needle = id.find('_');
Chris Masone34af2182011-08-22 11:59:36 -0700283 DLOG_IF(ERROR, needle == string::npos) << "No _ in storage id?!?!";
Chris Masone626719f2011-08-18 16:58:48 -0700284 id.replace(id.begin() + needle + 1, id.end(), hardware_address_);
Chris Masone5dec5f42011-07-22 14:07:55 -0700285 return id;
286}
287
Gaurav Shah6d2c72d2012-10-16 16:30:44 -0700288vector<GeolocationInfo> Device::GetGeolocationObjects() const {
289 return vector<GeolocationInfo>();
290};
291
Jason Glasgowb5790052012-01-27 01:03:52 -0500292string Device::GetTechnologyString(Error */*error*/) {
293 return Technology::NameFromIdentifier(technology());
294}
295
Chris Masone19e30402011-07-19 15:48:47 -0700296const string& Device::FriendlyName() const {
Chris Masone7df0c672011-07-15 10:24:54 -0700297 return link_name_;
Darin Petkovafa6fc42011-06-21 16:21:08 -0700298}
299
Chris Masone19e30402011-07-19 15:48:47 -0700300const string& Device::UniqueName() const {
301 return unique_id_;
302}
303
Chris Masone5dec5f42011-07-22 14:07:55 -0700304bool Device::Load(StoreInterface *storage) {
305 const string id = GetStorageIdentifier();
306 if (!storage->ContainsGroup(id)) {
307 LOG(WARNING) << "Device is not available in the persistent store: " << id;
308 return false;
309 }
Eric Shienbrood9a245532012-03-07 14:20:39 -0500310 enabled_persistent_ = true;
311 storage->GetBool(id, kStoragePowered, &enabled_persistent_);
Paul Stewart6ff27f52012-07-11 06:51:41 -0700312 uint64 rx_byte_count = 0, tx_byte_count = 0;
313
314 manager_->device_info()->GetByteCounts(
315 interface_index_, &rx_byte_count, &tx_byte_count);
316 // If there is a byte-count present in the profile, the return value
317 // of Device::Get*ByteCount() should be the this stored value plus
318 // whatever additional bytes we receive since time-of-load. We
319 // accomplish this by the subtractions below, which can validly
320 // roll over "negative" in the subtractions below and in Get*ByteCount.
321 uint64 profile_byte_count;
322 if (storage->GetUint64(id, kStorageReceiveByteCount, &profile_byte_count)) {
323 receive_byte_offset_ = rx_byte_count - profile_byte_count;
324 }
325 if (storage->GetUint64(id, kStorageTransmitByteCount, &profile_byte_count)) {
326 transmit_byte_offset_ = tx_byte_count - profile_byte_count;
327 }
328
Chris Masone5dec5f42011-07-22 14:07:55 -0700329 return true;
330}
331
332bool Device::Save(StoreInterface *storage) {
333 const string id = GetStorageIdentifier();
Eric Shienbrood9a245532012-03-07 14:20:39 -0500334 storage->SetBool(id, kStoragePowered, enabled_persistent_);
Chris Masone34af2182011-08-22 11:59:36 -0700335 if (ipconfig_.get()) {
336 // The _0 is an index into the list of IPConfigs that this device might
337 // have. We only have one IPConfig right now, and I hope to never have
338 // to support more, as sleffler indicates that associating IPConfigs
339 // with devices is wrong and due to be changed in flimflam anyhow.
340 string suffix = hardware_address_ + "_0";
341 ipconfig_->Save(storage, suffix);
342 storage->SetString(id, kStorageIPConfigs, SerializeIPConfigs(suffix));
343 }
Ben Chanb061f892013-02-27 17:46:55 -0800344 storage->SetUint64(id, kStorageReceiveByteCount, GetReceiveByteCount());
345 storage->SetUint64(id, kStorageTransmitByteCount, GetTransmitByteCount());
Chris Masone5dec5f42011-07-22 14:07:55 -0700346 return true;
347}
348
mukesh agrawal784566d2012-08-08 18:32:58 -0700349void Device::OnBeforeSuspend() {
350 // Nothing to be done in the general case.
351}
352
353void Device::OnAfterResume() {
354 if (ipconfig_) {
355 SLOG(Device, 3) << "Renewing IP address on resume.";
356 ipconfig_->RenewIP();
357 }
358}
359
Darin Petkov2b8e44e2012-06-25 15:13:26 +0200360void Device::DropConnection() {
361 SLOG(Device, 2) << __func__;
362 DestroyIPConfig();
363 SelectService(NULL);
364}
365
Darin Petkovafa6fc42011-06-21 16:21:08 -0700366void Device::DestroyIPConfig() {
Paul Stewart2bf1d352011-12-06 15:02:55 -0800367 DisableIPv6();
Darin Petkovafa6fc42011-06-21 16:21:08 -0700368 if (ipconfig_.get()) {
369 ipconfig_->ReleaseIP();
370 ipconfig_ = NULL;
371 }
Paul Stewarte6132022011-08-16 09:11:02 -0700372 DestroyConnection();
Darin Petkovafa6fc42011-06-21 16:21:08 -0700373}
374
Arman Ugurayed8e6102012-11-29 14:47:20 -0800375bool Device::ShouldUseArpGateway() const {
376 return false;
377}
378
Paul Stewart2bf1d352011-12-06 15:02:55 -0800379bool Device::AcquireIPConfig() {
Paul Stewartd408fdf2012-05-07 17:15:57 -0700380 return AcquireIPConfigWithLeaseName(string());
381}
382
383bool Device::AcquireIPConfigWithLeaseName(const string &lease_name) {
Darin Petkovafa6fc42011-06-21 16:21:08 -0700384 DestroyIPConfig();
Paul Stewart2bf1d352011-12-06 15:02:55 -0800385 EnableIPv6();
Arman Ugurayed8e6102012-11-29 14:47:20 -0800386 bool arp_gateway = manager_->GetArpGateway() && ShouldUseArpGateway();
Paul Stewartd408fdf2012-05-07 17:15:57 -0700387 ipconfig_ = dhcp_provider_->CreateConfig(link_name_,
388 manager_->GetHostName(),
389 lease_name,
Arman Ugurayed8e6102012-11-29 14:47:20 -0800390 arp_gateway);
Eric Shienbrood9a245532012-03-07 14:20:39 -0500391 ipconfig_->RegisterUpdateCallback(Bind(&Device::OnIPConfigUpdated,
392 weak_ptr_factory_.GetWeakPtr()));
Paul Stewart1062d9d2012-04-27 10:42:27 -0700393 dispatcher_->PostTask(Bind(&Device::ConfigureStaticIPTask,
394 weak_ptr_factory_.GetWeakPtr()));
Darin Petkovafa6fc42011-06-21 16:21:08 -0700395 return ipconfig_->RequestIP();
396}
397
Albert Chaulk0e1cdea2013-02-27 15:32:55 -0800398void Device::DestroyIPConfigLease(const string &name) {
399 dhcp_provider_->DestroyLease(name);
400}
401
mukesh agrawalbebf1b82013-04-23 15:06:33 -0700402void Device::HelpRegisterConstDerivedString(
Jason Glasgowb5790052012-01-27 01:03:52 -0500403 const string &name,
mukesh agrawalbebf1b82013-04-23 15:06:33 -0700404 string(Device::*get)(Error *error)) {
Jason Glasgowb5790052012-01-27 01:03:52 -0500405 store_.RegisterDerivedString(
406 name,
mukesh agrawalbebf1b82013-04-23 15:06:33 -0700407 StringAccessor(new CustomAccessor<Device, string>(this, get, NULL)));
Chris Masone4e851612011-07-01 10:46:53 -0700408}
409
Jason Glasgow08afdff2012-04-03 10:22:26 -0400410void Device::HelpRegisterConstDerivedRpcIdentifiers(
411 const string &name,
412 RpcIdentifiers(Device::*get)(Error *)) {
413 store_.RegisterDerivedRpcIdentifiers(
414 name,
415 RpcIdentifiersAccessor(
416 new CustomAccessor<Device, RpcIdentifiers>(this, get, NULL)));
417}
418
Paul Stewart6ff27f52012-07-11 06:51:41 -0700419void Device::HelpRegisterConstDerivedUint64(
420 const string &name,
421 uint64(Device::*get)(Error *)) {
422 store_.RegisterDerivedUint64(
423 name,
424 Uint64Accessor(
425 new CustomAccessor<Device, uint64>(this, get, NULL)));
426}
427
Paul Stewart1062d9d2012-04-27 10:42:27 -0700428void Device::ConfigureStaticIPTask() {
429 SLOG(Device, 2) << __func__ << " selected_service " << selected_service_.get()
430 << " ipconfig " << ipconfig_.get();
431
432 if (!selected_service_ || !ipconfig_) {
433 return;
434 }
435
436 const StaticIPParameters &static_ip_parameters =
437 selected_service_->static_ip_parameters();
438 if (static_ip_parameters.ContainsAddress()) {
439 SLOG(Device, 2) << __func__ << " " << " configuring static IP parameters.";
440 // If the parameters contain an IP address, apply them now and bring
441 // the interface up. When DHCP information arrives, it will supplement
442 // the static information.
443 OnIPConfigUpdated(ipconfig_, true);
444 } else {
445 SLOG(Device, 2) << __func__ << " " << " no static IP address.";
446 }
447}
448
Darin Petkov79d74c92012-03-07 17:20:32 +0100449void Device::OnIPConfigUpdated(const IPConfigRefPtr &ipconfig, bool success) {
Ben Chanfad4a0b2012-04-18 15:49:59 -0700450 SLOG(Device, 2) << __func__ << " " << " success: " << success;
Paul Stewartc39f1132011-06-22 12:02:28 -0700451 if (success) {
Paul Stewarte6132022011-08-16 09:11:02 -0700452 CreateConnection();
Paul Stewart1062d9d2012-04-27 10:42:27 -0700453 if (selected_service_) {
454 ipconfig->ApplyStaticIPParameters(
Paul Stewartdef189e2012-08-02 20:12:09 -0700455 selected_service_->mutable_static_ip_parameters());
Paul Stewart1062d9d2012-04-27 10:42:27 -0700456 }
Paul Stewarte6132022011-08-16 09:11:02 -0700457 connection_->UpdateFromIPConfig(ipconfig);
Paul Stewartc1dec4d2011-12-08 15:25:28 -0800458 // SetConnection must occur after the UpdateFromIPConfig so the
459 // service can use the values derived from the connection.
Paul Stewart1062d9d2012-04-27 10:42:27 -0700460 if (selected_service_) {
Paul Stewartc1dec4d2011-12-08 15:25:28 -0800461 selected_service_->SetConnection(connection_);
Paul Stewartbe5f5b32011-12-07 17:11:11 -0800462 }
Paul Stewartc1dec4d2011-12-08 15:25:28 -0800463 // The service state change needs to happen last, so that at the
464 // time we report the state change to the manager, the service
465 // has its connection.
466 SetServiceState(Service::kStateConnected);
Christopher Wiley5519e9e2013-01-08 16:55:56 -0800467 OnConnected();
Thieu Le85e050b2012-03-13 15:04:38 -0700468 portal_attempts_to_online_ = 0;
Paul Stewart20088d82012-02-16 06:58:55 -0800469 // Subtle: Start portal detection after transitioning the service
470 // to the Connected state because this call may immediately transition
471 // to the Online state.
Thieu Led1760922012-09-11 14:15:35 -0700472 if (selected_service_) {
473 StartPortalDetection();
474 }
Paul Stewart036dba02012-08-07 12:34:41 -0700475 StartLinkMonitor();
Ben Chanb061f892013-02-27 17:46:55 -0800476 StartTrafficMonitor();
Prathmesh Prabhuba99b592013-04-17 15:13:14 -0700477 SetupConnectionHealthChecker();
Paul Stewarte6132022011-08-16 09:11:02 -0700478 } else {
mukesh agrawalcc0fded2012-05-09 13:40:58 -0700479 // TODO(pstew): This logic gets yet more complex when multiple
480 // IPConfig types are run in parallel (e.g. DHCP and DHCP6)
481 if (selected_service_ &&
482 selected_service_->static_ip_parameters().ContainsAddress()) {
483 // Consider three cases:
484 //
485 // 1. We're here because DHCP failed while starting up. There
486 // are two subcases:
487 // a. DHCP has failed, and Static IP config has _not yet_
488 // completed. It's fine to do nothing, because we'll
489 // apply the static config shortly.
490 // b. DHCP has failed, and Static IP config has _already_
491 // completed. It's fine to do nothing, because we can
492 // continue to use the static config that's already
493 // been applied.
494 //
495 // 2. We're here because a previously valid DHCP configuration
496 // is no longer valid. There's still a static IP config,
497 // because the condition in the if clause evaluated to true.
498 // Furthermore, the static config includes an IP address for
499 // us to use.
500 //
501 // The current configuration may include some DHCP
502 // parameters, overriden by any static parameters
503 // provided. We continue to use this configuration, because
504 // the only configuration element that is leased to us (IP
505 // address) will be overriden by a static parameter.
506 return;
507 }
508
Christopher Wileyabd3b502012-09-26 13:08:52 -0700509 if (selected_service_) {
510 Error error;
511 selected_service_->DisconnectWithFailure(Service::kFailureDHCP, &error);
512 }
Paul Stewarte6132022011-08-16 09:11:02 -0700513 DestroyConnection();
Paul Stewartc39f1132011-06-22 12:02:28 -0700514 }
Chris Masone8fe2c7e2011-06-09 15:51:19 -0700515}
516
Christopher Wiley5519e9e2013-01-08 16:55:56 -0800517void Device::OnConnected() {}
518
Paul Stewart8596f9f2013-03-14 07:58:26 -0700519void Device::OnConnectionUpdated() {
520 if (selected_service_) {
521 manager_->UpdateService(selected_service_);
522 }
523}
524
Paul Stewarte6132022011-08-16 09:11:02 -0700525void Device::CreateConnection() {
Ben Chanfad4a0b2012-04-18 15:49:59 -0700526 SLOG(Device, 2) << __func__;
Paul Stewarte6132022011-08-16 09:11:02 -0700527 if (!connection_.get()) {
mukesh agrawal23ac6b72013-01-31 18:52:37 -0800528 connection_ = new Connection(interface_index_,
529 link_name_,
530 technology_,
531 manager_->device_info());
Paul Stewarte6132022011-08-16 09:11:02 -0700532 }
533}
534
535void Device::DestroyConnection() {
Ben Chanfad4a0b2012-04-18 15:49:59 -0700536 SLOG(Device, 2) << __func__;
Paul Stewart20088d82012-02-16 06:58:55 -0800537 StopPortalDetection();
Paul Stewart036dba02012-08-07 12:34:41 -0700538 StopLinkMonitor();
Ben Chanb061f892013-02-27 17:46:55 -0800539 StopTrafficMonitor();
Paul Stewartbe5f5b32011-12-07 17:11:11 -0800540 if (selected_service_.get()) {
Paul Stewartc1dec4d2011-12-08 15:25:28 -0800541 selected_service_->SetConnection(NULL);
Paul Stewartbe5f5b32011-12-07 17:11:11 -0800542 }
Paul Stewartc8f4bef2011-12-13 09:45:51 -0800543 connection_ = NULL;
Arman Ugurayf84a4242013-04-09 20:01:07 -0700544 health_checker_.reset();
Paul Stewarte6132022011-08-16 09:11:02 -0700545}
546
Paul Stewart03dba0b2011-08-22 16:32:45 -0700547void Device::SelectService(const ServiceRefPtr &service) {
Darin Petkov457728b2013-01-09 09:49:08 +0100548 SLOG(Device, 2) << __func__ << ": service "
549 << (service ? service->unique_name() : "*reset*");
mukesh agrawal8a3188d2011-12-01 20:56:44 +0000550
551 if (selected_service_.get() == service.get()) {
552 // No change to |selected_service_|. Return early to avoid
553 // changing its state.
554 return;
555 }
556
Paul Stewartbe5f5b32011-12-07 17:11:11 -0800557 if (selected_service_.get()) {
558 if (selected_service_->state() != Service::kStateFailure) {
559 selected_service_->SetState(Service::kStateIdle);
560 }
Paul Stewart20b0a092012-05-22 20:39:57 -0700561 // Just in case the Device subclass has not already done so, make
562 // sure the previously selected service has its connection removed.
Paul Stewartc1dec4d2011-12-08 15:25:28 -0800563 selected_service_->SetConnection(NULL);
Paul Stewartc8860612012-09-28 07:36:21 -0700564 StopLinkMonitor();
Ben Chanb061f892013-02-27 17:46:55 -0800565 StopTrafficMonitor();
Paul Stewartc8860612012-09-28 07:36:21 -0700566 StopPortalDetection();
Paul Stewart03dba0b2011-08-22 16:32:45 -0700567 }
568 selected_service_ = service;
569}
570
571void Device::SetServiceState(Service::ConnectState state) {
572 if (selected_service_.get()) {
573 selected_service_->SetState(state);
574 }
575}
576
577void Device::SetServiceFailure(Service::ConnectFailure failure_state) {
578 if (selected_service_.get()) {
579 selected_service_->SetFailure(failure_state);
580 }
581}
582
Eric Shienbroodcc95c5d2012-03-30 15:25:49 -0400583void Device::SetServiceFailureSilent(Service::ConnectFailure failure_state) {
584 if (selected_service_.get()) {
585 selected_service_->SetFailureSilent(failure_state);
586 }
587}
588
Chris Masone34af2182011-08-22 11:59:36 -0700589string Device::SerializeIPConfigs(const string &suffix) {
590 return StringPrintf("%s:%s", suffix.c_str(), ipconfig_->type().c_str());
Chris Masone5dec5f42011-07-22 14:07:55 -0700591}
592
Paul Stewart2bf1d352011-12-06 15:02:55 -0800593bool Device::SetIPFlag(IPAddress::Family family, const string &flag,
594 const string &value) {
595 string ip_version;
596 if (family == IPAddress::kFamilyIPv4) {
597 ip_version = kIPFlagVersion4;
598 } else if (family == IPAddress::kFamilyIPv6) {
599 ip_version = kIPFlagVersion6;
600 } else {
601 NOTIMPLEMENTED();
602 }
603 FilePath flag_file(StringPrintf(kIPFlagTemplate, ip_version.c_str(),
604 link_name_.c_str(), flag.c_str()));
Ben Chanfad4a0b2012-04-18 15:49:59 -0700605 SLOG(Device, 2) << "Writing " << value << " to flag file "
606 << flag_file.value();
Paul Stewart2bf1d352011-12-06 15:02:55 -0800607 if (file_util::WriteFile(flag_file, value.c_str(), value.length()) != 1) {
608 LOG(ERROR) << StringPrintf("IP flag write failed: %s to %s",
609 value.c_str(), flag_file.value().c_str());
610 return false;
611 }
612 return true;
613}
614
Paul Stewart6ff27f52012-07-11 06:51:41 -0700615void Device::ResetByteCounters() {
616 manager_->device_info()->GetByteCounts(
617 interface_index_, &receive_byte_offset_, &transmit_byte_offset_);
618 manager_->UpdateDevice(this);
619}
620
Prathmesh Prabhuba99b592013-04-17 15:13:14 -0700621void Device::SetupConnectionHealthChecker() {
622 DCHECK(connection_);
623 if (!health_checker_.get()) {
624 health_checker_.reset(new ConnectionHealthChecker(
625 connection_,
626 dispatcher_,
627 manager_->health_checker_remote_ips(),
628 Bind(&Device::OnConnectionHealthCheckerResult,
629 weak_ptr_factory_.GetWeakPtr())));
630 } else {
631 health_checker_->SetConnection(connection_);
632 }
633 // Add URL in either case because a connection reset could have dropped past
634 // DNS queries.
635 health_checker_->AddRemoteURL(manager_->GetPortalCheckURL());
636}
637
Arman Ugurayf84a4242013-04-09 20:01:07 -0700638void Device::RequestConnectionHealthCheck() {
639 if (!health_checker_.get()) {
640 SLOG(Device, 2) << "No health checker exists, cannot request "
641 << "health check.";
642 return;
643 }
644 if (health_checker_->health_check_in_progress()) {
645 SLOG(Device, 2) << "Health check already in progress.";
646 return;
647 }
648 health_checker_->Start();
649}
650
651void Device::OnConnectionHealthCheckerResult(
652 ConnectionHealthChecker::Result result) {
Prathmesh Prabhu5489b7a2013-04-10 13:33:59 -0700653 SLOG(Device, 2)
654 << FriendlyName()
655 << ": ConnectionHealthChecker result: "
656 << ConnectionHealthChecker::ResultToString(result);
Arman Ugurayf84a4242013-04-09 20:01:07 -0700657}
658
Paul Stewartd215af62012-04-24 23:25:50 -0700659bool Device::RestartPortalDetection() {
660 StopPortalDetection();
661 return StartPortalDetection();
662}
663
Paul Stewartc681fa02012-03-02 19:40:04 -0800664bool Device::RequestPortalDetection() {
665 if (!selected_service_) {
Ben Chanfad4a0b2012-04-18 15:49:59 -0700666 SLOG(Device, 2) << FriendlyName()
Paul Stewartc681fa02012-03-02 19:40:04 -0800667 << ": No selected service, so no need for portal check.";
668 return false;
669 }
670
671 if (!connection_.get()) {
Ben Chanfad4a0b2012-04-18 15:49:59 -0700672 SLOG(Device, 2) << FriendlyName()
Paul Stewartc681fa02012-03-02 19:40:04 -0800673 << ": No connection, so no need for portal check.";
674 return false;
675 }
676
677 if (selected_service_->state() != Service::kStatePortal) {
Ben Chanfad4a0b2012-04-18 15:49:59 -0700678 SLOG(Device, 2) << FriendlyName()
Paul Stewartc681fa02012-03-02 19:40:04 -0800679 << ": Service is not in portal state. No need to start check.";
680 return false;
681 }
682
683 if (!connection_->is_default()) {
Ben Chanfad4a0b2012-04-18 15:49:59 -0700684 SLOG(Device, 2) << FriendlyName()
Paul Stewartc681fa02012-03-02 19:40:04 -0800685 << ": Service is not the default connection. Don't start check.";
686 return false;
687 }
688
689 if (portal_detector_.get() && portal_detector_->IsInProgress()) {
Ben Chanfad4a0b2012-04-18 15:49:59 -0700690 SLOG(Device, 2) << FriendlyName()
691 << ": Portal detection is already running.";
Paul Stewartc681fa02012-03-02 19:40:04 -0800692 return true;
693 }
694
695 return StartPortalDetection();
696}
697
Paul Stewart20088d82012-02-16 06:58:55 -0800698bool Device::StartPortalDetection() {
Darin Petkov457728b2013-01-09 09:49:08 +0100699 DCHECK(selected_service_);
Paul Stewartd215af62012-04-24 23:25:50 -0700700 if (selected_service_->IsPortalDetectionDisabled()) {
Darin Petkov457728b2013-01-09 09:49:08 +0100701 SLOG(Device, 2) << "Service " << selected_service_->unique_name()
Paul Stewartd215af62012-04-24 23:25:50 -0700702 << ": Portal detection is disabled; "
703 << "marking service online.";
704 SetServiceConnectedState(Service::kStateOnline);
705 return false;
706 }
707
708 if (selected_service_->IsPortalDetectionAuto() &&
709 !manager_->IsPortalDetectionEnabled(technology())) {
Paul Stewart20088d82012-02-16 06:58:55 -0800710 // If portal detection is disabled for this technology, immediately set
711 // the service state to "Online".
Ben Chanfad4a0b2012-04-18 15:49:59 -0700712 SLOG(Device, 2) << "Device " << FriendlyName()
713 << ": Portal detection is disabled; "
714 << "marking service online.";
Paul Stewart20088d82012-02-16 06:58:55 -0800715 SetServiceConnectedState(Service::kStateOnline);
716 return false;
717 }
718
Paul Stewart20088d82012-02-16 06:58:55 -0800719 if (selected_service_->HasProxyConfig()) {
720 // Services with HTTP proxy configurations should not be checked by the
721 // connection manager, since we don't have the ability to evaluate
722 // arbitrary proxy configs and their possible credentials.
Ben Chanfad4a0b2012-04-18 15:49:59 -0700723 SLOG(Device, 2) << "Device " << FriendlyName()
724 << ": Service has proxy config; marking it online.";
Paul Stewart20088d82012-02-16 06:58:55 -0800725 SetServiceConnectedState(Service::kStateOnline);
726 return false;
727 }
728
729 portal_detector_.reset(new PortalDetector(connection_,
730 dispatcher_,
Eric Shienbrood3e20a232012-02-16 11:35:56 -0500731 portal_detector_callback_));
Paul Stewart20088d82012-02-16 06:58:55 -0800732 if (!portal_detector_->Start(manager_->GetPortalCheckURL())) {
733 LOG(ERROR) << "Device " << FriendlyName()
734 << ": Portal detection failed to start: likely bad URL: "
735 << manager_->GetPortalCheckURL();
736 SetServiceConnectedState(Service::kStateOnline);
737 return false;
738 }
739
Ben Chanfad4a0b2012-04-18 15:49:59 -0700740 SLOG(Device, 2) << "Device " << FriendlyName()
741 << ": Portal detection has started.";
Paul Stewart20088d82012-02-16 06:58:55 -0800742 return true;
743}
744
745void Device::StopPortalDetection() {
Ben Chanfad4a0b2012-04-18 15:49:59 -0700746 SLOG(Device, 2) << "Device " << FriendlyName()
747 << ": Portal detection has stopped.";
Paul Stewart20088d82012-02-16 06:58:55 -0800748 portal_detector_.reset();
749}
750
Paul Stewart036dba02012-08-07 12:34:41 -0700751void Device::set_link_monitor(LinkMonitor *link_monitor) {
752 link_monitor_.reset(link_monitor);
753}
754
755bool Device::StartLinkMonitor() {
756 if (!manager_->IsTechnologyLinkMonitorEnabled(technology())) {
757 SLOG(Device, 2) << "Device " << FriendlyName()
758 << ": Link Monitoring is disabled.";
759 return false;
760 }
761
762 if (!link_monitor()) {
763 set_link_monitor(
764 new LinkMonitor(
765 connection_, dispatcher_, metrics(), manager_->device_info(),
766 Bind(&Device::OnLinkMonitorFailure, weak_ptr_factory_.GetWeakPtr())));
767 }
768
769 SLOG(Device, 2) << "Device " << FriendlyName()
770 << ": Link Monitor starting.";
771 return link_monitor_->Start();
772}
773
774void Device::StopLinkMonitor() {
775 SLOG(Device, 2) << "Device " << FriendlyName()
776 << ": Link Monitor stopping.";
777 link_monitor_.reset();
778}
779
780void Device::OnLinkMonitorFailure() {
781 LOG(ERROR) << "Device " << FriendlyName()
782 << ": Link Monitor indicates failure.";
783}
784
Ben Chanb061f892013-02-27 17:46:55 -0800785void Device::set_traffic_monitor(TrafficMonitor *traffic_monitor) {
786 traffic_monitor_.reset(traffic_monitor);
787}
788
789bool Device::StartTrafficMonitor() {
Thieu Le03026662013-04-04 10:45:11 -0700790 SLOG(Device, 2) << __func__;
Ben Chanb061f892013-02-27 17:46:55 -0800791 if (!traffic_monitor_enabled_) {
792 SLOG(Device, 2) << "Device " << FriendlyName()
793 << ": Traffic Monitoring is disabled.";
794 return false;
795 }
796
797 if (!traffic_monitor_.get()) {
798 traffic_monitor_.reset(new TrafficMonitor(this, dispatcher_));
Thieu Le03026662013-04-04 10:45:11 -0700799 traffic_monitor_->set_tcp_out_traffic_not_routed_callback(
800 Bind(&Device::OnNoNetworkRouting, weak_ptr_factory_.GetWeakPtr()));
Ben Chanb061f892013-02-27 17:46:55 -0800801 }
802
803 SLOG(Device, 2) << "Device " << FriendlyName()
804 << ": Traffic Monitor starting.";
805 traffic_monitor_->Start();
806 return true;
807}
808
809void Device::StopTrafficMonitor() {
Thieu Le03026662013-04-04 10:45:11 -0700810 SLOG(Device, 2) << __func__;
Ben Chanb061f892013-02-27 17:46:55 -0800811 SLOG(Device, 2) << "Device " << FriendlyName()
812 << ": Traffic Monitor stopping.";
813 traffic_monitor_.reset();
814}
815
Thieu Le03026662013-04-04 10:45:11 -0700816void Device::OnNoNetworkRouting() {
Ben Chanb061f892013-02-27 17:46:55 -0800817 SLOG(Device, 2) << "Device " << FriendlyName()
Arman Ugurayf84a4242013-04-09 20:01:07 -0700818 << ": Traffic Monitor detects network congestion.";
Ben Chanb061f892013-02-27 17:46:55 -0800819}
820
Paul Stewart20088d82012-02-16 06:58:55 -0800821void Device::SetServiceConnectedState(Service::ConnectState state) {
822 DCHECK(selected_service_.get());
823
824 if (!selected_service_.get()) {
825 LOG(ERROR) << FriendlyName() << ": "
826 << "Portal detection completed but no selected service exists!";
827 return;
828 }
829
830 if (!selected_service_->IsConnected()) {
831 LOG(ERROR) << FriendlyName() << ": "
832 << "Portal detection completed but selected service "
Darin Petkov457728b2013-01-09 09:49:08 +0100833 << selected_service_->unique_name()
Paul Stewart20088d82012-02-16 06:58:55 -0800834 << " is in non-connected state.";
835 return;
836 }
837
Paul Stewartc681fa02012-03-02 19:40:04 -0800838 if (state == Service::kStatePortal && connection_->is_default() &&
839 manager_->GetPortalCheckInterval() != 0) {
840 CHECK(portal_detector_.get());
841 if (!portal_detector_->StartAfterDelay(
842 manager_->GetPortalCheckURL(),
843 manager_->GetPortalCheckInterval())) {
844 LOG(ERROR) << "Device " << FriendlyName()
845 << ": Portal detection failed to restart: likely bad URL: "
846 << manager_->GetPortalCheckURL();
847 SetServiceState(Service::kStateOnline);
848 portal_detector_.reset();
849 return;
850 }
Ben Chanfad4a0b2012-04-18 15:49:59 -0700851 SLOG(Device, 2) << "Device " << FriendlyName()
852 << ": Portal detection retrying.";
Paul Stewartc681fa02012-03-02 19:40:04 -0800853 } else {
Ben Chanfad4a0b2012-04-18 15:49:59 -0700854 SLOG(Device, 2) << "Device " << FriendlyName()
855 << ": Portal will not retry.";
Paul Stewartc681fa02012-03-02 19:40:04 -0800856 portal_detector_.reset();
857 }
858
Paul Stewart20088d82012-02-16 06:58:55 -0800859 SetServiceState(state);
860}
861
862void Device::PortalDetectorCallback(const PortalDetector::Result &result) {
863 if (!result.final) {
Ben Chanfad4a0b2012-04-18 15:49:59 -0700864 SLOG(Device, 2) << "Device " << FriendlyName()
865 << ": Received non-final status: "
866 << PortalDetector::StatusToString(result.status);
Paul Stewart20088d82012-02-16 06:58:55 -0800867 return;
868 }
869
Ben Chanfad4a0b2012-04-18 15:49:59 -0700870 SLOG(Device, 2) << "Device " << FriendlyName()
871 << ": Received final status: "
872 << PortalDetector::StatusToString(result.status);
Paul Stewart20088d82012-02-16 06:58:55 -0800873
Thieu Le85e050b2012-03-13 15:04:38 -0700874 portal_attempts_to_online_ += result.num_attempts;
875
876 metrics()->SendEnumToUMA(
877 metrics()->GetFullMetricName(Metrics::kMetricPortalResult, technology()),
878 Metrics::PortalDetectionResultToEnum(result),
879 Metrics::kPortalResultMax);
880
Paul Stewart20088d82012-02-16 06:58:55 -0800881 if (result.status == PortalDetector::kStatusSuccess) {
882 SetServiceConnectedState(Service::kStateOnline);
Thieu Le85e050b2012-03-13 15:04:38 -0700883
884 metrics()->SendToUMA(
885 metrics()->GetFullMetricName(
886 Metrics::kMetricPortalAttemptsToOnline, technology()),
887 portal_attempts_to_online_,
888 Metrics::kMetricPortalAttemptsToOnlineMin,
889 Metrics::kMetricPortalAttemptsToOnlineMax,
890 Metrics::kMetricPortalAttemptsToOnlineNumBuckets);
Paul Stewart20088d82012-02-16 06:58:55 -0800891 } else {
892 SetServiceConnectedState(Service::kStatePortal);
Thieu Le85e050b2012-03-13 15:04:38 -0700893
894 metrics()->SendToUMA(
895 metrics()->GetFullMetricName(
896 Metrics::kMetricPortalAttempts, technology()),
897 result.num_attempts,
898 Metrics::kMetricPortalAttemptsMin,
899 Metrics::kMetricPortalAttemptsMax,
900 Metrics::kMetricPortalAttemptsNumBuckets);
Paul Stewart20088d82012-02-16 06:58:55 -0800901 }
902}
903
Gaurav Shah1b7a6162011-11-09 11:41:01 -0800904vector<string> Device::AvailableIPConfigs(Error */*error*/) {
Jason Glasgow08afdff2012-04-03 10:22:26 -0400905 if (ipconfig_.get()) {
906 string id = ipconfig_->GetRpcIdentifier();
907 return vector<string>(1, id);
908 }
909 return vector<string>();
Chris Masone4e851612011-07-01 10:46:53 -0700910}
911
912string Device::GetRpcConnectionIdentifier() {
913 return adaptor_->GetRpcConnectionIdentifier();
914}
915
Paul Stewart036dba02012-08-07 12:34:41 -0700916uint64 Device::GetLinkMonitorResponseTime(Error *error) {
917 if (!link_monitor_.get()) {
918 // It is not strictly an error that the link monitor does not
919 // exist, but returning an error here allows the GetProperties
920 // call in our Adaptor to omit this parameter.
921 error->Populate(Error::kNotFound, "Device is not running LinkMonitor");
922 return 0;
923 }
924 return link_monitor_->GetResponseTimeMilliseconds();
925}
926
Ben Chanb061f892013-02-27 17:46:55 -0800927uint64 Device::GetReceiveByteCount() {
Paul Stewart6ff27f52012-07-11 06:51:41 -0700928 uint64 rx_byte_count = 0, tx_byte_count = 0;
929 manager_->device_info()->GetByteCounts(
930 interface_index_, &rx_byte_count, &tx_byte_count);
931 return rx_byte_count - receive_byte_offset_;
932}
933
Ben Chanb061f892013-02-27 17:46:55 -0800934uint64 Device::GetTransmitByteCount() {
Paul Stewart6ff27f52012-07-11 06:51:41 -0700935 uint64 rx_byte_count = 0, tx_byte_count = 0;
936 manager_->device_info()->GetByteCounts(
937 interface_index_, &rx_byte_count, &tx_byte_count);
938 return tx_byte_count - transmit_byte_offset_;
939}
940
Ben Chanb061f892013-02-27 17:46:55 -0800941uint64 Device::GetReceiveByteCountProperty(Error */*error*/) {
942 return GetReceiveByteCount();
943}
944
945uint64 Device::GetTransmitByteCountProperty(Error */*error*/) {
946 return GetTransmitByteCount();
947}
948
Eric Shienbrood7fce52c2012-04-13 19:11:02 -0400949bool Device::IsUnderlyingDeviceEnabled() const {
950 return false;
951}
952
Eric Shienbrood9a245532012-03-07 14:20:39 -0500953// callback
954void Device::OnEnabledStateChanged(const ResultCallback &callback,
955 const Error &error) {
Ben Chanfad4a0b2012-04-18 15:49:59 -0700956 SLOG(Device, 2) << __func__ << "(" << enabled_pending_ << ")";
Eric Shienbrood9a245532012-03-07 14:20:39 -0500957 if (error.IsSuccess()) {
958 enabled_ = enabled_pending_;
959 manager_->UpdateEnabledTechnologies();
960 adaptor_->EmitBoolChanged(flimflam::kPoweredProperty, enabled_);
961 adaptor_->UpdateEnabled();
962 }
Gary Morainbaeefdf2012-04-30 14:53:35 -0700963 enabled_pending_ = enabled_;
Eric Shienbrood9a245532012-03-07 14:20:39 -0500964 if (!callback.is_null())
965 callback.Run(error);
966}
967
968void Device::SetEnabled(bool enable) {
Ben Chanfad4a0b2012-04-18 15:49:59 -0700969 SLOG(Device, 2) << __func__ << "(" << enable << ")";
Jason Glasgow4a490792012-04-10 15:02:05 -0400970 Error error;
971 SetEnabledInternal(enable, false, &error, ResultCallback());
Jason Glasgow7234ec32012-05-23 16:01:21 -0400972 LOG_IF(ERROR, error.IsFailure() && !error.IsOngoing())
Jason Glasgow4a490792012-04-10 15:02:05 -0400973 << "Enabled failed, but no way to report the failure.";
Eric Shienbrood9a245532012-03-07 14:20:39 -0500974}
975
976void Device::SetEnabledPersistent(bool enable,
977 Error *error,
978 const ResultCallback &callback) {
979 SetEnabledInternal(enable, true, error, callback);
980}
981
982void Device::SetEnabledInternal(bool enable,
983 bool persist,
984 Error *error,
985 const ResultCallback &callback) {
Jason Glasgow4a490792012-04-10 15:02:05 -0400986 DCHECK(error);
Ben Chanfad4a0b2012-04-18 15:49:59 -0700987 SLOG(Device, 2) << "Device " << link_name_ << " "
988 << (enable ? "starting" : "stopping");
Eric Shienbrood9a245532012-03-07 14:20:39 -0500989 if (enable == enabled_) {
Jason Glasgow4a490792012-04-10 15:02:05 -0400990 error->Reset();
Eric Shienbrood9a245532012-03-07 14:20:39 -0500991 return;
992 }
993
994 if (enabled_pending_ == enable) {
Jason Glasgow4a490792012-04-10 15:02:05 -0400995 Error::PopulateAndLog(error, Error::kInProgress,
996 "Enable operation already in progress");
Eric Shienbrood9a245532012-03-07 14:20:39 -0500997 return;
998 }
999
1000 if (persist) {
1001 enabled_persistent_ = enable;
Darin Petkove7c6ad32012-06-29 10:22:09 +02001002 manager_->UpdateDevice(this);
Eric Shienbrood9a245532012-03-07 14:20:39 -05001003 }
1004
1005 enabled_pending_ = enable;
1006 EnabledStateChangedCallback enabled_callback =
1007 Bind(&Device::OnEnabledStateChanged,
1008 weak_ptr_factory_.GetWeakPtr(), callback);
1009 if (enable) {
1010 running_ = true;
Eric Shienbrood9a245532012-03-07 14:20:39 -05001011 Start(error, enabled_callback);
1012 } else {
1013 running_ = false;
1014 DestroyIPConfig(); // breaks a reference cycle
1015 SelectService(NULL); // breaks a reference cycle
1016 rtnl_handler_->SetInterfaceFlags(interface_index(), 0, IFF_UP);
Ben Chanfad4a0b2012-04-18 15:49:59 -07001017 SLOG(Device, 3) << "Device " << link_name_ << " ipconfig_ "
1018 << (ipconfig_ ? "is set." : "is not set.");
1019 SLOG(Device, 3) << "Device " << link_name_ << " connection_ "
1020 << (connection_ ? "is set." : "is not set.");
1021 SLOG(Device, 3) << "Device " << link_name_ << " selected_service_ "
1022 << (selected_service_ ? "is set." : "is not set.");
Eric Shienbrood9a245532012-03-07 14:20:39 -05001023 Stop(error, enabled_callback);
1024 }
1025}
1026
Paul Stewart75897df2011-04-27 09:05:53 -07001027} // namespace shill