blob: 2684f39848dd61597852ffea25df069e2830bb19 [file] [log] [blame]
mukesh agrawal8a3188d2011-12-01 20:56:44 +00001// Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
Paul Stewartb50f0b92011-05-16 16:31:42 -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/wifi.h"
6
Wade Guthrie92d06362013-04-25 15:41:30 -07007#include <linux/if.h> // Needs definitions from netinet/ether.h
8#include <netinet/ether.h>
Paul Stewartb50f0b92011-05-16 16:31:42 -07009#include <stdio.h>
mukesh agrawalc7426a42011-06-03 13:04:28 -070010#include <string.h>
Paul Stewartb50f0b92011-05-16 16:31:42 -070011
mukesh agrawal8a3188d2011-12-01 20:56:44 +000012#include <algorithm>
Wade Guthrie5a4e2ef2013-04-30 12:51:39 -070013#include <limits>
mukesh agrawalab87ea42011-05-18 11:44:49 -070014#include <map>
Paul Stewartb50f0b92011-05-16 16:31:42 -070015#include <string>
mukesh agrawalab87ea42011-05-18 11:44:49 -070016#include <vector>
Paul Stewartb50f0b92011-05-16 16:31:42 -070017
Eric Shienbrood3e20a232012-02-16 11:35:56 -050018#include <base/bind.h>
Wade Guthrie5a4e2ef2013-04-30 12:51:39 -070019#include <base/file_path.h>
20#include <base/file_util.h>
mukesh agrawal7a4e4002011-09-06 11:26:05 -070021#include <base/string_util.h>
Wade Guthrie5a4e2ef2013-04-30 12:51:39 -070022#include <base/stringprintf.h>
Chris Masoneb925cc82011-06-22 15:39:57 -070023#include <chromeos/dbus/service_constants.h>
mukesh agrawal16bc1b82012-02-09 18:38:26 -080024#include <glib.h>
Paul Stewartb50f0b92011-05-16 16:31:42 -070025
26#include "shill/control_interface.h"
Paul Stewartced6a0b2011-11-08 15:32:04 -080027#include "shill/dbus_adaptor.h"
Paul Stewartb50f0b92011-05-16 16:31:42 -070028#include "shill/device.h"
mukesh agrawal7a4e4002011-09-06 11:26:05 -070029#include "shill/error.h"
Wade Guthrie2edd58b2013-05-23 11:16:08 -070030#include "shill/file_reader.h"
Gaurav Shah6d2c72d2012-10-16 16:30:44 -070031#include "shill/geolocation_info.h"
mukesh agrawal7a4e4002011-09-06 11:26:05 -070032#include "shill/ieee80211.h"
Paul Stewart3c508e12012-08-09 11:40:06 -070033#include "shill/link_monitor.h"
Christopher Wileyb691efd2012-08-09 13:51:51 -070034#include "shill/logging.h"
Chris Masone7aa5f902011-07-11 11:13:35 -070035#include "shill/manager.h"
Thieu Le67370f62012-02-14 23:01:42 +000036#include "shill/metrics.h"
Wade Guthriebb9fca22013-04-10 17:21:42 -070037#include "shill/netlink_manager.h"
Wade Guthrie7347bf22013-04-30 11:21:51 -070038#include "shill/netlink_message.h"
Wade Guthriebee87c22013-03-06 11:00:46 -080039#include "shill/nl80211_message.h"
mukesh agrawal4d0401c2012-01-06 16:05:31 -080040#include "shill/property_accessor.h"
Darin Petkovd1967262011-07-18 14:55:18 -070041#include "shill/proxy_factory.h"
Eric Shienbrood9a245532012-03-07 14:20:39 -050042#include "shill/rtnl_handler.h"
Wade Guthrie5a4e2ef2013-04-30 12:51:39 -070043#include "shill/scan_session.h"
Paul Stewart5581d072012-12-17 17:30:20 -080044#include "shill/scope_logger.h"
mukesh agrawal5c05b292012-03-07 10:12:52 -080045#include "shill/shill_time.h"
Paul Stewart735eab52013-03-29 09:19:23 -070046#include "shill/supplicant_eap_state_handler.h"
mukesh agrawalaf571952011-07-14 14:31:12 -070047#include "shill/supplicant_interface_proxy_interface.h"
Paul Stewart835934a2012-12-06 19:27:09 -080048#include "shill/supplicant_network_proxy_interface.h"
mukesh agrawalaf571952011-07-14 14:31:12 -070049#include "shill/supplicant_process_proxy_interface.h"
Gaurav Shah435de2c2011-11-17 19:01:07 -080050#include "shill/technology.h"
mukesh agrawalb54601c2011-06-07 17:39:22 -070051#include "shill/wifi_endpoint.h"
Paul Stewart3c504012013-01-17 17:49:58 -080052#include "shill/wifi_provider.h"
mukesh agrawalb54601c2011-06-07 17:39:22 -070053#include "shill/wifi_service.h"
mukesh agrawal6e277772011-09-29 15:04:23 -070054#include "shill/wpa_supplicant.h"
Paul Stewartb50f0b92011-05-16 16:31:42 -070055
Eric Shienbrood3e20a232012-02-16 11:35:56 -050056using base::Bind;
mukesh agrawal15908392011-11-16 18:29:25 +000057using base::StringPrintf;
Wade Guthrie5a4e2ef2013-04-30 12:51:39 -070058using file_util::PathExists;
mukesh agrawal7a4e4002011-09-06 11:26:05 -070059using std::map;
mukesh agrawalab87ea42011-05-18 11:44:49 -070060using std::string;
mukesh agrawal7a4e4002011-09-06 11:26:05 -070061using std::vector;
mukesh agrawalab87ea42011-05-18 11:44:49 -070062
Paul Stewartb50f0b92011-05-16 16:31:42 -070063namespace shill {
mukesh agrawal7a4e4002011-09-06 11:26:05 -070064
65// statics
mukesh agrawal4d0401c2012-01-06 16:05:31 -080066const char *WiFi::kDefaultBgscanMethod =
Paul Stewart0654ece2013-03-26 15:21:26 -070067 WPASupplicant::kNetworkBgscanMethodSimple;
mukesh agrawal4d0401c2012-01-06 16:05:31 -080068const uint16 WiFi::kDefaultBgscanShortIntervalSeconds = 30;
69const int32 WiFi::kDefaultBgscanSignalThresholdDbm = -50;
70const uint16 WiFi::kDefaultScanIntervalSeconds = 180;
Darin Petkov4a66cc52012-06-15 10:08:29 +020071// Scan interval while connected.
72const uint16 WiFi::kBackgroundScanIntervalSeconds = 3601;
mukesh agrawal5c05b292012-03-07 10:12:52 -080073// Age (in seconds) beyond which a BSS cache entry will not be preserved,
74// across a suspend/resume.
75const time_t WiFi::kMaxBSSResumeAgeSeconds = 10;
mukesh agrawal7ec71312011-11-10 02:08:26 +000076const char WiFi::kInterfaceStateUnknown[] = "shill-unknown";
mukesh agrawalf2028172012-03-13 14:20:22 -070077const time_t WiFi::kRescanIntervalSeconds = 1;
Paul Stewarte369ece2012-05-22 09:11:03 -070078const int WiFi::kNumFastScanAttempts = 3;
79const int WiFi::kFastScanIntervalSeconds = 10;
Paul Stewart2b05e622012-07-13 20:38:44 -070080const int WiFi::kPendingTimeoutSeconds = 15;
Paul Stewart44663922012-07-30 11:03:03 -070081const int WiFi::kReconnectTimeoutSeconds = 10;
Wade Guthrie5a4e2ef2013-04-30 12:51:39 -070082const size_t WiFi::kMinumumFrequenciesToScan = 4; // Arbitrary but > 0.
Wade Guthrie2edd58b2013-05-23 11:16:08 -070083const float WiFi::kDefaultFractionPerScan = 0.34;
Wade Guthrie5a4e2ef2013-04-30 12:51:39 -070084const char WiFi::kProgressiveScanFlagFile[] = "/home/chronos/.progressive_scan";
Wade Guthrie2edd58b2013-05-23 11:16:08 -070085const char WiFi::kProgressiveScanFieldTrialFlagFile[] =
86 "/home/chronos/.progressive_scan_variation";
mukesh agrawalb54601c2011-06-07 17:39:22 -070087
Paul Stewartb50f0b92011-05-16 16:31:42 -070088WiFi::WiFi(ControlInterface *control_interface,
89 EventDispatcher *dispatcher,
Thieu Le3426c8f2012-01-11 17:35:11 -080090 Metrics *metrics,
Paul Stewartf1ce5d22011-05-19 13:10:20 -070091 Manager *manager,
Chris Masone3bd3c8c2011-06-13 08:20:26 -070092 const string& link,
Paul Stewarta41e38d2011-11-11 07:47:29 -080093 const string &address,
Paul Stewartb50f0b92011-05-16 16:31:42 -070094 int interface_index)
Chris Masonea82b7112011-05-25 15:16:29 -070095 : Device(control_interface,
96 dispatcher,
Thieu Le3426c8f2012-01-11 17:35:11 -080097 metrics,
Chris Masonea82b7112011-05-25 15:16:29 -070098 manager,
Chris Masone3bd3c8c2011-06-13 08:20:26 -070099 link,
Chris Masone626719f2011-08-18 16:58:48 -0700100 address,
Gaurav Shah435de2c2011-11-17 19:01:07 -0800101 interface_index,
102 Technology::kWifi),
Paul Stewart3c504012013-01-17 17:49:58 -0800103 provider_(manager->wifi_provider()),
Eric Shienbrood9a245532012-03-07 14:20:39 -0500104 weak_ptr_factory_(this),
Darin Petkovab565bb2011-10-06 02:55:51 -0700105 proxy_factory_(ProxyFactory::GetInstance()),
mukesh agrawal5c05b292012-03-07 10:12:52 -0800106 time_(Time::GetInstance()),
Darin Petkov2b8e44e2012-06-25 15:13:26 +0200107 supplicant_present_(false),
mukesh agrawal15908392011-11-16 18:29:25 +0000108 supplicant_state_(kInterfaceStateUnknown),
109 supplicant_bss_("(unknown)"),
mukesh agrawal5c05b292012-03-07 10:12:52 -0800110 need_bss_flush_(false),
Wade Guthriebb9fca22013-04-10 17:21:42 -0700111 resumed_at_((struct timeval) {0}),
Paul Stewarte369ece2012-05-22 09:11:03 -0700112 fast_scans_remaining_(kNumFastScanAttempts),
Christopher Wiley8f81e2a2012-10-17 16:51:32 -0700113 has_already_completed_(false),
Paul Stewarta47c3c62012-12-18 12:14:29 -0800114 is_debugging_connection_(false),
Paul Stewart735eab52013-03-29 09:19:23 -0700115 eap_state_handler_(new SupplicantEAPStateHandler()),
mukesh agrawal4d0401c2012-01-06 16:05:31 -0800116 bgscan_short_interval_seconds_(kDefaultBgscanShortIntervalSeconds),
117 bgscan_signal_threshold_dbm_(kDefaultBgscanSignalThresholdDbm),
Wade Guthriebee87c22013-03-06 11:00:46 -0800118 scan_interval_seconds_(kDefaultScanIntervalSeconds),
Wade Guthrie5a4e2ef2013-04-30 12:51:39 -0700119 progressive_scan_enabled_(false),
120 netlink_manager_(NetlinkManager::GetInstance()),
121 min_frequencies_to_scan_(kMinumumFrequenciesToScan),
Wade Guthrie2edd58b2013-05-23 11:16:08 -0700122 max_frequencies_to_scan_(std::numeric_limits<int>::max()),
Wade Guthrie0cf3c982013-05-29 09:11:35 -0700123 fraction_per_scan_(kDefaultFractionPerScan),
124 scan_state_(kScanIdle),
Paul Stewartf6f96482013-07-12 12:49:15 -0700125 scan_method_(kScanMethodNone),
126 receive_byte_count_at_connect_(0) {
mukesh agrawalde29fa82011-09-16 16:16:36 -0700127 PropertyStore *store = this->mutable_store();
Darin Petkov4a66cc52012-06-15 10:08:29 +0200128 store->RegisterDerivedString(
129 flimflam::kBgscanMethodProperty,
130 StringAccessor(
131 // TODO(petkov): CustomMappedAccessor is used for convenience because
132 // it provides a way to define a custom clearer (unlike
133 // CustomAccessor). We need to implement a fully custom accessor with
134 // no extra argument.
135 new CustomMappedAccessor<WiFi, string, int>(this,
136 &WiFi::ClearBgscanMethod,
137 &WiFi::GetBgscanMethod,
138 &WiFi::SetBgscanMethod,
139 0))); // Unused.
mukesh agrawal4d0401c2012-01-06 16:05:31 -0800140 HelpRegisterDerivedUint16(store,
141 flimflam::kBgscanShortIntervalProperty,
142 &WiFi::GetBgscanShortInterval,
143 &WiFi::SetBgscanShortInterval);
144 HelpRegisterDerivedInt32(store,
145 flimflam::kBgscanSignalThresholdProperty,
146 &WiFi::GetBgscanSignalThreshold,
147 &WiFi::SetBgscanSignalThreshold);
Chris Masone853b81b2011-06-24 14:11:41 -0700148
Chris Masoneb925cc82011-06-22 15:39:57 -0700149 // TODO(quiche): Decide if scan_pending_ is close enough to
150 // "currently scanning" that we don't care, or if we want to track
151 // scan pending/currently scanning/no scan scheduled as a tri-state
152 // kind of thing.
Wade Guthrie0cf3c982013-05-29 09:11:35 -0700153 HelpRegisterConstDerivedBool(store,
154 flimflam::kScanningProperty,
155 &WiFi::GetScanPending);
mukesh agrawal4d0401c2012-01-06 16:05:31 -0800156 HelpRegisterDerivedUint16(store,
157 flimflam::kScanIntervalProperty,
158 &WiFi::GetScanInterval,
159 &WiFi::SetScanInterval);
Paul Stewart5581d072012-12-17 17:30:20 -0800160 ScopeLogger::GetInstance()->RegisterScopeEnableChangedCallback(
161 ScopeLogger::kWiFi,
162 Bind(&WiFi::OnWiFiDebugScopeChanged, weak_ptr_factory_.GetWeakPtr()));
Wade Guthriebb9fca22013-04-10 17:21:42 -0700163 CHECK(netlink_manager_);
Wade Guthrie2edd58b2013-05-23 11:16:08 -0700164 if (PathExists(FilePath(kProgressiveScanFlagFile))) {
165 // Setup manually-enrolled progressive scan.
166 progressive_scan_enabled_ = true;
167 } else {
168 // TODO(wdg): Remove after progressive scan field trial is over.
169 // Only do the field trial if the user hasn't already enabled progressive
170 // scan manually. crbug.com/250945
171 ParseFieldTrialFile(FilePath(kProgressiveScanFieldTrialFlagFile));
172 }
Ben Chanfad4a0b2012-04-18 15:49:59 -0700173 SLOG(WiFi, 2) << "WiFi device " << link_name() << " initialized.";
Paul Stewartb50f0b92011-05-16 16:31:42 -0700174}
175
mukesh agrawalaf571952011-07-14 14:31:12 -0700176WiFi::~WiFi() {}
Paul Stewartb50f0b92011-05-16 16:31:42 -0700177
Wade Guthrie2edd58b2013-05-23 11:16:08 -0700178void WiFi::ParseFieldTrialFile(const FilePath &info_file_path) {
179 FileReader file_reader;
180 if (!file_reader.Open(info_file_path)) {
181 SLOG(WiFi, 7) << "Not enrolled in progressive scan field trial.";
182 return;
183 }
184 string line;
185 file_reader.ReadLine(&line);
186 switch (line[0]) {
187 case '1':
188 min_frequencies_to_scan_ = 4;
189 max_frequencies_to_scan_ = 4;
190 fraction_per_scan_ = .34;
191 progressive_scan_enabled_ = true;
192 break;
193 case '2':
194 min_frequencies_to_scan_ = 4;
195 max_frequencies_to_scan_ = 4;
196 fraction_per_scan_ = .51;
197 progressive_scan_enabled_ = true;
198 break;
199 case '3':
200 min_frequencies_to_scan_ = 8;
201 max_frequencies_to_scan_ = 8;
202 fraction_per_scan_ = .51;
203 progressive_scan_enabled_ = true;
204 break;
205 case '4':
206 min_frequencies_to_scan_ = 8;
207 max_frequencies_to_scan_ = 8;
208 fraction_per_scan_ = 1.1;
209 progressive_scan_enabled_ = true;
210 break;
211 case 'c': // FALLTHROUGH.
212 case 'x': // FALLTHROUGH.
213 default:
214 progressive_scan_enabled_ = false;
215 break;
216 }
217 LOG(INFO) << "Progressive scan (via field_trial) "
218 << (progressive_scan_enabled_ ? "enabled" : "disabled");
219 if (progressive_scan_enabled_) {
220 LOG(INFO) << " min_frequencies_to_scan_ = " << min_frequencies_to_scan_;
221 LOG(INFO) << " max_frequencies_to_scan_ = " << max_frequencies_to_scan_;
222 LOG(INFO) << " fraction_per_scan_ = " << fraction_per_scan_;
223 }
224
225 file_reader.Close();
226}
227
mukesh agrawal6813e762013-07-10 19:05:08 -0700228void WiFi::Start(Error *error,
229 const EnabledStateChangedCallback &/*callback*/) {
Darin Petkov2b8e44e2012-06-25 15:13:26 +0200230 SLOG(WiFi, 2) << "WiFi " << link_name() << " starting.";
231 if (enabled()) {
232 return;
mukesh agrawalc7426a42011-06-03 13:04:28 -0700233 }
Eric Shienbrood9a245532012-03-07 14:20:39 -0500234 OnEnabledStateChanged(EnabledStateChangedCallback(), Error());
Darin Petkov2b8e44e2012-06-25 15:13:26 +0200235 if (error) {
Eric Shienbrood9a245532012-03-07 14:20:39 -0500236 error->Reset(); // indicate immediate completion
Darin Petkov2b8e44e2012-06-25 15:13:26 +0200237 }
238 if (on_supplicant_appear_.IsCancelled()) {
239 // Registers the WPA supplicant appear/vanish callbacks only once per WiFi
240 // device instance.
241 on_supplicant_appear_.Reset(
242 Bind(&WiFi::OnSupplicantAppear, Unretained(this)));
243 on_supplicant_vanish_.Reset(
244 Bind(&WiFi::OnSupplicantVanish, Unretained(this)));
Paul Stewart0654ece2013-03-26 15:21:26 -0700245 manager()->dbus_manager()->WatchName(WPASupplicant::kDBusAddr,
Darin Petkov2b8e44e2012-06-25 15:13:26 +0200246 on_supplicant_appear_.callback(),
247 on_supplicant_vanish_.callback());
248 }
Wade Guthriebee87c22013-03-06 11:00:46 -0800249 // Subscribe to multicast events.
Wade Guthriebb9fca22013-04-10 17:21:42 -0700250 netlink_manager_->SubscribeToEvents(Nl80211Message::kMessageTypeString,
251 NetlinkManager::kEventTypeConfig);
252 netlink_manager_->SubscribeToEvents(Nl80211Message::kMessageTypeString,
253 NetlinkManager::kEventTypeScan);
254 netlink_manager_->SubscribeToEvents(Nl80211Message::kMessageTypeString,
255 NetlinkManager::kEventTypeRegulatory);
256 netlink_manager_->SubscribeToEvents(Nl80211Message::kMessageTypeString,
257 NetlinkManager::kEventTypeMlme);
Wade Guthrie92d06362013-04-25 15:41:30 -0700258 ConfigureScanFrequencies();
Wade Guthrie0cf3c982013-05-29 09:11:35 -0700259 // Connect to WPA supplicant if it's already present. If not, we'll connect to
260 // it when it appears.
261 ConnectToSupplicant();
mukesh agrawalab87ea42011-05-18 11:44:49 -0700262}
263
mukesh agrawal6813e762013-07-10 19:05:08 -0700264void WiFi::Stop(Error *error, const EnabledStateChangedCallback &/*callback*/) {
Ben Chanfad4a0b2012-04-18 15:49:59 -0700265 SLOG(WiFi, 2) << "WiFi " << link_name() << " stopping.";
Darin Petkov2b8e44e2012-06-25 15:13:26 +0200266 DropConnection();
mukesh agrawalb66c6462012-05-07 11:45:25 -0700267 StopScanTimer();
Paul Stewart3c504012013-01-17 17:49:58 -0800268 for (EndpointMap::iterator it = endpoint_by_rpcid_.begin();
269 it != endpoint_by_rpcid_.end(); ++it) {
270 provider_->OnEndpointRemoved(it->second);
271 }
mukesh agrawal15908392011-11-16 18:29:25 +0000272 endpoint_by_rpcid_.clear();
Paul Stewart3c504012013-01-17 17:49:58 -0800273 for (ReverseServiceMap::const_iterator it = rpcid_by_service_.begin();
274 it != rpcid_by_service_.end(); ++it) {
275 RemoveNetwork(it->second);
mukesh agrawal5c4dd0b2011-09-14 13:53:14 -0700276 }
Paul Stewart549d44c2012-07-03 12:40:25 -0700277 rpcid_by_service_.clear();
Paul Stewart549d44c2012-07-03 12:40:25 -0700278 supplicant_interface_proxy_.reset(); // breaks a reference cycle
279 // TODO(quiche): Remove interface from supplicant.
280 supplicant_process_proxy_.reset();
mukesh agrawalb20776f2012-02-10 16:00:36 -0800281 current_service_ = NULL; // breaks a reference cycle
mukesh agrawal7ec71312011-11-10 02:08:26 +0000282 pending_service_ = NULL; // breaks a reference cycle
Paul Stewarta47c3c62012-12-18 12:14:29 -0800283 is_debugging_connection_ = false;
Wade Guthrieb0def9f2013-07-12 13:49:18 -0700284 SetScanState(kScanIdle, kScanMethodNone, __func__);
Paul Stewart2b05e622012-07-13 20:38:44 -0700285 StopPendingTimer();
Paul Stewart44663922012-07-30 11:03:03 -0700286 StopReconnectTimer();
mukesh agrawal5c4dd0b2011-09-14 13:53:14 -0700287
Eric Shienbrood9a245532012-03-07 14:20:39 -0500288 OnEnabledStateChanged(EnabledStateChangedCallback(), Error());
289 if (error)
290 error->Reset(); // indicate immediate completion
mukesh agrawalc4f368f2012-06-04 19:45:52 -0700291 weak_ptr_factory_.InvalidateWeakPtrs();
mukesh agrawal5c4dd0b2011-09-14 13:53:14 -0700292
Ben Chanfad4a0b2012-04-18 15:49:59 -0700293 SLOG(WiFi, 3) << "WiFi " << link_name() << " supplicant_process_proxy_ "
294 << (supplicant_process_proxy_.get() ?
295 "is set." : "is not set.");
296 SLOG(WiFi, 3) << "WiFi " << link_name() << " supplicant_interface_proxy_ "
297 << (supplicant_interface_proxy_.get() ?
298 "is set." : "is not set.");
299 SLOG(WiFi, 3) << "WiFi " << link_name() << " pending_service_ "
300 << (pending_service_.get() ? "is set." : "is not set.");
301 SLOG(WiFi, 3) << "WiFi " << link_name() << " has "
302 << endpoint_by_rpcid_.size() << " EndpointMap entries.";
Paul Stewarta41e38d2011-11-11 07:47:29 -0800303}
304
Wade Guthrie68d41092013-04-02 12:56:02 -0700305void WiFi::Scan(ScanType scan_type, Error */*error*/) {
mukesh agrawal32399322011-09-01 10:53:43 -0700306 LOG(INFO) << __func__;
Wade Guthrie5a4e2ef2013-04-30 12:51:39 -0700307 if (progressive_scan_enabled_ && scan_type == kProgressiveScan) {
Wade Guthrie299c4272013-06-25 16:18:32 -0700308 LOG(INFO) << "Doing progressive scan on " << link_name();
Wade Guthrie5a4e2ef2013-04-30 12:51:39 -0700309 if (!scan_session_) {
310 // TODO(wdg): Perform in-depth testing to determine the best values for
311 // the different scans. chromium:235293
312 ScanSession::FractionList scan_fractions;
Wade Guthrie2edd58b2013-05-23 11:16:08 -0700313 float total_fraction = 0.0;
314 do {
315 total_fraction += fraction_per_scan_;
316 scan_fractions.push_back(fraction_per_scan_);
317 } while (total_fraction < 1.0);
Wade Guthriedf6d61b2013-07-17 11:43:55 -0700318 DCHECK(scan_state_ == kScanIdle);
319 DCHECK(scan_method_ == kScanMethodNone);
Wade Guthrie5a4e2ef2013-04-30 12:51:39 -0700320 scan_session_.reset(
321 new ScanSession(netlink_manager_,
322 dispatcher(),
323 provider_->GetScanFrequencies(),
324 all_scan_frequencies_,
325 interface_index(),
326 scan_fractions,
327 min_frequencies_to_scan_,
328 max_frequencies_to_scan_,
329 Bind(&WiFi::OnFailedProgressiveScan,
Wade Guthrief22681f2013-05-31 11:46:31 -0700330 weak_ptr_factory_.GetWeakPtr()),
331 metrics()));
Wade Guthrie5a4e2ef2013-04-30 12:51:39 -0700332 for (const auto &ssid : provider_->GetHiddenSSIDList()) {
333 scan_session_->AddSsid(ByteString(&ssid.front(), ssid.size()));
334 }
335 }
336 dispatcher()->PostTask(
337 Bind(&WiFi::ProgressiveScanTask, weak_ptr_factory_.GetWeakPtr()));
338 } else {
Wade Guthrie299c4272013-06-25 16:18:32 -0700339 LOG(INFO) << "Doing full scan on " << link_name() << " - progressive scan "
340 << (progressive_scan_enabled_ ? "ENABLED" : "DISABLED");
Wade Guthrie5a4e2ef2013-04-30 12:51:39 -0700341 // Needs to send a D-Bus message, but may be called from D-Bus
342 // signal handler context (via Manager::RequestScan). So defer work
343 // to event loop.
344 dispatcher()->PostTask(
345 Bind(&WiFi::ScanTask, weak_ptr_factory_.GetWeakPtr()));
346 }
mukesh agrawal32399322011-09-01 10:53:43 -0700347}
348
mukesh agrawalb4bc57d2011-12-07 01:07:47 +0000349void WiFi::BSSAdded(const ::DBus::Path &path,
350 const map<string, ::DBus::Variant> &properties) {
Eric Shienbrood3e20a232012-02-16 11:35:56 -0500351 // Called from a D-Bus signal handler, and may need to send a D-Bus
mukesh agrawalb4bc57d2011-12-07 01:07:47 +0000352 // message. So defer work to event loop.
Eric Shienbrood9a245532012-03-07 14:20:39 -0500353 dispatcher()->PostTask(Bind(&WiFi::BSSAddedTask,
354 weak_ptr_factory_.GetWeakPtr(),
355 path, properties));
mukesh agrawal261daca2011-12-02 18:56:56 +0000356}
357
358void WiFi::BSSRemoved(const ::DBus::Path &path) {
Eric Shienbrood3e20a232012-02-16 11:35:56 -0500359 // Called from a D-Bus signal handler, and may need to send a D-Bus
mukesh agrawalb4bc57d2011-12-07 01:07:47 +0000360 // message. So defer work to event loop.
Eric Shienbrood9a245532012-03-07 14:20:39 -0500361 dispatcher()->PostTask(Bind(&WiFi::BSSRemovedTask,
362 weak_ptr_factory_.GetWeakPtr(), path));
mukesh agrawalb54601c2011-06-07 17:39:22 -0700363}
364
Paul Stewartbc6e7392012-05-24 07:07:48 -0700365void WiFi::Certification(const map<string, ::DBus::Variant> &properties) {
366 dispatcher()->PostTask(Bind(&WiFi::CertificationTask,
367 weak_ptr_factory_.GetWeakPtr(), properties));
368}
369
Paul Stewartdb0f9172012-11-30 16:48:09 -0800370void WiFi::EAPEvent(const string &status, const string &parameter) {
371 dispatcher()->PostTask(Bind(&WiFi::EAPEventTask,
372 weak_ptr_factory_.GetWeakPtr(),
373 status,
374 parameter));
375}
376
mukesh agrawal7ec71312011-11-10 02:08:26 +0000377void WiFi::PropertiesChanged(const map<string, ::DBus::Variant> &properties) {
Darin Petkov9cd7ca12012-07-03 11:06:40 +0200378 SLOG(WiFi, 2) << __func__;
mukesh agrawal15908392011-11-16 18:29:25 +0000379 // Called from D-Bus signal handler, but may need to send a D-Bus
380 // message. So defer work to event loop.
Eric Shienbrood9a245532012-03-07 14:20:39 -0500381 dispatcher()->PostTask(Bind(&WiFi::PropertiesChangedTask,
382 weak_ptr_factory_.GetWeakPtr(), properties));
mukesh agrawal7ec71312011-11-10 02:08:26 +0000383}
384
mukesh agrawalb54601c2011-06-07 17:39:22 -0700385void WiFi::ScanDone() {
386 LOG(INFO) << __func__;
387
mukesh agrawal7ec71312011-11-10 02:08:26 +0000388 // Defer handling of scan result processing, because that processing
389 // may require the the registration of new D-Bus objects. And such
mukesh agrawalb54601c2011-06-07 17:39:22 -0700390 // registration can't be done in the context of a D-Bus signal
391 // handler.
Eric Shienbrood9a245532012-03-07 14:20:39 -0500392 dispatcher()->PostTask(Bind(&WiFi::ScanDoneTask,
393 weak_ptr_factory_.GetWeakPtr()));
mukesh agrawalb54601c2011-06-07 17:39:22 -0700394}
395
mukesh agrawal6e277772011-09-29 15:04:23 -0700396void WiFi::ConnectTo(WiFiService *service,
mukesh agrawal64896322011-12-01 01:13:10 +0000397 map<string, DBus::Variant> service_params) {
mukesh agrawale9adda12012-02-09 18:33:48 -0800398 CHECK(service) << "Can't connect to NULL service.";
mukesh agrawal445e72c2011-06-22 11:13:50 -0700399 DBus::Path network_path;
mukesh agrawalb54601c2011-06-07 17:39:22 -0700400
mukesh agrawal7ec71312011-11-10 02:08:26 +0000401 // TODO(quiche): Handle cases where already connected.
mukesh agrawal8a3188d2011-12-01 20:56:44 +0000402 if (pending_service_ && pending_service_ == service) {
Paul Stewartee6b3d72013-07-12 16:07:51 -0700403 // TODO(quiche): Return an error to the caller. crbug.com/206812
Darin Petkov457728b2013-01-09 09:49:08 +0100404 LOG(INFO) << "WiFi " << link_name() << " ignoring ConnectTo service "
405 << service->unique_name()
mukesh agrawal8a3188d2011-12-01 20:56:44 +0000406 << ", which is already pending.";
407 return;
408 }
409
410 if (pending_service_ && pending_service_ != service) {
Wade Guthriedf6d61b2013-07-17 11:43:55 -0700411 // This is a signal to SetPendingService(NULL) to not modify the scan
412 // state since the overall story arc isn't reflected by the disconnect.
413 // It is, instead, described by the transition to either kScanFoundNothing
414 // or kScanConnecting (made by |SetPendingService|, below).
415 if (scan_method_ != kScanMethodNone) {
416 SetScanState(kScanTransitionToConnecting, scan_method_, __func__);
417 }
mukesh agrawal8a3188d2011-12-01 20:56:44 +0000418 DisconnectFrom(pending_service_);
419 }
mukesh agrawal32399322011-09-01 10:53:43 -0700420
Paul Stewart835934a2012-12-06 19:27:09 -0800421 Error unused_error;
422 network_path = FindNetworkRpcidForService(service, &unused_error);
423 if (network_path.empty()) {
424 try {
425 const uint32_t scan_ssid = 1; // "True": Use directed probe.
Paul Stewart0654ece2013-03-26 15:21:26 -0700426 service_params[WPASupplicant::kNetworkPropertyScanSSID].writer().
Paul Stewart835934a2012-12-06 19:27:09 -0800427 append_uint32(scan_ssid);
428 AppendBgscan(service, &service_params);
429 network_path = supplicant_interface_proxy_->AddNetwork(service_params);
430 CHECK(!network_path.empty()); // No DBus path should be empty.
431 rpcid_by_service_[service] = network_path;
432 } catch (const DBus::Error &e) { // NOLINT
433 LOG(ERROR) << "exception while adding network: " << e.what();
Wade Guthriedf6d61b2013-07-17 11:43:55 -0700434 SetScanState(kScanIdle, scan_method_, __func__);
Paul Stewart835934a2012-12-06 19:27:09 -0800435 return;
436 }
mukesh agrawal6e277772011-09-29 15:04:23 -0700437 }
mukesh agrawal445e72c2011-06-22 11:13:50 -0700438
Paul Stewarta47c3c62012-12-18 12:14:29 -0800439 if (service->HasRecentConnectionIssues()) {
440 SetConnectionDebugging(true);
441 }
mukesh agrawal445e72c2011-06-22 11:13:50 -0700442 supplicant_interface_proxy_->SelectNetwork(network_path);
Paul Stewart2b05e622012-07-13 20:38:44 -0700443 SetPendingService(service);
mukesh agrawal8a3188d2011-12-01 20:56:44 +0000444 CHECK(current_service_.get() != pending_service_.get());
445
mukesh agrawalf2f68a52011-09-01 12:15:48 -0700446 // SelectService here (instead of in LinkEvent, like Ethernet), so
447 // that, if we fail to bring up L2, we can attribute failure correctly.
448 //
mukesh agrawal7ec71312011-11-10 02:08:26 +0000449 // TODO(quiche): When we add code for dealing with connection failures,
mukesh agrawalf2f68a52011-09-01 12:15:48 -0700450 // reconsider if this is the right place to change the selected service.
Paul Stewartee6b3d72013-07-12 16:07:51 -0700451 // see discussion in crbug.com/203282.
mukesh agrawalf2f68a52011-09-01 12:15:48 -0700452 SelectService(service);
mukesh agrawal15908392011-11-16 18:29:25 +0000453}
454
mukesh agrawal0ed0f2e2011-12-05 20:36:17 +0000455void WiFi::DisconnectFrom(WiFiService *service) {
456 if (service != current_service_ && service != pending_service_) {
457 // TODO(quiche): Once we have asynchronous reply support, we should
Paul Stewartee6b3d72013-07-12 16:07:51 -0700458 // generate a D-Bus error here. (crbug.com/206812)
mukesh agrawal0ed0f2e2011-12-05 20:36:17 +0000459 LOG(WARNING) << "In " << __func__ << "(): "
460 << " ignoring request to disconnect from service "
Darin Petkov457728b2013-01-09 09:49:08 +0100461 << service->unique_name()
mukesh agrawal0ed0f2e2011-12-05 20:36:17 +0000462 << " which is neither current nor pending";
463 return;
464 }
465
466 if (pending_service_ && service != pending_service_) {
467 // TODO(quiche): Once we have asynchronous reply support, we should
Paul Stewartee6b3d72013-07-12 16:07:51 -0700468 // generate a D-Bus error here. (crbug.com/206812)
mukesh agrawal0ed0f2e2011-12-05 20:36:17 +0000469 LOG(WARNING) << "In " << __func__ << "(): "
470 << " ignoring request to disconnect from service "
Darin Petkov457728b2013-01-09 09:49:08 +0100471 << service->unique_name()
mukesh agrawal0ed0f2e2011-12-05 20:36:17 +0000472 << " which is not the pending service.";
473 return;
474 }
475
476 if (!pending_service_ && service != current_service_) {
477 // TODO(quiche): Once we have asynchronous reply support, we should
Paul Stewartee6b3d72013-07-12 16:07:51 -0700478 // generate a D-Bus error here. (crbug.com/206812)
mukesh agrawal0ed0f2e2011-12-05 20:36:17 +0000479 LOG(WARNING) << "In " << __func__ << "(): "
480 << " ignoring request to disconnect from service "
Darin Petkov457728b2013-01-09 09:49:08 +0100481 << service->unique_name()
mukesh agrawal0ed0f2e2011-12-05 20:36:17 +0000482 << " which is not the current service.";
483 return;
484 }
485
Paul Stewartff96a842012-08-13 15:59:10 -0700486 if (pending_service_) {
487 // Since wpa_supplicant has not yet set CurrentBSS, we can't depend
488 // on this to drive the service state back to idle. Do that here.
489 pending_service_->SetState(Service::kStateIdle);
490 }
491
Paul Stewart2b05e622012-07-13 20:38:44 -0700492 SetPendingService(NULL);
Paul Stewart44663922012-07-30 11:03:03 -0700493 StopReconnectTimer();
Paul Stewart549d44c2012-07-03 12:40:25 -0700494
495 if (!supplicant_present_) {
Christopher Wileyc6184482012-10-24 15:31:56 -0700496 LOG(ERROR) << "In " << __func__ << "(): "
497 << "wpa_supplicant is not present; silently resetting "
498 << "current_service_.";
499 if (current_service_ == selected_service()) {
500 DropConnection();
501 }
Paul Stewart549d44c2012-07-03 12:40:25 -0700502 current_service_ = NULL;
503 return;
504 }
505
mukesh agrawal0ed0f2e2011-12-05 20:36:17 +0000506 try {
507 supplicant_interface_proxy_->Disconnect();
508 // We'll call RemoveNetwork and reset |current_service_| after
509 // supplicant notifies us that the CurrentBSS has changed.
Ben Chan80326f32012-05-04 17:51:32 -0700510 } catch (const DBus::Error &e) { // NOLINT
mukesh agrawal0ed0f2e2011-12-05 20:36:17 +0000511 // Can't depend on getting a notification of CurrentBSS change.
Christopher Wileyc6184482012-10-24 15:31:56 -0700512 // So effect changes immediately. For instance, this can happen when
513 // a disconnect is triggered by a BSS going away.
Paul Stewart835934a2012-12-06 19:27:09 -0800514 Error unused_error;
515 RemoveNetworkForService(service, &unused_error);
Christopher Wileyc6184482012-10-24 15:31:56 -0700516 if (service == selected_service()) {
517 DropConnection();
518 }
mukesh agrawal0ed0f2e2011-12-05 20:36:17 +0000519 current_service_ = NULL;
520 }
521
mukesh agrawal4d0401c2012-01-06 16:05:31 -0800522 CHECK(current_service_ == NULL ||
523 current_service_.get() != pending_service_.get());
mukesh agrawal0ed0f2e2011-12-05 20:36:17 +0000524}
525
Paul Stewart835934a2012-12-06 19:27:09 -0800526bool WiFi::DisableNetwork(const ::DBus::Path &network) {
527 scoped_ptr<SupplicantNetworkProxyInterface> supplicant_network_proxy(
528 proxy_factory_->CreateSupplicantNetworkProxy(
Paul Stewart0654ece2013-03-26 15:21:26 -0700529 network, WPASupplicant::kDBusAddr));
Paul Stewart835934a2012-12-06 19:27:09 -0800530 try {
531 supplicant_network_proxy->SetEnabled(false);
532 } catch (const DBus::Error &e) { // NOLINT
533 LOG(ERROR) << "DisableNetwork for " << network << " failed.";
534 return false;
535 }
536 return true;
537}
538
Paul Stewart71f6ecd2012-09-13 14:52:18 -0700539bool WiFi::RemoveNetwork(const ::DBus::Path &network) {
540 try {
541 supplicant_interface_proxy_->RemoveNetwork(network);
542 } catch (const DBus::Error &e) { // NOLINT
Ben Chan381fdcc2012-10-14 21:10:36 -0700543 // RemoveNetwork can fail with three different errors.
544 //
545 // If RemoveNetwork fails with a NetworkUnknown error, supplicant has
546 // already removed the network object, so return true as if
547 // RemoveNetwork removes the network object successfully.
548 //
549 // As shill always passes a valid network object path, RemoveNetwork
550 // should not fail with an InvalidArgs error. Return false in such case
551 // as something weird may have happened. Similarly, return false in case
552 // of an UnknownError.
Paul Stewart0654ece2013-03-26 15:21:26 -0700553 if (strcmp(e.name(), WPASupplicant::kErrorNetworkUnknown) != 0) {
Ben Chan381fdcc2012-10-14 21:10:36 -0700554 return false;
555 }
Paul Stewart71f6ecd2012-09-13 14:52:18 -0700556 }
557 return true;
558}
559
mukesh agrawal8a3188d2011-12-01 20:56:44 +0000560bool WiFi::IsIdle() const {
Paul Stewart3d9bcf52011-12-12 15:02:22 -0800561 return !current_service_ && !pending_service_;
562}
563
Paul Stewart835934a2012-12-06 19:27:09 -0800564void WiFi::ClearCachedCredentials(const WiFiService *service) {
565 Error unused_error;
566 RemoveNetworkForService(service, &unused_error);
Paul Stewart66c86002012-01-30 18:00:52 -0800567}
568
Paul Stewart3c504012013-01-17 17:49:58 -0800569void WiFi::NotifyEndpointChanged(const WiFiEndpointConstRefPtr &endpoint) {
Paul Stewart0427cc12013-03-25 13:50:39 -0700570 provider_->OnEndpointUpdated(endpoint);
mukesh agrawalb20776f2012-02-10 16:00:36 -0800571}
572
Darin Petkov4a66cc52012-06-15 10:08:29 +0200573void WiFi::AppendBgscan(WiFiService *service,
574 map<string, DBus::Variant> *service_params) const {
575 int scan_interval = kBackgroundScanIntervalSeconds;
576 string method = bgscan_method_;
577 if (method.empty()) {
578 // If multiple APs are detected for this SSID, configure the default method.
579 // Otherwise, disable background scanning completely.
580 if (service->GetEndpointCount() > 1) {
581 method = kDefaultBgscanMethod;
582 } else {
583 LOG(INFO) << "Background scan disabled -- single Endpoint for Service.";
584 return;
585 }
Paul Stewart0654ece2013-03-26 15:21:26 -0700586 } else if (method.compare(WPASupplicant::kNetworkBgscanMethodNone) == 0) {
Christopher Wileya998df22012-07-11 15:14:55 -0700587 LOG(INFO) << "Background scan disabled -- chose None method.";
588 return;
Darin Petkov4a66cc52012-06-15 10:08:29 +0200589 } else {
590 // If the background scan method was explicitly specified, honor the
591 // configured background scan interval.
592 scan_interval = scan_interval_seconds_;
593 }
594 DCHECK(!method.empty());
595 string config_string = StringPrintf("%s:%d:%d:%d",
596 method.c_str(),
597 bgscan_short_interval_seconds_,
598 bgscan_signal_threshold_dbm_,
599 scan_interval);
600 LOG(INFO) << "Background scan: " << config_string;
Paul Stewart0654ece2013-03-26 15:21:26 -0700601 (*service_params)[WPASupplicant::kNetworkPropertyBgscan].writer()
Darin Petkov4a66cc52012-06-15 10:08:29 +0200602 .append_string(config_string.c_str());
mukesh agrawal4d0401c2012-01-06 16:05:31 -0800603}
604
Darin Petkov4a66cc52012-06-15 10:08:29 +0200605string WiFi::GetBgscanMethod(const int &/*argument*/, Error */* error */) {
606 return bgscan_method_.empty() ? kDefaultBgscanMethod : bgscan_method_;
607}
608
mukesh agrawalbebf1b82013-04-23 15:06:33 -0700609bool WiFi::SetBgscanMethod(
Darin Petkov4a66cc52012-06-15 10:08:29 +0200610 const int &/*argument*/, const string &method, Error *error) {
Paul Stewart0654ece2013-03-26 15:21:26 -0700611 if (method != WPASupplicant::kNetworkBgscanMethodSimple &&
612 method != WPASupplicant::kNetworkBgscanMethodLearn &&
613 method != WPASupplicant::kNetworkBgscanMethodNone) {
mukesh agrawal4d0401c2012-01-06 16:05:31 -0800614 const string error_message =
615 StringPrintf("Unrecognized bgscan method %s", method.c_str());
616 LOG(WARNING) << error_message;
617 error->Populate(Error::kInvalidArguments, error_message);
mukesh agrawalbebf1b82013-04-23 15:06:33 -0700618 return false;
mukesh agrawal4d0401c2012-01-06 16:05:31 -0800619 }
mukesh agrawalbebf1b82013-04-23 15:06:33 -0700620 if (bgscan_method_ == method) {
621 return false;
622 }
mukesh agrawal4d0401c2012-01-06 16:05:31 -0800623 bgscan_method_ = method;
624 // We do not update kNetworkPropertyBgscan for |pending_service_| or
625 // |current_service_|, because supplicant does not allow for
626 // reconfiguration without disconnect and reconnect.
mukesh agrawalbebf1b82013-04-23 15:06:33 -0700627 return true;
mukesh agrawal4d0401c2012-01-06 16:05:31 -0800628}
629
mukesh agrawalbebf1b82013-04-23 15:06:33 -0700630bool WiFi::SetBgscanShortInterval(const uint16 &seconds, Error */*error*/) {
631 if (bgscan_short_interval_seconds_ == seconds) {
632 return false;
633 }
mukesh agrawal4d0401c2012-01-06 16:05:31 -0800634 bgscan_short_interval_seconds_ = seconds;
635 // We do not update kNetworkPropertyBgscan for |pending_service_| or
636 // |current_service_|, because supplicant does not allow for
637 // reconfiguration without disconnect and reconnect.
mukesh agrawalbebf1b82013-04-23 15:06:33 -0700638 return true;
mukesh agrawal4d0401c2012-01-06 16:05:31 -0800639}
640
mukesh agrawalbebf1b82013-04-23 15:06:33 -0700641bool WiFi::SetBgscanSignalThreshold(const int32 &dbm, Error */*error*/) {
642 if (bgscan_signal_threshold_dbm_ == dbm) {
643 return false;
644 }
mukesh agrawal4d0401c2012-01-06 16:05:31 -0800645 bgscan_signal_threshold_dbm_ = dbm;
646 // We do not update kNetworkPropertyBgscan for |pending_service_| or
647 // |current_service_|, because supplicant does not allow for
648 // reconfiguration without disconnect and reconnect.
mukesh agrawalbebf1b82013-04-23 15:06:33 -0700649 return true;
mukesh agrawal4d0401c2012-01-06 16:05:31 -0800650}
651
mukesh agrawalbebf1b82013-04-23 15:06:33 -0700652bool WiFi::SetScanInterval(const uint16 &seconds, Error */*error*/) {
653 if (scan_interval_seconds_ == seconds) {
654 return false;
655 }
mukesh agrawal4d0401c2012-01-06 16:05:31 -0800656 scan_interval_seconds_ = seconds;
mukesh agrawalb66c6462012-05-07 11:45:25 -0700657 if (running()) {
658 StartScanTimer();
659 }
660 // The scan interval affects both foreground scans (handled by
661 // |scan_timer_callback_|), and background scans (handled by
662 // supplicant). However, we do not update |pending_service_| or
663 // |current_service_|, because supplicant does not allow for
664 // reconfiguration without disconnect and reconnect.
mukesh agrawalbebf1b82013-04-23 15:06:33 -0700665 return true;
mukesh agrawal4d0401c2012-01-06 16:05:31 -0800666}
667
Darin Petkov4a66cc52012-06-15 10:08:29 +0200668void WiFi::ClearBgscanMethod(const int &/*argument*/, Error */*error*/) {
669 bgscan_method_.clear();
670}
671
mukesh agrawal15908392011-11-16 18:29:25 +0000672void WiFi::CurrentBSSChanged(const ::DBus::Path &new_bss) {
Ben Chanfad4a0b2012-04-18 15:49:59 -0700673 SLOG(WiFi, 3) << "WiFi " << link_name() << " CurrentBSS "
674 << supplicant_bss_ << " -> " << new_bss;
mukesh agrawal15908392011-11-16 18:29:25 +0000675 supplicant_bss_ = new_bss;
Christopher Wiley8f81e2a2012-10-17 16:51:32 -0700676 has_already_completed_ = false;
Paul Stewart44663922012-07-30 11:03:03 -0700677
678 // Any change in CurrentBSS means supplicant is actively changing our
679 // connectivity. We no longer need to track any previously pending
680 // reconnect.
681 StopReconnectTimer();
682
Paul Stewart0654ece2013-03-26 15:21:26 -0700683 if (new_bss == WPASupplicant::kCurrentBSSNull) {
mukesh agrawal15908392011-11-16 18:29:25 +0000684 HandleDisconnect();
Paul Stewart3c504012013-01-17 17:49:58 -0800685 if (!provider_->GetHiddenSSIDList().empty()) {
mukesh agrawalb66c6462012-05-07 11:45:25 -0700686 // Before disconnecting, wpa_supplicant probably scanned for
687 // APs. So, in the normal case, we defer to the timer for the next scan.
688 //
689 // However, in the case of hidden SSIDs, supplicant knows about
690 // at most one of them. (That would be the hidden SSID we were
691 // connected to, if applicable.)
692 //
693 // So, in this case, we initiate an immediate scan. This scan
694 // will include the hidden SSIDs we know about (up to the limit of
695 // kScanMAxSSIDsPerScan).
696 //
697 // We may want to reconsider this immediate scan, if/when shill
698 // takes greater responsibility for scanning (vs. letting
699 // supplicant handle most of it).
Wade Guthrie68d41092013-04-02 12:56:02 -0700700 Scan(kProgressiveScan, NULL);
mukesh agrawalb66c6462012-05-07 11:45:25 -0700701 }
mukesh agrawal15908392011-11-16 18:29:25 +0000702 } else {
703 HandleRoam(new_bss);
704 }
705
Paul Stewart735eab52013-03-29 09:19:23 -0700706 // Reset the EAP handler only after calling HandleDisconnect() above
707 // so our EAP state could be used to detect a failed authentication.
708 eap_state_handler_->Reset();
Paul Stewart1369c2b2013-01-11 05:41:26 -0800709
Paul Stewart2b05e622012-07-13 20:38:44 -0700710 // If we are selecting a new service, or if we're clearing selection
711 // of a something other than the pending service, call SelectService.
712 // Otherwise skip SelectService, since this will cause the pending
713 // service to be marked as Idle.
714 if (current_service_ || selected_service() != pending_service_) {
715 SelectService(current_service_);
716 }
717
mukesh agrawal8a3188d2011-12-01 20:56:44 +0000718 // Invariant check: a Service can either be current, or pending, but
719 // not both.
mukesh agrawal15908392011-11-16 18:29:25 +0000720 CHECK(current_service_.get() != pending_service_.get() ||
721 current_service_.get() == NULL);
Paul Stewarta47c3c62012-12-18 12:14:29 -0800722
723 // If we are no longer debugging a problematic WiFi connection, return
724 // to the debugging level indicated by the WiFi debugging scope.
725 if ((!current_service_ || !current_service_->HasRecentConnectionIssues()) &&
726 (!pending_service_ || !pending_service_->HasRecentConnectionIssues())) {
727 SetConnectionDebugging(false);
728 }
mukesh agrawal15908392011-11-16 18:29:25 +0000729}
730
731void WiFi::HandleDisconnect() {
732 // Identify the affected service. We expect to get a disconnect
733 // event when we fall off a Service that we were connected
734 // to. However, we also allow for the case where we get a disconnect
735 // event while attempting to connect from a disconnected state.
736 WiFiService *affected_service =
737 current_service_.get() ? current_service_.get() : pending_service_.get();
738
739 current_service_ = NULL;
740 if (!affected_service) {
Ben Chanfad4a0b2012-04-18 15:49:59 -0700741 SLOG(WiFi, 2) << "WiFi " << link_name()
742 << " disconnected while not connected or connecting";
mukesh agrawal15908392011-11-16 18:29:25 +0000743 return;
Christopher Wileyc6184482012-10-24 15:31:56 -0700744 }
745 if (affected_service == selected_service()) {
Paul Stewart20b0a092012-05-22 20:39:57 -0700746 // If our selected service has disconnected, destroy IP configuration state.
Christopher Wileyc6184482012-10-24 15:31:56 -0700747 DropConnection();
mukesh agrawal15908392011-11-16 18:29:25 +0000748 }
749
Paul Stewart835934a2012-12-06 19:27:09 -0800750 Error error;
751 if (!DisableNetworkForService(affected_service, &error)) {
752 if (error.type() == Error::kNotFound) {
753 SLOG(WiFi, 2) << "WiFi " << link_name() << " disconnected from "
Darin Petkov457728b2013-01-09 09:49:08 +0100754 << " (or failed to connect to) service "
755 << affected_service->unique_name() << ", "
Paul Stewart835934a2012-12-06 19:27:09 -0800756 << "but could not find supplicant network to disable.";
757 } else {
Wade Guthrie727e0202013-06-27 11:22:38 -0700758 LOG(FATAL) << "DisableNetwork failed on " << link_name()
759 << "for service " << affected_service->unique_name() << ".";
Paul Stewart71f6ecd2012-09-13 14:52:18 -0700760 }
mukesh agrawal15908392011-11-16 18:29:25 +0000761 }
762
Ben Chanfad4a0b2012-04-18 15:49:59 -0700763 SLOG(WiFi, 2) << "WiFi " << link_name() << " disconnected from "
Darin Petkov457728b2013-01-09 09:49:08 +0100764 << " (or failed to connect to) service "
765 << affected_service->unique_name();
Paul Stewart1369c2b2013-01-11 05:41:26 -0800766 Service::ConnectFailure failure;
Paul Stewartbca08f82013-07-09 16:32:37 -0700767 if (SuspectCredentials(affected_service, &failure)) {
mukesh agrawalcf24a242012-05-21 16:46:11 -0700768 // If we suspect bad credentials, set failure, to trigger an error
mukesh agrawal56e32202012-07-26 16:32:11 -0700769 // mole in Chrome.
Paul Stewart1369c2b2013-01-11 05:41:26 -0800770 affected_service->SetFailure(failure);
771 LOG(ERROR) << "Connection failure is due to suspect credentials: returning "
772 << Service::ConnectFailureToString(failure);
Paul Stewartf2d60912012-07-15 08:37:30 -0700773 } else {
774 affected_service->SetFailureSilent(Service::kFailureUnknown);
mukesh agrawalcf24a242012-05-21 16:46:11 -0700775 }
mukesh agrawale1d90e92012-02-15 17:36:08 -0800776 affected_service->NotifyCurrentEndpoint(NULL);
Thieu Le67370f62012-02-14 23:01:42 +0000777 metrics()->NotifyServiceDisconnect(affected_service);
mukesh agrawal15908392011-11-16 18:29:25 +0000778
779 if (affected_service == pending_service_.get()) {
780 // The attempt to connect to |pending_service_| failed. Clear
781 // |pending_service_|, to indicate we're no longer in the middle
782 // of a connect request.
Paul Stewart2b05e622012-07-13 20:38:44 -0700783 SetPendingService(NULL);
mukesh agrawal15908392011-11-16 18:29:25 +0000784 } else if (pending_service_.get()) {
785 // We've attributed the disconnection to what was the
786 // |current_service_|, rather than the |pending_service_|.
787 //
788 // If we're wrong about that (i.e. supplicant reported this
789 // CurrentBSS change after attempting to connect to
790 // |pending_service_|), we're depending on supplicant to retry
791 // connecting to |pending_service_|, and delivering another
792 // CurrentBSS change signal in the future.
793 //
794 // Log this fact, to help us debug (in case our assumptions are
795 // wrong).
Darin Petkov457728b2013-01-09 09:49:08 +0100796 SLOG(WiFi, 2) << "WiFi " << link_name() << " pending connection to service "
797 << pending_service_->unique_name()
Ben Chanfad4a0b2012-04-18 15:49:59 -0700798 << " after disconnect";
mukesh agrawal15908392011-11-16 18:29:25 +0000799 }
Paul Stewarte369ece2012-05-22 09:11:03 -0700800
801 // If we disconnect, initially scan at a faster frequency, to make sure
802 // we've found all available APs.
803 RestartFastScanAttempts();
mukesh agrawal15908392011-11-16 18:29:25 +0000804}
805
806// We use the term "Roam" loosely. In particular, we include the case
807// where we "Roam" to a BSS from the disconnected state.
808void WiFi::HandleRoam(const ::DBus::Path &new_bss) {
809 EndpointMap::iterator endpoint_it = endpoint_by_rpcid_.find(new_bss);
810 if (endpoint_it == endpoint_by_rpcid_.end()) {
811 LOG(WARNING) << "WiFi " << link_name() << " connected to unknown BSS "
812 << new_bss;
813 return;
814 }
815
Paul Stewart3c504012013-01-17 17:49:58 -0800816 const WiFiEndpointConstRefPtr endpoint(endpoint_it->second);
817 WiFiServiceRefPtr service = provider_->FindServiceForEndpoint(endpoint);
mukesh agrawal15908392011-11-16 18:29:25 +0000818 if (!service.get()) {
819 LOG(WARNING) << "WiFi " << link_name()
820 << " could not find Service for Endpoint "
Paul Stewart3c504012013-01-17 17:49:58 -0800821 << endpoint->bssid_string()
mukesh agrawal15908392011-11-16 18:29:25 +0000822 << " (service will be unchanged)";
823 return;
824 }
825
Ben Chanfad4a0b2012-04-18 15:49:59 -0700826 SLOG(WiFi, 2) << "WiFi " << link_name()
Paul Stewart3c504012013-01-17 17:49:58 -0800827 << " roamed to Endpoint " << endpoint->bssid_string()
828 << " " << LogSSID(endpoint->ssid_string());
mukesh agrawal15908392011-11-16 18:29:25 +0000829
Paul Stewart3c504012013-01-17 17:49:58 -0800830 service->NotifyCurrentEndpoint(endpoint);
Wade Guthrie60a37062013-04-02 11:39:09 -0700831 provider_->IncrementConnectCount(endpoint->frequency());
Thieu Lee41a72d2012-02-06 20:46:51 +0000832
mukesh agrawal15908392011-11-16 18:29:25 +0000833 if (pending_service_.get() &&
834 service.get() != pending_service_.get()) {
835 // The Service we've roamed on to is not the one we asked for.
836 // We assume that this is transient, and that wpa_supplicant
837 // is trying / will try to connect to |pending_service_|.
838 //
839 // If it succeeds, we'll end up back here, but with |service|
840 // pointing at the same service as |pending_service_|.
841 //
842 // If it fails, we'll process things in HandleDisconnect.
843 //
844 // So we leave |pending_service_| untouched.
Ben Chanfad4a0b2012-04-18 15:49:59 -0700845 SLOG(WiFi, 2) << "WiFi " << link_name()
846 << " new current Endpoint "
Paul Stewart3c504012013-01-17 17:49:58 -0800847 << endpoint->bssid_string()
Ben Chanfad4a0b2012-04-18 15:49:59 -0700848 << " is not part of pending service "
Darin Petkov457728b2013-01-09 09:49:08 +0100849 << pending_service_->unique_name();
mukesh agrawal15908392011-11-16 18:29:25 +0000850
851 // Sanity check: if we didn't roam onto |pending_service_|, we
852 // should still be on |current_service_|.
853 if (service.get() != current_service_.get()) {
854 LOG(WARNING) << "WiFi " << link_name()
855 << " new current Endpoint "
Paul Stewart3c504012013-01-17 17:49:58 -0800856 << endpoint->bssid_string()
mukesh agrawal15908392011-11-16 18:29:25 +0000857 << " is neither part of pending service "
Darin Petkov457728b2013-01-09 09:49:08 +0100858 << pending_service_->unique_name()
mukesh agrawal15908392011-11-16 18:29:25 +0000859 << " nor part of current service "
Darin Petkov457728b2013-01-09 09:49:08 +0100860 << (current_service_ ?
861 current_service_->unique_name() :
mukesh agrawal15908392011-11-16 18:29:25 +0000862 "(NULL)");
863 // Although we didn't expect to get here, we should keep
864 // |current_service_| in sync with what supplicant has done.
865 current_service_ = service;
866 }
867 return;
868 }
869
870 if (pending_service_.get()) {
871 // We assume service.get() == pending_service_.get() here, because
872 // of the return in the previous if clause.
873 //
874 // Boring case: we've connected to the service we asked
875 // for. Simply update |current_service_| and |pending_service_|.
876 current_service_ = service;
Wade Guthrieb0def9f2013-07-12 13:49:18 -0700877 SetScanState(kScanConnected, scan_method_, __func__);
Wade Guthriedf6d61b2013-07-17 11:43:55 -0700878 SetPendingService(NULL);
mukesh agrawal15908392011-11-16 18:29:25 +0000879 return;
880 }
881
882 // |pending_service_| was NULL, so we weren't attempting to connect
883 // to a new Service. Sanity check that we're still on
884 // |current_service_|.
885 if (service.get() != current_service_.get()) {
886 LOG(WARNING)
887 << "WiFi " << link_name()
888 << " new current Endpoint "
Paul Stewart3c504012013-01-17 17:49:58 -0800889 << endpoint->bssid_string()
mukesh agrawal15908392011-11-16 18:29:25 +0000890 << (current_service_.get() ?
mukesh agrawal8a3188d2011-12-01 20:56:44 +0000891 StringPrintf(" is not part of current service %s",
Darin Petkov457728b2013-01-09 09:49:08 +0100892 current_service_->unique_name().c_str()) :
mukesh agrawal8a3188d2011-12-01 20:56:44 +0000893 " with no current service");
mukesh agrawal15908392011-11-16 18:29:25 +0000894 // We didn't expect to be here, but let's cope as well as we
895 // can. Update |current_service_| to keep it in sync with
896 // supplicant.
897 current_service_ = service;
Paul Stewartabbe2792012-07-15 07:50:35 -0700898
899 // If this service isn't already marked as actively connecting (likely,
900 // since this service is a bit of a surprise) set the service as
901 // associating.
902 if (!current_service_->IsConnecting()) {
903 current_service_->SetState(Service::kStateAssociating);
904 }
905
mukesh agrawal15908392011-11-16 18:29:25 +0000906 return;
907 }
908
909 // At this point, we know that |pending_service_| was NULL, and that
910 // we're still on |current_service_|. This is the most boring case
911 // of all, because there's no state to update here.
912 return;
mukesh agrawalb54601c2011-06-07 17:39:22 -0700913}
914
Paul Stewart835934a2012-12-06 19:27:09 -0800915string WiFi::FindNetworkRpcidForService(
916 const WiFiService *service, Error *error) {
917 ReverseServiceMap::const_iterator rpcid_it =
918 rpcid_by_service_.find(service);
919 if (rpcid_it == rpcid_by_service_.end()) {
920 const string error_message =
Darin Petkov457728b2013-01-09 09:49:08 +0100921 StringPrintf(
922 "WiFi %s cannot find supplicant network rpcid for service %s",
923 link_name().c_str(), service->unique_name().c_str());
Paul Stewart835934a2012-12-06 19:27:09 -0800924 // There are contexts where this is not an error, such as when a service
925 // is clearing whatever cached credentials may not exist.
926 SLOG(WiFi, 2) << error_message;
927 if (error) {
928 error->Populate(Error::kNotFound, error_message);
929 }
930 return "";
931 }
932
933 return rpcid_it->second;
934}
935
936bool WiFi::DisableNetworkForService(const WiFiService *service, Error *error) {
937 string rpcid = FindNetworkRpcidForService(service, error);
938 if (rpcid.empty()) {
939 // Error is already populated.
940 return false;
941 }
942
943 if (!DisableNetwork(rpcid)) {
944 const string error_message =
Darin Petkov457728b2013-01-09 09:49:08 +0100945 StringPrintf("WiFi %s cannot disable network for service %s: "
Paul Stewart835934a2012-12-06 19:27:09 -0800946 "DBus operation failed for rpcid %s.",
Darin Petkov457728b2013-01-09 09:49:08 +0100947 link_name().c_str(), service->unique_name().c_str(),
Paul Stewart835934a2012-12-06 19:27:09 -0800948 rpcid.c_str());
949 Error::PopulateAndLog(error, Error::kOperationFailed, error_message);
950
951 // Make sure that such errored networks are removed, so problems do not
952 // propogate to future connection attempts.
953 RemoveNetwork(rpcid);
954 rpcid_by_service_.erase(service);
955
956 return false;
957 }
958
959 return true;
960}
961
962bool WiFi::RemoveNetworkForService(const WiFiService *service, Error *error) {
963 string rpcid = FindNetworkRpcidForService(service, error);
964 if (rpcid.empty()) {
965 // Error is already populated.
966 return false;
967 }
968
969 // Erase the rpcid from our tables regardless of failure below, since even
970 // if in failure, we never want to use this network again.
971 rpcid_by_service_.erase(service);
972
973 // TODO(quiche): Reconsider giving up immediately. Maybe give
974 // wpa_supplicant some time to retry, first.
975 if (!RemoveNetwork(rpcid)) {
976 const string error_message =
Darin Petkov457728b2013-01-09 09:49:08 +0100977 StringPrintf("WiFi %s cannot remove network for service %s: "
Paul Stewart835934a2012-12-06 19:27:09 -0800978 "DBus operation failed for rpcid %s.",
Darin Petkov457728b2013-01-09 09:49:08 +0100979 link_name().c_str(), service->unique_name().c_str(),
Paul Stewart835934a2012-12-06 19:27:09 -0800980 rpcid.c_str());
981 Error::PopulateAndLog(error, Error::kOperationFailed, error_message);
982 return false;
983 }
984
985 return true;
986}
987
mukesh agrawalb4bc57d2011-12-07 01:07:47 +0000988void WiFi::BSSAddedTask(
989 const ::DBus::Path &path,
990 const map<string, ::DBus::Variant> &properties) {
mukesh agrawalb4bc57d2011-12-07 01:07:47 +0000991 // Note: we assume that BSSIDs are unique across endpoints. This
992 // means that if an AP reuses the same BSSID for multiple SSIDs, we
993 // lose.
mukesh agrawalb20776f2012-02-10 16:00:36 -0800994 WiFiEndpointRefPtr endpoint(
995 new WiFiEndpoint(proxy_factory_, this, path, properties));
Wade Guthrie592ecd52012-11-12 13:12:30 -0800996 SLOG(WiFi, 1) << "Found endpoint. "
997 << "RPC path: " << path << ", "
Darin Petkov50cb78a2013-02-06 16:17:49 +0100998 << LogSSID(endpoint->ssid_string()) << ", "
Wade Guthrie592ecd52012-11-12 13:12:30 -0800999 << "bssid: " << endpoint->bssid_string() << ", "
1000 << "signal: " << endpoint->signal_strength() << ", "
1001 << "security: " << endpoint->security_mode() << ", "
1002 << "frequency: " << endpoint->frequency();
mukesh agrawalb4bc57d2011-12-07 01:07:47 +00001003
1004 if (endpoint->ssid_string().empty()) {
1005 // Don't bother trying to find or create a Service for an Endpoint
1006 // without an SSID. We wouldn't be able to connect to it anyway.
1007 return;
1008 }
1009
mukesh agrawalb3857612012-01-18 16:23:29 -08001010 if (endpoint->ssid()[0] == 0) {
1011 // Assume that an SSID starting with NULL is bogus/misconfigured,
1012 // and filter it out.
1013 return;
1014 }
1015
Paul Stewart3c504012013-01-17 17:49:58 -08001016 provider_->OnEndpointAdded(endpoint);
mukesh agrawalb4bc57d2011-12-07 01:07:47 +00001017
mukesh agrawale9adda12012-02-09 18:33:48 -08001018 // Do this last, to maintain the invariant that any Endpoint we
1019 // know about has a corresponding Service.
mukesh agrawalb20776f2012-02-10 16:00:36 -08001020 //
1021 // TODO(quiche): Write test to verify correct behavior in the case
1022 // where we get multiple BSSAdded events for a single endpoint.
1023 // (Old Endpoint's refcount should fall to zero, and old Endpoint
1024 // should be destroyed.)
mukesh agrawale9adda12012-02-09 18:33:48 -08001025 endpoint_by_rpcid_[path] = endpoint;
mukesh agrawalb20776f2012-02-10 16:00:36 -08001026 endpoint->Start();
mukesh agrawalb4bc57d2011-12-07 01:07:47 +00001027}
1028
1029void WiFi::BSSRemovedTask(const ::DBus::Path &path) {
1030 EndpointMap::iterator i = endpoint_by_rpcid_.find(path);
1031 if (i == endpoint_by_rpcid_.end()) {
1032 LOG(WARNING) << "WiFi " << link_name()
1033 << " could not find BSS " << path
1034 << " to remove.";
1035 return;
1036 }
1037
1038 WiFiEndpointRefPtr endpoint = i->second;
1039 CHECK(endpoint);
1040 endpoint_by_rpcid_.erase(i);
1041
Paul Stewart3c504012013-01-17 17:49:58 -08001042 WiFiServiceRefPtr service = provider_->OnEndpointRemoved(endpoint);
1043 if (!service) {
1044 return;
1045 }
1046 Error unused_error;
1047 RemoveNetworkForService(service, &unused_error);
mukesh agrawalb4bc57d2011-12-07 01:07:47 +00001048
mukesh agrawal8a3188d2011-12-01 20:56:44 +00001049 bool disconnect_service = !service->HasEndpoints() &&
1050 (service->IsConnecting() || service->IsConnected());
mukesh agrawal8a3188d2011-12-01 20:56:44 +00001051
1052 if (disconnect_service) {
mukesh agrawaldc7b8442012-09-27 13:48:14 -07001053 LOG(INFO) << "Disconnecting from service " << service->unique_name()
1054 << ": BSSRemoved";
mukesh agrawal8a3188d2011-12-01 20:56:44 +00001055 DisconnectFrom(service);
1056 }
mukesh agrawalb4bc57d2011-12-07 01:07:47 +00001057}
1058
Paul Stewartbc6e7392012-05-24 07:07:48 -07001059void WiFi::CertificationTask(
1060 const map<string, ::DBus::Variant> &properties) {
1061 if (!current_service_) {
1062 LOG(ERROR) << "WiFi " << link_name() << " " << __func__
1063 << " with no current service.";
1064 return;
1065 }
1066
Paul Stewart735eab52013-03-29 09:19:23 -07001067 string subject;
1068 uint32 depth;
1069 if (WPASupplicant::ExtractRemoteCertification(properties, &subject, &depth)) {
1070 current_service_->AddEAPCertification(subject, depth);
Paul Stewartbc6e7392012-05-24 07:07:48 -07001071 }
Paul Stewartbc6e7392012-05-24 07:07:48 -07001072}
1073
Paul Stewartdb0f9172012-11-30 16:48:09 -08001074void WiFi::EAPEventTask(const string &status, const string &parameter) {
Paul Stewartdb0f9172012-11-30 16:48:09 -08001075 if (!current_service_) {
1076 LOG(ERROR) << "WiFi " << link_name() << " " << __func__
1077 << " with no current service.";
1078 return;
1079 }
Paul Stewart735eab52013-03-29 09:19:23 -07001080 Service::ConnectFailure failure = Service::kFailureUnknown;
1081 eap_state_handler_->ParseStatus(status, parameter, &failure);
Paul Stewartdb0f9172012-11-30 16:48:09 -08001082 if (failure != Service::kFailureUnknown) {
Paul Stewart735eab52013-03-29 09:19:23 -07001083 // Avoid a reporting failure twice by resetting EAP state handler early.
1084 eap_state_handler_->Reset();
mukesh agrawald4dc0832013-03-25 14:38:26 -07001085 Error unused_error;
mukesh agrawald4dc0832013-03-25 14:38:26 -07001086 current_service_->DisconnectWithFailure(failure, &unused_error);
Paul Stewartdb0f9172012-11-30 16:48:09 -08001087 }
1088}
1089
mukesh agrawal15908392011-11-16 18:29:25 +00001090void WiFi::PropertiesChangedTask(
1091 const map<string, ::DBus::Variant> &properties) {
1092 // TODO(quiche): Handle changes in other properties (e.g. signal
1093 // strength).
1094
1095 // Note that order matters here. In particular, we want to process
1096 // changes in the current BSS before changes in state. This is so
1097 // that we update the state of the correct Endpoint/Service.
1098
1099 map<string, ::DBus::Variant>::const_iterator properties_it =
Paul Stewart0654ece2013-03-26 15:21:26 -07001100 properties.find(WPASupplicant::kInterfacePropertyCurrentBSS);
mukesh agrawal15908392011-11-16 18:29:25 +00001101 if (properties_it != properties.end()) {
1102 CurrentBSSChanged(properties_it->second.reader().get_path());
1103 }
1104
Paul Stewart0654ece2013-03-26 15:21:26 -07001105 properties_it = properties.find(WPASupplicant::kInterfacePropertyState);
mukesh agrawal15908392011-11-16 18:29:25 +00001106 if (properties_it != properties.end()) {
1107 StateChanged(properties_it->second.reader().get_string());
1108 }
1109}
1110
mukesh agrawaldc42bb32011-07-28 10:40:26 -07001111void WiFi::ScanDoneTask() {
Ben Chanfad4a0b2012-04-18 15:49:59 -07001112 SLOG(WiFi, 2) << __func__ << " need_bss_flush_ " << need_bss_flush_;
Wade Guthrie5a4e2ef2013-04-30 12:51:39 -07001113 if (scan_session_) {
1114 // Post |ProgressiveScanTask| so it runs after any |BSSAddedTask|s that have
1115 // been posted. This allows connections on new BSSes to be started before
1116 // we decide whether to abort the progressive scan or continue scanning.
1117 dispatcher()->PostTask(
1118 Bind(&WiFi::ProgressiveScanTask, weak_ptr_factory_.GetWeakPtr()));
1119 } else {
Wade Guthrie0cf3c982013-05-29 09:11:35 -07001120 // Post |UpdateScanStateAfterScanDone| so it runs after any |BSSAddedTask|s
1121 // that have been posted. This allows connections on new BSSes to be
1122 // started before we decide whether the scan was fruitful.
1123 dispatcher()->PostTask(Bind(&WiFi::UpdateScanStateAfterScanDone,
1124 weak_ptr_factory_.GetWeakPtr()));
Wade Guthrie5a4e2ef2013-04-30 12:51:39 -07001125 }
mukesh agrawal5c05b292012-03-07 10:12:52 -08001126 if (need_bss_flush_) {
1127 CHECK(supplicant_interface_proxy_ != NULL);
1128 // Compute |max_age| relative to |resumed_at_|, to account for the
1129 // time taken to scan.
1130 struct timeval now;
1131 uint32_t max_age;
1132 time_->GetTimeMonotonic(&now);
1133 max_age = kMaxBSSResumeAgeSeconds + (now.tv_sec - resumed_at_.tv_sec);
1134 supplicant_interface_proxy_->FlushBSS(max_age);
1135 need_bss_flush_ = false;
1136 }
mukesh agrawalb66c6462012-05-07 11:45:25 -07001137 StartScanTimer();
mukesh agrawalb54601c2011-06-07 17:39:22 -07001138}
1139
Wade Guthrie0cf3c982013-05-29 09:11:35 -07001140void WiFi::UpdateScanStateAfterScanDone() {
Wade Guthriedf6d61b2013-07-17 11:43:55 -07001141 if (scan_state_ != kScanIdle && IsIdle()) {
1142 SetScanState(kScanFoundNothing, scan_method_, __func__);
Wade Guthrie0cf3c982013-05-29 09:11:35 -07001143 }
1144}
1145
mukesh agrawal32399322011-09-01 10:53:43 -07001146void WiFi::ScanTask() {
Ben Chanfad4a0b2012-04-18 15:49:59 -07001147 SLOG(WiFi, 2) << "WiFi " << link_name() << " scan requested.";
Paul Stewartfae4dae2012-09-13 07:43:32 -07001148 if (!enabled()) {
1149 SLOG(WiFi, 2) << "Ignoring scan request while device is not enabled.";
Wade Guthrieb0def9f2013-07-12 13:49:18 -07001150 SetScanState(kScanIdle, kScanMethodNone, __func__); // Probably redundant.
Paul Stewartfae4dae2012-09-13 07:43:32 -07001151 return;
1152 }
1153 if (!supplicant_present_ || !supplicant_interface_proxy_.get()) {
1154 SLOG(WiFi, 2) << "Ignoring scan request while supplicant is not present.";
Wade Guthrieb0def9f2013-07-12 13:49:18 -07001155 SetScanState(kScanIdle, kScanMethodNone, __func__);
Paul Stewartfae4dae2012-09-13 07:43:32 -07001156 return;
1157 }
Christopher Wileyc68c8672012-11-20 16:52:21 -08001158 if ((pending_service_.get() && pending_service_->IsConnecting()) ||
1159 (current_service_.get() && current_service_->IsConnecting())) {
1160 SLOG(WiFi, 2) << "Ignoring scan request while connecting to an AP.";
1161 return;
1162 }
Paul Stewarta41e38d2011-11-11 07:47:29 -08001163 map<string, DBus::Variant> scan_args;
Paul Stewart0654ece2013-03-26 15:21:26 -07001164 scan_args[WPASupplicant::kPropertyScanType].writer().
1165 append_string(WPASupplicant::kScanTypeActive);
Paul Stewartced6a0b2011-11-08 15:32:04 -08001166
Paul Stewart3c504012013-01-17 17:49:58 -08001167 ByteArrays hidden_ssids = provider_->GetHiddenSSIDList();
Paul Stewartced6a0b2011-11-08 15:32:04 -08001168 if (!hidden_ssids.empty()) {
Paul Stewart3c504012013-01-17 17:49:58 -08001169 // TODO(pstew): Devise a better method for time-sharing with SSIDs that do
1170 // not fit in.
Paul Stewart0654ece2013-03-26 15:21:26 -07001171 if (hidden_ssids.size() >= WPASupplicant::kScanMaxSSIDsPerScan) {
Paul Stewart3c504012013-01-17 17:49:58 -08001172 hidden_ssids.erase(
Paul Stewart0654ece2013-03-26 15:21:26 -07001173 hidden_ssids.begin() + WPASupplicant::kScanMaxSSIDsPerScan - 1,
Paul Stewart3c504012013-01-17 17:49:58 -08001174 hidden_ssids.end());
1175 }
1176 // Add Broadcast SSID, signified by an empty ByteArray. If we specify
1177 // SSIDs to wpa_supplicant, we need to explicitly specify the default
1178 // behavior of doing a broadcast probe.
1179 hidden_ssids.push_back(ByteArray());
1180
Paul Stewart0654ece2013-03-26 15:21:26 -07001181 scan_args[WPASupplicant::kPropertyScanSSIDs] =
Paul Stewartced6a0b2011-11-08 15:32:04 -08001182 DBusAdaptor::ByteArraysToVariant(hidden_ssids);
1183 }
1184
Gaurav Shah10109f22011-11-11 20:16:22 -08001185 try {
Wade Guthrie0cf3c982013-05-29 09:11:35 -07001186 // Only set the scan state/method if we are starting a full scan from
1187 // scratch. Keep the existing method if this is a failover from a
1188 // progressive scan.
1189 if (scan_state_ != kScanScanning) {
Wade Guthrieb0def9f2013-07-12 13:49:18 -07001190 SetScanState(kScanScanning, kScanMethodFull, __func__);
Wade Guthrie0cf3c982013-05-29 09:11:35 -07001191 }
Wade Guthrieb0def9f2013-07-12 13:49:18 -07001192 supplicant_interface_proxy_->Scan(scan_args);
Ben Chan80326f32012-05-04 17:51:32 -07001193 } catch (const DBus::Error &e) { // NOLINT
Darin Petkov2b8e44e2012-06-25 15:13:26 +02001194 // A scan may fail if, for example, the wpa_supplicant vanishing
1195 // notification is posted after this task has already started running.
1196 LOG(WARNING) << "Scan failed: " << e.what();
Gaurav Shah10109f22011-11-11 20:16:22 -08001197 }
mukesh agrawal32399322011-09-01 10:53:43 -07001198}
1199
Wade Guthrie5a4e2ef2013-04-30 12:51:39 -07001200void WiFi::ProgressiveScanTask() {
1201 SLOG(WiFi, 2) << __func__ << " - scan requested for " << link_name();
1202 if (!enabled()) {
1203 LOG(INFO) << "Ignoring scan request while device is not enabled.";
Wade Guthrieb0def9f2013-07-12 13:49:18 -07001204 SetScanState(kScanIdle, kScanMethodNone, __func__); // Probably redundant.
Wade Guthrie5a4e2ef2013-04-30 12:51:39 -07001205 return;
1206 }
1207 if (!scan_session_) {
1208 SLOG(WiFi, 2) << "No scan session -- returning";
Wade Guthrieb0def9f2013-07-12 13:49:18 -07001209 SetScanState(kScanIdle, kScanMethodNone, __func__);
Wade Guthrie5a4e2ef2013-04-30 12:51:39 -07001210 return;
1211 }
Wade Guthrieb0def9f2013-07-12 13:49:18 -07001212 // TODO(wdg): We don't currently support progressive background scans. If
1213 // we did, we couldn't bail out, here, if we're connected. Progressive scan
1214 // state will have to be modified to include whether there was a connection
1215 // when the scan started. Then, this code would only bail out if we didn't
1216 // start with a connection but one exists at this point.
Wade Guthrie5a4e2ef2013-04-30 12:51:39 -07001217 if (!IsIdle()) {
1218 SLOG(WiFi, 2) << "Ignoring scan request while connecting to an AP.";
1219 scan_session_.reset();
Wade Guthrie5a4e2ef2013-04-30 12:51:39 -07001220 return;
1221 }
1222 if (scan_session_->HasMoreFrequencies()) {
1223 SLOG(WiFi, 2) << "Initiating a scan -- returning";
Wade Guthrieb0def9f2013-07-12 13:49:18 -07001224 SetScanState(kScanScanning, kScanMethodProgressive, __func__);
Wade Guthrie5a4e2ef2013-04-30 12:51:39 -07001225 // After us initiating a scan, supplicant will gather the scan results and
1226 // send us zero or more |BSSAdded| events followed by a |ScanDone|.
1227 scan_session_->InitiateScan();
1228 return;
1229 }
1230 LOG(ERROR) << "A complete progressive scan turned-up nothing -- "
1231 << "do a regular scan";
1232 scan_session_.reset();
Wade Guthrieb0def9f2013-07-12 13:49:18 -07001233 SetScanState(kScanScanning, kScanMethodProgressiveFinishedToFull, __func__);
Wade Guthrie5a4e2ef2013-04-30 12:51:39 -07001234 Scan(kFullScan, NULL);
1235}
1236
1237void WiFi::OnFailedProgressiveScan() {
1238 LOG(ERROR) << "Couldn't issue a scan on " << link_name()
1239 << " -- doing a regular scan";
1240 scan_session_.reset();
Wade Guthrieb0def9f2013-07-12 13:49:18 -07001241 SetScanState(kScanScanning, kScanMethodProgressiveErrorToFull, __func__);
Wade Guthrie5a4e2ef2013-04-30 12:51:39 -07001242 Scan(kFullScan, NULL);
1243}
1244
Albert Chaulk0e1cdea2013-02-27 15:32:55 -08001245string WiFi::GetServiceLeaseName(const WiFiService &service) {
1246 return service.GetStorageIdentifier();
1247}
1248
1249void WiFi::DestroyServiceLease(const WiFiService &service) {
1250 DestroyIPConfigLease(GetServiceLeaseName(service));
1251}
1252
mukesh agrawal15908392011-11-16 18:29:25 +00001253void WiFi::StateChanged(const string &new_state) {
1254 const string old_state = supplicant_state_;
mukesh agrawal7ec71312011-11-10 02:08:26 +00001255 supplicant_state_ = new_state;
mukesh agrawal15908392011-11-16 18:29:25 +00001256 LOG(INFO) << "WiFi " << link_name() << " " << __func__ << " "
1257 << old_state << " -> " << new_state;
1258
1259 WiFiService *affected_service;
1260 // Identify the service to which the state change applies. If
1261 // |pending_service_| is non-NULL, then the state change applies to
1262 // |pending_service_|. Otherwise, it applies to |current_service_|.
1263 //
1264 // This policy is driven by the fact that the |pending_service_|
1265 // doesn't become the |current_service_| until wpa_supplicant
1266 // reports a CurrentBSS change to the |pending_service_|. And the
mukesh agrawalc01f3982012-01-24 13:48:39 -08001267 // CurrentBSS change won't be reported until the |pending_service_|
Paul Stewart0654ece2013-03-26 15:21:26 -07001268 // reaches the WPASupplicant::kInterfaceStateCompleted state.
mukesh agrawal15908392011-11-16 18:29:25 +00001269 affected_service =
1270 pending_service_.get() ? pending_service_.get() : current_service_.get();
1271 if (!affected_service) {
Ben Chanfad4a0b2012-04-18 15:49:59 -07001272 SLOG(WiFi, 2) << "WiFi " << link_name() << " " << __func__
1273 << " with no service";
mukesh agrawal15908392011-11-16 18:29:25 +00001274 return;
1275 }
1276
Paul Stewart0654ece2013-03-26 15:21:26 -07001277 if (new_state == WPASupplicant::kInterfaceStateCompleted) {
Paul Stewart44663922012-07-30 11:03:03 -07001278 if (affected_service->IsConnected()) {
1279 StopReconnectTimer();
Christopher Wiley5519e9e2013-01-08 16:55:56 -08001280 EnableHighBitrates();
Christopher Wiley8f81e2a2012-10-17 16:51:32 -07001281 } else if (has_already_completed_) {
1282 LOG(INFO) << link_name() << " L3 configuration already started.";
Paul Stewart44663922012-07-30 11:03:03 -07001283 } else if (AcquireIPConfigWithLeaseName(
Albert Chaulk0e1cdea2013-02-27 15:32:55 -08001284 GetServiceLeaseName(*affected_service))) {
Paul Stewartd408fdf2012-05-07 17:15:57 -07001285 LOG(INFO) << link_name() << " is up; started L3 configuration.";
mukesh agrawalc01f3982012-01-24 13:48:39 -08001286 affected_service->SetState(Service::kStateConfiguring);
Paul Stewartf6f96482013-07-12 12:49:15 -07001287 if (affected_service->IsSecurityMatch(flimflam::kSecurityWep)) {
1288 // With the overwhelming majority of WEP networks, we cannot assume
1289 // our credentials are correct just because we have successfully
1290 // connected. It is more useful to track received data as the L3
1291 // configuration proceeds to see if we can decrypt anything.
1292 receive_byte_count_at_connect_ = GetReceiveByteCount();
1293 } else {
1294 affected_service->ResetSuspectedCredentialFailures();
1295 }
mukesh agrawalc01f3982012-01-24 13:48:39 -08001296 } else {
1297 LOG(ERROR) << "Unable to acquire DHCP config.";
1298 }
Christopher Wiley8f81e2a2012-10-17 16:51:32 -07001299 has_already_completed_ = true;
Paul Stewart0654ece2013-03-26 15:21:26 -07001300 } else if (new_state == WPASupplicant::kInterfaceStateAssociated) {
mukesh agrawal15908392011-11-16 18:29:25 +00001301 affected_service->SetState(Service::kStateAssociating);
Paul Stewart0654ece2013-03-26 15:21:26 -07001302 } else if (new_state == WPASupplicant::kInterfaceStateAuthenticating ||
1303 new_state == WPASupplicant::kInterfaceStateAssociating ||
1304 new_state == WPASupplicant::kInterfaceState4WayHandshake ||
1305 new_state == WPASupplicant::kInterfaceStateGroupHandshake) {
mukesh agrawal15908392011-11-16 18:29:25 +00001306 // Ignore transitions into these states from Completed, to avoid
1307 // bothering the user when roaming, or re-keying.
Paul Stewart0654ece2013-03-26 15:21:26 -07001308 if (old_state != WPASupplicant::kInterfaceStateCompleted)
mukesh agrawal15908392011-11-16 18:29:25 +00001309 affected_service->SetState(Service::kStateAssociating);
1310 // TOOD(quiche): On backwards transitions, we should probably set
1311 // a timeout for getting back into the completed state. At present,
1312 // we depend on wpa_supplicant eventually reporting that CurrentBSS
mukesh agrawal8a3188d2011-12-01 20:56:44 +00001313 // has changed. But there may be cases where that signal is not sent.
Paul Stewartee6b3d72013-07-12 16:07:51 -07001314 // (crbug.com/206208)
Paul Stewart0654ece2013-03-26 15:21:26 -07001315 } else if (new_state == WPASupplicant::kInterfaceStateDisconnected &&
Paul Stewart44663922012-07-30 11:03:03 -07001316 affected_service == current_service_ &&
1317 affected_service->IsConnected()) {
1318 // This means that wpa_supplicant failed in a re-connect attempt, but
1319 // may still be reconnecting. Give wpa_supplicant a limited amount of
1320 // time to transition out this condition by either connecting or changing
1321 // CurrentBSS.
1322 StartReconnectTimer();
mukesh agrawal15908392011-11-16 18:29:25 +00001323 } else {
1324 // Other transitions do not affect Service state.
1325 //
1326 // Note in particular that we ignore a State change into
1327 // kInterfaceStateDisconnected, in favor of observing the corresponding
1328 // change in CurrentBSS.
1329 }
mukesh agrawal7ec71312011-11-10 02:08:26 +00001330}
1331
Paul Stewart1369c2b2013-01-11 05:41:26 -08001332bool WiFi::SuspectCredentials(
Paul Stewartbca08f82013-07-09 16:32:37 -07001333 WiFiServiceRefPtr service, Service::ConnectFailure *failure) const {
1334 if (service->IsSecurityMatch(flimflam::kSecurityPsk)) {
Paul Stewart0654ece2013-03-26 15:21:26 -07001335 if (supplicant_state_ == WPASupplicant::kInterfaceState4WayHandshake &&
Paul Stewartbca08f82013-07-09 16:32:37 -07001336 service->AddSuspectedCredentialFailure()) {
Paul Stewart1369c2b2013-01-11 05:41:26 -08001337 if (failure) {
1338 *failure = Service::kFailureBadPassphrase;
1339 }
1340 return true;
1341 }
Paul Stewartbca08f82013-07-09 16:32:37 -07001342 } else if (service->IsSecurityMatch(flimflam::kSecurity8021x)) {
Paul Stewart735eab52013-03-29 09:19:23 -07001343 if (eap_state_handler_->is_eap_in_progress() &&
Paul Stewartbca08f82013-07-09 16:32:37 -07001344 service->AddSuspectedCredentialFailure()) {
Paul Stewart1369c2b2013-01-11 05:41:26 -08001345 if (failure) {
1346 *failure = Service::kFailureEAPAuthentication;
1347 }
1348 return true;
1349 }
mukesh agrawalcf24a242012-05-21 16:46:11 -07001350 }
1351
Paul Stewart1369c2b2013-01-11 05:41:26 -08001352 return false;
mukesh agrawalcf24a242012-05-21 16:46:11 -07001353}
1354
mukesh agrawal16bc1b82012-02-09 18:38:26 -08001355// static
1356bool WiFi::SanitizeSSID(string *ssid) {
1357 CHECK(ssid);
1358
1359 size_t ssid_len = ssid->length();
1360 size_t i;
1361 bool changed = false;
1362
Gary Morainac1bdb42012-02-16 17:42:29 -08001363 for (i = 0; i < ssid_len; ++i) {
mukesh agrawal16bc1b82012-02-09 18:38:26 -08001364 if (!g_ascii_isprint((*ssid)[i])) {
1365 (*ssid)[i] = '?';
1366 changed = true;
1367 }
1368 }
1369
1370 return changed;
1371}
1372
Darin Petkov50cb78a2013-02-06 16:17:49 +01001373// static
1374string WiFi::LogSSID(const string &ssid) {
1375 string out;
1376 for (string::const_iterator it = ssid.begin(); it != ssid.end(); ++it) {
1377 // Replace '[' and ']' (in addition to non-printable characters) so that
1378 // it's easy to match the right substring through a non-greedy regex.
1379 if (*it == '[' || *it == ']' || !g_ascii_isprint(*it)) {
1380 base::StringAppendF(&out, "\\x%02x", *it);
1381 } else {
1382 out += *it;
1383 }
1384 }
1385 return StringPrintf("[SSID=%s]", out.c_str());
1386}
1387
Paul Stewart3c508e12012-08-09 11:40:06 -07001388void WiFi::OnLinkMonitorFailure() {
1389 // If we have never found the gateway, let's be conservative and not
1390 // do anything, in case this network topology does not have a gateway.
1391 if (!link_monitor()->IsGatewayFound()) {
1392 LOG(INFO) << "In " << __func__ << "(): "
1393 << "Skipping reassociate since gateway was never found.";
1394 return;
1395 }
1396
1397 if (!supplicant_present_) {
1398 LOG(ERROR) << "In " << __func__ << "(): "
1399 << "wpa_supplicant is not present. Cannot reassociate.";
1400 return;
1401 }
1402
1403 try {
Christopher Wileye0b2a012012-10-31 13:11:27 -07001404 // This will force a transition out of connected, if we are actually
1405 // connected.
Paul Stewart3c508e12012-08-09 11:40:06 -07001406 supplicant_interface_proxy_->Reassociate();
Christopher Wileye0b2a012012-10-31 13:11:27 -07001407 // If we don't eventually get a transition back into a connected state,
1408 // there is something wrong.
1409 StartReconnectTimer();
Paul Stewart3c508e12012-08-09 11:40:06 -07001410 LOG(INFO) << "In " << __func__ << "(): Called Reassociate().";
1411 } catch (const DBus::Error &e) { // NOLINT
1412 LOG(ERROR) << "In " << __func__ << "(): failed to call Reassociate().";
1413 return;
1414 }
1415}
1416
Arman Ugurayed8e6102012-11-29 14:47:20 -08001417bool WiFi::ShouldUseArpGateway() const {
1418 return true;
1419}
1420
Paul Stewart3c504012013-01-17 17:49:58 -08001421void WiFi::DisassociateFromService(const WiFiServiceRefPtr &service) {
1422 DisconnectFrom(service);
1423 if (service == selected_service()) {
1424 DropConnection();
1425 }
1426 Error unused_error;
1427 RemoveNetworkForService(service, &unused_error);
1428}
1429
Gaurav Shah6d2c72d2012-10-16 16:30:44 -07001430vector<GeolocationInfo> WiFi::GetGeolocationObjects() const {
1431 vector<GeolocationInfo> objects;
1432 for (EndpointMap::const_iterator it = endpoint_by_rpcid_.begin();
1433 it != endpoint_by_rpcid_.end();
1434 ++it) {
1435 GeolocationInfo geoinfo;
1436 WiFiEndpointRefPtr endpoint = it->second;
1437 geoinfo.AddField(kGeoMacAddressProperty, endpoint->bssid_string());
1438 geoinfo.AddField(kGeoSignalStrengthProperty,
1439 StringPrintf("%d", endpoint->signal_strength()));
1440 geoinfo.AddField(
1441 kGeoChannelProperty,
1442 StringPrintf("%d",
1443 Metrics::WiFiFrequencyToChannel(endpoint->frequency())));
Paul Stewartee6b3d72013-07-12 16:07:51 -07001444 // TODO(gauravsh): Include age field. crbug.com/217554
Gaurav Shah6d2c72d2012-10-16 16:30:44 -07001445 objects.push_back(geoinfo);
1446 }
1447 return objects;
1448}
1449
mukesh agrawal4d0401c2012-01-06 16:05:31 -08001450void WiFi::HelpRegisterDerivedInt32(
1451 PropertyStore *store,
1452 const string &name,
1453 int32(WiFi::*get)(Error *error),
mukesh agrawalbebf1b82013-04-23 15:06:33 -07001454 bool(WiFi::*set)(const int32 &value, Error *error)) {
mukesh agrawal4d0401c2012-01-06 16:05:31 -08001455 store->RegisterDerivedInt32(
1456 name,
1457 Int32Accessor(new CustomAccessor<WiFi, int32>(this, get, set)));
1458}
1459
mukesh agrawal4d0401c2012-01-06 16:05:31 -08001460void WiFi::HelpRegisterDerivedUint16(
1461 PropertyStore *store,
1462 const string &name,
1463 uint16(WiFi::*get)(Error *error),
mukesh agrawalbebf1b82013-04-23 15:06:33 -07001464 bool(WiFi::*set)(const uint16 &value, Error *error)) {
mukesh agrawal4d0401c2012-01-06 16:05:31 -08001465 store->RegisterDerivedUint16(
1466 name,
1467 Uint16Accessor(new CustomAccessor<WiFi, uint16>(this, get, set)));
1468}
1469
Wade Guthrie0cf3c982013-05-29 09:11:35 -07001470void WiFi::HelpRegisterConstDerivedBool(
1471 PropertyStore *store,
1472 const string &name,
1473 bool(WiFi::*get)(Error *error)) {
1474 store->RegisterDerivedBool(
1475 name,
1476 BoolAccessor(new CustomAccessor<WiFi, bool>(this, get, NULL)));
1477}
1478
mukesh agrawal2f9df4e2012-08-08 12:29:20 -07001479void WiFi::OnAfterResume() {
mukesh agrawal5c05b292012-03-07 10:12:52 -08001480 LOG(INFO) << __func__;
mukesh agrawal2f9df4e2012-08-08 12:29:20 -07001481 Device::OnAfterResume(); // May refresh ipconfig_
mukesh agrawal5c05b292012-03-07 10:12:52 -08001482
mukesh agrawal2f9df4e2012-08-08 12:29:20 -07001483 // We want to flush the BSS cache, but we don't want to conflict
Wade Guthrie0cf3c982013-05-29 09:11:35 -07001484 // with an active connection attempt. So record the need to flush,
1485 // and take care of flushing when the next scan completes.
mukesh agrawal2f9df4e2012-08-08 12:29:20 -07001486 //
1487 // Note that supplicant will automatically expire old cache
1488 // entries (after, e.g., a BSS is not found in two consecutive
1489 // scans). However, our explicit flush accelerates re-association
1490 // in cases where a BSS disappeared while we were asleep. (See,
1491 // e.g. WiFiRoaming.005SuspendRoam.)
1492 time_->GetTimeMonotonic(&resumed_at_);
1493 need_bss_flush_ = true;
1494
Wade Guthrie0cf3c982013-05-29 09:11:35 -07001495 // Abort any current scan (at the shill-level; let any request that's
1496 // already gone out finish) since we don't know when it started.
1497 AbortScan();
1498
1499 if (IsIdle()) {
mukesh agrawal2f9df4e2012-08-08 12:29:20 -07001500 // Not scanning/connecting/connected, so let's get things rolling.
Wade Guthrie68d41092013-04-02 12:56:02 -07001501 Scan(kProgressiveScan, NULL);
Wade Guthrie0cf3c982013-05-29 09:11:35 -07001502 RestartFastScanAttempts();
mukesh agrawal2f9df4e2012-08-08 12:29:20 -07001503 } else {
1504 SLOG(WiFi, 1) << __func__
Wade Guthrie0cf3c982013-05-29 09:11:35 -07001505 << " skipping scan, already connecting or connected.";
Gary Morainac1bdb42012-02-16 17:42:29 -08001506 }
1507}
1508
Wade Guthrie0cf3c982013-05-29 09:11:35 -07001509void WiFi::AbortScan() {
1510 if (scan_session_) {
1511 scan_session_.reset();
1512 }
Wade Guthrieb0def9f2013-07-12 13:49:18 -07001513 SetScanState(kScanIdle, kScanMethodNone, __func__);
Wade Guthrie0cf3c982013-05-29 09:11:35 -07001514}
1515
Christopher Wiley5519e9e2013-01-08 16:55:56 -08001516void WiFi::OnConnected() {
1517 Device::OnConnected();
1518 EnableHighBitrates();
Paul Stewartf6f96482013-07-12 12:49:15 -07001519 if (current_service_ &&
1520 current_service_->IsSecurityMatch(flimflam::kSecurityWep)) {
1521 // With a WEP network, we are now reasonably certain the credentials are
1522 // correct, whereas with other network types we were able to determine
1523 // this earlier when the association process succeeded.
1524 current_service_->ResetSuspectedCredentialFailures();
1525 }
1526}
1527
1528void WiFi::OnIPConfigFailure() {
1529 if (!current_service_) {
1530 LOG(ERROR) << "WiFi " << link_name() << " " << __func__
1531 << " with no current service.";
1532 return;
1533 }
1534 if (current_service_->IsSecurityMatch(flimflam::kSecurityWep) &&
1535 GetReceiveByteCount() == receive_byte_count_at_connect_ &&
1536 current_service_->AddSuspectedCredentialFailure()) {
1537 // If we've connected to a WEP network and haven't successfully
1538 // decrypted any bytes at all during the configuration process,
1539 // it is fair to suspect that our credentials to this network
1540 // may not be correct.
1541 Error error;
1542 current_service_->DisconnectWithFailure(Service::kFailureBadPassphrase,
1543 &error);
1544 return;
1545 }
1546
1547 Device::OnIPConfigFailure();
Christopher Wiley5519e9e2013-01-08 16:55:56 -08001548}
1549
Paul Stewarte369ece2012-05-22 09:11:03 -07001550void WiFi::RestartFastScanAttempts() {
1551 fast_scans_remaining_ = kNumFastScanAttempts;
1552 StartScanTimer();
1553}
1554
mukesh agrawalb66c6462012-05-07 11:45:25 -07001555void WiFi::StartScanTimer() {
1556 if (scan_interval_seconds_ == 0) {
1557 StopScanTimer();
1558 return;
1559 }
1560 scan_timer_callback_.Reset(
1561 Bind(&WiFi::ScanTimerHandler, weak_ptr_factory_.GetWeakPtr()));
Paul Stewarte369ece2012-05-22 09:11:03 -07001562 // Repeat the first few scans after disconnect relatively quickly so we
1563 // have reasonable trust that no APs we are looking for are present.
1564 dispatcher()->PostDelayedTask(scan_timer_callback_.callback(),
1565 fast_scans_remaining_ > 0 ?
1566 kFastScanIntervalSeconds * 1000 : scan_interval_seconds_ * 1000);
mukesh agrawalb66c6462012-05-07 11:45:25 -07001567}
1568
1569void WiFi::StopScanTimer() {
1570 scan_timer_callback_.Cancel();
1571}
1572
1573void WiFi::ScanTimerHandler() {
1574 SLOG(WiFi, 2) << "WiFi Device " << link_name() << ": " << __func__;
Wade Guthrie0cf3c982013-05-29 09:11:35 -07001575 if (scan_state_ == kScanIdle && IsIdle()) {
Wade Guthrie68d41092013-04-02 12:56:02 -07001576 Scan(kProgressiveScan, NULL);
Paul Stewarte369ece2012-05-22 09:11:03 -07001577 if (fast_scans_remaining_ > 0) {
1578 --fast_scans_remaining_;
1579 }
mukesh agrawalb66c6462012-05-07 11:45:25 -07001580 }
1581 StartScanTimer();
1582}
1583
Paul Stewart2b05e622012-07-13 20:38:44 -07001584void WiFi::StartPendingTimer() {
1585 pending_timeout_callback_.Reset(
1586 Bind(&WiFi::PendingTimeoutHandler, weak_ptr_factory_.GetWeakPtr()));
1587 dispatcher()->PostDelayedTask(pending_timeout_callback_.callback(),
1588 kPendingTimeoutSeconds * 1000);
1589}
1590
1591void WiFi::StopPendingTimer() {
Paul Stewartbca08f82013-07-09 16:32:37 -07001592 SLOG(WiFi, 2) << "WiFi Device " << link_name() << ": " << __func__;
Paul Stewart2b05e622012-07-13 20:38:44 -07001593 pending_timeout_callback_.Cancel();
1594}
1595
1596void WiFi::SetPendingService(const WiFiServiceRefPtr &service) {
Paul Stewartff96a842012-08-13 15:59:10 -07001597 SLOG(WiFi, 2) << "WiFi " << link_name() << " setting pending service to "
Darin Petkov457728b2013-01-09 09:49:08 +01001598 << (service ? service->unique_name(): "NULL");
Paul Stewart2b05e622012-07-13 20:38:44 -07001599 if (service) {
Wade Guthriedf6d61b2013-07-17 11:43:55 -07001600 SetScanState(kScanConnecting, scan_method_, __func__);
Paul Stewart2b05e622012-07-13 20:38:44 -07001601 service->SetState(Service::kStateAssociating);
1602 StartPendingTimer();
Wade Guthriedf6d61b2013-07-17 11:43:55 -07001603 } else {
1604 // SetPendingService(NULL) is called in the following cases:
1605 // a) |ConnectTo|->|DisconnectFrom|. Connecting to a service, disconnect
1606 // the old service (scan_state_ == kScanTransitionToConnecting). No
1607 // state transition is needed here.
1608 // b) |HandleRoam|. Connected to a service, it's no longer pending
1609 // (scan_state_ == kScanIdle). No state transition is needed here.
1610 // c) |DisconnectFrom| and |HandleDisconnect|. Disconnected/disconnecting
1611 // from a service not during a scan (scan_state_ == kScanIdle). No
1612 // state transition is needed here.
1613 // d) |DisconnectFrom| and |HandleDisconnect|. Disconnected/disconnecting
1614 // from a service during a scan (scan_state_ == kScanScanning or
1615 // kScanConnecting). This is an odd case -- let's discard any
1616 // statistics we're gathering by transitioning directly into kScanIdle.
1617 if (scan_state_ == kScanScanning || scan_state_ == kScanConnecting) {
1618 SetScanState(kScanIdle, kScanMethodNone, __func__);
1619 }
1620 if (pending_service_) {
1621 StopPendingTimer();
1622 }
Paul Stewart2b05e622012-07-13 20:38:44 -07001623 }
1624 pending_service_ = service;
1625}
1626
1627void WiFi::PendingTimeoutHandler() {
mukesh agrawald4dc0832013-03-25 14:38:26 -07001628 Error unused_error;
Paul Stewart2b05e622012-07-13 20:38:44 -07001629 LOG(INFO) << "WiFi Device " << link_name() << ": " << __func__;
1630 CHECK(pending_service_);
Wade Guthriedf6d61b2013-07-17 11:43:55 -07001631 SetScanState(kScanFoundNothing, scan_method_, __func__);
mukesh agrawald4dc0832013-03-25 14:38:26 -07001632 pending_service_->DisconnectWithFailure(
1633 Service::kFailureOutOfRange, &unused_error);
Paul Stewart17d90652013-04-04 15:09:11 -07001634
1635 // A hidden service may have no endpoints, since wpa_supplicant
1636 // failed to attain a CurrentBSS. If so, the service has no
1637 // reference to |this| device and cannot call WiFi::DisconnectFrom()
1638 // to reset pending_service_. In this case, we must perform the
1639 // disconnect here ourselves.
1640 if (pending_service_) {
1641 CHECK(!pending_service_->HasEndpoints());
1642 LOG(INFO) << "Hidden service was not found.";
1643 DisconnectFrom(pending_service_);
1644 }
Paul Stewart2b05e622012-07-13 20:38:44 -07001645}
1646
Paul Stewart44663922012-07-30 11:03:03 -07001647void WiFi::StartReconnectTimer() {
Paul Stewart1aff7302012-08-04 20:04:47 -07001648 if (!reconnect_timeout_callback_.IsCancelled()) {
1649 LOG(INFO) << "WiFi Device " << link_name() << ": " << __func__
1650 << ": reconnect timer already running.";
1651 return;
1652 }
Paul Stewart44663922012-07-30 11:03:03 -07001653 LOG(INFO) << "WiFi Device " << link_name() << ": " << __func__;
1654 reconnect_timeout_callback_.Reset(
1655 Bind(&WiFi::ReconnectTimeoutHandler, weak_ptr_factory_.GetWeakPtr()));
1656 dispatcher()->PostDelayedTask(reconnect_timeout_callback_.callback(),
1657 kReconnectTimeoutSeconds * 1000);
1658}
1659
1660void WiFi::StopReconnectTimer() {
1661 SLOG(WiFi, 2) << "WiFi Device " << link_name() << ": " << __func__;
1662 reconnect_timeout_callback_.Cancel();
1663}
1664
1665void WiFi::ReconnectTimeoutHandler() {
1666 LOG(INFO) << "WiFi Device " << link_name() << ": " << __func__;
Paul Stewart1aff7302012-08-04 20:04:47 -07001667 reconnect_timeout_callback_.Cancel();
Paul Stewart44663922012-07-30 11:03:03 -07001668 CHECK(current_service_);
1669 current_service_->SetFailureSilent(Service::kFailureConnect);
1670 DisconnectFrom(current_service_);
1671}
1672
Darin Petkov2b8e44e2012-06-25 15:13:26 +02001673void WiFi::OnSupplicantAppear(const string &/*owner*/) {
1674 LOG(INFO) << "WPA supplicant appeared.";
1675 if (supplicant_present_) {
Darin Petkov9cd7ca12012-07-03 11:06:40 +02001676 // Restart the WiFi device if it's started already. This will reset the
1677 // state and connect the device to the new WPA supplicant instance.
1678 if (enabled()) {
1679 Restart();
1680 }
Darin Petkov2b8e44e2012-06-25 15:13:26 +02001681 return;
1682 }
1683 supplicant_present_ = true;
1684 ConnectToSupplicant();
1685}
1686
1687void WiFi::OnSupplicantVanish() {
1688 LOG(INFO) << "WPA supplicant vanished.";
1689 if (!supplicant_present_) {
1690 return;
1691 }
1692 supplicant_present_ = false;
1693 // Restart the WiFi device if it's started already. This will effectively
1694 // suspend the device until the WPA supplicant reappears.
1695 if (enabled()) {
1696 Restart();
1697 }
1698}
1699
Paul Stewart5581d072012-12-17 17:30:20 -08001700void WiFi::OnWiFiDebugScopeChanged(bool enabled) {
1701 SLOG(WiFi, 2) << "WiFi debug scope changed; enable is now " << enabled;
1702 if (!supplicant_process_proxy_.get()) {
Wade Guthrie0cf3c982013-05-29 09:11:35 -07001703 SLOG(WiFi, 2) << "Supplicant process proxy not present.";
Paul Stewart5581d072012-12-17 17:30:20 -08001704 return;
1705 }
1706 string current_level;
1707 try {
1708 current_level = supplicant_process_proxy_->GetDebugLevel();
1709 } catch (const DBus::Error &e) { // NOLINT
1710 LOG(ERROR) << __func__ << ": Failed to get wpa_supplicant debug level.";
1711 return;
1712 }
1713
Paul Stewart0654ece2013-03-26 15:21:26 -07001714 if (current_level != WPASupplicant::kDebugLevelInfo &&
1715 current_level != WPASupplicant::kDebugLevelDebug) {
Paul Stewart5581d072012-12-17 17:30:20 -08001716 SLOG(WiFi, 2) << "WiFi debug level is currently "
1717 << current_level
1718 << "; assuming that it is being controlled elsewhere.";
1719 return;
1720 }
Paul Stewart0654ece2013-03-26 15:21:26 -07001721 string new_level = enabled ? WPASupplicant::kDebugLevelDebug :
1722 WPASupplicant::kDebugLevelInfo;
Paul Stewart5581d072012-12-17 17:30:20 -08001723
1724 if (new_level == current_level) {
1725 SLOG(WiFi, 2) << "WiFi debug level is already the desired level "
1726 << current_level;
1727 return;
1728 }
1729
1730 try {
1731 supplicant_process_proxy_->SetDebugLevel(new_level);
1732 } catch (const DBus::Error &e) { // NOLINT
1733 LOG(ERROR) << __func__ << ": Failed to set wpa_supplicant debug level.";
1734 }
1735}
1736
Paul Stewarta47c3c62012-12-18 12:14:29 -08001737void WiFi::SetConnectionDebugging(bool enabled) {
1738 if (is_debugging_connection_ == enabled) {
1739 return;
1740 }
1741 OnWiFiDebugScopeChanged(
1742 enabled ||
1743 ScopeLogger::GetInstance()->IsScopeEnabled(ScopeLogger::kWiFi));
1744 is_debugging_connection_ = enabled;
1745}
1746
Darin Petkov2b8e44e2012-06-25 15:13:26 +02001747void WiFi::ConnectToSupplicant() {
1748 LOG(INFO) << link_name() << ": " << (enabled() ? "enabled" : "disabled")
1749 << " supplicant: "
1750 << (supplicant_present_ ? "present" : "absent")
1751 << " proxy: "
1752 << (supplicant_process_proxy_.get() ? "non-null" : "null");
1753 if (!enabled() || !supplicant_present_ || supplicant_process_proxy_.get()) {
1754 return;
1755 }
1756 supplicant_process_proxy_.reset(
1757 proxy_factory_->CreateSupplicantProcessProxy(
Paul Stewart0654ece2013-03-26 15:21:26 -07001758 WPASupplicant::kDBusPath, WPASupplicant::kDBusAddr));
Paul Stewart5581d072012-12-17 17:30:20 -08001759 OnWiFiDebugScopeChanged(
1760 ScopeLogger::GetInstance()->IsScopeEnabled(ScopeLogger::kWiFi));
Darin Petkov2b8e44e2012-06-25 15:13:26 +02001761 ::DBus::Path interface_path;
1762 try {
1763 map<string, DBus::Variant> create_interface_args;
Paul Stewart0654ece2013-03-26 15:21:26 -07001764 create_interface_args[WPASupplicant::kInterfacePropertyName].writer().
Darin Petkov2b8e44e2012-06-25 15:13:26 +02001765 append_string(link_name().c_str());
Paul Stewart0654ece2013-03-26 15:21:26 -07001766 create_interface_args[WPASupplicant::kInterfacePropertyDriver].writer().
1767 append_string(WPASupplicant::kDriverNL80211);
Darin Petkov2b8e44e2012-06-25 15:13:26 +02001768 create_interface_args[
Paul Stewart0654ece2013-03-26 15:21:26 -07001769 WPASupplicant::kInterfacePropertyConfigFile].writer().
Paul Stewart196f50f2013-03-27 18:02:11 -07001770 append_string(WPASupplicant::kSupplicantConfPath);
Darin Petkov2b8e44e2012-06-25 15:13:26 +02001771 interface_path =
1772 supplicant_process_proxy_->CreateInterface(create_interface_args);
1773 } catch (const DBus::Error &e) { // NOLINT
Paul Stewart0654ece2013-03-26 15:21:26 -07001774 if (!strcmp(e.name(), WPASupplicant::kErrorInterfaceExists)) {
Darin Petkov2b8e44e2012-06-25 15:13:26 +02001775 interface_path =
1776 supplicant_process_proxy_->GetInterface(link_name());
1777 // TODO(quiche): Is it okay to crash here, if device is missing?
1778 } else {
Paul Stewartb80c81c2012-06-28 13:05:45 -07001779 LOG(ERROR) << __func__ << ": Failed to create interface with supplicant.";
1780 return;
Darin Petkov2b8e44e2012-06-25 15:13:26 +02001781 }
1782 }
1783
1784 supplicant_interface_proxy_.reset(
1785 proxy_factory_->CreateSupplicantInterfaceProxy(
Paul Stewart0654ece2013-03-26 15:21:26 -07001786 this, interface_path, WPASupplicant::kDBusAddr));
Darin Petkov2b8e44e2012-06-25 15:13:26 +02001787
1788 RTNLHandler::GetInstance()->SetInterfaceFlags(interface_index(), IFF_UP,
1789 IFF_UP);
1790 // TODO(quiche) Set ApScan=1 and BSSExpireAge=190, like flimflam does?
1791
1792 // Clear out any networks that might previously have been configured
1793 // for this interface.
1794 supplicant_interface_proxy_->RemoveAllNetworks();
1795
1796 // Flush interface's BSS cache, so that we get BSSAdded signals for
1797 // all BSSes (not just new ones since the last scan).
1798 supplicant_interface_proxy_->FlushBSS(0);
1799
1800 try {
1801 // TODO(pstew): Disable fast_reauth until supplicant can properly deal
1802 // with RADIUS servers that respond strangely to such requests.
Paul Stewartee6b3d72013-07-12 16:07:51 -07001803 // crbug.com/208561
Darin Petkov2b8e44e2012-06-25 15:13:26 +02001804 supplicant_interface_proxy_->SetFastReauth(false);
1805 } catch (const DBus::Error &e) { // NOLINT
Christopher Wiley5519e9e2013-01-08 16:55:56 -08001806 LOG(ERROR) << "Failed to disable fast_reauth. "
1807 << "May be running an older version of wpa_supplicant.";
Darin Petkov2b8e44e2012-06-25 15:13:26 +02001808 }
1809
1810 try {
1811 // Helps with passing WiFiRomaing.001SSIDSwitchBack.
1812 supplicant_interface_proxy_->SetScanInterval(kRescanIntervalSeconds);
1813 } catch (const DBus::Error &e) { // NOLINT
Christopher Wiley5519e9e2013-01-08 16:55:56 -08001814 LOG(ERROR) << "Failed to set scan_interval. "
1815 << "May be running an older version of wpa_supplicant.";
1816 }
1817
1818 try {
1819 supplicant_interface_proxy_->SetDisableHighBitrates(true);
1820 } catch (const DBus::Error &e) { // NOLINT
1821 LOG(ERROR) << "Failed to disable high bitrates. "
1822 << "May be running an older version of wpa_supplicant.";
Darin Petkov2b8e44e2012-06-25 15:13:26 +02001823 }
1824
Wade Guthrie68d41092013-04-02 12:56:02 -07001825 Scan(kProgressiveScan, NULL);
Darin Petkov2b8e44e2012-06-25 15:13:26 +02001826 StartScanTimer();
1827}
1828
Christopher Wiley5519e9e2013-01-08 16:55:56 -08001829void WiFi::EnableHighBitrates() {
1830 LOG(INFO) << "Enabling high bitrates.";
1831 try {
1832 supplicant_interface_proxy_->EnableHighBitrates();
1833 } catch (const DBus::Error &e) { // NOLINT
1834 LOG(ERROR) << "exception while enabling high rates: " << e.what();
1835 }
1836}
1837
Darin Petkov2b8e44e2012-06-25 15:13:26 +02001838void WiFi::Restart() {
1839 LOG(INFO) << link_name() << " restarting.";
1840 WiFiRefPtr me = this; // Make sure we don't get destructed.
1841 // Go through the manager rather than starting and stopping the device
1842 // directly so that the device can be configured with the profile.
1843 manager()->DeregisterDevice(me);
1844 manager()->RegisterDevice(me);
1845}
1846
Wade Guthrie92d06362013-04-25 15:41:30 -07001847void WiFi::ConfigureScanFrequencies() {
1848 GetWiphyMessage get_wiphy;
1849 get_wiphy.attributes()->SetU32AttributeValue(NL80211_ATTR_IFINDEX,
1850 interface_index());
Wade Guthrie7347bf22013-04-30 11:21:51 -07001851 netlink_manager_->SendNl80211Message(
1852 &get_wiphy,
1853 Bind(&WiFi::OnNewWiphy, weak_ptr_factory_.GetWeakPtr()),
1854 Bind(&NetlinkManager::OnNetlinkMessageError));
Wade Guthrie92d06362013-04-25 15:41:30 -07001855}
1856
Wade Guthrie7347bf22013-04-30 11:21:51 -07001857void WiFi::OnNewWiphy(const Nl80211Message &nl80211_message) {
Wade Guthrie92d06362013-04-25 15:41:30 -07001858 // Verify NL80211_CMD_NEW_WIPHY
Wade Guthrie7347bf22013-04-30 11:21:51 -07001859 if (nl80211_message.command() != NewWiphyMessage::kCommand) {
Wade Guthrie92d06362013-04-25 15:41:30 -07001860 LOG(ERROR) << "Received unexpected command:"
Wade Guthrie7347bf22013-04-30 11:21:51 -07001861 << nl80211_message.command();
Wade Guthrie92d06362013-04-25 15:41:30 -07001862 return;
1863 }
1864
1865 // The attributes, for this message, are complicated.
1866 // NL80211_ATTR_BANDS contains an array of bands...
1867 AttributeListConstRefPtr wiphy_bands;
Wade Guthrie7347bf22013-04-30 11:21:51 -07001868 if (!nl80211_message.const_attributes()->ConstGetNestedAttributeList(
Wade Guthrie92d06362013-04-25 15:41:30 -07001869 NL80211_ATTR_WIPHY_BANDS, &wiphy_bands)) {
1870 LOG(ERROR) << "NL80211_CMD_NEW_WIPHY had no NL80211_ATTR_WIPHY_BANDS";
1871 return;
1872 }
1873
1874 AttributeIdIterator band_iter(*wiphy_bands);
1875 for (; !band_iter.AtEnd(); band_iter.Advance()) {
1876 AttributeListConstRefPtr wiphy_band;
1877 if (!wiphy_bands->ConstGetNestedAttributeList(band_iter.GetId(),
1878 &wiphy_band)) {
1879 LOG(WARNING) << "WiFi band " << band_iter.GetId() << " not found";
1880 continue;
1881 }
1882
1883 // ...Each band has a FREQS attribute...
1884 AttributeListConstRefPtr frequencies;
1885 if (!wiphy_band->ConstGetNestedAttributeList(NL80211_BAND_ATTR_FREQS,
1886 &frequencies)) {
1887 LOG(ERROR) << "BAND " << band_iter.GetId()
1888 << " had no 'frequencies' attribute";
1889 continue;
1890 }
1891
1892 // ...And each FREQS attribute contains an array of information about the
1893 // frequency...
1894 AttributeIdIterator freq_iter(*frequencies);
1895 for (; !freq_iter.AtEnd(); freq_iter.Advance()) {
1896 AttributeListConstRefPtr frequency;
1897 if (frequencies->ConstGetNestedAttributeList(freq_iter.GetId(),
1898 &frequency)) {
1899 // ...Including the frequency, itself (the part we want).
1900 uint32_t frequency_value = 0;
1901 if (frequency->GetU32AttributeValue(NL80211_FREQUENCY_ATTR_FREQ,
1902 &frequency_value)) {
Wade Guthrie2edd58b2013-05-23 11:16:08 -07001903 SLOG(WiFi, 7) << "Found frequency[" << freq_iter.GetId()
Wade Guthrie92d06362013-04-25 15:41:30 -07001904 << "] = " << frequency_value;
1905 all_scan_frequencies_.insert(frequency_value);
1906 }
1907 }
1908 }
1909 }
1910}
1911
Wade Guthrie0cf3c982013-05-29 09:11:35 -07001912bool WiFi::GetScanPending(Error */* error */) {
1913 return scan_state_ == kScanScanning;
1914}
1915
Wade Guthrieb0def9f2013-07-12 13:49:18 -07001916void WiFi::SetScanState(ScanState new_state,
1917 ScanMethod new_method,
1918 const char *reason) {
Wade Guthrie0cf3c982013-05-29 09:11:35 -07001919 if (new_state == kScanIdle)
1920 new_method = kScanMethodNone;
Wade Guthrieb9e0ee72013-05-31 09:23:30 -07001921 if (new_state == kScanConnected) {
1922 // The scan method shouldn't be changed by the connection process, so
1923 // we'll put a CHECK, here, to verify. NOTE: this assumption is also
1924 // enforced by the parameters to the call to |ReportScanResultToUma|.
1925 CHECK(new_method == scan_method_);
1926 }
Wade Guthrie0cf3c982013-05-29 09:11:35 -07001927
1928 int log_level = 6;
1929 bool state_changed = true;
1930 bool is_terminal_state = false;
1931 if (new_state == scan_state_ && new_method == scan_method_) {
1932 log_level = 7;
1933 state_changed = false;
1934 } else if (new_state == kScanConnected || new_state == kScanFoundNothing) {
1935 // These 'terminal' states are slightly more interesting than the
1936 // intermediate states.
1937 log_level = 5;
1938 is_terminal_state = true;
1939 }
1940
1941 base::TimeDelta elapsed_time;
1942 if (new_state == kScanScanning) {
1943 if (!scan_timer_.Start()) {
1944 LOG(ERROR) << "Scan start unreliable";
1945 }
1946 } else {
1947 if (!scan_timer_.GetElapsedTime(&elapsed_time)) {
1948 LOG(ERROR) << "Scan time unreliable";
1949 }
1950 }
Wade Guthrieb0def9f2013-07-12 13:49:18 -07001951 SLOG(WiFi, log_level) << (reason ? reason : "<unknown>")
1952 << " - " << link_name()
Wade Guthrie0cf3c982013-05-29 09:11:35 -07001953 << ": Scan state: "
1954 << ScanStateString(scan_state_, scan_method_)
1955 << " -> " << ScanStateString(new_state, new_method)
1956 << " @ " << elapsed_time.InMillisecondsF()
1957 << " ms into scan.";
1958 if (!state_changed)
1959 return;
1960
1961 // Actually change the state.
1962 ScanState old_state = scan_state_;
Wade Guthrieb9e0ee72013-05-31 09:23:30 -07001963 ScanMethod old_method = scan_method_;
Wade Guthrie0cf3c982013-05-29 09:11:35 -07001964 scan_state_ = new_state;
1965 scan_method_ = new_method;
1966 if (new_state == kScanScanning || old_state == kScanScanning) {
1967 Error error;
1968 adaptor()->EmitBoolChanged(flimflam::kScanningProperty,
1969 GetScanPending(&error));
1970 }
Wade Guthrie44f290d2013-05-28 10:16:25 -07001971 switch (new_state) {
1972 case kScanIdle:
1973 metrics()->ResetScanTimer(interface_index());
Wade Guthriedf6d61b2013-07-17 11:43:55 -07001974 metrics()->ResetConnectTimer(interface_index());
1975 if (scan_session_) {
1976 scan_session_.reset();
1977 }
Wade Guthrie44f290d2013-05-28 10:16:25 -07001978 break;
Wade Guthrieb0def9f2013-07-12 13:49:18 -07001979 case kScanScanning:
1980 metrics()->NotifyDeviceScanStarted(interface_index());
1981 break;
Wade Guthrie44f290d2013-05-28 10:16:25 -07001982 case kScanConnecting:
1983 metrics()->NotifyDeviceScanFinished(interface_index());
1984 // TODO(wdg): Provide |is_auto_connecting| to this interface. For now,
1985 // I'll lie (because I don't care about the auto-connect metrics).
1986 metrics()->NotifyDeviceConnectStarted(interface_index(), false);
1987 break;
1988 case kScanConnected:
1989 metrics()->NotifyDeviceConnectFinished(interface_index());
1990 break;
1991 case kScanFoundNothing:
1992 // Note that finishing a scan that hasn't started (if, for example, we
1993 // get here when we fail to complete a connection) does nothing.
1994 metrics()->NotifyDeviceScanFinished(interface_index());
1995 metrics()->ResetConnectTimer(interface_index());
1996 break;
Wade Guthriedf6d61b2013-07-17 11:43:55 -07001997 case kScanTransitionToConnecting: // FALLTHROUGH
Wade Guthrie44f290d2013-05-28 10:16:25 -07001998 default:
1999 break;
2000 }
Wade Guthrie0cf3c982013-05-29 09:11:35 -07002001 if (is_terminal_state) {
Wade Guthrieb0def9f2013-07-12 13:49:18 -07002002 ReportScanResultToUma(new_state, old_method);
Wade Guthrie0cf3c982013-05-29 09:11:35 -07002003 // Now that we've logged a terminal state, let's call ourselves to
2004 // transistion to the idle state.
Wade Guthrieb0def9f2013-07-12 13:49:18 -07002005 SetScanState(kScanIdle, kScanMethodNone, reason);
Wade Guthrie0cf3c982013-05-29 09:11:35 -07002006 }
2007}
2008
2009// static
2010string WiFi::ScanStateString(ScanState state, ScanMethod method) {
2011 switch (state) {
2012 case kScanIdle:
2013 return "IDLE";
2014 case kScanScanning:
2015 DCHECK(method != kScanMethodNone) << "Scanning with no scan method.";
2016 switch (method) {
2017 case kScanMethodFull:
2018 return "FULL_START";
2019 case kScanMethodProgressive:
2020 return "PROGRESSIVE_START";
2021 case kScanMethodProgressiveErrorToFull:
2022 return "PROGRESSIVE_ERROR_FULL_START";
2023 case kScanMethodProgressiveFinishedToFull:
2024 return "PROGRESSIVE_FINISHED_FULL_START";
2025 default:
2026 NOTREACHED();
2027 }
Wade Guthriedf6d61b2013-07-17 11:43:55 -07002028 case kScanTransitionToConnecting:
2029 return "TRANSITION_TO_CONNECTING";
Wade Guthrie0cf3c982013-05-29 09:11:35 -07002030 case kScanConnecting:
2031 switch (method) {
2032 case kScanMethodNone:
2033 return "CONNECTING (not scan related)";
2034 case kScanMethodFull:
2035 return "FULL_CONNECTING";
2036 case kScanMethodProgressive:
2037 return "PROGRESSIVE_CONNECTING";
2038 case kScanMethodProgressiveErrorToFull:
2039 return "PROGRESSIVE_ERROR_FULL_CONNECTING";
2040 case kScanMethodProgressiveFinishedToFull:
2041 return "PROGRESSIVE_FINISHED_FULL_CONNECTING";
2042 default:
2043 NOTREACHED();
2044 }
2045 case kScanConnected:
2046 switch (method) {
2047 case kScanMethodNone:
2048 return "CONNECTED (not scan related; e.g., from a supplicant roam)";
2049 case kScanMethodFull:
2050 return "FULL_CONNECTED";
2051 case kScanMethodProgressive:
2052 return "PROGRESSIVE_CONNECTED";
2053 case kScanMethodProgressiveErrorToFull:
2054 return "PROGRESSIVE_ERROR_FULL_CONNECTED";
2055 case kScanMethodProgressiveFinishedToFull:
2056 return "PROGRESSIVE_FINISHED_FULL_CONNECTED";
2057 default:
2058 NOTREACHED();
2059 }
2060 case kScanFoundNothing:
2061 switch (method) {
2062 case kScanMethodNone:
2063 return "CONNECT FAILED (not scan related)";
2064 case kScanMethodFull:
2065 return "FULL_NOCONNECTION";
2066 case kScanMethodProgressive:
2067 // This is possible if shill started to connect but timed out before
2068 // the connection was completed.
2069 return "PROGRESSIVE_FINISHED_NOCONNECTION";
2070 case kScanMethodProgressiveErrorToFull:
2071 return "PROGRESSIVE_ERROR_FULL_NOCONNECTION";
2072 case kScanMethodProgressiveFinishedToFull:
2073 return "PROGRESSIVE_FINISHED_FULL_NOCONNECTION";
2074 default:
2075 NOTREACHED();
2076 }
2077 default:
2078 NOTREACHED();
2079 }
2080 return ""; // To shut up the compiler (that doesn't understand NOTREACHED).
2081}
2082
Wade Guthrieb9e0ee72013-05-31 09:23:30 -07002083void WiFi::ReportScanResultToUma(ScanState state, ScanMethod method) {
2084 Metrics::WiFiScanResult result = Metrics::kScanResultMax;
2085 if (state == kScanConnected) {
2086 switch (method) {
2087 case kScanMethodFull:
2088 result = Metrics::kScanResultFullScanConnected;
2089 break;
2090 case kScanMethodProgressive:
2091 result = Metrics::kScanResultProgressiveConnected;
2092 break;
2093 case kScanMethodProgressiveErrorToFull:
2094 result = Metrics::kScanResultProgressiveErrorButFullConnected;
2095 break;
2096 case kScanMethodProgressiveFinishedToFull:
2097 result = Metrics::kScanResultProgressiveAndFullConnected;
2098 break;
2099 default:
2100 // OK: Connect resulting from something other than scan.
2101 break;
2102 }
2103 } else if (state == kScanFoundNothing) {
2104 switch (method) {
2105 case kScanMethodFull:
2106 result = Metrics::kScanResultFullScanFoundNothing;
2107 break;
2108 case kScanMethodProgressiveErrorToFull:
2109 result = Metrics::kScanResultProgressiveErrorAndFullFoundNothing;
2110 break;
2111 case kScanMethodProgressiveFinishedToFull:
2112 result = Metrics::kScanResultProgressiveAndFullFoundNothing;
2113 break;
2114 default:
2115 // OK: Connect failed, not scan related.
2116 break;
2117 }
2118 }
2119
2120 if (result != Metrics::kScanResultMax) {
2121 metrics()->SendEnumToUMA(Metrics::kMetricScanResult,
2122 result,
2123 Metrics::kScanResultMax);
2124 }
2125}
2126
Paul Stewartb50f0b92011-05-16 16:31:42 -07002127} // namespace shill