blob: cc23b77a265d2741fe1e3ce262302a524cef5367 [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
Paul Stewartb50f0b92011-05-16 16:31:42 -07007#include <stdio.h>
mukesh agrawalc7426a42011-06-03 13:04:28 -07008#include <string.h>
mukesh agrawalf2f68a52011-09-01 12:15:48 -07009#include <netinet/ether.h>
mukesh agrawal5c4dd0b2011-09-14 13:53:14 -070010#include <linux/if.h> // Needs definitions from netinet/ether.h
Paul Stewartb50f0b92011-05-16 16:31:42 -070011
mukesh agrawal8a3188d2011-12-01 20:56:44 +000012#include <algorithm>
mukesh agrawalab87ea42011-05-18 11:44:49 -070013#include <map>
Paul Stewartced6a0b2011-11-08 15:32:04 -080014#include <set>
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>
mukesh agrawal15908392011-11-16 18:29:25 +000019#include <base/stringprintf.h>
mukesh agrawal7a4e4002011-09-06 11:26:05 -070020#include <base/string_number_conversions.h>
21#include <base/string_util.h>
Chris Masoneb925cc82011-06-22 15:39:57 -070022#include <chromeos/dbus/service_constants.h>
mukesh agrawal16bc1b82012-02-09 18:38:26 -080023#include <glib.h>
Paul Stewartb50f0b92011-05-16 16:31:42 -070024
Wade Guthried6153612012-08-23 11:36:14 -070025#include "shill/config80211.h"
Paul Stewartb50f0b92011-05-16 16:31:42 -070026#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"
Paul Stewart26b327e2011-10-19 11:38:09 -070030#include "shill/event_dispatcher.h"
mukesh agrawal7a4e4002011-09-06 11:26:05 -070031#include "shill/key_value_store.h"
32#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"
Chris Masone7aa5f902011-07-11 11:13:35 -070037#include "shill/profile.h"
mukesh agrawal4d0401c2012-01-06 16:05:31 -080038#include "shill/property_accessor.h"
Darin Petkovd1967262011-07-18 14:55:18 -070039#include "shill/proxy_factory.h"
Eric Shienbrood9a245532012-03-07 14:20:39 -050040#include "shill/rtnl_handler.h"
mukesh agrawal5c05b292012-03-07 10:12:52 -080041#include "shill/shill_time.h"
Paul Stewarta41e38d2011-11-11 07:47:29 -080042#include "shill/store_interface.h"
mukesh agrawalaf571952011-07-14 14:31:12 -070043#include "shill/supplicant_interface_proxy_interface.h"
44#include "shill/supplicant_process_proxy_interface.h"
Gaurav Shah435de2c2011-11-17 19:01:07 -080045#include "shill/technology.h"
mukesh agrawalb54601c2011-06-07 17:39:22 -070046#include "shill/wifi_endpoint.h"
47#include "shill/wifi_service.h"
mukesh agrawal6e277772011-09-29 15:04:23 -070048#include "shill/wpa_supplicant.h"
Paul Stewartb50f0b92011-05-16 16:31:42 -070049
Eric Shienbrood3e20a232012-02-16 11:35:56 -050050using base::Bind;
mukesh agrawal15908392011-11-16 18:29:25 +000051using base::StringPrintf;
mukesh agrawal7a4e4002011-09-06 11:26:05 -070052using std::map;
Paul Stewartced6a0b2011-11-08 15:32:04 -080053using std::set;
mukesh agrawalab87ea42011-05-18 11:44:49 -070054using std::string;
mukesh agrawal7a4e4002011-09-06 11:26:05 -070055using std::vector;
mukesh agrawalab87ea42011-05-18 11:44:49 -070056
Paul Stewartb50f0b92011-05-16 16:31:42 -070057namespace shill {
mukesh agrawal7a4e4002011-09-06 11:26:05 -070058
59// statics
mukesh agrawal4d0401c2012-01-06 16:05:31 -080060const char *WiFi::kDefaultBgscanMethod =
61 wpa_supplicant::kNetworkBgscanMethodSimple;
62const uint16 WiFi::kDefaultBgscanShortIntervalSeconds = 30;
63const int32 WiFi::kDefaultBgscanSignalThresholdDbm = -50;
64const uint16 WiFi::kDefaultScanIntervalSeconds = 180;
Darin Petkov4a66cc52012-06-15 10:08:29 +020065// Scan interval while connected.
66const uint16 WiFi::kBackgroundScanIntervalSeconds = 3601;
mukesh agrawal7a4e4002011-09-06 11:26:05 -070067// Note that WiFi generates some manager-level errors, because it implements
68// the Manager.GetWiFiService flimflam API. The API is implemented here,
69// rather than in manager, to keep WiFi-specific logic in the right place.
mukesh agrawal7a4e4002011-09-06 11:26:05 -070070const char WiFi::kManagerErrorSSIDRequired[] = "must specify SSID";
71const char WiFi::kManagerErrorSSIDTooLong[] = "SSID is too long";
72const char WiFi::kManagerErrorSSIDTooShort[] = "SSID is too short";
mukesh agrawal7a4e4002011-09-06 11:26:05 -070073const char WiFi::kManagerErrorUnsupportedSecurityMode[] =
74 "security mode is unsupported";
mukesh agrawal7a4e4002011-09-06 11:26:05 -070075const char WiFi::kManagerErrorUnsupportedServiceMode[] =
76 "service mode is unsupported";
mukesh agrawal5c05b292012-03-07 10:12:52 -080077// Age (in seconds) beyond which a BSS cache entry will not be preserved,
78// across a suspend/resume.
79const time_t WiFi::kMaxBSSResumeAgeSeconds = 10;
mukesh agrawal7ec71312011-11-10 02:08:26 +000080const char WiFi::kInterfaceStateUnknown[] = "shill-unknown";
mukesh agrawalf2028172012-03-13 14:20:22 -070081const time_t WiFi::kRescanIntervalSeconds = 1;
Paul Stewarte369ece2012-05-22 09:11:03 -070082const int WiFi::kNumFastScanAttempts = 3;
83const int WiFi::kFastScanIntervalSeconds = 10;
Paul Stewart2b05e622012-07-13 20:38:44 -070084const int WiFi::kPendingTimeoutSeconds = 15;
Paul Stewart44663922012-07-30 11:03:03 -070085const int WiFi::kReconnectTimeoutSeconds = 10;
mukesh agrawalb54601c2011-06-07 17:39:22 -070086
Paul Stewartb50f0b92011-05-16 16:31:42 -070087WiFi::WiFi(ControlInterface *control_interface,
88 EventDispatcher *dispatcher,
Thieu Le3426c8f2012-01-11 17:35:11 -080089 Metrics *metrics,
Paul Stewartf1ce5d22011-05-19 13:10:20 -070090 Manager *manager,
Chris Masone3bd3c8c2011-06-13 08:20:26 -070091 const string& link,
Paul Stewarta41e38d2011-11-11 07:47:29 -080092 const string &address,
Paul Stewartb50f0b92011-05-16 16:31:42 -070093 int interface_index)
Chris Masonea82b7112011-05-25 15:16:29 -070094 : Device(control_interface,
95 dispatcher,
Thieu Le3426c8f2012-01-11 17:35:11 -080096 metrics,
Chris Masonea82b7112011-05-25 15:16:29 -070097 manager,
Chris Masone3bd3c8c2011-06-13 08:20:26 -070098 link,
Chris Masone626719f2011-08-18 16:58:48 -070099 address,
Gaurav Shah435de2c2011-11-17 19:01:07 -0800100 interface_index,
101 Technology::kWifi),
Eric Shienbrood9a245532012-03-07 14:20:39 -0500102 weak_ptr_factory_(this),
Darin Petkovab565bb2011-10-06 02:55:51 -0700103 proxy_factory_(ProxyFactory::GetInstance()),
mukesh agrawal5c05b292012-03-07 10:12:52 -0800104 time_(Time::GetInstance()),
Darin Petkov2b8e44e2012-06-25 15:13:26 +0200105 supplicant_present_(false),
mukesh agrawal15908392011-11-16 18:29:25 +0000106 supplicant_state_(kInterfaceStateUnknown),
107 supplicant_bss_("(unknown)"),
Paul Stewart66c86002012-01-30 18:00:52 -0800108 clear_cached_credentials_pending_(false),
mukesh agrawal5c05b292012-03-07 10:12:52 -0800109 need_bss_flush_(false),
Darin Petkove636c692012-05-31 10:22:17 +0200110 resumed_at_((struct timeval){0}),
Paul Stewarte369ece2012-05-22 09:11:03 -0700111 fast_scans_remaining_(kNumFastScanAttempts),
mukesh agrawal4d0401c2012-01-06 16:05:31 -0800112 bgscan_short_interval_seconds_(kDefaultBgscanShortIntervalSeconds),
113 bgscan_signal_threshold_dbm_(kDefaultBgscanSignalThresholdDbm),
Chris Masone853b81b2011-06-24 14:11:41 -0700114 scan_pending_(false),
mukesh agrawal4d0401c2012-01-06 16:05:31 -0800115 scan_interval_seconds_(kDefaultScanIntervalSeconds) {
mukesh agrawalde29fa82011-09-16 16:16:36 -0700116 PropertyStore *store = this->mutable_store();
Darin Petkov4a66cc52012-06-15 10:08:29 +0200117 store->RegisterDerivedString(
118 flimflam::kBgscanMethodProperty,
119 StringAccessor(
120 // TODO(petkov): CustomMappedAccessor is used for convenience because
121 // it provides a way to define a custom clearer (unlike
122 // CustomAccessor). We need to implement a fully custom accessor with
123 // no extra argument.
124 new CustomMappedAccessor<WiFi, string, int>(this,
125 &WiFi::ClearBgscanMethod,
126 &WiFi::GetBgscanMethod,
127 &WiFi::SetBgscanMethod,
128 0))); // Unused.
mukesh agrawal4d0401c2012-01-06 16:05:31 -0800129 HelpRegisterDerivedUint16(store,
130 flimflam::kBgscanShortIntervalProperty,
131 &WiFi::GetBgscanShortInterval,
132 &WiFi::SetBgscanShortInterval);
133 HelpRegisterDerivedInt32(store,
134 flimflam::kBgscanSignalThresholdProperty,
135 &WiFi::GetBgscanSignalThreshold,
136 &WiFi::SetBgscanSignalThreshold);
Chris Masone853b81b2011-06-24 14:11:41 -0700137
Chris Masoneb925cc82011-06-22 15:39:57 -0700138 // TODO(quiche): Decide if scan_pending_ is close enough to
139 // "currently scanning" that we don't care, or if we want to track
140 // scan pending/currently scanning/no scan scheduled as a tri-state
141 // kind of thing.
Paul Stewartac4ac002011-08-26 12:04:26 -0700142 store->RegisterConstBool(flimflam::kScanningProperty, &scan_pending_);
mukesh agrawal4d0401c2012-01-06 16:05:31 -0800143 HelpRegisterDerivedUint16(store,
144 flimflam::kScanIntervalProperty,
145 &WiFi::GetScanInterval,
146 &WiFi::SetScanInterval);
Ben Chanfad4a0b2012-04-18 15:49:59 -0700147 SLOG(WiFi, 2) << "WiFi device " << link_name() << " initialized.";
Paul Stewartb50f0b92011-05-16 16:31:42 -0700148}
149
mukesh agrawalaf571952011-07-14 14:31:12 -0700150WiFi::~WiFi() {}
Paul Stewartb50f0b92011-05-16 16:31:42 -0700151
Eric Shienbrood9a245532012-03-07 14:20:39 -0500152void WiFi::Start(Error *error, const EnabledStateChangedCallback &callback) {
Darin Petkov2b8e44e2012-06-25 15:13:26 +0200153 SLOG(WiFi, 2) << "WiFi " << link_name() << " starting.";
154 if (enabled()) {
155 return;
mukesh agrawalc7426a42011-06-03 13:04:28 -0700156 }
Eric Shienbrood9a245532012-03-07 14:20:39 -0500157 OnEnabledStateChanged(EnabledStateChangedCallback(), Error());
Darin Petkov2b8e44e2012-06-25 15:13:26 +0200158 if (error) {
Eric Shienbrood9a245532012-03-07 14:20:39 -0500159 error->Reset(); // indicate immediate completion
Darin Petkov2b8e44e2012-06-25 15:13:26 +0200160 }
161 if (on_supplicant_appear_.IsCancelled()) {
162 // Registers the WPA supplicant appear/vanish callbacks only once per WiFi
163 // device instance.
164 on_supplicant_appear_.Reset(
165 Bind(&WiFi::OnSupplicantAppear, Unretained(this)));
166 on_supplicant_vanish_.Reset(
167 Bind(&WiFi::OnSupplicantVanish, Unretained(this)));
168 manager()->dbus_manager()->WatchName(wpa_supplicant::kDBusAddr,
169 on_supplicant_appear_.callback(),
170 on_supplicant_vanish_.callback());
171 }
172 // Connect to WPA supplicant if it's already present. If not, we'll connect to
173 // it when it appears.
174 ConnectToSupplicant();
Wade Guthried6153612012-08-23 11:36:14 -0700175 Config80211 *config80211 = Config80211::GetInstance();
176 if (config80211) {
177 config80211->SetWifiState(Config80211::kWifiUp);
178 }
mukesh agrawalab87ea42011-05-18 11:44:49 -0700179}
180
Eric Shienbrood9a245532012-03-07 14:20:39 -0500181void WiFi::Stop(Error *error, const EnabledStateChangedCallback &callback) {
Ben Chanfad4a0b2012-04-18 15:49:59 -0700182 SLOG(WiFi, 2) << "WiFi " << link_name() << " stopping.";
Darin Petkov2b8e44e2012-06-25 15:13:26 +0200183 DropConnection();
mukesh agrawalb66c6462012-05-07 11:45:25 -0700184 StopScanTimer();
mukesh agrawal15908392011-11-16 18:29:25 +0000185 endpoint_by_rpcid_.clear();
mukesh agrawal5c4dd0b2011-09-14 13:53:14 -0700186
Paul Stewartced6a0b2011-11-08 15:32:04 -0800187 for (vector<WiFiServiceRefPtr>::const_iterator it = services_.begin();
188 it != services_.end();
mukesh agrawal5c4dd0b2011-09-14 13:53:14 -0700189 ++it) {
Ben Chanfad4a0b2012-04-18 15:49:59 -0700190 SLOG(WiFi, 3) << "WiFi " << link_name() << " deregistering service "
191 << (*it)->friendly_name();
mukesh agrawal5c4dd0b2011-09-14 13:53:14 -0700192 manager()->DeregisterService(*it);
193 }
Paul Stewart549d44c2012-07-03 12:40:25 -0700194 rpcid_by_service_.clear();
Paul Stewartced6a0b2011-11-08 15:32:04 -0800195 services_.clear(); // breaks reference cycles
Paul Stewart549d44c2012-07-03 12:40:25 -0700196 supplicant_interface_proxy_.reset(); // breaks a reference cycle
197 // TODO(quiche): Remove interface from supplicant.
198 supplicant_process_proxy_.reset();
mukesh agrawalb20776f2012-02-10 16:00:36 -0800199 current_service_ = NULL; // breaks a reference cycle
mukesh agrawal7ec71312011-11-10 02:08:26 +0000200 pending_service_ = NULL; // breaks a reference cycle
Darin Petkov2b8e44e2012-06-25 15:13:26 +0200201 scan_pending_ = false;
Paul Stewart2b05e622012-07-13 20:38:44 -0700202 StopPendingTimer();
Paul Stewart44663922012-07-30 11:03:03 -0700203 StopReconnectTimer();
mukesh agrawal5c4dd0b2011-09-14 13:53:14 -0700204
Eric Shienbrood9a245532012-03-07 14:20:39 -0500205 OnEnabledStateChanged(EnabledStateChangedCallback(), Error());
206 if (error)
207 error->Reset(); // indicate immediate completion
mukesh agrawalc4f368f2012-06-04 19:45:52 -0700208 weak_ptr_factory_.InvalidateWeakPtrs();
mukesh agrawal5c4dd0b2011-09-14 13:53:14 -0700209
Ben Chanfad4a0b2012-04-18 15:49:59 -0700210 SLOG(WiFi, 3) << "WiFi " << link_name() << " supplicant_process_proxy_ "
211 << (supplicant_process_proxy_.get() ?
212 "is set." : "is not set.");
213 SLOG(WiFi, 3) << "WiFi " << link_name() << " supplicant_interface_proxy_ "
214 << (supplicant_interface_proxy_.get() ?
215 "is set." : "is not set.");
216 SLOG(WiFi, 3) << "WiFi " << link_name() << " pending_service_ "
217 << (pending_service_.get() ? "is set." : "is not set.");
218 SLOG(WiFi, 3) << "WiFi " << link_name() << " has "
219 << endpoint_by_rpcid_.size() << " EndpointMap entries.";
220 SLOG(WiFi, 3) << "WiFi " << link_name() << " has " << services_.size()
221 << " Services.";
mukesh agrawalab87ea42011-05-18 11:44:49 -0700222}
223
Paul Stewarta41e38d2011-11-11 07:47:29 -0800224bool WiFi::Load(StoreInterface *storage) {
225 LoadHiddenServices(storage);
226 return Device::Load(storage);
227}
228
mukesh agrawal1830fa12011-09-26 14:31:40 -0700229void WiFi::Scan(Error */*error*/) {
mukesh agrawal32399322011-09-01 10:53:43 -0700230 LOG(INFO) << __func__;
231
mukesh agrawal7ec71312011-11-10 02:08:26 +0000232 // Needs to send a D-Bus message, but may be called from D-Bus
233 // signal handler context (via Manager::RequestScan). So defer work
mukesh agrawal32399322011-09-01 10:53:43 -0700234 // to event loop.
Eric Shienbrood9a245532012-03-07 14:20:39 -0500235 dispatcher()->PostTask(Bind(&WiFi::ScanTask, weak_ptr_factory_.GetWeakPtr()));
mukesh agrawal32399322011-09-01 10:53:43 -0700236}
237
mukesh agrawalb4bc57d2011-12-07 01:07:47 +0000238void WiFi::BSSAdded(const ::DBus::Path &path,
239 const map<string, ::DBus::Variant> &properties) {
Eric Shienbrood3e20a232012-02-16 11:35:56 -0500240 // Called from a D-Bus signal handler, and may need to send a D-Bus
mukesh agrawalb4bc57d2011-12-07 01:07:47 +0000241 // message. So defer work to event loop.
Eric Shienbrood9a245532012-03-07 14:20:39 -0500242 dispatcher()->PostTask(Bind(&WiFi::BSSAddedTask,
243 weak_ptr_factory_.GetWeakPtr(),
244 path, properties));
mukesh agrawal261daca2011-12-02 18:56:56 +0000245}
246
247void WiFi::BSSRemoved(const ::DBus::Path &path) {
Eric Shienbrood3e20a232012-02-16 11:35:56 -0500248 // Called from a D-Bus signal handler, and may need to send a D-Bus
mukesh agrawalb4bc57d2011-12-07 01:07:47 +0000249 // message. So defer work to event loop.
Eric Shienbrood9a245532012-03-07 14:20:39 -0500250 dispatcher()->PostTask(Bind(&WiFi::BSSRemovedTask,
251 weak_ptr_factory_.GetWeakPtr(), path));
mukesh agrawalb54601c2011-06-07 17:39:22 -0700252}
253
Paul Stewartbc6e7392012-05-24 07:07:48 -0700254void WiFi::Certification(const map<string, ::DBus::Variant> &properties) {
255 dispatcher()->PostTask(Bind(&WiFi::CertificationTask,
256 weak_ptr_factory_.GetWeakPtr(), properties));
257}
258
mukesh agrawal7ec71312011-11-10 02:08:26 +0000259void WiFi::PropertiesChanged(const map<string, ::DBus::Variant> &properties) {
Darin Petkov9cd7ca12012-07-03 11:06:40 +0200260 SLOG(WiFi, 2) << __func__;
mukesh agrawal15908392011-11-16 18:29:25 +0000261 // Called from D-Bus signal handler, but may need to send a D-Bus
262 // message. So defer work to event loop.
Eric Shienbrood9a245532012-03-07 14:20:39 -0500263 dispatcher()->PostTask(Bind(&WiFi::PropertiesChangedTask,
264 weak_ptr_factory_.GetWeakPtr(), properties));
mukesh agrawal7ec71312011-11-10 02:08:26 +0000265}
266
mukesh agrawalb54601c2011-06-07 17:39:22 -0700267void WiFi::ScanDone() {
268 LOG(INFO) << __func__;
269
mukesh agrawal7ec71312011-11-10 02:08:26 +0000270 // Defer handling of scan result processing, because that processing
271 // may require the the registration of new D-Bus objects. And such
mukesh agrawalb54601c2011-06-07 17:39:22 -0700272 // registration can't be done in the context of a D-Bus signal
273 // handler.
Eric Shienbrood9a245532012-03-07 14:20:39 -0500274 dispatcher()->PostTask(Bind(&WiFi::ScanDoneTask,
275 weak_ptr_factory_.GetWeakPtr()));
mukesh agrawalb54601c2011-06-07 17:39:22 -0700276}
277
mukesh agrawal6e277772011-09-29 15:04:23 -0700278void WiFi::ConnectTo(WiFiService *service,
mukesh agrawal64896322011-12-01 01:13:10 +0000279 map<string, DBus::Variant> service_params) {
mukesh agrawale9adda12012-02-09 18:33:48 -0800280 CHECK(service) << "Can't connect to NULL service.";
mukesh agrawal445e72c2011-06-22 11:13:50 -0700281 DBus::Path network_path;
mukesh agrawalb54601c2011-06-07 17:39:22 -0700282
mukesh agrawal7ec71312011-11-10 02:08:26 +0000283 // TODO(quiche): Handle cases where already connected.
mukesh agrawal8a3188d2011-12-01 20:56:44 +0000284 if (pending_service_ && pending_service_ == service) {
285 // TODO(quiche): Return an error to the caller. crosbug.com/23832
286 LOG(INFO) << "WiFi " << link_name() << " ignoring ConnectTo "
287 << service->friendly_name()
288 << ", which is already pending.";
289 return;
290 }
291
292 if (pending_service_ && pending_service_ != service) {
293 DisconnectFrom(pending_service_);
294 }
mukesh agrawal32399322011-09-01 10:53:43 -0700295
mukesh agrawal6e277772011-09-29 15:04:23 -0700296 try {
mukesh agrawal64896322011-12-01 01:13:10 +0000297 const uint32_t scan_ssid = 1; // "True": Use directed probe.
298 service_params[wpa_supplicant::kNetworkPropertyScanSSID].writer().
299 append_uint32(scan_ssid);
Darin Petkov4a66cc52012-06-15 10:08:29 +0200300 AppendBgscan(service, &service_params);
301 network_path = supplicant_interface_proxy_->AddNetwork(service_params);
mukesh agrawal15908392011-11-16 18:29:25 +0000302 rpcid_by_service_[service] = network_path;
Ben Chan80326f32012-05-04 17:51:32 -0700303 } catch (const DBus::Error &e) { // NOLINT
mukesh agrawal6e277772011-09-29 15:04:23 -0700304 LOG(ERROR) << "exception while adding network: " << e.what();
305 return;
306 }
mukesh agrawal445e72c2011-06-22 11:13:50 -0700307
mukesh agrawal445e72c2011-06-22 11:13:50 -0700308 supplicant_interface_proxy_->SelectNetwork(network_path);
Paul Stewart2b05e622012-07-13 20:38:44 -0700309 SetPendingService(service);
mukesh agrawal8a3188d2011-12-01 20:56:44 +0000310 CHECK(current_service_.get() != pending_service_.get());
311
mukesh agrawalf2f68a52011-09-01 12:15:48 -0700312 // SelectService here (instead of in LinkEvent, like Ethernet), so
313 // that, if we fail to bring up L2, we can attribute failure correctly.
314 //
mukesh agrawal7ec71312011-11-10 02:08:26 +0000315 // TODO(quiche): When we add code for dealing with connection failures,
mukesh agrawalf2f68a52011-09-01 12:15:48 -0700316 // reconsider if this is the right place to change the selected service.
317 // see discussion in crosbug.com/20191.
318 SelectService(service);
mukesh agrawal15908392011-11-16 18:29:25 +0000319}
320
mukesh agrawal0ed0f2e2011-12-05 20:36:17 +0000321void WiFi::DisconnectFrom(WiFiService *service) {
322 if (service != current_service_ && service != pending_service_) {
323 // TODO(quiche): Once we have asynchronous reply support, we should
324 // generate a D-Bus error here. (crosbug.com/23832)
325 LOG(WARNING) << "In " << __func__ << "(): "
326 << " ignoring request to disconnect from service "
327 << service->friendly_name()
328 << " which is neither current nor pending";
329 return;
330 }
331
332 if (pending_service_ && service != pending_service_) {
333 // TODO(quiche): Once we have asynchronous reply support, we should
334 // generate a D-Bus error here. (crosbug.com/23832)
335 LOG(WARNING) << "In " << __func__ << "(): "
336 << " ignoring request to disconnect from service "
337 << service->friendly_name()
338 << " which is not the pending service.";
339 return;
340 }
341
342 if (!pending_service_ && service != current_service_) {
343 // TODO(quiche): Once we have asynchronous reply support, we should
344 // generate a D-Bus error here. (crosbug.com/23832)
345 LOG(WARNING) << "In " << __func__ << "(): "
346 << " ignoring request to disconnect from service "
347 << service->friendly_name()
348 << " which is not the current service.";
349 return;
350 }
351
Paul Stewartff96a842012-08-13 15:59:10 -0700352 if (pending_service_) {
353 // Since wpa_supplicant has not yet set CurrentBSS, we can't depend
354 // on this to drive the service state back to idle. Do that here.
355 pending_service_->SetState(Service::kStateIdle);
356 }
357
Paul Stewart2b05e622012-07-13 20:38:44 -0700358 SetPendingService(NULL);
Paul Stewart44663922012-07-30 11:03:03 -0700359 StopReconnectTimer();
Paul Stewart549d44c2012-07-03 12:40:25 -0700360
361 if (!supplicant_present_) {
362 LOG(INFO) << "In " << __func__ << "(): "
363 << "wpa_supplicant is not present; silently resetting "
364 << "current_service_.";
365 current_service_ = NULL;
366 return;
367 }
368
mukesh agrawal0ed0f2e2011-12-05 20:36:17 +0000369 try {
370 supplicant_interface_proxy_->Disconnect();
371 // We'll call RemoveNetwork and reset |current_service_| after
372 // supplicant notifies us that the CurrentBSS has changed.
Ben Chan80326f32012-05-04 17:51:32 -0700373 } catch (const DBus::Error &e) { // NOLINT
mukesh agrawal0ed0f2e2011-12-05 20:36:17 +0000374 // Can't depend on getting a notification of CurrentBSS change.
375 // So effect changes immediately.
376 ReverseServiceMap::const_iterator rpcid_it =
377 rpcid_by_service_.find(service);
378 DCHECK(rpcid_it != rpcid_by_service_.end());
379 if (rpcid_it == rpcid_by_service_.end()) {
380 LOG(WARNING) << "WiFi " << link_name() << " can not disconnect from "
381 << service->friendly_name() << ": "
382 << "could not find supplicant network to disable.";
383 } else {
384 supplicant_interface_proxy_->RemoveNetwork(rpcid_it->second);
385 }
386 current_service_ = NULL;
387 }
388
mukesh agrawal4d0401c2012-01-06 16:05:31 -0800389 CHECK(current_service_ == NULL ||
390 current_service_.get() != pending_service_.get());
mukesh agrawal0ed0f2e2011-12-05 20:36:17 +0000391}
392
mukesh agrawal8a3188d2011-12-01 20:56:44 +0000393bool WiFi::IsIdle() const {
Paul Stewart3d9bcf52011-12-12 15:02:22 -0800394 return !current_service_ && !pending_service_;
395}
396
Paul Stewart66c86002012-01-30 18:00:52 -0800397void WiFi::ClearCachedCredentials() {
398 LOG(INFO) << __func__;
399
400 // Needs to send a D-Bus message, but may be called from D-Bus
401 // caller context (via Manager::PopProfile). So defer work
402 // to event loop.
403 if (!clear_cached_credentials_pending_) {
404 clear_cached_credentials_pending_ = true;
Eric Shienbrood9a245532012-03-07 14:20:39 -0500405 dispatcher()->PostTask(Bind(&WiFi::ClearCachedCredentialsTask,
406 weak_ptr_factory_.GetWeakPtr()));
Paul Stewart66c86002012-01-30 18:00:52 -0800407 }
408}
409
mukesh agrawalb20776f2012-02-10 16:00:36 -0800410void WiFi::NotifyEndpointChanged(const WiFiEndpoint &endpoint) {
411 WiFiService *service = FindServiceForEndpoint(endpoint);
412 DCHECK(service);
413 if (service) {
414 service->NotifyEndpointUpdated(endpoint);
mukesh agrawalb20776f2012-02-10 16:00:36 -0800415 }
416}
417
Darin Petkov4a66cc52012-06-15 10:08:29 +0200418void WiFi::AppendBgscan(WiFiService *service,
419 map<string, DBus::Variant> *service_params) const {
420 int scan_interval = kBackgroundScanIntervalSeconds;
421 string method = bgscan_method_;
422 if (method.empty()) {
423 // If multiple APs are detected for this SSID, configure the default method.
424 // Otherwise, disable background scanning completely.
425 if (service->GetEndpointCount() > 1) {
426 method = kDefaultBgscanMethod;
427 } else {
428 LOG(INFO) << "Background scan disabled -- single Endpoint for Service.";
429 return;
430 }
Christopher Wileya998df22012-07-11 15:14:55 -0700431 } else if (method.compare(wpa_supplicant::kNetworkBgscanMethodNone) == 0) {
432 LOG(INFO) << "Background scan disabled -- chose None method.";
433 return;
Darin Petkov4a66cc52012-06-15 10:08:29 +0200434 } else {
435 // If the background scan method was explicitly specified, honor the
436 // configured background scan interval.
437 scan_interval = scan_interval_seconds_;
438 }
439 DCHECK(!method.empty());
440 string config_string = StringPrintf("%s:%d:%d:%d",
441 method.c_str(),
442 bgscan_short_interval_seconds_,
443 bgscan_signal_threshold_dbm_,
444 scan_interval);
445 LOG(INFO) << "Background scan: " << config_string;
446 (*service_params)[wpa_supplicant::kNetworkPropertyBgscan].writer()
447 .append_string(config_string.c_str());
mukesh agrawal4d0401c2012-01-06 16:05:31 -0800448}
449
Darin Petkov4a66cc52012-06-15 10:08:29 +0200450string WiFi::GetBgscanMethod(const int &/*argument*/, Error */* error */) {
451 return bgscan_method_.empty() ? kDefaultBgscanMethod : bgscan_method_;
452}
453
454void WiFi::SetBgscanMethod(
455 const int &/*argument*/, const string &method, Error *error) {
mukesh agrawal4d0401c2012-01-06 16:05:31 -0800456 if (method != wpa_supplicant::kNetworkBgscanMethodSimple &&
Christopher Wileya998df22012-07-11 15:14:55 -0700457 method != wpa_supplicant::kNetworkBgscanMethodLearn &&
458 method != wpa_supplicant::kNetworkBgscanMethodNone) {
mukesh agrawal4d0401c2012-01-06 16:05:31 -0800459 const string error_message =
460 StringPrintf("Unrecognized bgscan method %s", method.c_str());
461 LOG(WARNING) << error_message;
462 error->Populate(Error::kInvalidArguments, error_message);
463 return;
464 }
465
466 bgscan_method_ = method;
467 // We do not update kNetworkPropertyBgscan for |pending_service_| or
468 // |current_service_|, because supplicant does not allow for
469 // reconfiguration without disconnect and reconnect.
470}
471
472void WiFi::SetBgscanShortInterval(const uint16 &seconds, Error */*error*/) {
473 bgscan_short_interval_seconds_ = seconds;
474 // We do not update kNetworkPropertyBgscan for |pending_service_| or
475 // |current_service_|, because supplicant does not allow for
476 // reconfiguration without disconnect and reconnect.
477}
478
479void WiFi::SetBgscanSignalThreshold(const int32 &dbm, Error */*error*/) {
480 bgscan_signal_threshold_dbm_ = dbm;
481 // We do not update kNetworkPropertyBgscan for |pending_service_| or
482 // |current_service_|, because supplicant does not allow for
483 // reconfiguration without disconnect and reconnect.
484}
485
486void WiFi::SetScanInterval(const uint16 &seconds, Error */*error*/) {
487 scan_interval_seconds_ = seconds;
mukesh agrawalb66c6462012-05-07 11:45:25 -0700488 if (running()) {
489 StartScanTimer();
490 }
491 // The scan interval affects both foreground scans (handled by
492 // |scan_timer_callback_|), and background scans (handled by
493 // supplicant). However, we do not update |pending_service_| or
494 // |current_service_|, because supplicant does not allow for
495 // reconfiguration without disconnect and reconnect.
mukesh agrawal4d0401c2012-01-06 16:05:31 -0800496}
497
Darin Petkov4a66cc52012-06-15 10:08:29 +0200498void WiFi::ClearBgscanMethod(const int &/*argument*/, Error */*error*/) {
499 bgscan_method_.clear();
500}
501
mukesh agrawal165e6142011-11-22 02:22:56 +0000502// To avoid creating duplicate services, call FindServiceForEndpoint
503// before calling this method.
mukesh agrawal15908392011-11-16 18:29:25 +0000504WiFiServiceRefPtr WiFi::CreateServiceForEndpoint(const WiFiEndpoint &endpoint,
505 bool hidden_ssid) {
506 WiFiServiceRefPtr service =
507 new WiFiService(control_interface(),
508 dispatcher(),
Thieu Le3426c8f2012-01-11 17:35:11 -0800509 metrics(),
mukesh agrawal15908392011-11-16 18:29:25 +0000510 manager(),
511 this,
512 endpoint.ssid(),
513 endpoint.network_mode(),
514 endpoint.security_mode(),
515 hidden_ssid);
mukesh agrawal165e6142011-11-22 02:22:56 +0000516 services_.push_back(service);
mukesh agrawal15908392011-11-16 18:29:25 +0000517 return service;
518}
519
520void WiFi::CurrentBSSChanged(const ::DBus::Path &new_bss) {
Ben Chanfad4a0b2012-04-18 15:49:59 -0700521 SLOG(WiFi, 3) << "WiFi " << link_name() << " CurrentBSS "
522 << supplicant_bss_ << " -> " << new_bss;
mukesh agrawal15908392011-11-16 18:29:25 +0000523 supplicant_bss_ = new_bss;
Paul Stewart44663922012-07-30 11:03:03 -0700524
525 // Any change in CurrentBSS means supplicant is actively changing our
526 // connectivity. We no longer need to track any previously pending
527 // reconnect.
528 StopReconnectTimer();
529
mukesh agrawal15908392011-11-16 18:29:25 +0000530 if (new_bss == wpa_supplicant::kCurrentBSSNull) {
531 HandleDisconnect();
mukesh agrawalb66c6462012-05-07 11:45:25 -0700532 if (!GetHiddenSSIDList().empty()) {
533 // Before disconnecting, wpa_supplicant probably scanned for
534 // APs. So, in the normal case, we defer to the timer for the next scan.
535 //
536 // However, in the case of hidden SSIDs, supplicant knows about
537 // at most one of them. (That would be the hidden SSID we were
538 // connected to, if applicable.)
539 //
540 // So, in this case, we initiate an immediate scan. This scan
541 // will include the hidden SSIDs we know about (up to the limit of
542 // kScanMAxSSIDsPerScan).
543 //
544 // We may want to reconsider this immediate scan, if/when shill
545 // takes greater responsibility for scanning (vs. letting
546 // supplicant handle most of it).
547 Scan(NULL);
548 }
mukesh agrawal15908392011-11-16 18:29:25 +0000549 } else {
550 HandleRoam(new_bss);
551 }
552
Paul Stewart2b05e622012-07-13 20:38:44 -0700553 // If we are selecting a new service, or if we're clearing selection
554 // of a something other than the pending service, call SelectService.
555 // Otherwise skip SelectService, since this will cause the pending
556 // service to be marked as Idle.
557 if (current_service_ || selected_service() != pending_service_) {
558 SelectService(current_service_);
559 }
560
mukesh agrawal8a3188d2011-12-01 20:56:44 +0000561 // Invariant check: a Service can either be current, or pending, but
562 // not both.
mukesh agrawal15908392011-11-16 18:29:25 +0000563 CHECK(current_service_.get() != pending_service_.get() ||
564 current_service_.get() == NULL);
mukesh agrawal15908392011-11-16 18:29:25 +0000565}
566
567void WiFi::HandleDisconnect() {
568 // Identify the affected service. We expect to get a disconnect
569 // event when we fall off a Service that we were connected
570 // to. However, we also allow for the case where we get a disconnect
571 // event while attempting to connect from a disconnected state.
572 WiFiService *affected_service =
573 current_service_.get() ? current_service_.get() : pending_service_.get();
574
575 current_service_ = NULL;
576 if (!affected_service) {
Ben Chanfad4a0b2012-04-18 15:49:59 -0700577 SLOG(WiFi, 2) << "WiFi " << link_name()
578 << " disconnected while not connected or connecting";
mukesh agrawal15908392011-11-16 18:29:25 +0000579 return;
Paul Stewart20b0a092012-05-22 20:39:57 -0700580 } else if (affected_service == selected_service()) {
581 // If our selected service has disconnected, destroy IP configuration state.
582 DestroyIPConfig();
mukesh agrawal15908392011-11-16 18:29:25 +0000583 }
584
585 ReverseServiceMap::const_iterator rpcid_it =
586 rpcid_by_service_.find(affected_service);
587 if (rpcid_it == rpcid_by_service_.end()) {
Ben Chanfad4a0b2012-04-18 15:49:59 -0700588 SLOG(WiFi, 2) << "WiFi " << link_name() << " disconnected from "
589 << " (or failed to connect to) "
590 << affected_service->friendly_name() << ", "
591 << "but could not find supplicant network to disable.";
mukesh agrawalcf24a242012-05-21 16:46:11 -0700592 } else {
593 // TODO(quiche): Reconsider giving up immediately. Maybe give
594 // wpa_supplicant some time to retry, first.
595 supplicant_interface_proxy_->RemoveNetwork(rpcid_it->second);
mukesh agrawal15908392011-11-16 18:29:25 +0000596 }
597
Ben Chanfad4a0b2012-04-18 15:49:59 -0700598 SLOG(WiFi, 2) << "WiFi " << link_name() << " disconnected from "
599 << " (or failed to connect to) "
600 << affected_service->friendly_name();
mukesh agrawalcf24a242012-05-21 16:46:11 -0700601 if (SuspectCredentials(*affected_service)) {
602 // If we suspect bad credentials, set failure, to trigger an error
mukesh agrawal56e32202012-07-26 16:32:11 -0700603 // mole in Chrome.
Paul Stewartf2d60912012-07-15 08:37:30 -0700604 affected_service->SetFailure(Service::kFailureBadPassphrase);
mukesh agrawalcf24a242012-05-21 16:46:11 -0700605 LOG(ERROR) << "Connection failure during 4-Way Handshake. Bad passphrase?";
Paul Stewartf2d60912012-07-15 08:37:30 -0700606 } else {
607 affected_service->SetFailureSilent(Service::kFailureUnknown);
mukesh agrawalcf24a242012-05-21 16:46:11 -0700608 }
mukesh agrawale1d90e92012-02-15 17:36:08 -0800609 affected_service->NotifyCurrentEndpoint(NULL);
Thieu Le67370f62012-02-14 23:01:42 +0000610 metrics()->NotifyServiceDisconnect(affected_service);
mukesh agrawal15908392011-11-16 18:29:25 +0000611
612 if (affected_service == pending_service_.get()) {
613 // The attempt to connect to |pending_service_| failed. Clear
614 // |pending_service_|, to indicate we're no longer in the middle
615 // of a connect request.
Paul Stewart2b05e622012-07-13 20:38:44 -0700616 SetPendingService(NULL);
mukesh agrawal15908392011-11-16 18:29:25 +0000617 } else if (pending_service_.get()) {
618 // We've attributed the disconnection to what was the
619 // |current_service_|, rather than the |pending_service_|.
620 //
621 // If we're wrong about that (i.e. supplicant reported this
622 // CurrentBSS change after attempting to connect to
623 // |pending_service_|), we're depending on supplicant to retry
624 // connecting to |pending_service_|, and delivering another
625 // CurrentBSS change signal in the future.
626 //
627 // Log this fact, to help us debug (in case our assumptions are
628 // wrong).
Ben Chanfad4a0b2012-04-18 15:49:59 -0700629 SLOG(WiFi, 2) << "WiFi " << link_name() << " pending connection to "
630 << pending_service_->friendly_name()
631 << " after disconnect";
mukesh agrawal15908392011-11-16 18:29:25 +0000632 }
Paul Stewarte369ece2012-05-22 09:11:03 -0700633
634 // If we disconnect, initially scan at a faster frequency, to make sure
635 // we've found all available APs.
636 RestartFastScanAttempts();
mukesh agrawal15908392011-11-16 18:29:25 +0000637}
638
639// We use the term "Roam" loosely. In particular, we include the case
640// where we "Roam" to a BSS from the disconnected state.
641void WiFi::HandleRoam(const ::DBus::Path &new_bss) {
642 EndpointMap::iterator endpoint_it = endpoint_by_rpcid_.find(new_bss);
643 if (endpoint_it == endpoint_by_rpcid_.end()) {
644 LOG(WARNING) << "WiFi " << link_name() << " connected to unknown BSS "
645 << new_bss;
646 return;
647 }
648
649 const WiFiEndpoint &endpoint(*endpoint_it->second);
mukesh agrawal165e6142011-11-22 02:22:56 +0000650 WiFiServiceRefPtr service = FindServiceForEndpoint(endpoint);
mukesh agrawal15908392011-11-16 18:29:25 +0000651 if (!service.get()) {
652 LOG(WARNING) << "WiFi " << link_name()
653 << " could not find Service for Endpoint "
654 << endpoint.bssid_string()
655 << " (service will be unchanged)";
656 return;
657 }
658
Ben Chanfad4a0b2012-04-18 15:49:59 -0700659 SLOG(WiFi, 2) << "WiFi " << link_name()
660 << " roamed to Endpoint " << endpoint.bssid_string()
661 << " (SSID " << endpoint.ssid_string() << ")";
mukesh agrawal15908392011-11-16 18:29:25 +0000662
mukesh agrawale1d90e92012-02-15 17:36:08 -0800663 service->NotifyCurrentEndpoint(&endpoint);
Thieu Lee41a72d2012-02-06 20:46:51 +0000664
mukesh agrawal15908392011-11-16 18:29:25 +0000665 if (pending_service_.get() &&
666 service.get() != pending_service_.get()) {
667 // The Service we've roamed on to is not the one we asked for.
668 // We assume that this is transient, and that wpa_supplicant
669 // is trying / will try to connect to |pending_service_|.
670 //
671 // If it succeeds, we'll end up back here, but with |service|
672 // pointing at the same service as |pending_service_|.
673 //
674 // If it fails, we'll process things in HandleDisconnect.
675 //
676 // So we leave |pending_service_| untouched.
Ben Chanfad4a0b2012-04-18 15:49:59 -0700677 SLOG(WiFi, 2) << "WiFi " << link_name()
678 << " new current Endpoint "
679 << endpoint.bssid_string()
680 << " is not part of pending service "
681 << pending_service_->friendly_name();
mukesh agrawal15908392011-11-16 18:29:25 +0000682
683 // Sanity check: if we didn't roam onto |pending_service_|, we
684 // should still be on |current_service_|.
685 if (service.get() != current_service_.get()) {
686 LOG(WARNING) << "WiFi " << link_name()
687 << " new current Endpoint "
688 << endpoint.bssid_string()
689 << " is neither part of pending service "
690 << pending_service_->friendly_name()
691 << " nor part of current service "
692 << (current_service_.get() ?
693 current_service_->friendly_name() :
694 "(NULL)");
695 // Although we didn't expect to get here, we should keep
696 // |current_service_| in sync with what supplicant has done.
697 current_service_ = service;
698 }
699 return;
700 }
701
702 if (pending_service_.get()) {
703 // We assume service.get() == pending_service_.get() here, because
704 // of the return in the previous if clause.
705 //
706 // Boring case: we've connected to the service we asked
707 // for. Simply update |current_service_| and |pending_service_|.
708 current_service_ = service;
Paul Stewart2b05e622012-07-13 20:38:44 -0700709 SetPendingService(NULL);
mukesh agrawal15908392011-11-16 18:29:25 +0000710 return;
711 }
712
713 // |pending_service_| was NULL, so we weren't attempting to connect
714 // to a new Service. Sanity check that we're still on
715 // |current_service_|.
716 if (service.get() != current_service_.get()) {
717 LOG(WARNING)
718 << "WiFi " << link_name()
719 << " new current Endpoint "
720 << endpoint.bssid_string()
721 << (current_service_.get() ?
mukesh agrawal8a3188d2011-12-01 20:56:44 +0000722 StringPrintf(" is not part of current service %s",
mukesh agrawal15908392011-11-16 18:29:25 +0000723 current_service_->friendly_name().c_str()) :
mukesh agrawal8a3188d2011-12-01 20:56:44 +0000724 " with no current service");
mukesh agrawal15908392011-11-16 18:29:25 +0000725 // We didn't expect to be here, but let's cope as well as we
726 // can. Update |current_service_| to keep it in sync with
727 // supplicant.
728 current_service_ = service;
Paul Stewartabbe2792012-07-15 07:50:35 -0700729
730 // If this service isn't already marked as actively connecting (likely,
731 // since this service is a bit of a surprise) set the service as
732 // associating.
733 if (!current_service_->IsConnecting()) {
734 current_service_->SetState(Service::kStateAssociating);
735 }
736
mukesh agrawal15908392011-11-16 18:29:25 +0000737 return;
738 }
739
740 // At this point, we know that |pending_service_| was NULL, and that
741 // we're still on |current_service_|. This is the most boring case
742 // of all, because there's no state to update here.
743 return;
mukesh agrawalb54601c2011-06-07 17:39:22 -0700744}
745
Paul Stewarta41e38d2011-11-11 07:47:29 -0800746WiFiServiceRefPtr WiFi::FindService(const vector<uint8_t> &ssid,
747 const string &mode,
748 const string &security) const {
Paul Stewart6ab23a92011-11-09 17:17:47 -0800749 for (vector<WiFiServiceRefPtr>::const_iterator it = services_.begin();
750 it != services_.end();
751 ++it) {
752 if ((*it)->ssid() == ssid && (*it)->mode() == mode &&
753 (*it)->IsSecurityMatch(security)) {
754 return *it;
755 }
756 }
757 return NULL;
758}
759
mukesh agrawal165e6142011-11-22 02:22:56 +0000760WiFiServiceRefPtr WiFi::FindServiceForEndpoint(const WiFiEndpoint &endpoint) {
761 return FindService(endpoint.ssid(),
762 endpoint.network_mode(),
763 endpoint.security_mode());
764}
765
Paul Stewartced6a0b2011-11-08 15:32:04 -0800766ByteArrays WiFi::GetHiddenSSIDList() {
767 // Create a unique set of hidden SSIDs.
768 set<ByteArray> hidden_ssids_set;
769 for (vector<WiFiServiceRefPtr>::const_iterator it = services_.begin();
770 it != services_.end();
771 ++it) {
Paul Stewart10ccbb32012-04-26 15:59:30 -0700772 if ((*it)->hidden_ssid() && (*it)->IsRemembered()) {
Paul Stewartced6a0b2011-11-08 15:32:04 -0800773 hidden_ssids_set.insert((*it)->ssid());
774 }
775 }
Ben Chanfad4a0b2012-04-18 15:49:59 -0700776 SLOG(WiFi, 2) << "Found " << hidden_ssids_set.size() << " hidden services";
Paul Stewartced6a0b2011-11-08 15:32:04 -0800777 ByteArrays hidden_ssids(hidden_ssids_set.begin(), hidden_ssids_set.end());
778 if (!hidden_ssids.empty()) {
779 // TODO(pstew): Devise a better method for time-sharing with SSIDs that do
780 // not fit in.
781 if (hidden_ssids.size() >= wpa_supplicant::kScanMaxSSIDsPerScan) {
782 hidden_ssids.erase(
783 hidden_ssids.begin() + wpa_supplicant::kScanMaxSSIDsPerScan - 1,
784 hidden_ssids.end());
785 }
786 // Add Broadcast SSID, signified by an empty ByteArray. If we specify
787 // SSIDs to wpa_supplicant, we need to explicitly specify the default
788 // behavior of doing a broadcast probe.
789 hidden_ssids.push_back(ByteArray());
790 }
791 return hidden_ssids;
792}
793
Paul Stewarta41e38d2011-11-11 07:47:29 -0800794bool WiFi::LoadHiddenServices(StoreInterface *storage) {
795 bool created_hidden_service = false;
796 set<string> groups = storage->GetGroupsWithKey(flimflam::kWifiHiddenSsid);
797 for (set<string>::iterator it = groups.begin(); it != groups.end(); ++it) {
798 bool is_hidden = false;
799 if (!storage->GetBool(*it, flimflam::kWifiHiddenSsid, &is_hidden)) {
Ben Chanfad4a0b2012-04-18 15:49:59 -0700800 SLOG(WiFi, 2) << "Storage group " << *it << " returned by "
801 << "GetGroupsWithKey failed for GetBool("
802 << flimflam::kWifiHiddenSsid
803 << ") -- possible non-bool key";
Paul Stewarta41e38d2011-11-11 07:47:29 -0800804 continue;
805 }
806 if (!is_hidden) {
807 continue;
808 }
809 string ssid_hex;
810 vector<uint8_t> ssid_bytes;
811 if (!storage->GetString(*it, flimflam::kSSIDProperty, &ssid_hex) ||
812 !base::HexStringToBytes(ssid_hex, &ssid_bytes)) {
Ben Chanfad4a0b2012-04-18 15:49:59 -0700813 SLOG(WiFi, 2) << "Hidden network is missing/invalid \""
814 << flimflam::kSSIDProperty << "\" property";
Paul Stewarta41e38d2011-11-11 07:47:29 -0800815 continue;
816 }
817 string device_address;
818 string network_mode;
819 string security;
820 // It is gross that we have to do this, but the only place we can
821 // get information about the service is from its storage name.
822 if (!WiFiService::ParseStorageIdentifier(*it, &device_address,
823 &network_mode, &security) ||
824 device_address != address()) {
Ben Chanfad4a0b2012-04-18 15:49:59 -0700825 SLOG(WiFi, 2) << "Hidden network has unparsable storage identifier \""
826 << *it << "\"";
Paul Stewarta41e38d2011-11-11 07:47:29 -0800827 continue;
828 }
829 if (FindService(ssid_bytes, network_mode, security).get()) {
830 // If service already exists, we have nothing to do, since the
831 // service has already loaded its configuration from storage.
832 // This is guaranteed to happen in both cases where Load() is
833 // called on a device (via a ConfigureDevice() call on the
834 // profile):
835 // - In RegisterDevice() the Device hasn't been started yet,
836 // so it has no services registered, except for those
837 // created by previous iterations of LoadHiddenService().
838 // The latter can happen if another profile in the Manager's
839 // stack defines the same ssid/mode/security. Even this
840 // case is okay, since even if the profiles differ
841 // materially on configuration and credentials, the "right"
842 // one will be configured in the course of the
843 // RegisterService() call below.
844 // - In PushProfile(), all registered services have been
845 // introduced to the profile via ConfigureService() prior
846 // to calling ConfigureDevice() on the profile.
847 continue;
848 }
849 WiFiServiceRefPtr service(new WiFiService(control_interface(),
850 dispatcher(),
Thieu Le3426c8f2012-01-11 17:35:11 -0800851 metrics(),
Paul Stewarta41e38d2011-11-11 07:47:29 -0800852 manager(),
853 this,
854 ssid_bytes,
855 network_mode,
856 security,
857 true));
858 services_.push_back(service);
859
860 // By registering the service, the rest of the configuration
861 // will be loaded from the profile into the service via ConfigureService().
862 manager()->RegisterService(service);
863
864 created_hidden_service = true;
865 }
866
867 // If we are idle and we created a service as a result of opening the
868 // profile, we should initiate a scan for our new hidden SSID.
869 if (running() && created_hidden_service &&
870 supplicant_state_ == wpa_supplicant::kInterfaceStateInactive) {
871 Scan(NULL);
872 }
873
874 return created_hidden_service;
875}
876
Paul Stewart66c86002012-01-30 18:00:52 -0800877void WiFi::ClearCachedCredentialsTask() {
Paul Stewart57f3d9d2012-04-11 18:21:41 -0700878 try {
879 supplicant_interface_proxy_->ClearCachedCredentials();
Ben Chan80326f32012-05-04 17:51:32 -0700880 } catch (const DBus::Error &e) { // NOLINT
Paul Stewart57f3d9d2012-04-11 18:21:41 -0700881 LOG(WARNING) << "Clear of cached credentials failed.";
882 }
Paul Stewart66c86002012-01-30 18:00:52 -0800883 clear_cached_credentials_pending_ = false;
884}
885
mukesh agrawalb4bc57d2011-12-07 01:07:47 +0000886void WiFi::BSSAddedTask(
887 const ::DBus::Path &path,
888 const map<string, ::DBus::Variant> &properties) {
mukesh agrawalb4bc57d2011-12-07 01:07:47 +0000889 // Note: we assume that BSSIDs are unique across endpoints. This
890 // means that if an AP reuses the same BSSID for multiple SSIDs, we
891 // lose.
mukesh agrawalb20776f2012-02-10 16:00:36 -0800892 WiFiEndpointRefPtr endpoint(
893 new WiFiEndpoint(proxy_factory_, this, path, properties));
mukesh agrawalb4bc57d2011-12-07 01:07:47 +0000894 LOG(INFO) << "Found endpoint. "
mukesh agrawale9adda12012-02-09 18:33:48 -0800895 << "RPC path: " << path << ", "
mukesh agrawalb4bc57d2011-12-07 01:07:47 +0000896 << "ssid: " << endpoint->ssid_string() << ", "
897 << "bssid: " << endpoint->bssid_string() << ", "
898 << "signal: " << endpoint->signal_strength() << ", "
Thieu Lee41a72d2012-02-06 20:46:51 +0000899 << "security: " << endpoint->security_mode() << ", "
900 << "frequency: " << endpoint->frequency();
mukesh agrawalb4bc57d2011-12-07 01:07:47 +0000901
902 if (endpoint->ssid_string().empty()) {
903 // Don't bother trying to find or create a Service for an Endpoint
904 // without an SSID. We wouldn't be able to connect to it anyway.
905 return;
906 }
907
mukesh agrawalb3857612012-01-18 16:23:29 -0800908 if (endpoint->ssid()[0] == 0) {
909 // Assume that an SSID starting with NULL is bogus/misconfigured,
910 // and filter it out.
911 return;
912 }
913
mukesh agrawalb4bc57d2011-12-07 01:07:47 +0000914 WiFiServiceRefPtr service = FindServiceForEndpoint(*endpoint);
915 if (service) {
916 LOG(INFO) << "Assigned endpoint " << endpoint->bssid_string()
917 << " to service " << service->friendly_name() << ".";
918 service->AddEndpoint(endpoint);
919
920 if (manager()->HasService(service)) {
921 manager()->UpdateService(service);
922 } else {
Darin Petkov4a66cc52012-06-15 10:08:29 +0200923 // Expect registered by now if >1.
924 DCHECK_EQ(1, service->GetEndpointCount());
mukesh agrawalb4bc57d2011-12-07 01:07:47 +0000925 manager()->RegisterService(service);
926 }
mukesh agrawale9adda12012-02-09 18:33:48 -0800927 } else {
928 const bool hidden_ssid = false;
929 service = CreateServiceForEndpoint(*endpoint, hidden_ssid);
930 LOG(INFO) << "New service " << service->GetRpcIdentifier()
931 << " (" << service->friendly_name() << ")";
932 service->AddEndpoint(endpoint);
933 manager()->RegisterService(service);
mukesh agrawalb4bc57d2011-12-07 01:07:47 +0000934 }
935
mukesh agrawale9adda12012-02-09 18:33:48 -0800936 // Do this last, to maintain the invariant that any Endpoint we
937 // know about has a corresponding Service.
mukesh agrawalb20776f2012-02-10 16:00:36 -0800938 //
939 // TODO(quiche): Write test to verify correct behavior in the case
940 // where we get multiple BSSAdded events for a single endpoint.
941 // (Old Endpoint's refcount should fall to zero, and old Endpoint
942 // should be destroyed.)
mukesh agrawale9adda12012-02-09 18:33:48 -0800943 endpoint_by_rpcid_[path] = endpoint;
mukesh agrawalb20776f2012-02-10 16:00:36 -0800944 endpoint->Start();
mukesh agrawalb4bc57d2011-12-07 01:07:47 +0000945}
946
947void WiFi::BSSRemovedTask(const ::DBus::Path &path) {
948 EndpointMap::iterator i = endpoint_by_rpcid_.find(path);
949 if (i == endpoint_by_rpcid_.end()) {
950 LOG(WARNING) << "WiFi " << link_name()
951 << " could not find BSS " << path
952 << " to remove.";
953 return;
954 }
955
956 WiFiEndpointRefPtr endpoint = i->second;
957 CHECK(endpoint);
958 endpoint_by_rpcid_.erase(i);
959
mukesh agrawalb4bc57d2011-12-07 01:07:47 +0000960 WiFiServiceRefPtr service = FindServiceForEndpoint(*endpoint);
mukesh agrawale9adda12012-02-09 18:33:48 -0800961 CHECK(service) << "Can't find Service for Endpoint "
962 << path << " "
963 << "(with BSSID " << endpoint->bssid_string() << ").";
Ben Chanfad4a0b2012-04-18 15:49:59 -0700964 SLOG(WiFi, 2) << "Removing Endpoint " << endpoint->bssid_string()
965 << " from Service " << service->friendly_name();
mukesh agrawalb4bc57d2011-12-07 01:07:47 +0000966 service->RemoveEndpoint(endpoint);
mukesh agrawalb4bc57d2011-12-07 01:07:47 +0000967
mukesh agrawal8a3188d2011-12-01 20:56:44 +0000968 bool disconnect_service = !service->HasEndpoints() &&
969 (service->IsConnecting() || service->IsConnected());
970 bool forget_service =
971 // Forget Services without Endpoints, except that we always keep
972 // hidden services around. (We need them around to populate the
973 // hidden SSIDs list.)
974 !service->HasEndpoints() && !service->hidden_ssid();
975 bool deregister_service =
976 // Only deregister a Service if we're forgetting it. Otherwise,
977 // Manager can't keep our configuration up-to-date (as Profiles
978 // change).
979 forget_service;
980
981 if (disconnect_service) {
982 DisconnectFrom(service);
983 }
984
985 if (deregister_service) {
986 manager()->DeregisterService(service);
987 } else {
988 manager()->UpdateService(service);
989 }
990
991 if (forget_service) {
992 vector<WiFiServiceRefPtr>::iterator it;
993 it = std::find(services_.begin(), services_.end(), service);
994 if (it != services_.end()) {
995 services_.erase(it);
996 }
997 }
mukesh agrawalb4bc57d2011-12-07 01:07:47 +0000998}
999
Paul Stewartbc6e7392012-05-24 07:07:48 -07001000void WiFi::CertificationTask(
1001 const map<string, ::DBus::Variant> &properties) {
1002 if (!current_service_) {
1003 LOG(ERROR) << "WiFi " << link_name() << " " << __func__
1004 << " with no current service.";
1005 return;
1006 }
1007
1008 map<string, ::DBus::Variant>::const_iterator properties_it =
1009 properties.find(wpa_supplicant::kInterfacePropertyDepth);
1010 if (properties_it == properties.end()) {
1011 LOG(ERROR) << __func__ << " no depth parameter.";
1012 return;
1013 }
1014 uint32 depth = properties_it->second.reader().get_uint32();
1015 properties_it = properties.find(wpa_supplicant::kInterfacePropertySubject);
1016 if (properties_it == properties.end()) {
1017 LOG(ERROR) << __func__ << " no subject parameter.";
1018 return;
1019 }
1020 string subject(properties_it->second.reader().get_string());
1021 current_service_->AddEAPCertification(subject, depth);
1022}
1023
mukesh agrawal15908392011-11-16 18:29:25 +00001024void WiFi::PropertiesChangedTask(
1025 const map<string, ::DBus::Variant> &properties) {
1026 // TODO(quiche): Handle changes in other properties (e.g. signal
1027 // strength).
1028
1029 // Note that order matters here. In particular, we want to process
1030 // changes in the current BSS before changes in state. This is so
1031 // that we update the state of the correct Endpoint/Service.
1032
1033 map<string, ::DBus::Variant>::const_iterator properties_it =
1034 properties.find(wpa_supplicant::kInterfacePropertyCurrentBSS);
1035 if (properties_it != properties.end()) {
1036 CurrentBSSChanged(properties_it->second.reader().get_path());
1037 }
1038
1039 properties_it = properties.find(wpa_supplicant::kInterfacePropertyState);
1040 if (properties_it != properties.end()) {
1041 StateChanged(properties_it->second.reader().get_string());
1042 }
1043}
1044
mukesh agrawaldc42bb32011-07-28 10:40:26 -07001045void WiFi::ScanDoneTask() {
Ben Chanfad4a0b2012-04-18 15:49:59 -07001046 SLOG(WiFi, 2) << __func__ << " need_bss_flush_ " << need_bss_flush_;
mukesh agrawal5c05b292012-03-07 10:12:52 -08001047 if (need_bss_flush_) {
1048 CHECK(supplicant_interface_proxy_ != NULL);
1049 // Compute |max_age| relative to |resumed_at_|, to account for the
1050 // time taken to scan.
1051 struct timeval now;
1052 uint32_t max_age;
1053 time_->GetTimeMonotonic(&now);
1054 max_age = kMaxBSSResumeAgeSeconds + (now.tv_sec - resumed_at_.tv_sec);
1055 supplicant_interface_proxy_->FlushBSS(max_age);
1056 need_bss_flush_ = false;
1057 }
mukesh agrawalb54601c2011-06-07 17:39:22 -07001058 scan_pending_ = false;
mukesh agrawalb66c6462012-05-07 11:45:25 -07001059 StartScanTimer();
mukesh agrawalb54601c2011-06-07 17:39:22 -07001060}
1061
mukesh agrawal32399322011-09-01 10:53:43 -07001062void WiFi::ScanTask() {
Ben Chanfad4a0b2012-04-18 15:49:59 -07001063 SLOG(WiFi, 2) << "WiFi " << link_name() << " scan requested.";
Paul Stewarta41e38d2011-11-11 07:47:29 -08001064 map<string, DBus::Variant> scan_args;
mukesh agrawal6e277772011-09-29 15:04:23 -07001065 scan_args[wpa_supplicant::kPropertyScanType].writer().
1066 append_string(wpa_supplicant::kScanTypeActive);
Paul Stewartced6a0b2011-11-08 15:32:04 -08001067
1068 ByteArrays hidden_ssids = GetHiddenSSIDList();
1069 if (!hidden_ssids.empty()) {
1070 scan_args[wpa_supplicant::kPropertyScanSSIDs] =
1071 DBusAdaptor::ByteArraysToVariant(hidden_ssids);
1072 }
1073
Gaurav Shahf8721ee2011-11-07 09:12:46 -08001074 // TODO(quiche): Indicate scanning in UI. crosbug.com/14887
Gaurav Shah10109f22011-11-11 20:16:22 -08001075 try {
1076 supplicant_interface_proxy_->Scan(scan_args);
1077 scan_pending_ = true;
Ben Chan80326f32012-05-04 17:51:32 -07001078 } catch (const DBus::Error &e) { // NOLINT
Darin Petkov2b8e44e2012-06-25 15:13:26 +02001079 // A scan may fail if, for example, the wpa_supplicant vanishing
1080 // notification is posted after this task has already started running.
1081 LOG(WARNING) << "Scan failed: " << e.what();
Gaurav Shah10109f22011-11-11 20:16:22 -08001082 }
mukesh agrawal32399322011-09-01 10:53:43 -07001083}
1084
mukesh agrawal15908392011-11-16 18:29:25 +00001085void WiFi::StateChanged(const string &new_state) {
1086 const string old_state = supplicant_state_;
mukesh agrawal7ec71312011-11-10 02:08:26 +00001087 supplicant_state_ = new_state;
mukesh agrawal15908392011-11-16 18:29:25 +00001088 LOG(INFO) << "WiFi " << link_name() << " " << __func__ << " "
1089 << old_state << " -> " << new_state;
1090
1091 WiFiService *affected_service;
1092 // Identify the service to which the state change applies. If
1093 // |pending_service_| is non-NULL, then the state change applies to
1094 // |pending_service_|. Otherwise, it applies to |current_service_|.
1095 //
1096 // This policy is driven by the fact that the |pending_service_|
1097 // doesn't become the |current_service_| until wpa_supplicant
1098 // reports a CurrentBSS change to the |pending_service_|. And the
mukesh agrawalc01f3982012-01-24 13:48:39 -08001099 // CurrentBSS change won't be reported until the |pending_service_|
mukesh agrawal15908392011-11-16 18:29:25 +00001100 // reaches the wpa_supplicant::kInterfaceStateCompleted state.
1101 affected_service =
1102 pending_service_.get() ? pending_service_.get() : current_service_.get();
1103 if (!affected_service) {
Ben Chanfad4a0b2012-04-18 15:49:59 -07001104 SLOG(WiFi, 2) << "WiFi " << link_name() << " " << __func__
1105 << " with no service";
mukesh agrawal15908392011-11-16 18:29:25 +00001106 return;
1107 }
1108
Paul Stewart44663922012-07-30 11:03:03 -07001109 if (new_state == wpa_supplicant::kInterfaceStateCompleted) {
1110 if (affected_service->IsConnected()) {
1111 StopReconnectTimer();
1112 } else if (AcquireIPConfigWithLeaseName(
1113 affected_service->GetStorageIdentifier())) {
Paul Stewartd408fdf2012-05-07 17:15:57 -07001114 LOG(INFO) << link_name() << " is up; started L3 configuration.";
mukesh agrawalc01f3982012-01-24 13:48:39 -08001115 affected_service->SetState(Service::kStateConfiguring);
1116 } else {
1117 LOG(ERROR) << "Unable to acquire DHCP config.";
1118 }
mukesh agrawal15908392011-11-16 18:29:25 +00001119 } else if (new_state == wpa_supplicant::kInterfaceStateAssociated) {
1120 affected_service->SetState(Service::kStateAssociating);
1121 } else if (new_state == wpa_supplicant::kInterfaceStateAuthenticating ||
1122 new_state == wpa_supplicant::kInterfaceStateAssociating ||
1123 new_state == wpa_supplicant::kInterfaceState4WayHandshake ||
1124 new_state == wpa_supplicant::kInterfaceStateGroupHandshake) {
1125 // Ignore transitions into these states from Completed, to avoid
1126 // bothering the user when roaming, or re-keying.
1127 if (old_state != wpa_supplicant::kInterfaceStateCompleted)
1128 affected_service->SetState(Service::kStateAssociating);
1129 // TOOD(quiche): On backwards transitions, we should probably set
1130 // a timeout for getting back into the completed state. At present,
1131 // we depend on wpa_supplicant eventually reporting that CurrentBSS
mukesh agrawal8a3188d2011-12-01 20:56:44 +00001132 // has changed. But there may be cases where that signal is not sent.
mukesh agrawal15908392011-11-16 18:29:25 +00001133 // (crosbug.com/23207)
Paul Stewart44663922012-07-30 11:03:03 -07001134 } else if (new_state == wpa_supplicant::kInterfaceStateDisconnected &&
1135 affected_service == current_service_ &&
1136 affected_service->IsConnected()) {
1137 // This means that wpa_supplicant failed in a re-connect attempt, but
1138 // may still be reconnecting. Give wpa_supplicant a limited amount of
1139 // time to transition out this condition by either connecting or changing
1140 // CurrentBSS.
1141 StartReconnectTimer();
mukesh agrawal15908392011-11-16 18:29:25 +00001142 } else {
1143 // Other transitions do not affect Service state.
1144 //
1145 // Note in particular that we ignore a State change into
1146 // kInterfaceStateDisconnected, in favor of observing the corresponding
1147 // change in CurrentBSS.
1148 }
mukesh agrawal7ec71312011-11-10 02:08:26 +00001149}
1150
mukesh agrawalcf24a242012-05-21 16:46:11 -07001151bool WiFi::SuspectCredentials(const WiFiService &service) const {
1152 if (!service.IsSecurityMatch(flimflam::kSecurityPsk)) {
1153 // We can only diagnose credentials for WPA/RSN networks. For
1154 // others, assume the failure was not credential related.
1155 return false;
1156 }
1157
1158 return supplicant_state_ == wpa_supplicant::kInterfaceState4WayHandshake &&
1159 !service.has_ever_connected();
1160}
1161
mukesh agrawal7ec71312011-11-10 02:08:26 +00001162// Used by Manager.
mukesh agrawal7a4e4002011-09-06 11:26:05 -07001163WiFiServiceRefPtr WiFi::GetService(const KeyValueStore &args, Error *error) {
Darin Petkovb65c2452012-02-23 15:17:06 +01001164 CHECK_EQ(args.GetString(flimflam::kTypeProperty), flimflam::kTypeWifi);
mukesh agrawal7a4e4002011-09-06 11:26:05 -07001165
1166 if (args.ContainsString(flimflam::kModeProperty) &&
1167 args.GetString(flimflam::kModeProperty) !=
1168 flimflam::kModeManaged) {
mukesh agrawal06175d72012-04-23 16:46:01 -07001169 Error::PopulateAndLog(error, Error::kNotSupported,
1170 kManagerErrorUnsupportedServiceMode);
mukesh agrawal7a4e4002011-09-06 11:26:05 -07001171 return NULL;
1172 }
1173
1174 if (!args.ContainsString(flimflam::kSSIDProperty)) {
mukesh agrawal06175d72012-04-23 16:46:01 -07001175 Error::PopulateAndLog(error, Error::kInvalidArguments,
1176 kManagerErrorSSIDRequired);
mukesh agrawal7a4e4002011-09-06 11:26:05 -07001177 return NULL;
1178 }
1179
1180 string ssid = args.GetString(flimflam::kSSIDProperty);
1181 if (ssid.length() < 1) {
mukesh agrawal06175d72012-04-23 16:46:01 -07001182 Error::PopulateAndLog(error, Error::kInvalidNetworkName,
1183 kManagerErrorSSIDTooShort);
mukesh agrawal7a4e4002011-09-06 11:26:05 -07001184 return NULL;
1185 }
1186
1187 if (ssid.length() > IEEE_80211::kMaxSSIDLen) {
mukesh agrawal06175d72012-04-23 16:46:01 -07001188 Error::PopulateAndLog(error, Error::kInvalidNetworkName,
1189 kManagerErrorSSIDTooLong);
mukesh agrawal7a4e4002011-09-06 11:26:05 -07001190 return NULL;
1191 }
1192
1193 string security_method;
1194 if (args.ContainsString(flimflam::kSecurityProperty)) {
1195 security_method = args.GetString(flimflam::kSecurityProperty);
1196 } else {
1197 security_method = flimflam::kSecurityNone;
1198 }
1199
1200 if (security_method != flimflam::kSecurityNone &&
1201 security_method != flimflam::kSecurityWep &&
1202 security_method != flimflam::kSecurityPsk &&
1203 security_method != flimflam::kSecurityWpa &&
1204 security_method != flimflam::kSecurityRsn &&
1205 security_method != flimflam::kSecurity8021x) {
mukesh agrawal06175d72012-04-23 16:46:01 -07001206 Error::PopulateAndLog(error, Error::kNotSupported,
1207 kManagerErrorUnsupportedSecurityMode);
mukesh agrawal7a4e4002011-09-06 11:26:05 -07001208 return NULL;
1209 }
1210
Paul Stewart6ab23a92011-11-09 17:17:47 -08001211 bool hidden_ssid;
Paul Stewartced6a0b2011-11-08 15:32:04 -08001212 if (args.ContainsBool(flimflam::kWifiHiddenSsid)) {
1213 hidden_ssid = args.GetBool(flimflam::kWifiHiddenSsid);
Paul Stewart6ab23a92011-11-09 17:17:47 -08001214 } else {
1215 // If the service is not found, and the caller hasn't specified otherwise,
1216 // we assume this is is a hidden network.
1217 hidden_ssid = true;
Paul Stewartced6a0b2011-11-08 15:32:04 -08001218 }
1219
Paul Stewart6ab23a92011-11-09 17:17:47 -08001220 vector<uint8_t> ssid_bytes(ssid.begin(), ssid.end());
1221 WiFiServiceRefPtr service(FindService(ssid_bytes, flimflam::kModeManaged,
1222 security_method));
1223 if (!service.get()) {
mukesh agrawal1a056262011-10-05 14:36:54 -07001224 service = new WiFiService(control_interface(),
1225 dispatcher(),
Thieu Le3426c8f2012-01-11 17:35:11 -08001226 metrics(),
mukesh agrawal1a056262011-10-05 14:36:54 -07001227 manager(),
1228 this,
Paul Stewart6ab23a92011-11-09 17:17:47 -08001229 ssid_bytes,
mukesh agrawal1a056262011-10-05 14:36:54 -07001230 flimflam::kModeManaged,
Paul Stewartced6a0b2011-11-08 15:32:04 -08001231 security_method,
1232 hidden_ssid);
1233 services_.push_back(service);
mukesh agrawal261daca2011-12-02 18:56:56 +00001234 // NB: We do not register the newly created Service with the Manager.
1235 // The Service will be registered if/when we find Endpoints for it.
mukesh agrawal7a4e4002011-09-06 11:26:05 -07001236 }
1237
mukesh agrawalb172e4a2012-04-25 18:15:30 -07001238 if ((security_method == flimflam::kSecurityWep ||
1239 security_method == flimflam::kSecurityPsk ||
1240 security_method == flimflam::kSecurityWpa ||
1241 security_method == flimflam::kSecurityRsn) &&
1242 args.ContainsString(flimflam::kPassphraseProperty)) {
mukesh agrawal1a056262011-10-05 14:36:54 -07001243 service->SetPassphrase(args.GetString(flimflam::kPassphraseProperty),
1244 error);
1245 if (error->IsFailure()) {
1246 return NULL;
1247 }
1248 }
1249
Paul Stewartcb59fed2012-03-21 21:14:46 -07001250 service->Configure(args, error);
mukesh agrawal7a4e4002011-09-06 11:26:05 -07001251
Paul Stewart7f61e522012-03-22 11:13:45 -07001252 // TODO(pstew): Schedule a task to forget up all non-hidden services that
1253 // have no endpoints like the one we may have just created. crosbug.com/28224
1254
mukesh agrawal7a4e4002011-09-06 11:26:05 -07001255 return service;
1256}
1257
mukesh agrawal16bc1b82012-02-09 18:38:26 -08001258// static
1259bool WiFi::SanitizeSSID(string *ssid) {
1260 CHECK(ssid);
1261
1262 size_t ssid_len = ssid->length();
1263 size_t i;
1264 bool changed = false;
1265
Gary Morainac1bdb42012-02-16 17:42:29 -08001266 for (i = 0; i < ssid_len; ++i) {
mukesh agrawal16bc1b82012-02-09 18:38:26 -08001267 if (!g_ascii_isprint((*ssid)[i])) {
1268 (*ssid)[i] = '?';
1269 changed = true;
1270 }
1271 }
1272
1273 return changed;
1274}
1275
Paul Stewart3c508e12012-08-09 11:40:06 -07001276void WiFi::OnLinkMonitorFailure() {
1277 // If we have never found the gateway, let's be conservative and not
1278 // do anything, in case this network topology does not have a gateway.
1279 if (!link_monitor()->IsGatewayFound()) {
1280 LOG(INFO) << "In " << __func__ << "(): "
1281 << "Skipping reassociate since gateway was never found.";
1282 return;
1283 }
1284
1285 if (!supplicant_present_) {
1286 LOG(ERROR) << "In " << __func__ << "(): "
1287 << "wpa_supplicant is not present. Cannot reassociate.";
1288 return;
1289 }
1290
1291 try {
1292 supplicant_interface_proxy_->Reassociate();
1293 LOG(INFO) << "In " << __func__ << "(): Called Reassociate().";
1294 } catch (const DBus::Error &e) { // NOLINT
1295 LOG(ERROR) << "In " << __func__ << "(): failed to call Reassociate().";
1296 return;
1297 }
1298}
1299
mukesh agrawal4d0401c2012-01-06 16:05:31 -08001300void WiFi::HelpRegisterDerivedInt32(
1301 PropertyStore *store,
1302 const string &name,
1303 int32(WiFi::*get)(Error *error),
1304 void(WiFi::*set)(const int32 &value, Error *error)) {
1305 store->RegisterDerivedInt32(
1306 name,
1307 Int32Accessor(new CustomAccessor<WiFi, int32>(this, get, set)));
1308}
1309
mukesh agrawal4d0401c2012-01-06 16:05:31 -08001310void WiFi::HelpRegisterDerivedUint16(
1311 PropertyStore *store,
1312 const string &name,
1313 uint16(WiFi::*get)(Error *error),
1314 void(WiFi::*set)(const uint16 &value, Error *error)) {
1315 store->RegisterDerivedUint16(
1316 name,
1317 Uint16Accessor(new CustomAccessor<WiFi, uint16>(this, get, set)));
1318}
1319
mukesh agrawal2f9df4e2012-08-08 12:29:20 -07001320void WiFi::OnAfterResume() {
mukesh agrawal5c05b292012-03-07 10:12:52 -08001321 LOG(INFO) << __func__;
mukesh agrawal2f9df4e2012-08-08 12:29:20 -07001322 Device::OnAfterResume(); // May refresh ipconfig_
mukesh agrawal5c05b292012-03-07 10:12:52 -08001323
mukesh agrawal2f9df4e2012-08-08 12:29:20 -07001324 // We want to flush the BSS cache, but we don't want to conflict
1325 // with a running scan or an active connection attempt. So record
1326 // the need to flush, and take care of flushing when the next scan
1327 // completes.
1328 //
1329 // Note that supplicant will automatically expire old cache
1330 // entries (after, e.g., a BSS is not found in two consecutive
1331 // scans). However, our explicit flush accelerates re-association
1332 // in cases where a BSS disappeared while we were asleep. (See,
1333 // e.g. WiFiRoaming.005SuspendRoam.)
1334 time_->GetTimeMonotonic(&resumed_at_);
1335 need_bss_flush_ = true;
1336
1337 if (!scan_pending_ && IsIdle()) {
1338 // Not scanning/connecting/connected, so let's get things rolling.
1339 Scan(NULL);
1340 } else {
1341 SLOG(WiFi, 1) << __func__
1342 << " skipping scan, already scanning or connected.";
Gary Morainac1bdb42012-02-16 17:42:29 -08001343 }
1344}
1345
Paul Stewarte369ece2012-05-22 09:11:03 -07001346void WiFi::RestartFastScanAttempts() {
1347 fast_scans_remaining_ = kNumFastScanAttempts;
1348 StartScanTimer();
1349}
1350
mukesh agrawalb66c6462012-05-07 11:45:25 -07001351void WiFi::StartScanTimer() {
1352 if (scan_interval_seconds_ == 0) {
1353 StopScanTimer();
1354 return;
1355 }
1356 scan_timer_callback_.Reset(
1357 Bind(&WiFi::ScanTimerHandler, weak_ptr_factory_.GetWeakPtr()));
Paul Stewarte369ece2012-05-22 09:11:03 -07001358 // Repeat the first few scans after disconnect relatively quickly so we
1359 // have reasonable trust that no APs we are looking for are present.
1360 dispatcher()->PostDelayedTask(scan_timer_callback_.callback(),
1361 fast_scans_remaining_ > 0 ?
1362 kFastScanIntervalSeconds * 1000 : scan_interval_seconds_ * 1000);
mukesh agrawalb66c6462012-05-07 11:45:25 -07001363}
1364
1365void WiFi::StopScanTimer() {
1366 scan_timer_callback_.Cancel();
1367}
1368
1369void WiFi::ScanTimerHandler() {
1370 SLOG(WiFi, 2) << "WiFi Device " << link_name() << ": " << __func__;
1371 if (IsIdle() && !scan_pending_) {
1372 Scan(NULL);
Paul Stewarte369ece2012-05-22 09:11:03 -07001373 if (fast_scans_remaining_ > 0) {
1374 --fast_scans_remaining_;
1375 }
mukesh agrawalb66c6462012-05-07 11:45:25 -07001376 }
1377 StartScanTimer();
1378}
1379
Paul Stewart2b05e622012-07-13 20:38:44 -07001380void WiFi::StartPendingTimer() {
1381 pending_timeout_callback_.Reset(
1382 Bind(&WiFi::PendingTimeoutHandler, weak_ptr_factory_.GetWeakPtr()));
1383 dispatcher()->PostDelayedTask(pending_timeout_callback_.callback(),
1384 kPendingTimeoutSeconds * 1000);
1385}
1386
1387void WiFi::StopPendingTimer() {
1388 pending_timeout_callback_.Cancel();
1389}
1390
1391void WiFi::SetPendingService(const WiFiServiceRefPtr &service) {
Paul Stewartff96a842012-08-13 15:59:10 -07001392 SLOG(WiFi, 2) << "WiFi " << link_name() << " setting pending service to "
1393 << (service ? service->friendly_name(): "NULL");
Paul Stewart2b05e622012-07-13 20:38:44 -07001394 if (service) {
1395 service->SetState(Service::kStateAssociating);
1396 StartPendingTimer();
1397 } else if (pending_service_) {
1398 StopPendingTimer();
1399 }
1400 pending_service_ = service;
1401}
1402
1403void WiFi::PendingTimeoutHandler() {
1404 LOG(INFO) << "WiFi Device " << link_name() << ": " << __func__;
1405 CHECK(pending_service_);
Paul Stewartff96a842012-08-13 15:59:10 -07001406 // Take a reference since pending_service_ will reset below.
1407 ServiceRefPtr service = pending_service_;
Paul Stewart2b05e622012-07-13 20:38:44 -07001408 DisconnectFrom(pending_service_);
Paul Stewartff96a842012-08-13 15:59:10 -07001409 service->SetFailure(Service::kFailureOutOfRange);
Paul Stewart2b05e622012-07-13 20:38:44 -07001410}
1411
Paul Stewart44663922012-07-30 11:03:03 -07001412void WiFi::StartReconnectTimer() {
Paul Stewart1aff7302012-08-04 20:04:47 -07001413 if (!reconnect_timeout_callback_.IsCancelled()) {
1414 LOG(INFO) << "WiFi Device " << link_name() << ": " << __func__
1415 << ": reconnect timer already running.";
1416 return;
1417 }
Paul Stewart44663922012-07-30 11:03:03 -07001418 LOG(INFO) << "WiFi Device " << link_name() << ": " << __func__;
1419 reconnect_timeout_callback_.Reset(
1420 Bind(&WiFi::ReconnectTimeoutHandler, weak_ptr_factory_.GetWeakPtr()));
1421 dispatcher()->PostDelayedTask(reconnect_timeout_callback_.callback(),
1422 kReconnectTimeoutSeconds * 1000);
1423}
1424
1425void WiFi::StopReconnectTimer() {
1426 SLOG(WiFi, 2) << "WiFi Device " << link_name() << ": " << __func__;
1427 reconnect_timeout_callback_.Cancel();
1428}
1429
1430void WiFi::ReconnectTimeoutHandler() {
1431 LOG(INFO) << "WiFi Device " << link_name() << ": " << __func__;
Paul Stewart1aff7302012-08-04 20:04:47 -07001432 reconnect_timeout_callback_.Cancel();
Paul Stewart44663922012-07-30 11:03:03 -07001433 CHECK(current_service_);
1434 current_service_->SetFailureSilent(Service::kFailureConnect);
1435 DisconnectFrom(current_service_);
1436}
1437
Darin Petkov2b8e44e2012-06-25 15:13:26 +02001438void WiFi::OnSupplicantAppear(const string &/*owner*/) {
1439 LOG(INFO) << "WPA supplicant appeared.";
1440 if (supplicant_present_) {
Darin Petkov9cd7ca12012-07-03 11:06:40 +02001441 // Restart the WiFi device if it's started already. This will reset the
1442 // state and connect the device to the new WPA supplicant instance.
1443 if (enabled()) {
1444 Restart();
1445 }
Darin Petkov2b8e44e2012-06-25 15:13:26 +02001446 return;
1447 }
1448 supplicant_present_ = true;
1449 ConnectToSupplicant();
1450}
1451
1452void WiFi::OnSupplicantVanish() {
1453 LOG(INFO) << "WPA supplicant vanished.";
1454 if (!supplicant_present_) {
1455 return;
1456 }
1457 supplicant_present_ = false;
1458 // Restart the WiFi device if it's started already. This will effectively
1459 // suspend the device until the WPA supplicant reappears.
1460 if (enabled()) {
1461 Restart();
1462 }
1463}
1464
1465void WiFi::ConnectToSupplicant() {
1466 LOG(INFO) << link_name() << ": " << (enabled() ? "enabled" : "disabled")
1467 << " supplicant: "
1468 << (supplicant_present_ ? "present" : "absent")
1469 << " proxy: "
1470 << (supplicant_process_proxy_.get() ? "non-null" : "null");
1471 if (!enabled() || !supplicant_present_ || supplicant_process_proxy_.get()) {
1472 return;
1473 }
1474 supplicant_process_proxy_.reset(
1475 proxy_factory_->CreateSupplicantProcessProxy(
1476 wpa_supplicant::kDBusPath, wpa_supplicant::kDBusAddr));
1477 ::DBus::Path interface_path;
1478 try {
1479 map<string, DBus::Variant> create_interface_args;
1480 create_interface_args[wpa_supplicant::kInterfacePropertyName].writer().
1481 append_string(link_name().c_str());
1482 create_interface_args[wpa_supplicant::kInterfacePropertyDriver].writer().
1483 append_string(wpa_supplicant::kDriverNL80211);
1484 create_interface_args[
1485 wpa_supplicant::kInterfacePropertyConfigFile].writer().
1486 append_string(SCRIPTDIR "/wpa_supplicant.conf");
1487 interface_path =
1488 supplicant_process_proxy_->CreateInterface(create_interface_args);
1489 } catch (const DBus::Error &e) { // NOLINT
1490 if (!strcmp(e.name(), wpa_supplicant::kErrorInterfaceExists)) {
1491 interface_path =
1492 supplicant_process_proxy_->GetInterface(link_name());
1493 // TODO(quiche): Is it okay to crash here, if device is missing?
1494 } else {
Paul Stewartb80c81c2012-06-28 13:05:45 -07001495 LOG(ERROR) << __func__ << ": Failed to create interface with supplicant.";
1496 return;
Darin Petkov2b8e44e2012-06-25 15:13:26 +02001497 }
1498 }
1499
1500 supplicant_interface_proxy_.reset(
1501 proxy_factory_->CreateSupplicantInterfaceProxy(
1502 this, interface_path, wpa_supplicant::kDBusAddr));
1503
1504 RTNLHandler::GetInstance()->SetInterfaceFlags(interface_index(), IFF_UP,
1505 IFF_UP);
1506 // TODO(quiche) Set ApScan=1 and BSSExpireAge=190, like flimflam does?
1507
1508 // Clear out any networks that might previously have been configured
1509 // for this interface.
1510 supplicant_interface_proxy_->RemoveAllNetworks();
1511
1512 // Flush interface's BSS cache, so that we get BSSAdded signals for
1513 // all BSSes (not just new ones since the last scan).
1514 supplicant_interface_proxy_->FlushBSS(0);
1515
1516 try {
1517 // TODO(pstew): Disable fast_reauth until supplicant can properly deal
1518 // with RADIUS servers that respond strangely to such requests.
1519 // crosbug.com/25630
1520 supplicant_interface_proxy_->SetFastReauth(false);
1521 } catch (const DBus::Error &e) { // NOLINT
1522 LOG(INFO) << "Failed to disable fast_reauth."
1523 << "May be running an older version of wpa_supplicant.";
1524 }
1525
1526 try {
1527 // Helps with passing WiFiRomaing.001SSIDSwitchBack.
1528 supplicant_interface_proxy_->SetScanInterval(kRescanIntervalSeconds);
1529 } catch (const DBus::Error &e) { // NOLINT
1530 LOG(INFO) << "Failed to set scan_interval. "
1531 << "May be running an older version of wpa_supplicant.";
1532 }
1533
Darin Petkov2b8e44e2012-06-25 15:13:26 +02001534 Scan(NULL);
1535 StartScanTimer();
1536}
1537
1538void WiFi::Restart() {
1539 LOG(INFO) << link_name() << " restarting.";
1540 WiFiRefPtr me = this; // Make sure we don't get destructed.
1541 // Go through the manager rather than starting and stopping the device
1542 // directly so that the device can be configured with the profile.
1543 manager()->DeregisterDevice(me);
1544 manager()->RegisterDevice(me);
1545}
1546
Paul Stewartb50f0b92011-05-16 16:31:42 -07001547} // namespace shill