blob: 7bb92e302997dd549068d7e2509ad9824f8729ab [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
Chris Masone5dec5f42011-07-22 14:07:55 -070074const char Device::kStoragePowered[] = "Powered";
Chris Masone5dec5f42011-07-22 14:07:55 -070075// static
76const char Device::kStorageIPConfigs[] = "IPConfigs";
Paul Stewart6ff27f52012-07-11 06:51:41 -070077// static
78const 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_);
Jason Glasgowb5790052012-01-27 01:03:52 -0500145 HelpRegisterDerivedString(flimflam::kTypeProperty,
146 &Device::GetTechnologyString,
147 NULL);
Paul Stewart036dba02012-08-07 12:34:41 -0700148 HelpRegisterConstDerivedUint64(shill::kLinkMonitorResponseTimeProperty,
149 &Device::GetLinkMonitorResponseTime);
Jason Glasgowb5790052012-01-27 01:03:52 -0500150
Chris Masoneb925cc82011-06-22 15:39:57 -0700151 // TODO(cmasone): Chrome doesn't use this...does anyone?
Chris Masone27c4aa52011-07-02 13:10:14 -0700152 // store_.RegisterConstBool(flimflam::kReconnectProperty, &reconnect_);
Chris Masoneb925cc82011-06-22 15:39:57 -0700153
Chris Masone4e851612011-07-01 10:46:53 -0700154 // TODO(cmasone): Figure out what shill concept maps to flimflam's "Network".
Chris Masoneb925cc82011-06-22 15:39:57 -0700155 // known_properties_.push_back(flimflam::kNetworksProperty);
156
Chris Masone4d42df82011-07-02 17:09:39 -0700157 // flimflam::kScanningProperty: Registered in WiFi, Cellular
158 // flimflam::kScanIntervalProperty: Registered in WiFi, Cellular
Paul Stewart6ff27f52012-07-11 06:51:41 -0700159
160 if (manager_ && manager_->device_info()) { // Unit tests may not have these.
161 manager_->device_info()->GetByteCounts(
162 interface_index_, &receive_byte_offset_, &transmit_byte_offset_);
163 HelpRegisterConstDerivedUint64(shill::kReceiveByteCountProperty,
Ben Chanb061f892013-02-27 17:46:55 -0800164 &Device::GetReceiveByteCountProperty);
Paul Stewart6ff27f52012-07-11 06:51:41 -0700165 HelpRegisterConstDerivedUint64(shill::kTransmitByteCountProperty,
Ben Chanb061f892013-02-27 17:46:55 -0800166 &Device::GetTransmitByteCountProperty);
Paul Stewart6ff27f52012-07-11 06:51:41 -0700167 }
168
Arman Ugurayf84a4242013-04-09 20:01:07 -0700169 // TODO(armansito): Remove this hack once shill has support for caching DNS
170 // results.
171 health_check_ip_pool_.push_back("74.125.224.47");
172 health_check_ip_pool_.push_back("74.125.224.79");
173 health_check_ip_pool_.push_back("74.125.224.111");
174 health_check_ip_pool_.push_back("74.125.224.143");
175
Darin Petkova0a0efe2012-06-27 12:50:01 +0200176 LOG(INFO) << "Device created: " << link_name_
177 << " index " << interface_index_;
Paul Stewart75897df2011-04-27 09:05:53 -0700178}
179
180Device::~Device() {
Darin Petkova0a0efe2012-06-27 12:50:01 +0200181 LOG(INFO) << "Device destructed: " << link_name_
182 << " index " << interface_index_;
Paul Stewart75897df2011-04-27 09:05:53 -0700183}
184
Paul Stewartf1ce5d22011-05-19 13:10:20 -0700185void Device::LinkEvent(unsigned flags, unsigned change) {
Ben Chanfad4a0b2012-04-18 15:49:59 -0700186 SLOG(Device, 2) << "Device " << link_name_
187 << std::showbase << std::hex
188 << " flags " << flags << " changed " << change
189 << std::dec << std::noshowbase;
Paul Stewartf1ce5d22011-05-19 13:10:20 -0700190}
191
Wade Guthrie68d41092013-04-02 12:56:02 -0700192void Device::Scan(ScanType scan_type, Error *error) {
Ben Chanfad4a0b2012-04-18 15:49:59 -0700193 SLOG(Device, 2) << "Device " << link_name_ << " scan requested.";
Paul Stewartbe005172011-11-02 18:10:29 -0700194 Error::PopulateAndLog(error, Error::kNotSupported,
195 "Device doesn't support scan.");
Paul Stewartf1ce5d22011-05-19 13:10:20 -0700196}
197
Eric Shienbrood9a245532012-03-07 14:20:39 -0500198void Device::RegisterOnNetwork(const std::string &/*network_id*/, Error *error,
199 const ResultCallback &/*callback*/) {
200 Error::PopulateAndLog(error, Error::kNotSupported,
Paul Stewartbe005172011-11-02 18:10:29 -0700201 "Device doesn't support network registration.");
Darin Petkov9ae310f2011-08-30 15:41:13 -0700202}
203
Darin Petkovc64fe5e2012-01-11 12:46:13 +0100204void Device::RequirePIN(
Eric Shienbrood9a245532012-03-07 14:20:39 -0500205 const string &/*pin*/, bool /*require*/,
206 Error *error, const ResultCallback &/*callback*/) {
Ben Chanfad4a0b2012-04-18 15:49:59 -0700207 SLOG(Device, 2) << __func__;
Eric Shienbrood9a245532012-03-07 14:20:39 -0500208 Error::PopulateAndLog(error, Error::kNotSupported,
209 "Device doesn't support RequirePIN.");
Darin Petkove42e1012011-08-31 12:35:04 -0700210}
211
Eric Shienbrood9a245532012-03-07 14:20:39 -0500212void Device::EnterPIN(const string &/*pin*/,
213 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 EnterPIN.");
Darin Petkove42e1012011-08-31 12:35:04 -0700217}
218
mukesh agrawal1830fa12011-09-26 14:31:40 -0700219void Device::UnblockPIN(const string &/*unblock_code*/,
220 const string &/*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 UnblockPIN.");
Darin Petkove42e1012011-08-31 12:35:04 -0700225}
226
mukesh agrawal1830fa12011-09-26 14:31:40 -0700227void Device::ChangePIN(const string &/*old_pin*/,
228 const string &/*new_pin*/,
Eric Shienbrood9a245532012-03-07 14:20:39 -0500229 Error *error, const ResultCallback &/*callback*/) {
Ben Chanfad4a0b2012-04-18 15:49:59 -0700230 SLOG(Device, 2) << __func__;
Eric Shienbrood9a245532012-03-07 14:20:39 -0500231 Error::PopulateAndLog(error, Error::kNotSupported,
232 "Device doesn't support ChangePIN.");
Darin Petkove42e1012011-08-31 12:35:04 -0700233}
234
Ben Chanad663e12013-01-08 01:58:47 -0800235void Device::Reset(Error *error, const ResultCallback &/*callback*/) {
236 SLOG(Device, 2) << __func__;
237 Error::PopulateAndLog(error, Error::kNotSupported,
238 "Device doesn't support Reset.");
239}
240
Darin Petkovc37a9c42012-09-06 15:28:22 +0200241void Device::SetCarrier(const string &/*carrier*/,
242 Error *error, const ResultCallback &/*callback*/) {
243 SLOG(Device, 2) << __func__;
244 Error::PopulateAndLog(error, Error::kNotSupported,
245 "Device doesn't support SetCarrier.");
246}
247
Paul Stewart2bf1d352011-12-06 15:02:55 -0800248void Device::DisableIPv6() {
249 SetIPFlag(IPAddress::kFamilyIPv6, kIPFlagDisableIPv6, "1");
250}
251
252void Device::EnableIPv6() {
253 SetIPFlag(IPAddress::kFamilyIPv6, kIPFlagDisableIPv6, "0");
254}
255
256void Device::EnableIPv6Privacy() {
257 SetIPFlag(IPAddress::kFamilyIPv6, kIPFlagUseTempAddr,
258 kIPFlagUseTempAddrUsedAndDefault);
259}
260
Paul Stewartc8f4bef2011-12-13 09:45:51 -0800261void Device::DisableReversePathFilter() {
262 // TODO(pstew): Current kernel doesn't offer reverse-path filtering flag
263 // for IPv6. crosbug.com/24228
264 SetIPFlag(IPAddress::kFamilyIPv4, kIPFlagReversePathFilter,
265 kIPFlagReversePathFilterLooseMode);
266}
267
268void Device::EnableReversePathFilter() {
269 SetIPFlag(IPAddress::kFamilyIPv4, kIPFlagReversePathFilter,
270 kIPFlagReversePathFilterEnabled);
271}
272
Gaurav Shah435de2c2011-11-17 19:01:07 -0800273bool Device::IsConnected() const {
274 if (selected_service_)
275 return selected_service_->IsConnected();
276 return false;
277}
278
Paul Stewartd215af62012-04-24 23:25:50 -0700279bool Device::IsConnectedToService(const ServiceRefPtr &service) const {
280 return service == selected_service_ && IsConnected();
281}
282
mukesh agrawalf6b32092013-04-10 15:49:55 -0700283string Device::GetRpcIdentifier() const {
Chris Masone27c4aa52011-07-02 13:10:14 -0700284 return adaptor_->GetRpcIdentifier();
Chris Masone8fe2c7e2011-06-09 15:51:19 -0700285}
286
Chris Masone5dec5f42011-07-22 14:07:55 -0700287string Device::GetStorageIdentifier() {
288 string id = GetRpcIdentifier();
289 ControlInterface::RpcIdToStorageId(&id);
Chris Masone626719f2011-08-18 16:58:48 -0700290 size_t needle = id.find('_');
Chris Masone34af2182011-08-22 11:59:36 -0700291 DLOG_IF(ERROR, needle == string::npos) << "No _ in storage id?!?!";
Chris Masone626719f2011-08-18 16:58:48 -0700292 id.replace(id.begin() + needle + 1, id.end(), hardware_address_);
Chris Masone5dec5f42011-07-22 14:07:55 -0700293 return id;
294}
295
Gaurav Shah6d2c72d2012-10-16 16:30:44 -0700296vector<GeolocationInfo> Device::GetGeolocationObjects() const {
297 return vector<GeolocationInfo>();
298};
299
Jason Glasgowb5790052012-01-27 01:03:52 -0500300string Device::GetTechnologyString(Error */*error*/) {
301 return Technology::NameFromIdentifier(technology());
302}
303
Chris Masone19e30402011-07-19 15:48:47 -0700304const string& Device::FriendlyName() const {
Chris Masone7df0c672011-07-15 10:24:54 -0700305 return link_name_;
Darin Petkovafa6fc42011-06-21 16:21:08 -0700306}
307
Chris Masone19e30402011-07-19 15:48:47 -0700308const string& Device::UniqueName() const {
309 return unique_id_;
310}
311
Chris Masone5dec5f42011-07-22 14:07:55 -0700312bool Device::Load(StoreInterface *storage) {
313 const string id = GetStorageIdentifier();
314 if (!storage->ContainsGroup(id)) {
315 LOG(WARNING) << "Device is not available in the persistent store: " << id;
316 return false;
317 }
Eric Shienbrood9a245532012-03-07 14:20:39 -0500318 enabled_persistent_ = true;
319 storage->GetBool(id, kStoragePowered, &enabled_persistent_);
Paul Stewart6ff27f52012-07-11 06:51:41 -0700320 uint64 rx_byte_count = 0, tx_byte_count = 0;
321
322 manager_->device_info()->GetByteCounts(
323 interface_index_, &rx_byte_count, &tx_byte_count);
324 // If there is a byte-count present in the profile, the return value
325 // of Device::Get*ByteCount() should be the this stored value plus
326 // whatever additional bytes we receive since time-of-load. We
327 // accomplish this by the subtractions below, which can validly
328 // roll over "negative" in the subtractions below and in Get*ByteCount.
329 uint64 profile_byte_count;
330 if (storage->GetUint64(id, kStorageReceiveByteCount, &profile_byte_count)) {
331 receive_byte_offset_ = rx_byte_count - profile_byte_count;
332 }
333 if (storage->GetUint64(id, kStorageTransmitByteCount, &profile_byte_count)) {
334 transmit_byte_offset_ = tx_byte_count - profile_byte_count;
335 }
336
Chris Masone5dec5f42011-07-22 14:07:55 -0700337 return true;
338}
339
340bool Device::Save(StoreInterface *storage) {
341 const string id = GetStorageIdentifier();
Eric Shienbrood9a245532012-03-07 14:20:39 -0500342 storage->SetBool(id, kStoragePowered, enabled_persistent_);
Chris Masone34af2182011-08-22 11:59:36 -0700343 if (ipconfig_.get()) {
344 // The _0 is an index into the list of IPConfigs that this device might
345 // have. We only have one IPConfig right now, and I hope to never have
346 // to support more, as sleffler indicates that associating IPConfigs
347 // with devices is wrong and due to be changed in flimflam anyhow.
348 string suffix = hardware_address_ + "_0";
349 ipconfig_->Save(storage, suffix);
350 storage->SetString(id, kStorageIPConfigs, SerializeIPConfigs(suffix));
351 }
Ben Chanb061f892013-02-27 17:46:55 -0800352 storage->SetUint64(id, kStorageReceiveByteCount, GetReceiveByteCount());
353 storage->SetUint64(id, kStorageTransmitByteCount, GetTransmitByteCount());
Chris Masone5dec5f42011-07-22 14:07:55 -0700354 return true;
355}
356
mukesh agrawal784566d2012-08-08 18:32:58 -0700357void Device::OnBeforeSuspend() {
358 // Nothing to be done in the general case.
359}
360
361void Device::OnAfterResume() {
362 if (ipconfig_) {
363 SLOG(Device, 3) << "Renewing IP address on resume.";
364 ipconfig_->RenewIP();
365 }
366}
367
Darin Petkov2b8e44e2012-06-25 15:13:26 +0200368void Device::DropConnection() {
369 SLOG(Device, 2) << __func__;
370 DestroyIPConfig();
371 SelectService(NULL);
372}
373
Darin Petkovafa6fc42011-06-21 16:21:08 -0700374void Device::DestroyIPConfig() {
Paul Stewart2bf1d352011-12-06 15:02:55 -0800375 DisableIPv6();
Darin Petkovafa6fc42011-06-21 16:21:08 -0700376 if (ipconfig_.get()) {
377 ipconfig_->ReleaseIP();
378 ipconfig_ = NULL;
379 }
Paul Stewarte6132022011-08-16 09:11:02 -0700380 DestroyConnection();
Darin Petkovafa6fc42011-06-21 16:21:08 -0700381}
382
Arman Ugurayed8e6102012-11-29 14:47:20 -0800383bool Device::ShouldUseArpGateway() const {
384 return false;
385}
386
Paul Stewart2bf1d352011-12-06 15:02:55 -0800387bool Device::AcquireIPConfig() {
Paul Stewartd408fdf2012-05-07 17:15:57 -0700388 return AcquireIPConfigWithLeaseName(string());
389}
390
391bool Device::AcquireIPConfigWithLeaseName(const string &lease_name) {
Darin Petkovafa6fc42011-06-21 16:21:08 -0700392 DestroyIPConfig();
Paul Stewart2bf1d352011-12-06 15:02:55 -0800393 EnableIPv6();
Arman Ugurayed8e6102012-11-29 14:47:20 -0800394 bool arp_gateway = manager_->GetArpGateway() && ShouldUseArpGateway();
Paul Stewartd408fdf2012-05-07 17:15:57 -0700395 ipconfig_ = dhcp_provider_->CreateConfig(link_name_,
396 manager_->GetHostName(),
397 lease_name,
Arman Ugurayed8e6102012-11-29 14:47:20 -0800398 arp_gateway);
Eric Shienbrood9a245532012-03-07 14:20:39 -0500399 ipconfig_->RegisterUpdateCallback(Bind(&Device::OnIPConfigUpdated,
400 weak_ptr_factory_.GetWeakPtr()));
Paul Stewart1062d9d2012-04-27 10:42:27 -0700401 dispatcher_->PostTask(Bind(&Device::ConfigureStaticIPTask,
402 weak_ptr_factory_.GetWeakPtr()));
Darin Petkovafa6fc42011-06-21 16:21:08 -0700403 return ipconfig_->RequestIP();
404}
405
Albert Chaulk0e1cdea2013-02-27 15:32:55 -0800406void Device::DestroyIPConfigLease(const string &name) {
407 dhcp_provider_->DestroyLease(name);
408}
409
Jason Glasgowb5790052012-01-27 01:03:52 -0500410void Device::HelpRegisterDerivedString(
411 const string &name,
412 string(Device::*get)(Error *error),
413 void(Device::*set)(const string &value, Error *error)) {
414 store_.RegisterDerivedString(
415 name,
416 StringAccessor(new CustomAccessor<Device, string>(this, get, set)));
417}
418
mukesh agrawalffa3d042011-10-06 15:26:10 -0700419void Device::HelpRegisterDerivedStrings(
420 const string &name,
Eric Shienbrood9a245532012-03-07 14:20:39 -0500421 Strings(Device::*get)(Error *error),
422 void(Device::*set)(const Strings &value, Error *error)) {
Chris Masone27c4aa52011-07-02 13:10:14 -0700423 store_.RegisterDerivedStrings(
424 name,
425 StringsAccessor(new CustomAccessor<Device, Strings>(this, get, set)));
Chris Masone4e851612011-07-01 10:46:53 -0700426}
427
Jason Glasgow08afdff2012-04-03 10:22:26 -0400428void Device::HelpRegisterConstDerivedRpcIdentifiers(
429 const string &name,
430 RpcIdentifiers(Device::*get)(Error *)) {
431 store_.RegisterDerivedRpcIdentifiers(
432 name,
433 RpcIdentifiersAccessor(
434 new CustomAccessor<Device, RpcIdentifiers>(this, get, NULL)));
435}
436
Paul Stewart6ff27f52012-07-11 06:51:41 -0700437void Device::HelpRegisterConstDerivedUint64(
438 const string &name,
439 uint64(Device::*get)(Error *)) {
440 store_.RegisterDerivedUint64(
441 name,
442 Uint64Accessor(
443 new CustomAccessor<Device, uint64>(this, get, NULL)));
444}
445
Paul Stewart1062d9d2012-04-27 10:42:27 -0700446void Device::ConfigureStaticIPTask() {
447 SLOG(Device, 2) << __func__ << " selected_service " << selected_service_.get()
448 << " ipconfig " << ipconfig_.get();
449
450 if (!selected_service_ || !ipconfig_) {
451 return;
452 }
453
454 const StaticIPParameters &static_ip_parameters =
455 selected_service_->static_ip_parameters();
456 if (static_ip_parameters.ContainsAddress()) {
457 SLOG(Device, 2) << __func__ << " " << " configuring static IP parameters.";
458 // If the parameters contain an IP address, apply them now and bring
459 // the interface up. When DHCP information arrives, it will supplement
460 // the static information.
461 OnIPConfigUpdated(ipconfig_, true);
462 } else {
463 SLOG(Device, 2) << __func__ << " " << " no static IP address.";
464 }
465}
466
Darin Petkov79d74c92012-03-07 17:20:32 +0100467void Device::OnIPConfigUpdated(const IPConfigRefPtr &ipconfig, bool success) {
Ben Chanfad4a0b2012-04-18 15:49:59 -0700468 SLOG(Device, 2) << __func__ << " " << " success: " << success;
Paul Stewartc39f1132011-06-22 12:02:28 -0700469 if (success) {
Paul Stewarte6132022011-08-16 09:11:02 -0700470 CreateConnection();
Paul Stewart1062d9d2012-04-27 10:42:27 -0700471 if (selected_service_) {
472 ipconfig->ApplyStaticIPParameters(
Paul Stewartdef189e2012-08-02 20:12:09 -0700473 selected_service_->mutable_static_ip_parameters());
Paul Stewart1062d9d2012-04-27 10:42:27 -0700474 }
Paul Stewarte6132022011-08-16 09:11:02 -0700475 connection_->UpdateFromIPConfig(ipconfig);
Paul Stewartc1dec4d2011-12-08 15:25:28 -0800476 // SetConnection must occur after the UpdateFromIPConfig so the
477 // service can use the values derived from the connection.
Paul Stewart1062d9d2012-04-27 10:42:27 -0700478 if (selected_service_) {
Paul Stewartc1dec4d2011-12-08 15:25:28 -0800479 selected_service_->SetConnection(connection_);
Paul Stewartbe5f5b32011-12-07 17:11:11 -0800480 }
Paul Stewartc1dec4d2011-12-08 15:25:28 -0800481 // The service state change needs to happen last, so that at the
482 // time we report the state change to the manager, the service
483 // has its connection.
484 SetServiceState(Service::kStateConnected);
Christopher Wiley5519e9e2013-01-08 16:55:56 -0800485 OnConnected();
Thieu Le85e050b2012-03-13 15:04:38 -0700486 portal_attempts_to_online_ = 0;
Paul Stewart20088d82012-02-16 06:58:55 -0800487 // Subtle: Start portal detection after transitioning the service
488 // to the Connected state because this call may immediately transition
489 // to the Online state.
Thieu Led1760922012-09-11 14:15:35 -0700490 if (selected_service_) {
491 StartPortalDetection();
492 }
Paul Stewart036dba02012-08-07 12:34:41 -0700493 StartLinkMonitor();
Ben Chanb061f892013-02-27 17:46:55 -0800494 StartTrafficMonitor();
Paul Stewarte6132022011-08-16 09:11:02 -0700495 } else {
mukesh agrawalcc0fded2012-05-09 13:40:58 -0700496 // TODO(pstew): This logic gets yet more complex when multiple
497 // IPConfig types are run in parallel (e.g. DHCP and DHCP6)
498 if (selected_service_ &&
499 selected_service_->static_ip_parameters().ContainsAddress()) {
500 // Consider three cases:
501 //
502 // 1. We're here because DHCP failed while starting up. There
503 // are two subcases:
504 // a. DHCP has failed, and Static IP config has _not yet_
505 // completed. It's fine to do nothing, because we'll
506 // apply the static config shortly.
507 // b. DHCP has failed, and Static IP config has _already_
508 // completed. It's fine to do nothing, because we can
509 // continue to use the static config that's already
510 // been applied.
511 //
512 // 2. We're here because a previously valid DHCP configuration
513 // is no longer valid. There's still a static IP config,
514 // because the condition in the if clause evaluated to true.
515 // Furthermore, the static config includes an IP address for
516 // us to use.
517 //
518 // The current configuration may include some DHCP
519 // parameters, overriden by any static parameters
520 // provided. We continue to use this configuration, because
521 // the only configuration element that is leased to us (IP
522 // address) will be overriden by a static parameter.
523 return;
524 }
525
Christopher Wileyabd3b502012-09-26 13:08:52 -0700526 if (selected_service_) {
527 Error error;
528 selected_service_->DisconnectWithFailure(Service::kFailureDHCP, &error);
529 }
Paul Stewarte6132022011-08-16 09:11:02 -0700530 DestroyConnection();
Paul Stewartc39f1132011-06-22 12:02:28 -0700531 }
Chris Masone8fe2c7e2011-06-09 15:51:19 -0700532}
533
Christopher Wiley5519e9e2013-01-08 16:55:56 -0800534void Device::OnConnected() {}
535
Paul Stewart8596f9f2013-03-14 07:58:26 -0700536void Device::OnConnectionUpdated() {
537 if (selected_service_) {
538 manager_->UpdateService(selected_service_);
539 }
540}
541
Paul Stewarte6132022011-08-16 09:11:02 -0700542void Device::CreateConnection() {
Ben Chanfad4a0b2012-04-18 15:49:59 -0700543 SLOG(Device, 2) << __func__;
Paul Stewarte6132022011-08-16 09:11:02 -0700544 if (!connection_.get()) {
mukesh agrawal23ac6b72013-01-31 18:52:37 -0800545 connection_ = new Connection(interface_index_,
546 link_name_,
547 technology_,
548 manager_->device_info());
Arman Ugurayf84a4242013-04-09 20:01:07 -0700549 set_health_checker(
550 new ConnectionHealthChecker(
551 connection_,
552 dispatcher_,
553 Bind(&Device::OnConnectionHealthCheckerResult,
554 weak_ptr_factory_.GetWeakPtr())));
555 InitializeHealthCheckIps();
556 }
557}
558
559void Device::InitializeHealthCheckIps() {
560 IPAddress ip(IPAddress::kFamilyIPv4);
561 for (size_t i = 0; i < health_check_ip_pool_.size(); ++i) {
562 // TODO(armansito): DNS resolution fails when we run out-of-credit
563 // and shill currently doesn't cache resolved IPs. The hardcoded IP
564 // here corresponds to gstatic.google.com/generate_204, however I do
565 // not know if it will remain static. We should implement some sort of
566 // caching after portal detection for this to work.
567 ip.SetAddressFromString(health_check_ip_pool_[i]);
568 health_checker_->AddRemoteIP(ip);
Paul Stewarte6132022011-08-16 09:11:02 -0700569 }
570}
571
572void Device::DestroyConnection() {
Ben Chanfad4a0b2012-04-18 15:49:59 -0700573 SLOG(Device, 2) << __func__;
Paul Stewart20088d82012-02-16 06:58:55 -0800574 StopPortalDetection();
Paul Stewart036dba02012-08-07 12:34:41 -0700575 StopLinkMonitor();
Ben Chanb061f892013-02-27 17:46:55 -0800576 StopTrafficMonitor();
Paul Stewartbe5f5b32011-12-07 17:11:11 -0800577 if (selected_service_.get()) {
Paul Stewartc1dec4d2011-12-08 15:25:28 -0800578 selected_service_->SetConnection(NULL);
Paul Stewartbe5f5b32011-12-07 17:11:11 -0800579 }
Paul Stewartc8f4bef2011-12-13 09:45:51 -0800580 connection_ = NULL;
Arman Ugurayf84a4242013-04-09 20:01:07 -0700581 health_checker_.reset();
Paul Stewarte6132022011-08-16 09:11:02 -0700582}
583
Paul Stewart03dba0b2011-08-22 16:32:45 -0700584void Device::SelectService(const ServiceRefPtr &service) {
Darin Petkov457728b2013-01-09 09:49:08 +0100585 SLOG(Device, 2) << __func__ << ": service "
586 << (service ? service->unique_name() : "*reset*");
mukesh agrawal8a3188d2011-12-01 20:56:44 +0000587
588 if (selected_service_.get() == service.get()) {
589 // No change to |selected_service_|. Return early to avoid
590 // changing its state.
591 return;
592 }
593
Paul Stewartbe5f5b32011-12-07 17:11:11 -0800594 if (selected_service_.get()) {
595 if (selected_service_->state() != Service::kStateFailure) {
596 selected_service_->SetState(Service::kStateIdle);
597 }
Paul Stewart20b0a092012-05-22 20:39:57 -0700598 // Just in case the Device subclass has not already done so, make
599 // sure the previously selected service has its connection removed.
Paul Stewartc1dec4d2011-12-08 15:25:28 -0800600 selected_service_->SetConnection(NULL);
Paul Stewartc8860612012-09-28 07:36:21 -0700601 StopLinkMonitor();
Ben Chanb061f892013-02-27 17:46:55 -0800602 StopTrafficMonitor();
Paul Stewartc8860612012-09-28 07:36:21 -0700603 StopPortalDetection();
Paul Stewart03dba0b2011-08-22 16:32:45 -0700604 }
605 selected_service_ = service;
606}
607
608void Device::SetServiceState(Service::ConnectState state) {
609 if (selected_service_.get()) {
610 selected_service_->SetState(state);
611 }
612}
613
614void Device::SetServiceFailure(Service::ConnectFailure failure_state) {
615 if (selected_service_.get()) {
616 selected_service_->SetFailure(failure_state);
617 }
618}
619
Eric Shienbroodcc95c5d2012-03-30 15:25:49 -0400620void Device::SetServiceFailureSilent(Service::ConnectFailure failure_state) {
621 if (selected_service_.get()) {
622 selected_service_->SetFailureSilent(failure_state);
623 }
624}
625
Chris Masone34af2182011-08-22 11:59:36 -0700626string Device::SerializeIPConfigs(const string &suffix) {
627 return StringPrintf("%s:%s", suffix.c_str(), ipconfig_->type().c_str());
Chris Masone5dec5f42011-07-22 14:07:55 -0700628}
629
Paul Stewart2bf1d352011-12-06 15:02:55 -0800630bool Device::SetIPFlag(IPAddress::Family family, const string &flag,
631 const string &value) {
632 string ip_version;
633 if (family == IPAddress::kFamilyIPv4) {
634 ip_version = kIPFlagVersion4;
635 } else if (family == IPAddress::kFamilyIPv6) {
636 ip_version = kIPFlagVersion6;
637 } else {
638 NOTIMPLEMENTED();
639 }
640 FilePath flag_file(StringPrintf(kIPFlagTemplate, ip_version.c_str(),
641 link_name_.c_str(), flag.c_str()));
Ben Chanfad4a0b2012-04-18 15:49:59 -0700642 SLOG(Device, 2) << "Writing " << value << " to flag file "
643 << flag_file.value();
Paul Stewart2bf1d352011-12-06 15:02:55 -0800644 if (file_util::WriteFile(flag_file, value.c_str(), value.length()) != 1) {
645 LOG(ERROR) << StringPrintf("IP flag write failed: %s to %s",
646 value.c_str(), flag_file.value().c_str());
647 return false;
648 }
649 return true;
650}
651
Paul Stewart6ff27f52012-07-11 06:51:41 -0700652void Device::ResetByteCounters() {
653 manager_->device_info()->GetByteCounts(
654 interface_index_, &receive_byte_offset_, &transmit_byte_offset_);
655 manager_->UpdateDevice(this);
656}
657
Arman Ugurayf84a4242013-04-09 20:01:07 -0700658void Device::RequestConnectionHealthCheck() {
659 if (!health_checker_.get()) {
660 SLOG(Device, 2) << "No health checker exists, cannot request "
661 << "health check.";
662 return;
663 }
664 if (health_checker_->health_check_in_progress()) {
665 SLOG(Device, 2) << "Health check already in progress.";
666 return;
667 }
668 health_checker_->Start();
669}
670
671void Device::OnConnectionHealthCheckerResult(
672 ConnectionHealthChecker::Result result) {
Prathmesh Prabhu5489b7a2013-04-10 13:33:59 -0700673 SLOG(Device, 2)
674 << FriendlyName()
675 << ": ConnectionHealthChecker result: "
676 << ConnectionHealthChecker::ResultToString(result);
Arman Ugurayf84a4242013-04-09 20:01:07 -0700677}
678
Paul Stewartd215af62012-04-24 23:25:50 -0700679bool Device::RestartPortalDetection() {
680 StopPortalDetection();
681 return StartPortalDetection();
682}
683
Paul Stewartc681fa02012-03-02 19:40:04 -0800684bool Device::RequestPortalDetection() {
685 if (!selected_service_) {
Ben Chanfad4a0b2012-04-18 15:49:59 -0700686 SLOG(Device, 2) << FriendlyName()
Paul Stewartc681fa02012-03-02 19:40:04 -0800687 << ": No selected service, so no need for portal check.";
688 return false;
689 }
690
691 if (!connection_.get()) {
Ben Chanfad4a0b2012-04-18 15:49:59 -0700692 SLOG(Device, 2) << FriendlyName()
Paul Stewartc681fa02012-03-02 19:40:04 -0800693 << ": No connection, so no need for portal check.";
694 return false;
695 }
696
697 if (selected_service_->state() != Service::kStatePortal) {
Ben Chanfad4a0b2012-04-18 15:49:59 -0700698 SLOG(Device, 2) << FriendlyName()
Paul Stewartc681fa02012-03-02 19:40:04 -0800699 << ": Service is not in portal state. No need to start check.";
700 return false;
701 }
702
703 if (!connection_->is_default()) {
Ben Chanfad4a0b2012-04-18 15:49:59 -0700704 SLOG(Device, 2) << FriendlyName()
Paul Stewartc681fa02012-03-02 19:40:04 -0800705 << ": Service is not the default connection. Don't start check.";
706 return false;
707 }
708
709 if (portal_detector_.get() && portal_detector_->IsInProgress()) {
Ben Chanfad4a0b2012-04-18 15:49:59 -0700710 SLOG(Device, 2) << FriendlyName()
711 << ": Portal detection is already running.";
Paul Stewartc681fa02012-03-02 19:40:04 -0800712 return true;
713 }
714
715 return StartPortalDetection();
716}
717
Paul Stewart20088d82012-02-16 06:58:55 -0800718bool Device::StartPortalDetection() {
Darin Petkov457728b2013-01-09 09:49:08 +0100719 DCHECK(selected_service_);
Paul Stewartd215af62012-04-24 23:25:50 -0700720 if (selected_service_->IsPortalDetectionDisabled()) {
Darin Petkov457728b2013-01-09 09:49:08 +0100721 SLOG(Device, 2) << "Service " << selected_service_->unique_name()
Paul Stewartd215af62012-04-24 23:25:50 -0700722 << ": Portal detection is disabled; "
723 << "marking service online.";
724 SetServiceConnectedState(Service::kStateOnline);
725 return false;
726 }
727
728 if (selected_service_->IsPortalDetectionAuto() &&
729 !manager_->IsPortalDetectionEnabled(technology())) {
Paul Stewart20088d82012-02-16 06:58:55 -0800730 // If portal detection is disabled for this technology, immediately set
731 // the service state to "Online".
Ben Chanfad4a0b2012-04-18 15:49:59 -0700732 SLOG(Device, 2) << "Device " << FriendlyName()
733 << ": Portal detection is disabled; "
734 << "marking service online.";
Paul Stewart20088d82012-02-16 06:58:55 -0800735 SetServiceConnectedState(Service::kStateOnline);
736 return false;
737 }
738
Paul Stewart20088d82012-02-16 06:58:55 -0800739 if (selected_service_->HasProxyConfig()) {
740 // Services with HTTP proxy configurations should not be checked by the
741 // connection manager, since we don't have the ability to evaluate
742 // arbitrary proxy configs and their possible credentials.
Ben Chanfad4a0b2012-04-18 15:49:59 -0700743 SLOG(Device, 2) << "Device " << FriendlyName()
744 << ": Service has proxy config; marking it online.";
Paul Stewart20088d82012-02-16 06:58:55 -0800745 SetServiceConnectedState(Service::kStateOnline);
746 return false;
747 }
748
749 portal_detector_.reset(new PortalDetector(connection_,
750 dispatcher_,
Eric Shienbrood3e20a232012-02-16 11:35:56 -0500751 portal_detector_callback_));
Paul Stewart20088d82012-02-16 06:58:55 -0800752 if (!portal_detector_->Start(manager_->GetPortalCheckURL())) {
753 LOG(ERROR) << "Device " << FriendlyName()
754 << ": Portal detection failed to start: likely bad URL: "
755 << manager_->GetPortalCheckURL();
756 SetServiceConnectedState(Service::kStateOnline);
757 return false;
758 }
759
Ben Chanfad4a0b2012-04-18 15:49:59 -0700760 SLOG(Device, 2) << "Device " << FriendlyName()
761 << ": Portal detection has started.";
Paul Stewart20088d82012-02-16 06:58:55 -0800762 return true;
763}
764
765void Device::StopPortalDetection() {
Ben Chanfad4a0b2012-04-18 15:49:59 -0700766 SLOG(Device, 2) << "Device " << FriendlyName()
767 << ": Portal detection has stopped.";
Paul Stewart20088d82012-02-16 06:58:55 -0800768 portal_detector_.reset();
769}
770
Paul Stewart036dba02012-08-07 12:34:41 -0700771void Device::set_link_monitor(LinkMonitor *link_monitor) {
772 link_monitor_.reset(link_monitor);
773}
774
775bool Device::StartLinkMonitor() {
776 if (!manager_->IsTechnologyLinkMonitorEnabled(technology())) {
777 SLOG(Device, 2) << "Device " << FriendlyName()
778 << ": Link Monitoring is disabled.";
779 return false;
780 }
781
782 if (!link_monitor()) {
783 set_link_monitor(
784 new LinkMonitor(
785 connection_, dispatcher_, metrics(), manager_->device_info(),
786 Bind(&Device::OnLinkMonitorFailure, weak_ptr_factory_.GetWeakPtr())));
787 }
788
789 SLOG(Device, 2) << "Device " << FriendlyName()
790 << ": Link Monitor starting.";
791 return link_monitor_->Start();
792}
793
794void Device::StopLinkMonitor() {
795 SLOG(Device, 2) << "Device " << FriendlyName()
796 << ": Link Monitor stopping.";
797 link_monitor_.reset();
798}
799
800void Device::OnLinkMonitorFailure() {
801 LOG(ERROR) << "Device " << FriendlyName()
802 << ": Link Monitor indicates failure.";
803}
804
Ben Chanb061f892013-02-27 17:46:55 -0800805void Device::set_traffic_monitor(TrafficMonitor *traffic_monitor) {
806 traffic_monitor_.reset(traffic_monitor);
807}
808
Arman Ugurayf84a4242013-04-09 20:01:07 -0700809void Device::set_health_checker(ConnectionHealthChecker *health_checker) {
810 health_checker_.reset(health_checker);
811}
812
Ben Chanb061f892013-02-27 17:46:55 -0800813bool Device::StartTrafficMonitor() {
Thieu Le03026662013-04-04 10:45:11 -0700814 SLOG(Device, 2) << __func__;
Ben Chanb061f892013-02-27 17:46:55 -0800815 if (!traffic_monitor_enabled_) {
816 SLOG(Device, 2) << "Device " << FriendlyName()
817 << ": Traffic Monitoring is disabled.";
818 return false;
819 }
820
821 if (!traffic_monitor_.get()) {
822 traffic_monitor_.reset(new TrafficMonitor(this, dispatcher_));
Thieu Le03026662013-04-04 10:45:11 -0700823 traffic_monitor_->set_tcp_out_traffic_not_routed_callback(
824 Bind(&Device::OnNoNetworkRouting, weak_ptr_factory_.GetWeakPtr()));
Ben Chanb061f892013-02-27 17:46:55 -0800825 }
826
827 SLOG(Device, 2) << "Device " << FriendlyName()
828 << ": Traffic Monitor starting.";
829 traffic_monitor_->Start();
830 return true;
831}
832
833void Device::StopTrafficMonitor() {
Thieu Le03026662013-04-04 10:45:11 -0700834 SLOG(Device, 2) << __func__;
Ben Chanb061f892013-02-27 17:46:55 -0800835 SLOG(Device, 2) << "Device " << FriendlyName()
836 << ": Traffic Monitor stopping.";
837 traffic_monitor_.reset();
838}
839
Thieu Le03026662013-04-04 10:45:11 -0700840void Device::OnNoNetworkRouting() {
Ben Chanb061f892013-02-27 17:46:55 -0800841 SLOG(Device, 2) << "Device " << FriendlyName()
Arman Ugurayf84a4242013-04-09 20:01:07 -0700842 << ": Traffic Monitor detects network congestion.";
Ben Chanb061f892013-02-27 17:46:55 -0800843}
844
Paul Stewart20088d82012-02-16 06:58:55 -0800845void Device::SetServiceConnectedState(Service::ConnectState state) {
846 DCHECK(selected_service_.get());
847
848 if (!selected_service_.get()) {
849 LOG(ERROR) << FriendlyName() << ": "
850 << "Portal detection completed but no selected service exists!";
851 return;
852 }
853
854 if (!selected_service_->IsConnected()) {
855 LOG(ERROR) << FriendlyName() << ": "
856 << "Portal detection completed but selected service "
Darin Petkov457728b2013-01-09 09:49:08 +0100857 << selected_service_->unique_name()
Paul Stewart20088d82012-02-16 06:58:55 -0800858 << " is in non-connected state.";
859 return;
860 }
861
Paul Stewartc681fa02012-03-02 19:40:04 -0800862 if (state == Service::kStatePortal && connection_->is_default() &&
863 manager_->GetPortalCheckInterval() != 0) {
864 CHECK(portal_detector_.get());
865 if (!portal_detector_->StartAfterDelay(
866 manager_->GetPortalCheckURL(),
867 manager_->GetPortalCheckInterval())) {
868 LOG(ERROR) << "Device " << FriendlyName()
869 << ": Portal detection failed to restart: likely bad URL: "
870 << manager_->GetPortalCheckURL();
871 SetServiceState(Service::kStateOnline);
872 portal_detector_.reset();
873 return;
874 }
Ben Chanfad4a0b2012-04-18 15:49:59 -0700875 SLOG(Device, 2) << "Device " << FriendlyName()
876 << ": Portal detection retrying.";
Paul Stewartc681fa02012-03-02 19:40:04 -0800877 } else {
Ben Chanfad4a0b2012-04-18 15:49:59 -0700878 SLOG(Device, 2) << "Device " << FriendlyName()
879 << ": Portal will not retry.";
Paul Stewartc681fa02012-03-02 19:40:04 -0800880 portal_detector_.reset();
881 }
882
Paul Stewart20088d82012-02-16 06:58:55 -0800883 SetServiceState(state);
884}
885
886void Device::PortalDetectorCallback(const PortalDetector::Result &result) {
887 if (!result.final) {
Ben Chanfad4a0b2012-04-18 15:49:59 -0700888 SLOG(Device, 2) << "Device " << FriendlyName()
889 << ": Received non-final status: "
890 << PortalDetector::StatusToString(result.status);
Paul Stewart20088d82012-02-16 06:58:55 -0800891 return;
892 }
893
Ben Chanfad4a0b2012-04-18 15:49:59 -0700894 SLOG(Device, 2) << "Device " << FriendlyName()
895 << ": Received final status: "
896 << PortalDetector::StatusToString(result.status);
Paul Stewart20088d82012-02-16 06:58:55 -0800897
Thieu Le85e050b2012-03-13 15:04:38 -0700898 portal_attempts_to_online_ += result.num_attempts;
899
900 metrics()->SendEnumToUMA(
901 metrics()->GetFullMetricName(Metrics::kMetricPortalResult, technology()),
902 Metrics::PortalDetectionResultToEnum(result),
903 Metrics::kPortalResultMax);
904
Paul Stewart20088d82012-02-16 06:58:55 -0800905 if (result.status == PortalDetector::kStatusSuccess) {
906 SetServiceConnectedState(Service::kStateOnline);
Thieu Le85e050b2012-03-13 15:04:38 -0700907
908 metrics()->SendToUMA(
909 metrics()->GetFullMetricName(
910 Metrics::kMetricPortalAttemptsToOnline, technology()),
911 portal_attempts_to_online_,
912 Metrics::kMetricPortalAttemptsToOnlineMin,
913 Metrics::kMetricPortalAttemptsToOnlineMax,
914 Metrics::kMetricPortalAttemptsToOnlineNumBuckets);
Paul Stewart20088d82012-02-16 06:58:55 -0800915 } else {
916 SetServiceConnectedState(Service::kStatePortal);
Thieu Le85e050b2012-03-13 15:04:38 -0700917
918 metrics()->SendToUMA(
919 metrics()->GetFullMetricName(
920 Metrics::kMetricPortalAttempts, technology()),
921 result.num_attempts,
922 Metrics::kMetricPortalAttemptsMin,
923 Metrics::kMetricPortalAttemptsMax,
924 Metrics::kMetricPortalAttemptsNumBuckets);
Paul Stewart20088d82012-02-16 06:58:55 -0800925 }
926}
927
Gaurav Shah1b7a6162011-11-09 11:41:01 -0800928vector<string> Device::AvailableIPConfigs(Error */*error*/) {
Jason Glasgow08afdff2012-04-03 10:22:26 -0400929 if (ipconfig_.get()) {
930 string id = ipconfig_->GetRpcIdentifier();
931 return vector<string>(1, id);
932 }
933 return vector<string>();
Chris Masone4e851612011-07-01 10:46:53 -0700934}
935
936string Device::GetRpcConnectionIdentifier() {
937 return adaptor_->GetRpcConnectionIdentifier();
938}
939
Paul Stewart036dba02012-08-07 12:34:41 -0700940uint64 Device::GetLinkMonitorResponseTime(Error *error) {
941 if (!link_monitor_.get()) {
942 // It is not strictly an error that the link monitor does not
943 // exist, but returning an error here allows the GetProperties
944 // call in our Adaptor to omit this parameter.
945 error->Populate(Error::kNotFound, "Device is not running LinkMonitor");
946 return 0;
947 }
948 return link_monitor_->GetResponseTimeMilliseconds();
949}
950
Ben Chanb061f892013-02-27 17:46:55 -0800951uint64 Device::GetReceiveByteCount() {
Paul Stewart6ff27f52012-07-11 06:51:41 -0700952 uint64 rx_byte_count = 0, tx_byte_count = 0;
953 manager_->device_info()->GetByteCounts(
954 interface_index_, &rx_byte_count, &tx_byte_count);
955 return rx_byte_count - receive_byte_offset_;
956}
957
Ben Chanb061f892013-02-27 17:46:55 -0800958uint64 Device::GetTransmitByteCount() {
Paul Stewart6ff27f52012-07-11 06:51:41 -0700959 uint64 rx_byte_count = 0, tx_byte_count = 0;
960 manager_->device_info()->GetByteCounts(
961 interface_index_, &rx_byte_count, &tx_byte_count);
962 return tx_byte_count - transmit_byte_offset_;
963}
964
Ben Chanb061f892013-02-27 17:46:55 -0800965uint64 Device::GetReceiveByteCountProperty(Error */*error*/) {
966 return GetReceiveByteCount();
967}
968
969uint64 Device::GetTransmitByteCountProperty(Error */*error*/) {
970 return GetTransmitByteCount();
971}
972
Eric Shienbrood7fce52c2012-04-13 19:11:02 -0400973bool Device::IsUnderlyingDeviceEnabled() const {
974 return false;
975}
976
Eric Shienbrood9a245532012-03-07 14:20:39 -0500977// callback
978void Device::OnEnabledStateChanged(const ResultCallback &callback,
979 const Error &error) {
Ben Chanfad4a0b2012-04-18 15:49:59 -0700980 SLOG(Device, 2) << __func__ << "(" << enabled_pending_ << ")";
Eric Shienbrood9a245532012-03-07 14:20:39 -0500981 if (error.IsSuccess()) {
982 enabled_ = enabled_pending_;
983 manager_->UpdateEnabledTechnologies();
984 adaptor_->EmitBoolChanged(flimflam::kPoweredProperty, enabled_);
985 adaptor_->UpdateEnabled();
986 }
Gary Morainbaeefdf2012-04-30 14:53:35 -0700987 enabled_pending_ = enabled_;
Eric Shienbrood9a245532012-03-07 14:20:39 -0500988 if (!callback.is_null())
989 callback.Run(error);
990}
991
992void Device::SetEnabled(bool enable) {
Ben Chanfad4a0b2012-04-18 15:49:59 -0700993 SLOG(Device, 2) << __func__ << "(" << enable << ")";
Jason Glasgow4a490792012-04-10 15:02:05 -0400994 Error error;
995 SetEnabledInternal(enable, false, &error, ResultCallback());
Jason Glasgow7234ec32012-05-23 16:01:21 -0400996 LOG_IF(ERROR, error.IsFailure() && !error.IsOngoing())
Jason Glasgow4a490792012-04-10 15:02:05 -0400997 << "Enabled failed, but no way to report the failure.";
Eric Shienbrood9a245532012-03-07 14:20:39 -0500998}
999
1000void Device::SetEnabledPersistent(bool enable,
1001 Error *error,
1002 const ResultCallback &callback) {
1003 SetEnabledInternal(enable, true, error, callback);
1004}
1005
1006void Device::SetEnabledInternal(bool enable,
1007 bool persist,
1008 Error *error,
1009 const ResultCallback &callback) {
Jason Glasgow4a490792012-04-10 15:02:05 -04001010 DCHECK(error);
Ben Chanfad4a0b2012-04-18 15:49:59 -07001011 SLOG(Device, 2) << "Device " << link_name_ << " "
1012 << (enable ? "starting" : "stopping");
Eric Shienbrood9a245532012-03-07 14:20:39 -05001013 if (enable == enabled_) {
Jason Glasgow4a490792012-04-10 15:02:05 -04001014 error->Reset();
Eric Shienbrood9a245532012-03-07 14:20:39 -05001015 return;
1016 }
1017
1018 if (enabled_pending_ == enable) {
Jason Glasgow4a490792012-04-10 15:02:05 -04001019 Error::PopulateAndLog(error, Error::kInProgress,
1020 "Enable operation already in progress");
Eric Shienbrood9a245532012-03-07 14:20:39 -05001021 return;
1022 }
1023
1024 if (persist) {
1025 enabled_persistent_ = enable;
Darin Petkove7c6ad32012-06-29 10:22:09 +02001026 manager_->UpdateDevice(this);
Eric Shienbrood9a245532012-03-07 14:20:39 -05001027 }
1028
1029 enabled_pending_ = enable;
1030 EnabledStateChangedCallback enabled_callback =
1031 Bind(&Device::OnEnabledStateChanged,
1032 weak_ptr_factory_.GetWeakPtr(), callback);
1033 if (enable) {
1034 running_ = true;
Eric Shienbrood9a245532012-03-07 14:20:39 -05001035 Start(error, enabled_callback);
1036 } else {
1037 running_ = false;
1038 DestroyIPConfig(); // breaks a reference cycle
1039 SelectService(NULL); // breaks a reference cycle
1040 rtnl_handler_->SetInterfaceFlags(interface_index(), 0, IFF_UP);
Ben Chanfad4a0b2012-04-18 15:49:59 -07001041 SLOG(Device, 3) << "Device " << link_name_ << " ipconfig_ "
1042 << (ipconfig_ ? "is set." : "is not set.");
1043 SLOG(Device, 3) << "Device " << link_name_ << " connection_ "
1044 << (connection_ ? "is set." : "is not set.");
1045 SLOG(Device, 3) << "Device " << link_name_ << " selected_service_ "
1046 << (selected_service_ ? "is set." : "is not set.");
Eric Shienbrood9a245532012-03-07 14:20:39 -05001047 Stop(error, enabled_callback);
1048 }
1049}
1050
Paul Stewart75897df2011-04-27 09:05:53 -07001051} // namespace shill