blob: 6640c064566c9aaaa81c5956d30a997172f90ddf [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 Guthrie4823f4f2013-07-25 10:03:03 -0700184void Device::Scan(ScanType scan_type, Error *error, const string &reason) {
185 SLOG(Device, 2) << __func__ << " [Device] on " << link_name() << " from "
186 << reason;
Paul Stewartbe005172011-11-02 18:10:29 -0700187 Error::PopulateAndLog(error, Error::kNotSupported,
188 "Device doesn't support scan.");
Paul Stewartf1ce5d22011-05-19 13:10:20 -0700189}
190
Eric Shienbrood9a245532012-03-07 14:20:39 -0500191void Device::RegisterOnNetwork(const std::string &/*network_id*/, Error *error,
192 const ResultCallback &/*callback*/) {
193 Error::PopulateAndLog(error, Error::kNotSupported,
Paul Stewartbe005172011-11-02 18:10:29 -0700194 "Device doesn't support network registration.");
Darin Petkov9ae310f2011-08-30 15:41:13 -0700195}
196
Darin Petkovc64fe5e2012-01-11 12:46:13 +0100197void Device::RequirePIN(
Eric Shienbrood9a245532012-03-07 14:20:39 -0500198 const string &/*pin*/, bool /*require*/,
199 Error *error, const ResultCallback &/*callback*/) {
Ben Chanfad4a0b2012-04-18 15:49:59 -0700200 SLOG(Device, 2) << __func__;
Eric Shienbrood9a245532012-03-07 14:20:39 -0500201 Error::PopulateAndLog(error, Error::kNotSupported,
202 "Device doesn't support RequirePIN.");
Darin Petkove42e1012011-08-31 12:35:04 -0700203}
204
Eric Shienbrood9a245532012-03-07 14:20:39 -0500205void Device::EnterPIN(const string &/*pin*/,
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 EnterPIN.");
Darin Petkove42e1012011-08-31 12:35:04 -0700210}
211
mukesh agrawal1830fa12011-09-26 14:31:40 -0700212void Device::UnblockPIN(const string &/*unblock_code*/,
213 const string &/*pin*/,
Eric Shienbrood9a245532012-03-07 14:20:39 -0500214 Error *error, const ResultCallback &/*callback*/) {
Ben Chanfad4a0b2012-04-18 15:49:59 -0700215 SLOG(Device, 2) << __func__;
Eric Shienbrood9a245532012-03-07 14:20:39 -0500216 Error::PopulateAndLog(error, Error::kNotSupported,
217 "Device doesn't support UnblockPIN.");
Darin Petkove42e1012011-08-31 12:35:04 -0700218}
219
mukesh agrawal1830fa12011-09-26 14:31:40 -0700220void Device::ChangePIN(const string &/*old_pin*/,
221 const string &/*new_pin*/,
Eric Shienbrood9a245532012-03-07 14:20:39 -0500222 Error *error, const ResultCallback &/*callback*/) {
Ben Chanfad4a0b2012-04-18 15:49:59 -0700223 SLOG(Device, 2) << __func__;
Eric Shienbrood9a245532012-03-07 14:20:39 -0500224 Error::PopulateAndLog(error, Error::kNotSupported,
225 "Device doesn't support ChangePIN.");
Darin Petkove42e1012011-08-31 12:35:04 -0700226}
227
Ben Chanad663e12013-01-08 01:58:47 -0800228void Device::Reset(Error *error, const ResultCallback &/*callback*/) {
229 SLOG(Device, 2) << __func__;
230 Error::PopulateAndLog(error, Error::kNotSupported,
231 "Device doesn't support Reset.");
232}
233
Darin Petkovc37a9c42012-09-06 15:28:22 +0200234void Device::SetCarrier(const string &/*carrier*/,
235 Error *error, const ResultCallback &/*callback*/) {
236 SLOG(Device, 2) << __func__;
237 Error::PopulateAndLog(error, Error::kNotSupported,
238 "Device doesn't support SetCarrier.");
239}
240
Paul Stewart2bf1d352011-12-06 15:02:55 -0800241void Device::DisableIPv6() {
242 SetIPFlag(IPAddress::kFamilyIPv6, kIPFlagDisableIPv6, "1");
243}
244
245void Device::EnableIPv6() {
246 SetIPFlag(IPAddress::kFamilyIPv6, kIPFlagDisableIPv6, "0");
247}
248
249void Device::EnableIPv6Privacy() {
250 SetIPFlag(IPAddress::kFamilyIPv6, kIPFlagUseTempAddr,
251 kIPFlagUseTempAddrUsedAndDefault);
252}
253
Paul Stewartc8f4bef2011-12-13 09:45:51 -0800254void Device::DisableReversePathFilter() {
255 // TODO(pstew): Current kernel doesn't offer reverse-path filtering flag
Paul Stewartee6b3d72013-07-12 16:07:51 -0700256 // for IPv6. crbug.com/207193
Paul Stewartc8f4bef2011-12-13 09:45:51 -0800257 SetIPFlag(IPAddress::kFamilyIPv4, kIPFlagReversePathFilter,
258 kIPFlagReversePathFilterLooseMode);
259}
260
261void Device::EnableReversePathFilter() {
262 SetIPFlag(IPAddress::kFamilyIPv4, kIPFlagReversePathFilter,
263 kIPFlagReversePathFilterEnabled);
264}
265
Gaurav Shah435de2c2011-11-17 19:01:07 -0800266bool Device::IsConnected() const {
267 if (selected_service_)
268 return selected_service_->IsConnected();
269 return false;
270}
271
Paul Stewartd215af62012-04-24 23:25:50 -0700272bool Device::IsConnectedToService(const ServiceRefPtr &service) const {
273 return service == selected_service_ && IsConnected();
274}
275
mukesh agrawalf6b32092013-04-10 15:49:55 -0700276string Device::GetRpcIdentifier() const {
Chris Masone27c4aa52011-07-02 13:10:14 -0700277 return adaptor_->GetRpcIdentifier();
Chris Masone8fe2c7e2011-06-09 15:51:19 -0700278}
279
Chris Masone5dec5f42011-07-22 14:07:55 -0700280string Device::GetStorageIdentifier() {
281 string id = GetRpcIdentifier();
282 ControlInterface::RpcIdToStorageId(&id);
Chris Masone626719f2011-08-18 16:58:48 -0700283 size_t needle = id.find('_');
Chris Masone34af2182011-08-22 11:59:36 -0700284 DLOG_IF(ERROR, needle == string::npos) << "No _ in storage id?!?!";
Chris Masone626719f2011-08-18 16:58:48 -0700285 id.replace(id.begin() + needle + 1, id.end(), hardware_address_);
Chris Masone5dec5f42011-07-22 14:07:55 -0700286 return id;
287}
288
Gaurav Shah6d2c72d2012-10-16 16:30:44 -0700289vector<GeolocationInfo> Device::GetGeolocationObjects() const {
290 return vector<GeolocationInfo>();
291};
292
Jason Glasgowb5790052012-01-27 01:03:52 -0500293string Device::GetTechnologyString(Error */*error*/) {
294 return Technology::NameFromIdentifier(technology());
295}
296
Chris Masone19e30402011-07-19 15:48:47 -0700297const string& Device::FriendlyName() const {
Chris Masone7df0c672011-07-15 10:24:54 -0700298 return link_name_;
Darin Petkovafa6fc42011-06-21 16:21:08 -0700299}
300
Chris Masone19e30402011-07-19 15:48:47 -0700301const string& Device::UniqueName() const {
302 return unique_id_;
303}
304
Chris Masone5dec5f42011-07-22 14:07:55 -0700305bool Device::Load(StoreInterface *storage) {
306 const string id = GetStorageIdentifier();
307 if (!storage->ContainsGroup(id)) {
308 LOG(WARNING) << "Device is not available in the persistent store: " << id;
309 return false;
310 }
Eric Shienbrood9a245532012-03-07 14:20:39 -0500311 enabled_persistent_ = true;
312 storage->GetBool(id, kStoragePowered, &enabled_persistent_);
Paul Stewart6ff27f52012-07-11 06:51:41 -0700313 uint64 rx_byte_count = 0, tx_byte_count = 0;
314
315 manager_->device_info()->GetByteCounts(
316 interface_index_, &rx_byte_count, &tx_byte_count);
317 // If there is a byte-count present in the profile, the return value
318 // of Device::Get*ByteCount() should be the this stored value plus
319 // whatever additional bytes we receive since time-of-load. We
320 // accomplish this by the subtractions below, which can validly
321 // roll over "negative" in the subtractions below and in Get*ByteCount.
322 uint64 profile_byte_count;
323 if (storage->GetUint64(id, kStorageReceiveByteCount, &profile_byte_count)) {
324 receive_byte_offset_ = rx_byte_count - profile_byte_count;
325 }
326 if (storage->GetUint64(id, kStorageTransmitByteCount, &profile_byte_count)) {
327 transmit_byte_offset_ = tx_byte_count - profile_byte_count;
328 }
329
Chris Masone5dec5f42011-07-22 14:07:55 -0700330 return true;
331}
332
333bool Device::Save(StoreInterface *storage) {
334 const string id = GetStorageIdentifier();
Eric Shienbrood9a245532012-03-07 14:20:39 -0500335 storage->SetBool(id, kStoragePowered, enabled_persistent_);
Chris Masone34af2182011-08-22 11:59:36 -0700336 if (ipconfig_.get()) {
337 // The _0 is an index into the list of IPConfigs that this device might
338 // have. We only have one IPConfig right now, and I hope to never have
339 // to support more, as sleffler indicates that associating IPConfigs
340 // with devices is wrong and due to be changed in flimflam anyhow.
341 string suffix = hardware_address_ + "_0";
342 ipconfig_->Save(storage, suffix);
343 storage->SetString(id, kStorageIPConfigs, SerializeIPConfigs(suffix));
344 }
Ben Chanb061f892013-02-27 17:46:55 -0800345 storage->SetUint64(id, kStorageReceiveByteCount, GetReceiveByteCount());
346 storage->SetUint64(id, kStorageTransmitByteCount, GetTransmitByteCount());
Chris Masone5dec5f42011-07-22 14:07:55 -0700347 return true;
348}
349
mukesh agrawal784566d2012-08-08 18:32:58 -0700350void Device::OnBeforeSuspend() {
351 // Nothing to be done in the general case.
352}
353
354void Device::OnAfterResume() {
355 if (ipconfig_) {
356 SLOG(Device, 3) << "Renewing IP address on resume.";
357 ipconfig_->RenewIP();
358 }
mukesh agrawalbb2231c2013-07-17 16:32:24 -0700359 if (link_monitor_) {
360 SLOG(Device, 3) << "Informing Link Monitor of resume.";
361 link_monitor_->OnAfterResume();
362 }
mukesh agrawal784566d2012-08-08 18:32:58 -0700363}
364
Darin Petkov2b8e44e2012-06-25 15:13:26 +0200365void Device::DropConnection() {
366 SLOG(Device, 2) << __func__;
367 DestroyIPConfig();
368 SelectService(NULL);
369}
370
Darin Petkovafa6fc42011-06-21 16:21:08 -0700371void Device::DestroyIPConfig() {
Paul Stewart2bf1d352011-12-06 15:02:55 -0800372 DisableIPv6();
Darin Petkovafa6fc42011-06-21 16:21:08 -0700373 if (ipconfig_.get()) {
Paul Stewart217c61d2013-06-13 15:12:02 -0700374 ipconfig_->ReleaseIP(IPConfig::kReleaseReasonDisconnect);
Darin Petkovafa6fc42011-06-21 16:21:08 -0700375 ipconfig_ = NULL;
376 }
Paul Stewarte6132022011-08-16 09:11:02 -0700377 DestroyConnection();
Darin Petkovafa6fc42011-06-21 16:21:08 -0700378}
379
Arman Ugurayed8e6102012-11-29 14:47:20 -0800380bool Device::ShouldUseArpGateway() const {
381 return false;
382}
383
Paul Stewart2bf1d352011-12-06 15:02:55 -0800384bool Device::AcquireIPConfig() {
Paul Stewartd408fdf2012-05-07 17:15:57 -0700385 return AcquireIPConfigWithLeaseName(string());
386}
387
388bool Device::AcquireIPConfigWithLeaseName(const string &lease_name) {
Darin Petkovafa6fc42011-06-21 16:21:08 -0700389 DestroyIPConfig();
Paul Stewart2bf1d352011-12-06 15:02:55 -0800390 EnableIPv6();
Arman Ugurayed8e6102012-11-29 14:47:20 -0800391 bool arp_gateway = manager_->GetArpGateway() && ShouldUseArpGateway();
Paul Stewartd408fdf2012-05-07 17:15:57 -0700392 ipconfig_ = dhcp_provider_->CreateConfig(link_name_,
393 manager_->GetHostName(),
394 lease_name,
Arman Ugurayed8e6102012-11-29 14:47:20 -0800395 arp_gateway);
Eric Shienbrood9a245532012-03-07 14:20:39 -0500396 ipconfig_->RegisterUpdateCallback(Bind(&Device::OnIPConfigUpdated,
397 weak_ptr_factory_.GetWeakPtr()));
Paul Stewart1062d9d2012-04-27 10:42:27 -0700398 dispatcher_->PostTask(Bind(&Device::ConfigureStaticIPTask,
399 weak_ptr_factory_.GetWeakPtr()));
Darin Petkovafa6fc42011-06-21 16:21:08 -0700400 return ipconfig_->RequestIP();
401}
402
Albert Chaulk0e1cdea2013-02-27 15:32:55 -0800403void Device::DestroyIPConfigLease(const string &name) {
404 dhcp_provider_->DestroyLease(name);
405}
406
mukesh agrawalbebf1b82013-04-23 15:06:33 -0700407void Device::HelpRegisterConstDerivedString(
Jason Glasgowb5790052012-01-27 01:03:52 -0500408 const string &name,
mukesh agrawalbebf1b82013-04-23 15:06:33 -0700409 string(Device::*get)(Error *error)) {
Jason Glasgowb5790052012-01-27 01:03:52 -0500410 store_.RegisterDerivedString(
411 name,
mukesh agrawalbebf1b82013-04-23 15:06:33 -0700412 StringAccessor(new CustomAccessor<Device, string>(this, get, NULL)));
Chris Masone4e851612011-07-01 10:46:53 -0700413}
414
Jason Glasgow08afdff2012-04-03 10:22:26 -0400415void Device::HelpRegisterConstDerivedRpcIdentifiers(
416 const string &name,
417 RpcIdentifiers(Device::*get)(Error *)) {
418 store_.RegisterDerivedRpcIdentifiers(
419 name,
420 RpcIdentifiersAccessor(
421 new CustomAccessor<Device, RpcIdentifiers>(this, get, NULL)));
422}
423
Paul Stewart6ff27f52012-07-11 06:51:41 -0700424void Device::HelpRegisterConstDerivedUint64(
425 const string &name,
426 uint64(Device::*get)(Error *)) {
427 store_.RegisterDerivedUint64(
428 name,
429 Uint64Accessor(
430 new CustomAccessor<Device, uint64>(this, get, NULL)));
431}
432
Paul Stewart1062d9d2012-04-27 10:42:27 -0700433void Device::ConfigureStaticIPTask() {
434 SLOG(Device, 2) << __func__ << " selected_service " << selected_service_.get()
435 << " ipconfig " << ipconfig_.get();
436
437 if (!selected_service_ || !ipconfig_) {
438 return;
439 }
440
441 const StaticIPParameters &static_ip_parameters =
442 selected_service_->static_ip_parameters();
443 if (static_ip_parameters.ContainsAddress()) {
444 SLOG(Device, 2) << __func__ << " " << " configuring static IP parameters.";
445 // If the parameters contain an IP address, apply them now and bring
446 // the interface up. When DHCP information arrives, it will supplement
447 // the static information.
448 OnIPConfigUpdated(ipconfig_, true);
449 } else {
450 SLOG(Device, 2) << __func__ << " " << " no static IP address.";
451 }
452}
453
Darin Petkov79d74c92012-03-07 17:20:32 +0100454void Device::OnIPConfigUpdated(const IPConfigRefPtr &ipconfig, bool success) {
Ben Chanfad4a0b2012-04-18 15:49:59 -0700455 SLOG(Device, 2) << __func__ << " " << " success: " << success;
Paul Stewartc39f1132011-06-22 12:02:28 -0700456 if (success) {
Paul Stewarte6132022011-08-16 09:11:02 -0700457 CreateConnection();
Paul Stewart1062d9d2012-04-27 10:42:27 -0700458 if (selected_service_) {
459 ipconfig->ApplyStaticIPParameters(
Paul Stewartdef189e2012-08-02 20:12:09 -0700460 selected_service_->mutable_static_ip_parameters());
Paul Stewart217c61d2013-06-13 15:12:02 -0700461 if (selected_service_->static_ip_parameters().ContainsAddress()) {
462 // If we are using a statically configured IP address instead
463 // of a leased IP address, release any acquired lease so it may
464 // be used by others. This allows us to merge other non-leased
465 // parameters (like DNS) when they're available from a DHCP server
466 // and not overridden by static parameters, but at the same time
467 // we avoid taking up a dynamic IP address the DHCP server could
468 // assign to someone else who might actually use it.
469 ipconfig->ReleaseIP(IPConfig::kReleaseReasonStaticIP);
470 }
Paul Stewart1062d9d2012-04-27 10:42:27 -0700471 }
Paul Stewarte6132022011-08-16 09:11:02 -0700472 connection_->UpdateFromIPConfig(ipconfig);
Paul Stewartc1dec4d2011-12-08 15:25:28 -0800473 // SetConnection must occur after the UpdateFromIPConfig so the
474 // service can use the values derived from the connection.
Paul Stewart1062d9d2012-04-27 10:42:27 -0700475 if (selected_service_) {
Paul Stewartc1dec4d2011-12-08 15:25:28 -0800476 selected_service_->SetConnection(connection_);
Paul Stewartbe5f5b32011-12-07 17:11:11 -0800477 }
Paul Stewartc1dec4d2011-12-08 15:25:28 -0800478 // The service state change needs to happen last, so that at the
479 // time we report the state change to the manager, the service
480 // has its connection.
481 SetServiceState(Service::kStateConnected);
Christopher Wiley5519e9e2013-01-08 16:55:56 -0800482 OnConnected();
Thieu Le85e050b2012-03-13 15:04:38 -0700483 portal_attempts_to_online_ = 0;
Paul Stewart20088d82012-02-16 06:58:55 -0800484 // Subtle: Start portal detection after transitioning the service
485 // to the Connected state because this call may immediately transition
486 // to the Online state.
Thieu Led1760922012-09-11 14:15:35 -0700487 if (selected_service_) {
488 StartPortalDetection();
489 }
Paul Stewart036dba02012-08-07 12:34:41 -0700490 StartLinkMonitor();
Ben Chanb061f892013-02-27 17:46:55 -0800491 StartTrafficMonitor();
Prathmesh Prabhuba99b592013-04-17 15:13:14 -0700492 SetupConnectionHealthChecker();
Paul Stewarte6132022011-08-16 09:11:02 -0700493 } else {
mukesh agrawalcc0fded2012-05-09 13:40:58 -0700494 // TODO(pstew): This logic gets yet more complex when multiple
495 // IPConfig types are run in parallel (e.g. DHCP and DHCP6)
496 if (selected_service_ &&
497 selected_service_->static_ip_parameters().ContainsAddress()) {
498 // Consider three cases:
499 //
500 // 1. We're here because DHCP failed while starting up. There
501 // are two subcases:
502 // a. DHCP has failed, and Static IP config has _not yet_
503 // completed. It's fine to do nothing, because we'll
504 // apply the static config shortly.
505 // b. DHCP has failed, and Static IP config has _already_
506 // completed. It's fine to do nothing, because we can
507 // continue to use the static config that's already
508 // been applied.
509 //
510 // 2. We're here because a previously valid DHCP configuration
511 // is no longer valid. There's still a static IP config,
512 // because the condition in the if clause evaluated to true.
513 // Furthermore, the static config includes an IP address for
514 // us to use.
515 //
516 // The current configuration may include some DHCP
517 // parameters, overriden by any static parameters
518 // provided. We continue to use this configuration, because
519 // the only configuration element that is leased to us (IP
520 // address) will be overriden by a static parameter.
521 return;
522 }
523
Paul Stewartf6f96482013-07-12 12:49:15 -0700524 OnIPConfigFailure();
Paul Stewarte6132022011-08-16 09:11:02 -0700525 DestroyConnection();
Paul Stewartc39f1132011-06-22 12:02:28 -0700526 }
Chris Masone8fe2c7e2011-06-09 15:51:19 -0700527}
528
Paul Stewartf6f96482013-07-12 12:49:15 -0700529void Device::OnIPConfigFailure() {
530 if (selected_service_) {
531 Error error;
532 selected_service_->DisconnectWithFailure(Service::kFailureDHCP, &error);
533 }
534}
535
Christopher Wiley5519e9e2013-01-08 16:55:56 -0800536void Device::OnConnected() {}
537
Paul Stewart8596f9f2013-03-14 07:58:26 -0700538void Device::OnConnectionUpdated() {
539 if (selected_service_) {
540 manager_->UpdateService(selected_service_);
541 }
542}
543
Paul Stewarte6132022011-08-16 09:11:02 -0700544void Device::CreateConnection() {
Ben Chanfad4a0b2012-04-18 15:49:59 -0700545 SLOG(Device, 2) << __func__;
Paul Stewarte6132022011-08-16 09:11:02 -0700546 if (!connection_.get()) {
mukesh agrawal23ac6b72013-01-31 18:52:37 -0800547 connection_ = new Connection(interface_index_,
548 link_name_,
549 technology_,
550 manager_->device_info());
Paul Stewarte6132022011-08-16 09:11:02 -0700551 }
552}
553
554void Device::DestroyConnection() {
mukesh agrawal6813e762013-07-10 19:05:08 -0700555 SLOG(Device, 2) << __func__ << " on " << link_name_;
Paul Stewart20088d82012-02-16 06:58:55 -0800556 StopPortalDetection();
Paul Stewart036dba02012-08-07 12:34:41 -0700557 StopLinkMonitor();
Ben Chanb061f892013-02-27 17:46:55 -0800558 StopTrafficMonitor();
Paul Stewartbe5f5b32011-12-07 17:11:11 -0800559 if (selected_service_.get()) {
mukesh agrawal6813e762013-07-10 19:05:08 -0700560 SLOG(Device, 3) << "Clearing connection of service "
561 << selected_service_->unique_name();
Paul Stewartc1dec4d2011-12-08 15:25:28 -0800562 selected_service_->SetConnection(NULL);
Paul Stewartbe5f5b32011-12-07 17:11:11 -0800563 }
Paul Stewartc8f4bef2011-12-13 09:45:51 -0800564 connection_ = NULL;
Arman Ugurayf84a4242013-04-09 20:01:07 -0700565 health_checker_.reset();
Paul Stewarte6132022011-08-16 09:11:02 -0700566}
567
Paul Stewart03dba0b2011-08-22 16:32:45 -0700568void Device::SelectService(const ServiceRefPtr &service) {
Darin Petkov457728b2013-01-09 09:49:08 +0100569 SLOG(Device, 2) << __func__ << ": service "
mukesh agrawal6813e762013-07-10 19:05:08 -0700570 << (service ? service->unique_name() : "*reset*")
571 << " on " << link_name_;
mukesh agrawal8a3188d2011-12-01 20:56:44 +0000572
573 if (selected_service_.get() == service.get()) {
574 // No change to |selected_service_|. Return early to avoid
575 // changing its state.
576 return;
577 }
578
Paul Stewartbe5f5b32011-12-07 17:11:11 -0800579 if (selected_service_.get()) {
580 if (selected_service_->state() != Service::kStateFailure) {
581 selected_service_->SetState(Service::kStateIdle);
582 }
Paul Stewart20b0a092012-05-22 20:39:57 -0700583 // Just in case the Device subclass has not already done so, make
584 // sure the previously selected service has its connection removed.
Paul Stewartc1dec4d2011-12-08 15:25:28 -0800585 selected_service_->SetConnection(NULL);
Paul Stewartc8860612012-09-28 07:36:21 -0700586 StopLinkMonitor();
Ben Chanb061f892013-02-27 17:46:55 -0800587 StopTrafficMonitor();
Paul Stewartc8860612012-09-28 07:36:21 -0700588 StopPortalDetection();
Paul Stewart03dba0b2011-08-22 16:32:45 -0700589 }
590 selected_service_ = service;
591}
592
593void Device::SetServiceState(Service::ConnectState state) {
594 if (selected_service_.get()) {
595 selected_service_->SetState(state);
596 }
597}
598
599void Device::SetServiceFailure(Service::ConnectFailure failure_state) {
600 if (selected_service_.get()) {
601 selected_service_->SetFailure(failure_state);
602 }
603}
604
Eric Shienbroodcc95c5d2012-03-30 15:25:49 -0400605void Device::SetServiceFailureSilent(Service::ConnectFailure failure_state) {
606 if (selected_service_.get()) {
607 selected_service_->SetFailureSilent(failure_state);
608 }
609}
610
Chris Masone34af2182011-08-22 11:59:36 -0700611string Device::SerializeIPConfigs(const string &suffix) {
612 return StringPrintf("%s:%s", suffix.c_str(), ipconfig_->type().c_str());
Chris Masone5dec5f42011-07-22 14:07:55 -0700613}
614
Paul Stewart2bf1d352011-12-06 15:02:55 -0800615bool Device::SetIPFlag(IPAddress::Family family, const string &flag,
616 const string &value) {
617 string ip_version;
618 if (family == IPAddress::kFamilyIPv4) {
619 ip_version = kIPFlagVersion4;
620 } else if (family == IPAddress::kFamilyIPv6) {
621 ip_version = kIPFlagVersion6;
622 } else {
623 NOTIMPLEMENTED();
624 }
625 FilePath flag_file(StringPrintf(kIPFlagTemplate, ip_version.c_str(),
626 link_name_.c_str(), flag.c_str()));
Ben Chanfad4a0b2012-04-18 15:49:59 -0700627 SLOG(Device, 2) << "Writing " << value << " to flag file "
628 << flag_file.value();
Paul Stewart2bf1d352011-12-06 15:02:55 -0800629 if (file_util::WriteFile(flag_file, value.c_str(), value.length()) != 1) {
630 LOG(ERROR) << StringPrintf("IP flag write failed: %s to %s",
631 value.c_str(), flag_file.value().c_str());
632 return false;
633 }
634 return true;
635}
636
Paul Stewart6ff27f52012-07-11 06:51:41 -0700637void Device::ResetByteCounters() {
638 manager_->device_info()->GetByteCounts(
639 interface_index_, &receive_byte_offset_, &transmit_byte_offset_);
640 manager_->UpdateDevice(this);
641}
642
Prathmesh Prabhuba99b592013-04-17 15:13:14 -0700643void Device::SetupConnectionHealthChecker() {
644 DCHECK(connection_);
645 if (!health_checker_.get()) {
646 health_checker_.reset(new ConnectionHealthChecker(
647 connection_,
648 dispatcher_,
649 manager_->health_checker_remote_ips(),
650 Bind(&Device::OnConnectionHealthCheckerResult,
651 weak_ptr_factory_.GetWeakPtr())));
652 } else {
653 health_checker_->SetConnection(connection_);
654 }
655 // Add URL in either case because a connection reset could have dropped past
656 // DNS queries.
657 health_checker_->AddRemoteURL(manager_->GetPortalCheckURL());
658}
659
Arman Ugurayf84a4242013-04-09 20:01:07 -0700660void Device::RequestConnectionHealthCheck() {
661 if (!health_checker_.get()) {
662 SLOG(Device, 2) << "No health checker exists, cannot request "
663 << "health check.";
664 return;
665 }
666 if (health_checker_->health_check_in_progress()) {
667 SLOG(Device, 2) << "Health check already in progress.";
668 return;
669 }
670 health_checker_->Start();
671}
672
673void Device::OnConnectionHealthCheckerResult(
674 ConnectionHealthChecker::Result result) {
Prathmesh Prabhu5489b7a2013-04-10 13:33:59 -0700675 SLOG(Device, 2)
676 << FriendlyName()
677 << ": ConnectionHealthChecker result: "
678 << ConnectionHealthChecker::ResultToString(result);
Arman Ugurayf84a4242013-04-09 20:01:07 -0700679}
680
Paul Stewartd215af62012-04-24 23:25:50 -0700681bool Device::RestartPortalDetection() {
682 StopPortalDetection();
683 return StartPortalDetection();
684}
685
Paul Stewartc681fa02012-03-02 19:40:04 -0800686bool Device::RequestPortalDetection() {
687 if (!selected_service_) {
Ben Chanfad4a0b2012-04-18 15:49:59 -0700688 SLOG(Device, 2) << FriendlyName()
Paul Stewartc681fa02012-03-02 19:40:04 -0800689 << ": No selected service, so no need for portal check.";
690 return false;
691 }
692
693 if (!connection_.get()) {
Ben Chanfad4a0b2012-04-18 15:49:59 -0700694 SLOG(Device, 2) << FriendlyName()
Paul Stewartc681fa02012-03-02 19:40:04 -0800695 << ": No connection, so no need for portal check.";
696 return false;
697 }
698
699 if (selected_service_->state() != Service::kStatePortal) {
Ben Chanfad4a0b2012-04-18 15:49:59 -0700700 SLOG(Device, 2) << FriendlyName()
Paul Stewartc681fa02012-03-02 19:40:04 -0800701 << ": Service is not in portal state. No need to start check.";
702 return false;
703 }
704
705 if (!connection_->is_default()) {
Ben Chanfad4a0b2012-04-18 15:49:59 -0700706 SLOG(Device, 2) << FriendlyName()
Paul Stewartc681fa02012-03-02 19:40:04 -0800707 << ": Service is not the default connection. Don't start check.";
708 return false;
709 }
710
711 if (portal_detector_.get() && portal_detector_->IsInProgress()) {
Ben Chanfad4a0b2012-04-18 15:49:59 -0700712 SLOG(Device, 2) << FriendlyName()
713 << ": Portal detection is already running.";
Paul Stewartc681fa02012-03-02 19:40:04 -0800714 return true;
715 }
716
717 return StartPortalDetection();
718}
719
Paul Stewart20088d82012-02-16 06:58:55 -0800720bool Device::StartPortalDetection() {
Darin Petkov457728b2013-01-09 09:49:08 +0100721 DCHECK(selected_service_);
Paul Stewartd215af62012-04-24 23:25:50 -0700722 if (selected_service_->IsPortalDetectionDisabled()) {
Darin Petkov457728b2013-01-09 09:49:08 +0100723 SLOG(Device, 2) << "Service " << selected_service_->unique_name()
Paul Stewartd215af62012-04-24 23:25:50 -0700724 << ": Portal detection is disabled; "
725 << "marking service online.";
726 SetServiceConnectedState(Service::kStateOnline);
727 return false;
728 }
729
730 if (selected_service_->IsPortalDetectionAuto() &&
731 !manager_->IsPortalDetectionEnabled(technology())) {
Paul Stewart20088d82012-02-16 06:58:55 -0800732 // If portal detection is disabled for this technology, immediately set
733 // the service state to "Online".
Ben Chanfad4a0b2012-04-18 15:49:59 -0700734 SLOG(Device, 2) << "Device " << FriendlyName()
735 << ": Portal detection is disabled; "
736 << "marking service online.";
Paul Stewart20088d82012-02-16 06:58:55 -0800737 SetServiceConnectedState(Service::kStateOnline);
738 return false;
739 }
740
Paul Stewart20088d82012-02-16 06:58:55 -0800741 if (selected_service_->HasProxyConfig()) {
742 // Services with HTTP proxy configurations should not be checked by the
743 // connection manager, since we don't have the ability to evaluate
744 // arbitrary proxy configs and their possible credentials.
Ben Chanfad4a0b2012-04-18 15:49:59 -0700745 SLOG(Device, 2) << "Device " << FriendlyName()
746 << ": Service has proxy config; marking it online.";
Paul Stewart20088d82012-02-16 06:58:55 -0800747 SetServiceConnectedState(Service::kStateOnline);
748 return false;
749 }
750
751 portal_detector_.reset(new PortalDetector(connection_,
752 dispatcher_,
Eric Shienbrood3e20a232012-02-16 11:35:56 -0500753 portal_detector_callback_));
Paul Stewart20088d82012-02-16 06:58:55 -0800754 if (!portal_detector_->Start(manager_->GetPortalCheckURL())) {
755 LOG(ERROR) << "Device " << FriendlyName()
756 << ": Portal detection failed to start: likely bad URL: "
757 << manager_->GetPortalCheckURL();
758 SetServiceConnectedState(Service::kStateOnline);
759 return false;
760 }
761
Ben Chanfad4a0b2012-04-18 15:49:59 -0700762 SLOG(Device, 2) << "Device " << FriendlyName()
763 << ": Portal detection has started.";
Paul Stewart20088d82012-02-16 06:58:55 -0800764 return true;
765}
766
767void Device::StopPortalDetection() {
Ben Chanfad4a0b2012-04-18 15:49:59 -0700768 SLOG(Device, 2) << "Device " << FriendlyName()
mukesh agrawalbb2231c2013-07-17 16:32:24 -0700769 << ": Portal detection stopping.";
Paul Stewart20088d82012-02-16 06:58:55 -0800770 portal_detector_.reset();
771}
772
Paul Stewart036dba02012-08-07 12:34:41 -0700773void Device::set_link_monitor(LinkMonitor *link_monitor) {
774 link_monitor_.reset(link_monitor);
775}
776
777bool Device::StartLinkMonitor() {
778 if (!manager_->IsTechnologyLinkMonitorEnabled(technology())) {
779 SLOG(Device, 2) << "Device " << FriendlyName()
780 << ": Link Monitoring is disabled.";
781 return false;
782 }
783
784 if (!link_monitor()) {
785 set_link_monitor(
786 new LinkMonitor(
787 connection_, dispatcher_, metrics(), manager_->device_info(),
788 Bind(&Device::OnLinkMonitorFailure, weak_ptr_factory_.GetWeakPtr())));
789 }
790
791 SLOG(Device, 2) << "Device " << FriendlyName()
792 << ": Link Monitor starting.";
793 return link_monitor_->Start();
794}
795
796void Device::StopLinkMonitor() {
797 SLOG(Device, 2) << "Device " << FriendlyName()
798 << ": Link Monitor stopping.";
799 link_monitor_.reset();
800}
801
802void Device::OnLinkMonitorFailure() {
803 LOG(ERROR) << "Device " << FriendlyName()
804 << ": Link Monitor indicates failure.";
805}
806
Ben Chanb061f892013-02-27 17:46:55 -0800807void Device::set_traffic_monitor(TrafficMonitor *traffic_monitor) {
808 traffic_monitor_.reset(traffic_monitor);
809}
810
811bool Device::StartTrafficMonitor() {
Thieu Le03026662013-04-04 10:45:11 -0700812 SLOG(Device, 2) << __func__;
Ben Chanb061f892013-02-27 17:46:55 -0800813 if (!traffic_monitor_enabled_) {
814 SLOG(Device, 2) << "Device " << FriendlyName()
815 << ": Traffic Monitoring is disabled.";
816 return false;
817 }
818
819 if (!traffic_monitor_.get()) {
820 traffic_monitor_.reset(new TrafficMonitor(this, dispatcher_));
Thieu Le03026662013-04-04 10:45:11 -0700821 traffic_monitor_->set_tcp_out_traffic_not_routed_callback(
822 Bind(&Device::OnNoNetworkRouting, weak_ptr_factory_.GetWeakPtr()));
Ben Chanb061f892013-02-27 17:46:55 -0800823 }
824
825 SLOG(Device, 2) << "Device " << FriendlyName()
826 << ": Traffic Monitor starting.";
827 traffic_monitor_->Start();
828 return true;
829}
830
831void Device::StopTrafficMonitor() {
Thieu Le03026662013-04-04 10:45:11 -0700832 SLOG(Device, 2) << __func__;
Ben Chanb061f892013-02-27 17:46:55 -0800833 SLOG(Device, 2) << "Device " << FriendlyName()
834 << ": Traffic Monitor stopping.";
835 traffic_monitor_.reset();
836}
837
Thieu Le03026662013-04-04 10:45:11 -0700838void Device::OnNoNetworkRouting() {
Ben Chanb061f892013-02-27 17:46:55 -0800839 SLOG(Device, 2) << "Device " << FriendlyName()
Arman Ugurayf84a4242013-04-09 20:01:07 -0700840 << ": Traffic Monitor detects network congestion.";
Ben Chanb061f892013-02-27 17:46:55 -0800841}
842
Paul Stewart20088d82012-02-16 06:58:55 -0800843void Device::SetServiceConnectedState(Service::ConnectState state) {
844 DCHECK(selected_service_.get());
845
846 if (!selected_service_.get()) {
847 LOG(ERROR) << FriendlyName() << ": "
848 << "Portal detection completed but no selected service exists!";
849 return;
850 }
851
852 if (!selected_service_->IsConnected()) {
853 LOG(ERROR) << FriendlyName() << ": "
854 << "Portal detection completed but selected service "
Darin Petkov457728b2013-01-09 09:49:08 +0100855 << selected_service_->unique_name()
Paul Stewart20088d82012-02-16 06:58:55 -0800856 << " is in non-connected state.";
857 return;
858 }
859
Paul Stewartc681fa02012-03-02 19:40:04 -0800860 if (state == Service::kStatePortal && connection_->is_default() &&
861 manager_->GetPortalCheckInterval() != 0) {
862 CHECK(portal_detector_.get());
863 if (!portal_detector_->StartAfterDelay(
864 manager_->GetPortalCheckURL(),
865 manager_->GetPortalCheckInterval())) {
866 LOG(ERROR) << "Device " << FriendlyName()
867 << ": Portal detection failed to restart: likely bad URL: "
868 << manager_->GetPortalCheckURL();
869 SetServiceState(Service::kStateOnline);
870 portal_detector_.reset();
871 return;
872 }
Ben Chanfad4a0b2012-04-18 15:49:59 -0700873 SLOG(Device, 2) << "Device " << FriendlyName()
874 << ": Portal detection retrying.";
Paul Stewartc681fa02012-03-02 19:40:04 -0800875 } else {
Ben Chanfad4a0b2012-04-18 15:49:59 -0700876 SLOG(Device, 2) << "Device " << FriendlyName()
877 << ": Portal will not retry.";
Paul Stewartc681fa02012-03-02 19:40:04 -0800878 portal_detector_.reset();
879 }
880
Paul Stewart20088d82012-02-16 06:58:55 -0800881 SetServiceState(state);
882}
883
884void Device::PortalDetectorCallback(const PortalDetector::Result &result) {
885 if (!result.final) {
Ben Chanfad4a0b2012-04-18 15:49:59 -0700886 SLOG(Device, 2) << "Device " << FriendlyName()
887 << ": Received non-final status: "
888 << PortalDetector::StatusToString(result.status);
Paul Stewart20088d82012-02-16 06:58:55 -0800889 return;
890 }
891
Ben Chanfad4a0b2012-04-18 15:49:59 -0700892 SLOG(Device, 2) << "Device " << FriendlyName()
893 << ": Received final status: "
894 << PortalDetector::StatusToString(result.status);
Paul Stewart20088d82012-02-16 06:58:55 -0800895
Thieu Le85e050b2012-03-13 15:04:38 -0700896 portal_attempts_to_online_ += result.num_attempts;
897
898 metrics()->SendEnumToUMA(
899 metrics()->GetFullMetricName(Metrics::kMetricPortalResult, technology()),
900 Metrics::PortalDetectionResultToEnum(result),
901 Metrics::kPortalResultMax);
902
Paul Stewart20088d82012-02-16 06:58:55 -0800903 if (result.status == PortalDetector::kStatusSuccess) {
904 SetServiceConnectedState(Service::kStateOnline);
Thieu Le85e050b2012-03-13 15:04:38 -0700905
906 metrics()->SendToUMA(
907 metrics()->GetFullMetricName(
908 Metrics::kMetricPortalAttemptsToOnline, technology()),
909 portal_attempts_to_online_,
910 Metrics::kMetricPortalAttemptsToOnlineMin,
911 Metrics::kMetricPortalAttemptsToOnlineMax,
912 Metrics::kMetricPortalAttemptsToOnlineNumBuckets);
Paul Stewart20088d82012-02-16 06:58:55 -0800913 } else {
914 SetServiceConnectedState(Service::kStatePortal);
Thieu Le85e050b2012-03-13 15:04:38 -0700915
916 metrics()->SendToUMA(
917 metrics()->GetFullMetricName(
918 Metrics::kMetricPortalAttempts, technology()),
919 result.num_attempts,
920 Metrics::kMetricPortalAttemptsMin,
921 Metrics::kMetricPortalAttemptsMax,
922 Metrics::kMetricPortalAttemptsNumBuckets);
Paul Stewart20088d82012-02-16 06:58:55 -0800923 }
924}
925
Gaurav Shah1b7a6162011-11-09 11:41:01 -0800926vector<string> Device::AvailableIPConfigs(Error */*error*/) {
Jason Glasgow08afdff2012-04-03 10:22:26 -0400927 if (ipconfig_.get()) {
928 string id = ipconfig_->GetRpcIdentifier();
929 return vector<string>(1, id);
930 }
931 return vector<string>();
Chris Masone4e851612011-07-01 10:46:53 -0700932}
933
934string Device::GetRpcConnectionIdentifier() {
935 return adaptor_->GetRpcConnectionIdentifier();
936}
937
Paul Stewart036dba02012-08-07 12:34:41 -0700938uint64 Device::GetLinkMonitorResponseTime(Error *error) {
939 if (!link_monitor_.get()) {
940 // It is not strictly an error that the link monitor does not
941 // exist, but returning an error here allows the GetProperties
942 // call in our Adaptor to omit this parameter.
943 error->Populate(Error::kNotFound, "Device is not running LinkMonitor");
944 return 0;
945 }
946 return link_monitor_->GetResponseTimeMilliseconds();
947}
948
Ben Chanb061f892013-02-27 17:46:55 -0800949uint64 Device::GetReceiveByteCount() {
Paul Stewart6ff27f52012-07-11 06:51:41 -0700950 uint64 rx_byte_count = 0, tx_byte_count = 0;
951 manager_->device_info()->GetByteCounts(
952 interface_index_, &rx_byte_count, &tx_byte_count);
953 return rx_byte_count - receive_byte_offset_;
954}
955
Ben Chanb061f892013-02-27 17:46:55 -0800956uint64 Device::GetTransmitByteCount() {
Paul Stewart6ff27f52012-07-11 06:51:41 -0700957 uint64 rx_byte_count = 0, tx_byte_count = 0;
958 manager_->device_info()->GetByteCounts(
959 interface_index_, &rx_byte_count, &tx_byte_count);
960 return tx_byte_count - transmit_byte_offset_;
961}
962
Ben Chanb061f892013-02-27 17:46:55 -0800963uint64 Device::GetReceiveByteCountProperty(Error */*error*/) {
964 return GetReceiveByteCount();
965}
966
967uint64 Device::GetTransmitByteCountProperty(Error */*error*/) {
968 return GetTransmitByteCount();
969}
970
Eric Shienbrood7fce52c2012-04-13 19:11:02 -0400971bool Device::IsUnderlyingDeviceEnabled() const {
972 return false;
973}
974
Eric Shienbrood9a245532012-03-07 14:20:39 -0500975// callback
976void Device::OnEnabledStateChanged(const ResultCallback &callback,
977 const Error &error) {
mukesh agrawal46c27cc2013-07-10 16:39:10 -0700978 SLOG(Device, 2) << __func__
979 << " (target: " << enabled_pending_ << ","
980 << " success: " << error.IsSuccess() << ")"
981 << " on " << link_name_;
Eric Shienbrood9a245532012-03-07 14:20:39 -0500982 if (error.IsSuccess()) {
983 enabled_ = enabled_pending_;
984 manager_->UpdateEnabledTechnologies();
985 adaptor_->EmitBoolChanged(flimflam::kPoweredProperty, enabled_);
986 adaptor_->UpdateEnabled();
987 }
Gary Morainbaeefdf2012-04-30 14:53:35 -0700988 enabled_pending_ = enabled_;
Eric Shienbrood9a245532012-03-07 14:20:39 -0500989 if (!callback.is_null())
990 callback.Run(error);
991}
992
993void Device::SetEnabled(bool enable) {
Ben Chanfad4a0b2012-04-18 15:49:59 -0700994 SLOG(Device, 2) << __func__ << "(" << enable << ")";
Jason Glasgow4a490792012-04-10 15:02:05 -0400995 Error error;
996 SetEnabledInternal(enable, false, &error, ResultCallback());
Jason Glasgow7234ec32012-05-23 16:01:21 -0400997 LOG_IF(ERROR, error.IsFailure() && !error.IsOngoing())
Jason Glasgow4a490792012-04-10 15:02:05 -0400998 << "Enabled failed, but no way to report the failure.";
Eric Shienbrood9a245532012-03-07 14:20:39 -0500999}
1000
1001void Device::SetEnabledPersistent(bool enable,
1002 Error *error,
1003 const ResultCallback &callback) {
1004 SetEnabledInternal(enable, true, error, callback);
1005}
1006
1007void Device::SetEnabledInternal(bool enable,
1008 bool persist,
1009 Error *error,
1010 const ResultCallback &callback) {
Jason Glasgow4a490792012-04-10 15:02:05 -04001011 DCHECK(error);
Ben Chanfad4a0b2012-04-18 15:49:59 -07001012 SLOG(Device, 2) << "Device " << link_name_ << " "
1013 << (enable ? "starting" : "stopping");
Eric Shienbrood9a245532012-03-07 14:20:39 -05001014 if (enable == enabled_) {
Jason Glasgow4a490792012-04-10 15:02:05 -04001015 error->Reset();
Eric Shienbrood9a245532012-03-07 14:20:39 -05001016 return;
1017 }
1018
1019 if (enabled_pending_ == enable) {
Jason Glasgow4a490792012-04-10 15:02:05 -04001020 Error::PopulateAndLog(error, Error::kInProgress,
1021 "Enable operation already in progress");
Eric Shienbrood9a245532012-03-07 14:20:39 -05001022 return;
1023 }
1024
1025 if (persist) {
1026 enabled_persistent_ = enable;
Darin Petkove7c6ad32012-06-29 10:22:09 +02001027 manager_->UpdateDevice(this);
Eric Shienbrood9a245532012-03-07 14:20:39 -05001028 }
1029
1030 enabled_pending_ = enable;
1031 EnabledStateChangedCallback enabled_callback =
1032 Bind(&Device::OnEnabledStateChanged,
1033 weak_ptr_factory_.GetWeakPtr(), callback);
1034 if (enable) {
1035 running_ = true;
Eric Shienbrood9a245532012-03-07 14:20:39 -05001036 Start(error, enabled_callback);
1037 } else {
1038 running_ = false;
1039 DestroyIPConfig(); // breaks a reference cycle
1040 SelectService(NULL); // breaks a reference cycle
1041 rtnl_handler_->SetInterfaceFlags(interface_index(), 0, IFF_UP);
Ben Chanfad4a0b2012-04-18 15:49:59 -07001042 SLOG(Device, 3) << "Device " << link_name_ << " ipconfig_ "
1043 << (ipconfig_ ? "is set." : "is not set.");
1044 SLOG(Device, 3) << "Device " << link_name_ << " connection_ "
1045 << (connection_ ? "is set." : "is not set.");
1046 SLOG(Device, 3) << "Device " << link_name_ << " selected_service_ "
1047 << (selected_service_ ? "is set." : "is not set.");
Eric Shienbrood9a245532012-03-07 14:20:39 -05001048 Stop(error, enabled_callback);
1049 }
1050}
1051
Paul Stewart75897df2011-04-27 09:05:53 -07001052} // namespace shill