blob: f415d72f99da5b17f84a7ca3c70c855569efb95d [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>
Paul Stewartb50f0b92011-05-16 16:31:42 -070019#include <base/logging.h>
mukesh agrawal15908392011-11-16 18:29:25 +000020#include <base/stringprintf.h>
mukesh agrawal7a4e4002011-09-06 11:26:05 -070021#include <base/string_number_conversions.h>
22#include <base/string_util.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"
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"
Chris Masone7aa5f902011-07-11 11:13:35 -070033#include "shill/manager.h"
Thieu Le67370f62012-02-14 23:01:42 +000034#include "shill/metrics.h"
Gary Morainac1bdb42012-02-16 17:42:29 -080035#include "shill/power_manager.h"
Chris Masone7aa5f902011-07-11 11:13:35 -070036#include "shill/profile.h"
mukesh agrawal4d0401c2012-01-06 16:05:31 -080037#include "shill/property_accessor.h"
Darin Petkovd1967262011-07-18 14:55:18 -070038#include "shill/proxy_factory.h"
Eric Shienbrood9a245532012-03-07 14:20:39 -050039#include "shill/rtnl_handler.h"
mukesh agrawal5c05b292012-03-07 10:12:52 -080040#include "shill/shill_time.h"
Paul Stewarta41e38d2011-11-11 07:47:29 -080041#include "shill/store_interface.h"
mukesh agrawalaf571952011-07-14 14:31:12 -070042#include "shill/supplicant_interface_proxy_interface.h"
43#include "shill/supplicant_process_proxy_interface.h"
Gaurav Shah435de2c2011-11-17 19:01:07 -080044#include "shill/technology.h"
mukesh agrawalb54601c2011-06-07 17:39:22 -070045#include "shill/wifi_endpoint.h"
46#include "shill/wifi_service.h"
mukesh agrawal6e277772011-09-29 15:04:23 -070047#include "shill/wpa_supplicant.h"
Paul Stewartb50f0b92011-05-16 16:31:42 -070048
Eric Shienbrood3e20a232012-02-16 11:35:56 -050049using base::Bind;
mukesh agrawal15908392011-11-16 18:29:25 +000050using base::StringPrintf;
mukesh agrawal7a4e4002011-09-06 11:26:05 -070051using std::map;
Paul Stewartced6a0b2011-11-08 15:32:04 -080052using std::set;
mukesh agrawalab87ea42011-05-18 11:44:49 -070053using std::string;
mukesh agrawal7a4e4002011-09-06 11:26:05 -070054using std::vector;
mukesh agrawalab87ea42011-05-18 11:44:49 -070055
Paul Stewartb50f0b92011-05-16 16:31:42 -070056namespace shill {
mukesh agrawal7a4e4002011-09-06 11:26:05 -070057
58// statics
mukesh agrawal4d0401c2012-01-06 16:05:31 -080059const char *WiFi::kDefaultBgscanMethod =
60 wpa_supplicant::kNetworkBgscanMethodSimple;
61const uint16 WiFi::kDefaultBgscanShortIntervalSeconds = 30;
62const int32 WiFi::kDefaultBgscanSignalThresholdDbm = -50;
63const uint16 WiFi::kDefaultScanIntervalSeconds = 180;
mukesh agrawal7a4e4002011-09-06 11:26:05 -070064// Note that WiFi generates some manager-level errors, because it implements
65// the Manager.GetWiFiService flimflam API. The API is implemented here,
66// rather than in manager, to keep WiFi-specific logic in the right place.
67const char WiFi::kManagerErrorPassphraseRequired[] = "must specify passphrase";
68const char WiFi::kManagerErrorSSIDRequired[] = "must specify SSID";
69const char WiFi::kManagerErrorSSIDTooLong[] = "SSID is too long";
70const char WiFi::kManagerErrorSSIDTooShort[] = "SSID is too short";
mukesh agrawal7a4e4002011-09-06 11:26:05 -070071const char WiFi::kManagerErrorUnsupportedSecurityMode[] =
72 "security mode is unsupported";
mukesh agrawal7a4e4002011-09-06 11:26:05 -070073const char WiFi::kManagerErrorUnsupportedServiceMode[] =
74 "service mode is unsupported";
mukesh agrawal5c05b292012-03-07 10:12:52 -080075// Age (in seconds) beyond which a BSS cache entry will not be preserved,
76// across a suspend/resume.
77const time_t WiFi::kMaxBSSResumeAgeSeconds = 10;
mukesh agrawal7ec71312011-11-10 02:08:26 +000078const char WiFi::kInterfaceStateUnknown[] = "shill-unknown";
mukesh agrawalf2028172012-03-13 14:20:22 -070079const time_t WiFi::kRescanIntervalSeconds = 1;
mukesh agrawalb54601c2011-06-07 17:39:22 -070080
Paul Stewartb50f0b92011-05-16 16:31:42 -070081WiFi::WiFi(ControlInterface *control_interface,
82 EventDispatcher *dispatcher,
Thieu Le3426c8f2012-01-11 17:35:11 -080083 Metrics *metrics,
Paul Stewartf1ce5d22011-05-19 13:10:20 -070084 Manager *manager,
Chris Masone3bd3c8c2011-06-13 08:20:26 -070085 const string& link,
Paul Stewarta41e38d2011-11-11 07:47:29 -080086 const string &address,
Paul Stewartb50f0b92011-05-16 16:31:42 -070087 int interface_index)
Chris Masonea82b7112011-05-25 15:16:29 -070088 : Device(control_interface,
89 dispatcher,
Thieu Le3426c8f2012-01-11 17:35:11 -080090 metrics,
Chris Masonea82b7112011-05-25 15:16:29 -070091 manager,
Chris Masone3bd3c8c2011-06-13 08:20:26 -070092 link,
Chris Masone626719f2011-08-18 16:58:48 -070093 address,
Gaurav Shah435de2c2011-11-17 19:01:07 -080094 interface_index,
95 Technology::kWifi),
Eric Shienbrood9a245532012-03-07 14:20:39 -050096 weak_ptr_factory_(this),
Darin Petkovab565bb2011-10-06 02:55:51 -070097 proxy_factory_(ProxyFactory::GetInstance()),
mukesh agrawal5c05b292012-03-07 10:12:52 -080098 time_(Time::GetInstance()),
mukesh agrawal15908392011-11-16 18:29:25 +000099 supplicant_state_(kInterfaceStateUnknown),
100 supplicant_bss_("(unknown)"),
Paul Stewart66c86002012-01-30 18:00:52 -0800101 clear_cached_credentials_pending_(false),
mukesh agrawal5c05b292012-03-07 10:12:52 -0800102 need_bss_flush_(false),
mukesh agrawal4d0401c2012-01-06 16:05:31 -0800103 bgscan_method_(kDefaultBgscanMethod),
104 bgscan_short_interval_seconds_(kDefaultBgscanShortIntervalSeconds),
105 bgscan_signal_threshold_dbm_(kDefaultBgscanSignalThresholdDbm),
Chris Masone853b81b2011-06-24 14:11:41 -0700106 scan_pending_(false),
mukesh agrawal4d0401c2012-01-06 16:05:31 -0800107 scan_interval_seconds_(kDefaultScanIntervalSeconds) {
mukesh agrawalde29fa82011-09-16 16:16:36 -0700108 PropertyStore *store = this->mutable_store();
mukesh agrawal5c05b292012-03-07 10:12:52 -0800109 resumed_at_.tv_sec = 0;
110 resumed_at_.tv_usec = 0;
mukesh agrawal4d0401c2012-01-06 16:05:31 -0800111 HelpRegisterDerivedString(store,
112 flimflam::kBgscanMethodProperty,
113 &WiFi::GetBgscanMethod,
114 &WiFi::SetBgscanMethod);
115 HelpRegisterDerivedUint16(store,
116 flimflam::kBgscanShortIntervalProperty,
117 &WiFi::GetBgscanShortInterval,
118 &WiFi::SetBgscanShortInterval);
119 HelpRegisterDerivedInt32(store,
120 flimflam::kBgscanSignalThresholdProperty,
121 &WiFi::GetBgscanSignalThreshold,
122 &WiFi::SetBgscanSignalThreshold);
Chris Masone853b81b2011-06-24 14:11:41 -0700123
Chris Masoneb925cc82011-06-22 15:39:57 -0700124 // TODO(quiche): Decide if scan_pending_ is close enough to
125 // "currently scanning" that we don't care, or if we want to track
126 // scan pending/currently scanning/no scan scheduled as a tri-state
127 // kind of thing.
Paul Stewartac4ac002011-08-26 12:04:26 -0700128 store->RegisterConstBool(flimflam::kScanningProperty, &scan_pending_);
mukesh agrawal4d0401c2012-01-06 16:05:31 -0800129 HelpRegisterDerivedUint16(store,
130 flimflam::kScanIntervalProperty,
131 &WiFi::GetScanInterval,
132 &WiFi::SetScanInterval);
Paul Stewartac4ac002011-08-26 12:04:26 -0700133 VLOG(2) << "WiFi device " << link_name() << " initialized.";
Paul Stewartb50f0b92011-05-16 16:31:42 -0700134}
135
mukesh agrawalaf571952011-07-14 14:31:12 -0700136WiFi::~WiFi() {}
Paul Stewartb50f0b92011-05-16 16:31:42 -0700137
Eric Shienbrood9a245532012-03-07 14:20:39 -0500138void WiFi::Start(Error *error, const EnabledStateChangedCallback &callback) {
mukesh agrawalab87ea42011-05-18 11:44:49 -0700139 ::DBus::Path interface_path;
140
mukesh agrawalaf571952011-07-14 14:31:12 -0700141 supplicant_process_proxy_.reset(
Darin Petkovab565bb2011-10-06 02:55:51 -0700142 proxy_factory_->CreateSupplicantProcessProxy(
mukesh agrawal6e277772011-09-29 15:04:23 -0700143 wpa_supplicant::kDBusPath, wpa_supplicant::kDBusAddr));
mukesh agrawalc7426a42011-06-03 13:04:28 -0700144 try {
Paul Stewarta41e38d2011-11-11 07:47:29 -0800145 map<string, DBus::Variant> create_interface_args;
mukesh agrawalc7426a42011-06-03 13:04:28 -0700146 create_interface_args["Ifname"].writer().
Paul Stewartac4ac002011-08-26 12:04:26 -0700147 append_string(link_name().c_str());
mukesh agrawalc7426a42011-06-03 13:04:28 -0700148 create_interface_args["Driver"].writer().
mukesh agrawal6e277772011-09-29 15:04:23 -0700149 append_string(wpa_supplicant::kDriverNL80211);
mukesh agrawalc7426a42011-06-03 13:04:28 -0700150 // TODO(quiche) create_interface_args["ConfigFile"].writer().append_string
151 // (file with pkcs config info)
152 interface_path =
153 supplicant_process_proxy_->CreateInterface(create_interface_args);
154 } catch (const DBus::Error e) { // NOLINT
mukesh agrawal6e277772011-09-29 15:04:23 -0700155 if (!strcmp(e.name(), wpa_supplicant::kErrorInterfaceExists)) {
mukesh agrawalc7426a42011-06-03 13:04:28 -0700156 interface_path =
Paul Stewartac4ac002011-08-26 12:04:26 -0700157 supplicant_process_proxy_->GetInterface(link_name());
mukesh agrawal7ec71312011-11-10 02:08:26 +0000158 // TODO(quiche): Is it okay to crash here, if device is missing?
mukesh agrawalc7426a42011-06-03 13:04:28 -0700159 } else {
mukesh agrawal7ec71312011-11-10 02:08:26 +0000160 // TODO(quiche): Log error.
mukesh agrawalc7426a42011-06-03 13:04:28 -0700161 }
162 }
163
mukesh agrawalab87ea42011-05-18 11:44:49 -0700164 supplicant_interface_proxy_.reset(
Darin Petkovab565bb2011-10-06 02:55:51 -0700165 proxy_factory_->CreateSupplicantInterfaceProxy(
mukesh agrawal6e277772011-09-29 15:04:23 -0700166 this, interface_path, wpa_supplicant::kDBusAddr));
mukesh agrawalc7426a42011-06-03 13:04:28 -0700167
Eric Shienbrood9a245532012-03-07 14:20:39 -0500168 RTNLHandler::GetInstance()->SetInterfaceFlags(interface_index(), IFF_UP,
169 IFF_UP);
mukesh agrawal7ec71312011-11-10 02:08:26 +0000170 // TODO(quiche) Set ApScan=1 and BSSExpireAge=190, like flimflam does?
mukesh agrawalc7426a42011-06-03 13:04:28 -0700171
mukesh agrawal7ec71312011-11-10 02:08:26 +0000172 // Clear out any networks that might previously have been configured
mukesh agrawalc7426a42011-06-03 13:04:28 -0700173 // for this interface.
174 supplicant_interface_proxy_->RemoveAllNetworks();
175
mukesh agrawal7ec71312011-11-10 02:08:26 +0000176 // Flush interface's BSS cache, so that we get BSSAdded signals for
mukesh agrawalc7426a42011-06-03 13:04:28 -0700177 // all BSSes (not just new ones since the last scan).
178 supplicant_interface_proxy_->FlushBSS(0);
179
mukesh agrawal23e9f282012-02-17 15:36:36 -0800180 try {
181 // TODO(pstew): Disable fast_reauth until supplicant can properly deal
182 // with RADIUS servers that respond strangely to such requests.
183 // crosbug.com/25630
184 supplicant_interface_proxy_->SetFastReauth(false);
185 } catch (const DBus::Error e) { // NOLINT
mukesh agrawalf2028172012-03-13 14:20:22 -0700186 LOG(INFO) << "Failed to disable fast_reauth."
187 << "May be running an older version of wpa_supplicant.";
188 }
189
190 try {
191 // Helps with passing WiFiRomaing.001SSIDSwitchBack.
192 supplicant_interface_proxy_->SetScanInterval(kRescanIntervalSeconds);
193 } catch (const DBus::Error e) { // NOLINT
194 LOG(INFO) << "Failed to set scan_interval. "
mukesh agrawal23e9f282012-02-17 15:36:36 -0800195 << "May be running an older version of wpa_supplicant.";
196 }
Paul Stewart2987dcf2012-01-30 15:47:42 -0800197
Gary Morainac1bdb42012-02-16 17:42:29 -0800198 // Register for power state changes. HandlePowerStateChange() will be called
199 // when the power state changes.
Eric Shienbrood3e20a232012-02-16 11:35:56 -0500200 manager()->power_manager()->AddStateChangeCallback(
201 UniqueName(),
Eric Shienbrood9a245532012-03-07 14:20:39 -0500202 Bind(&WiFi::HandlePowerStateChange, weak_ptr_factory_.GetWeakPtr()));
Gary Morainac1bdb42012-02-16 17:42:29 -0800203
Darin Petkovc0865312011-09-16 15:31:20 -0700204 Scan(NULL);
Eric Shienbrood9a245532012-03-07 14:20:39 -0500205 OnEnabledStateChanged(EnabledStateChangedCallback(), Error());
206 if (error)
207 error->Reset(); // indicate immediate completion
mukesh agrawalab87ea42011-05-18 11:44:49 -0700208}
209
Eric Shienbrood9a245532012-03-07 14:20:39 -0500210void WiFi::Stop(Error *error, const EnabledStateChangedCallback &callback) {
mukesh agrawal5c4dd0b2011-09-14 13:53:14 -0700211 VLOG(2) << "WiFi " << link_name() << " stopping.";
mukesh agrawal7ec71312011-11-10 02:08:26 +0000212 // TODO(quiche): Remove interface from supplicant.
mukesh agrawal31950242011-07-14 11:53:38 -0700213 supplicant_interface_proxy_.reset(); // breaks a reference cycle
214 supplicant_process_proxy_.reset();
mukesh agrawal15908392011-11-16 18:29:25 +0000215 endpoint_by_rpcid_.clear();
mukesh agrawal15908392011-11-16 18:29:25 +0000216 rpcid_by_service_.clear();
Gary Morain91001122012-02-29 16:22:26 -0800217 manager()->power_manager()->RemoveStateChangeCallback(UniqueName());
mukesh agrawal5c4dd0b2011-09-14 13:53:14 -0700218
Paul Stewartced6a0b2011-11-08 15:32:04 -0800219 for (vector<WiFiServiceRefPtr>::const_iterator it = services_.begin();
220 it != services_.end();
mukesh agrawal5c4dd0b2011-09-14 13:53:14 -0700221 ++it) {
mukesh agrawalb20776f2012-02-10 16:00:36 -0800222 VLOG(3) << "WiFi " << link_name() << " deregistering service "
223 << (*it)->friendly_name();
mukesh agrawal5c4dd0b2011-09-14 13:53:14 -0700224 manager()->DeregisterService(*it);
225 }
Paul Stewartced6a0b2011-11-08 15:32:04 -0800226 services_.clear(); // breaks reference cycles
mukesh agrawalb20776f2012-02-10 16:00:36 -0800227 current_service_ = NULL; // breaks a reference cycle
mukesh agrawal7ec71312011-11-10 02:08:26 +0000228 pending_service_ = NULL; // breaks a reference cycle
mukesh agrawal5c4dd0b2011-09-14 13:53:14 -0700229
Eric Shienbrood9a245532012-03-07 14:20:39 -0500230 OnEnabledStateChanged(EnabledStateChangedCallback(), Error());
231 if (error)
232 error->Reset(); // indicate immediate completion
mukesh agrawal7ec71312011-11-10 02:08:26 +0000233 // TODO(quiche): Anything else to do?
mukesh agrawal5c4dd0b2011-09-14 13:53:14 -0700234
mukesh agrawal5c4dd0b2011-09-14 13:53:14 -0700235 VLOG(3) << "WiFi " << link_name() << " supplicant_process_proxy_ "
236 << (supplicant_process_proxy_.get() ? "is set." : "is not set.");
237 VLOG(3) << "WiFi " << link_name() << " supplicant_interface_proxy_ "
238 << (supplicant_interface_proxy_.get() ? "is set." : "is not set.");
mukesh agrawal7ec71312011-11-10 02:08:26 +0000239 VLOG(3) << "WiFi " << link_name() << " pending_service_ "
240 << (pending_service_.get() ? "is set." : "is not set.");
mukesh agrawal165e6142011-11-22 02:22:56 +0000241 VLOG(3) << "WiFi " << link_name() << " has " << endpoint_by_rpcid_.size()
mukesh agrawal5c4dd0b2011-09-14 13:53:14 -0700242 << " EndpointMap entries.";
mukesh agrawal165e6142011-11-22 02:22:56 +0000243 VLOG(3) << "WiFi " << link_name() << " has " << services_.size()
244 << " Services.";
mukesh agrawalab87ea42011-05-18 11:44:49 -0700245}
246
Paul Stewarta41e38d2011-11-11 07:47:29 -0800247bool WiFi::Load(StoreInterface *storage) {
248 LoadHiddenServices(storage);
249 return Device::Load(storage);
250}
251
mukesh agrawal1830fa12011-09-26 14:31:40 -0700252void WiFi::Scan(Error */*error*/) {
mukesh agrawal32399322011-09-01 10:53:43 -0700253 LOG(INFO) << __func__;
254
mukesh agrawal7ec71312011-11-10 02:08:26 +0000255 // Needs to send a D-Bus message, but may be called from D-Bus
256 // signal handler context (via Manager::RequestScan). So defer work
mukesh agrawal32399322011-09-01 10:53:43 -0700257 // to event loop.
Eric Shienbrood9a245532012-03-07 14:20:39 -0500258 dispatcher()->PostTask(Bind(&WiFi::ScanTask, weak_ptr_factory_.GetWeakPtr()));
mukesh agrawal32399322011-09-01 10:53:43 -0700259}
260
Paul Stewartfdd16072011-09-16 12:41:35 -0700261bool WiFi::TechnologyIs(const Technology::Identifier type) const {
262 return type == Technology::kWifi;
Paul Stewartb50f0b92011-05-16 16:31:42 -0700263}
264
mukesh agrawal8a3188d2011-12-01 20:56:44 +0000265bool WiFi::IsConnectingTo(const WiFiService &service) const {
mukesh agrawal4d0401c2012-01-06 16:05:31 -0800266 return pending_service_ == &service ||
267 (current_service_ == &service &&
268 service.state() != Service::kStateConnected);
mukesh agrawal8a3188d2011-12-01 20:56:44 +0000269}
270
mukesh agrawalb4bc57d2011-12-07 01:07:47 +0000271void WiFi::BSSAdded(const ::DBus::Path &path,
272 const map<string, ::DBus::Variant> &properties) {
Eric Shienbrood3e20a232012-02-16 11:35:56 -0500273 // Called from a D-Bus signal handler, and may need to send a D-Bus
mukesh agrawalb4bc57d2011-12-07 01:07:47 +0000274 // message. So defer work to event loop.
Eric Shienbrood9a245532012-03-07 14:20:39 -0500275 dispatcher()->PostTask(Bind(&WiFi::BSSAddedTask,
276 weak_ptr_factory_.GetWeakPtr(),
277 path, properties));
mukesh agrawal261daca2011-12-02 18:56:56 +0000278}
279
280void WiFi::BSSRemoved(const ::DBus::Path &path) {
Eric Shienbrood3e20a232012-02-16 11:35:56 -0500281 // Called from a D-Bus signal handler, and may need to send a D-Bus
mukesh agrawalb4bc57d2011-12-07 01:07:47 +0000282 // message. So defer work to event loop.
Eric Shienbrood9a245532012-03-07 14:20:39 -0500283 dispatcher()->PostTask(Bind(&WiFi::BSSRemovedTask,
284 weak_ptr_factory_.GetWeakPtr(), path));
mukesh agrawalb54601c2011-06-07 17:39:22 -0700285}
286
mukesh agrawal7ec71312011-11-10 02:08:26 +0000287void WiFi::PropertiesChanged(const map<string, ::DBus::Variant> &properties) {
mukesh agrawal15908392011-11-16 18:29:25 +0000288 LOG(INFO) << "In " << __func__ << "(): called";
289 // Called from D-Bus signal handler, but may need to send a D-Bus
290 // message. So defer work to event loop.
Eric Shienbrood9a245532012-03-07 14:20:39 -0500291 dispatcher()->PostTask(Bind(&WiFi::PropertiesChangedTask,
292 weak_ptr_factory_.GetWeakPtr(), properties));
mukesh agrawal7ec71312011-11-10 02:08:26 +0000293}
294
mukesh agrawalb54601c2011-06-07 17:39:22 -0700295void WiFi::ScanDone() {
296 LOG(INFO) << __func__;
297
mukesh agrawal7ec71312011-11-10 02:08:26 +0000298 // Defer handling of scan result processing, because that processing
299 // may require the the registration of new D-Bus objects. And such
mukesh agrawalb54601c2011-06-07 17:39:22 -0700300 // registration can't be done in the context of a D-Bus signal
301 // handler.
Eric Shienbrood9a245532012-03-07 14:20:39 -0500302 dispatcher()->PostTask(Bind(&WiFi::ScanDoneTask,
303 weak_ptr_factory_.GetWeakPtr()));
mukesh agrawalb54601c2011-06-07 17:39:22 -0700304}
305
mukesh agrawal6e277772011-09-29 15:04:23 -0700306void WiFi::ConnectTo(WiFiService *service,
mukesh agrawal64896322011-12-01 01:13:10 +0000307 map<string, DBus::Variant> service_params) {
mukesh agrawale9adda12012-02-09 18:33:48 -0800308 CHECK(service) << "Can't connect to NULL service.";
mukesh agrawal445e72c2011-06-22 11:13:50 -0700309 DBus::Path network_path;
mukesh agrawalb54601c2011-06-07 17:39:22 -0700310
mukesh agrawal7ec71312011-11-10 02:08:26 +0000311 // TODO(quiche): Handle cases where already connected.
mukesh agrawal8a3188d2011-12-01 20:56:44 +0000312 if (pending_service_ && pending_service_ == service) {
313 // TODO(quiche): Return an error to the caller. crosbug.com/23832
314 LOG(INFO) << "WiFi " << link_name() << " ignoring ConnectTo "
315 << service->friendly_name()
316 << ", which is already pending.";
317 return;
318 }
319
320 if (pending_service_ && pending_service_ != service) {
321 DisconnectFrom(pending_service_);
322 }
mukesh agrawal32399322011-09-01 10:53:43 -0700323
mukesh agrawal6e277772011-09-29 15:04:23 -0700324 try {
mukesh agrawal15908392011-11-16 18:29:25 +0000325 // TODO(quiche): Set a timeout here. In the normal case, we expect
326 // that, if wpa_supplicant fails to connect, it will eventually send
327 // a signal that its CurrentBSS has changed. But there may be cases
328 // where the signal is not sent. (crosbug.com/23206)
mukesh agrawal64896322011-12-01 01:13:10 +0000329 const uint32_t scan_ssid = 1; // "True": Use directed probe.
330 service_params[wpa_supplicant::kNetworkPropertyScanSSID].writer().
331 append_uint32(scan_ssid);
mukesh agrawal4d0401c2012-01-06 16:05:31 -0800332 service_params[wpa_supplicant::kNetworkPropertyBgscan].writer().
333 append_string(CreateBgscanConfigString().c_str());
mukesh agrawal6e277772011-09-29 15:04:23 -0700334 network_path =
335 supplicant_interface_proxy_->AddNetwork(service_params);
mukesh agrawal15908392011-11-16 18:29:25 +0000336 rpcid_by_service_[service] = network_path;
mukesh agrawal6e277772011-09-29 15:04:23 -0700337 } catch (const DBus::Error e) { // NOLINT
338 LOG(ERROR) << "exception while adding network: " << e.what();
339 return;
340 }
mukesh agrawal445e72c2011-06-22 11:13:50 -0700341
mukesh agrawal445e72c2011-06-22 11:13:50 -0700342 supplicant_interface_proxy_->SelectNetwork(network_path);
mukesh agrawal8a3188d2011-12-01 20:56:44 +0000343 pending_service_ = service;
344 CHECK(current_service_.get() != pending_service_.get());
345
mukesh agrawalf2f68a52011-09-01 12:15:48 -0700346 // SelectService here (instead of in LinkEvent, like Ethernet), so
347 // that, if we fail to bring up L2, we can attribute failure correctly.
348 //
mukesh agrawal7ec71312011-11-10 02:08:26 +0000349 // TODO(quiche): When we add code for dealing with connection failures,
mukesh agrawalf2f68a52011-09-01 12:15:48 -0700350 // reconsider if this is the right place to change the selected service.
351 // see discussion in crosbug.com/20191.
352 SelectService(service);
mukesh agrawal15908392011-11-16 18:29:25 +0000353}
354
mukesh agrawal0ed0f2e2011-12-05 20:36:17 +0000355void WiFi::DisconnectFrom(WiFiService *service) {
356 if (service != current_service_ && service != pending_service_) {
357 // TODO(quiche): Once we have asynchronous reply support, we should
358 // generate a D-Bus error here. (crosbug.com/23832)
359 LOG(WARNING) << "In " << __func__ << "(): "
360 << " ignoring request to disconnect from service "
361 << service->friendly_name()
362 << " which is neither current nor pending";
363 return;
364 }
365
366 if (pending_service_ && service != pending_service_) {
367 // TODO(quiche): Once we have asynchronous reply support, we should
368 // generate a D-Bus error here. (crosbug.com/23832)
369 LOG(WARNING) << "In " << __func__ << "(): "
370 << " ignoring request to disconnect from service "
371 << service->friendly_name()
372 << " which is not the pending service.";
373 return;
374 }
375
376 if (!pending_service_ && service != current_service_) {
377 // TODO(quiche): Once we have asynchronous reply support, we should
378 // generate a D-Bus error here. (crosbug.com/23832)
379 LOG(WARNING) << "In " << __func__ << "(): "
380 << " ignoring request to disconnect from service "
381 << service->friendly_name()
382 << " which is not the current service.";
383 return;
384 }
385
386 pending_service_ = NULL;
387 try {
388 supplicant_interface_proxy_->Disconnect();
389 // We'll call RemoveNetwork and reset |current_service_| after
390 // supplicant notifies us that the CurrentBSS has changed.
391 } catch (const DBus::Error e) { // NOLINT
392 // Can't depend on getting a notification of CurrentBSS change.
393 // So effect changes immediately.
394 ReverseServiceMap::const_iterator rpcid_it =
395 rpcid_by_service_.find(service);
396 DCHECK(rpcid_it != rpcid_by_service_.end());
397 if (rpcid_it == rpcid_by_service_.end()) {
398 LOG(WARNING) << "WiFi " << link_name() << " can not disconnect from "
399 << service->friendly_name() << ": "
400 << "could not find supplicant network to disable.";
401 } else {
402 supplicant_interface_proxy_->RemoveNetwork(rpcid_it->second);
403 }
404 current_service_ = NULL;
405 }
406
mukesh agrawal4d0401c2012-01-06 16:05:31 -0800407 CHECK(current_service_ == NULL ||
408 current_service_.get() != pending_service_.get());
mukesh agrawal0ed0f2e2011-12-05 20:36:17 +0000409}
410
mukesh agrawal8a3188d2011-12-01 20:56:44 +0000411bool WiFi::IsIdle() const {
Paul Stewart3d9bcf52011-12-12 15:02:22 -0800412 return !current_service_ && !pending_service_;
413}
414
Paul Stewart66c86002012-01-30 18:00:52 -0800415void WiFi::ClearCachedCredentials() {
416 LOG(INFO) << __func__;
417
418 // Needs to send a D-Bus message, but may be called from D-Bus
419 // caller context (via Manager::PopProfile). So defer work
420 // to event loop.
421 if (!clear_cached_credentials_pending_) {
422 clear_cached_credentials_pending_ = true;
Eric Shienbrood9a245532012-03-07 14:20:39 -0500423 dispatcher()->PostTask(Bind(&WiFi::ClearCachedCredentialsTask,
424 weak_ptr_factory_.GetWeakPtr()));
Paul Stewart66c86002012-01-30 18:00:52 -0800425 }
426}
427
mukesh agrawalb20776f2012-02-10 16:00:36 -0800428void WiFi::NotifyEndpointChanged(const WiFiEndpoint &endpoint) {
429 WiFiService *service = FindServiceForEndpoint(endpoint);
430 DCHECK(service);
431 if (service) {
432 service->NotifyEndpointUpdated(endpoint);
433 return;
434 }
435}
436
mukesh agrawal4d0401c2012-01-06 16:05:31 -0800437string WiFi::CreateBgscanConfigString() {
438 return StringPrintf("%s:%d:%d:%d",
439 bgscan_method_.c_str(),
440 bgscan_short_interval_seconds_,
441 bgscan_signal_threshold_dbm_,
442 scan_interval_seconds_);
443}
444
445void WiFi::SetBgscanMethod(const string &method, Error *error) {
446 if (method != wpa_supplicant::kNetworkBgscanMethodSimple &&
447 method != wpa_supplicant::kNetworkBgscanMethodLearn) {
448 const string error_message =
449 StringPrintf("Unrecognized bgscan method %s", method.c_str());
450 LOG(WARNING) << error_message;
451 error->Populate(Error::kInvalidArguments, error_message);
452 return;
453 }
454
455 bgscan_method_ = method;
456 // We do not update kNetworkPropertyBgscan for |pending_service_| or
457 // |current_service_|, because supplicant does not allow for
458 // reconfiguration without disconnect and reconnect.
459}
460
461void WiFi::SetBgscanShortInterval(const uint16 &seconds, Error */*error*/) {
462 bgscan_short_interval_seconds_ = seconds;
463 // We do not update kNetworkPropertyBgscan for |pending_service_| or
464 // |current_service_|, because supplicant does not allow for
465 // reconfiguration without disconnect and reconnect.
466}
467
468void WiFi::SetBgscanSignalThreshold(const int32 &dbm, Error */*error*/) {
469 bgscan_signal_threshold_dbm_ = dbm;
470 // We do not update kNetworkPropertyBgscan for |pending_service_| or
471 // |current_service_|, because supplicant does not allow for
472 // reconfiguration without disconnect and reconnect.
473}
474
475void WiFi::SetScanInterval(const uint16 &seconds, Error */*error*/) {
476 scan_interval_seconds_ = seconds;
477 // We do not update |pending_service_| or |current_service_|, because
478 // supplicant does not allow for reconfiguration without disconnect
479 // and reconnect.
480
481 // TODO(quiche): Update scan timer. crosbug.com/24337
482}
483
mukesh agrawal165e6142011-11-22 02:22:56 +0000484// To avoid creating duplicate services, call FindServiceForEndpoint
485// before calling this method.
mukesh agrawal15908392011-11-16 18:29:25 +0000486WiFiServiceRefPtr WiFi::CreateServiceForEndpoint(const WiFiEndpoint &endpoint,
487 bool hidden_ssid) {
488 WiFiServiceRefPtr service =
489 new WiFiService(control_interface(),
490 dispatcher(),
Thieu Le3426c8f2012-01-11 17:35:11 -0800491 metrics(),
mukesh agrawal15908392011-11-16 18:29:25 +0000492 manager(),
493 this,
494 endpoint.ssid(),
495 endpoint.network_mode(),
496 endpoint.security_mode(),
497 hidden_ssid);
mukesh agrawal165e6142011-11-22 02:22:56 +0000498 services_.push_back(service);
mukesh agrawal15908392011-11-16 18:29:25 +0000499 return service;
500}
501
502void WiFi::CurrentBSSChanged(const ::DBus::Path &new_bss) {
503 VLOG(3) << "WiFi " << link_name() << " CurrentBSS "
504 << supplicant_bss_ << " -> " << new_bss;
505 supplicant_bss_ = new_bss;
506 if (new_bss == wpa_supplicant::kCurrentBSSNull) {
507 HandleDisconnect();
508 } else {
509 HandleRoam(new_bss);
510 }
511
512 SelectService(current_service_);
mukesh agrawal8a3188d2011-12-01 20:56:44 +0000513 // Invariant check: a Service can either be current, or pending, but
514 // not both.
mukesh agrawal15908392011-11-16 18:29:25 +0000515 CHECK(current_service_.get() != pending_service_.get() ||
516 current_service_.get() == NULL);
517
518 // TODO(quiche): Update BSSID property on the Service
519 // (crosbug.com/22377).
520}
521
522void WiFi::HandleDisconnect() {
523 // Identify the affected service. We expect to get a disconnect
524 // event when we fall off a Service that we were connected
525 // to. However, we also allow for the case where we get a disconnect
526 // event while attempting to connect from a disconnected state.
527 WiFiService *affected_service =
528 current_service_.get() ? current_service_.get() : pending_service_.get();
529
530 current_service_ = NULL;
531 if (!affected_service) {
532 VLOG(2) << "WiFi " << link_name()
533 << " disconnected while not connected or connecting";
534 return;
535 }
536
537 ReverseServiceMap::const_iterator rpcid_it =
538 rpcid_by_service_.find(affected_service);
539 if (rpcid_it == rpcid_by_service_.end()) {
540 VLOG(2) << "WiFi " << link_name() << " disconnected from "
541 << " (or failed to connect to) "
542 << affected_service->friendly_name() << ", "
543 << "but could not find supplicant network to disable.";
544 return;
545 }
546
547 VLOG(2) << "WiFi " << link_name() << " disconnected from "
548 << " (or failed to connect to) "
549 << affected_service->friendly_name();
550 // TODO(quiche): Reconsider giving up immediately. Maybe give
551 // wpa_supplicant some time to retry, first.
552 supplicant_interface_proxy_->RemoveNetwork(rpcid_it->second);
mukesh agrawal568b5c62012-02-28 14:44:47 -0800553 // TOOD(quiche): In the event that the disconnect was deliberate, we
554 // might want to go to SetState(kStateIdle), rather than reporting a
555 // failure. crosbug.com/24700.
556 // TODO(quiche): In the event that we suspect a password failure,
557 // we should not be silent. crosbug.com/23211.
558 affected_service->SetFailureSilent(Service::kFailureUnknown);
mukesh agrawale1d90e92012-02-15 17:36:08 -0800559 affected_service->NotifyCurrentEndpoint(NULL);
Thieu Le67370f62012-02-14 23:01:42 +0000560 metrics()->NotifyServiceDisconnect(affected_service);
mukesh agrawal15908392011-11-16 18:29:25 +0000561
562 if (affected_service == pending_service_.get()) {
563 // The attempt to connect to |pending_service_| failed. Clear
564 // |pending_service_|, to indicate we're no longer in the middle
565 // of a connect request.
566 pending_service_ = NULL;
567 } else if (pending_service_.get()) {
568 // We've attributed the disconnection to what was the
569 // |current_service_|, rather than the |pending_service_|.
570 //
571 // If we're wrong about that (i.e. supplicant reported this
572 // CurrentBSS change after attempting to connect to
573 // |pending_service_|), we're depending on supplicant to retry
574 // connecting to |pending_service_|, and delivering another
575 // CurrentBSS change signal in the future.
576 //
577 // Log this fact, to help us debug (in case our assumptions are
578 // wrong).
579 VLOG(2) << "WiFi " << link_name() << " pending connection to "
580 << pending_service_->friendly_name()
581 << " after disconnect";
582 }
583}
584
585// We use the term "Roam" loosely. In particular, we include the case
586// where we "Roam" to a BSS from the disconnected state.
587void WiFi::HandleRoam(const ::DBus::Path &new_bss) {
588 EndpointMap::iterator endpoint_it = endpoint_by_rpcid_.find(new_bss);
589 if (endpoint_it == endpoint_by_rpcid_.end()) {
590 LOG(WARNING) << "WiFi " << link_name() << " connected to unknown BSS "
591 << new_bss;
592 return;
593 }
594
595 const WiFiEndpoint &endpoint(*endpoint_it->second);
mukesh agrawal165e6142011-11-22 02:22:56 +0000596 WiFiServiceRefPtr service = FindServiceForEndpoint(endpoint);
mukesh agrawal15908392011-11-16 18:29:25 +0000597 if (!service.get()) {
598 LOG(WARNING) << "WiFi " << link_name()
599 << " could not find Service for Endpoint "
600 << endpoint.bssid_string()
601 << " (service will be unchanged)";
602 return;
603 }
604
605 VLOG(2) << "WiFi " << link_name()
606 << " roamed to Endpoint " << endpoint.bssid_string()
607 << " (SSID " << endpoint.ssid_string() << ")";
608
mukesh agrawale1d90e92012-02-15 17:36:08 -0800609 service->NotifyCurrentEndpoint(&endpoint);
Thieu Lee41a72d2012-02-06 20:46:51 +0000610
mukesh agrawal15908392011-11-16 18:29:25 +0000611 if (pending_service_.get() &&
612 service.get() != pending_service_.get()) {
613 // The Service we've roamed on to is not the one we asked for.
614 // We assume that this is transient, and that wpa_supplicant
615 // is trying / will try to connect to |pending_service_|.
616 //
617 // If it succeeds, we'll end up back here, but with |service|
618 // pointing at the same service as |pending_service_|.
619 //
620 // If it fails, we'll process things in HandleDisconnect.
621 //
622 // So we leave |pending_service_| untouched.
623 VLOG(2) << "WiFi " << link_name()
624 << " new current Endpoint "
625 << endpoint.bssid_string()
626 << " is not part of pending service "
627 << pending_service_->friendly_name();
628
629 // Sanity check: if we didn't roam onto |pending_service_|, we
630 // should still be on |current_service_|.
631 if (service.get() != current_service_.get()) {
632 LOG(WARNING) << "WiFi " << link_name()
633 << " new current Endpoint "
634 << endpoint.bssid_string()
635 << " is neither part of pending service "
636 << pending_service_->friendly_name()
637 << " nor part of current service "
638 << (current_service_.get() ?
639 current_service_->friendly_name() :
640 "(NULL)");
641 // Although we didn't expect to get here, we should keep
642 // |current_service_| in sync with what supplicant has done.
643 current_service_ = service;
644 }
645 return;
646 }
647
648 if (pending_service_.get()) {
649 // We assume service.get() == pending_service_.get() here, because
650 // of the return in the previous if clause.
651 //
652 // Boring case: we've connected to the service we asked
653 // for. Simply update |current_service_| and |pending_service_|.
654 current_service_ = service;
655 pending_service_ = NULL;
656 return;
657 }
658
659 // |pending_service_| was NULL, so we weren't attempting to connect
660 // to a new Service. Sanity check that we're still on
661 // |current_service_|.
662 if (service.get() != current_service_.get()) {
663 LOG(WARNING)
664 << "WiFi " << link_name()
665 << " new current Endpoint "
666 << endpoint.bssid_string()
667 << (current_service_.get() ?
mukesh agrawal8a3188d2011-12-01 20:56:44 +0000668 StringPrintf(" is not part of current service %s",
mukesh agrawal15908392011-11-16 18:29:25 +0000669 current_service_->friendly_name().c_str()) :
mukesh agrawal8a3188d2011-12-01 20:56:44 +0000670 " with no current service");
mukesh agrawal15908392011-11-16 18:29:25 +0000671 // We didn't expect to be here, but let's cope as well as we
672 // can. Update |current_service_| to keep it in sync with
673 // supplicant.
674 current_service_ = service;
675 return;
676 }
677
678 // At this point, we know that |pending_service_| was NULL, and that
679 // we're still on |current_service_|. This is the most boring case
680 // of all, because there's no state to update here.
681 return;
mukesh agrawalb54601c2011-06-07 17:39:22 -0700682}
683
Paul Stewarta41e38d2011-11-11 07:47:29 -0800684WiFiServiceRefPtr WiFi::FindService(const vector<uint8_t> &ssid,
685 const string &mode,
686 const string &security) const {
Paul Stewart6ab23a92011-11-09 17:17:47 -0800687 for (vector<WiFiServiceRefPtr>::const_iterator it = services_.begin();
688 it != services_.end();
689 ++it) {
690 if ((*it)->ssid() == ssid && (*it)->mode() == mode &&
691 (*it)->IsSecurityMatch(security)) {
692 return *it;
693 }
694 }
695 return NULL;
696}
697
mukesh agrawal165e6142011-11-22 02:22:56 +0000698WiFiServiceRefPtr WiFi::FindServiceForEndpoint(const WiFiEndpoint &endpoint) {
699 return FindService(endpoint.ssid(),
700 endpoint.network_mode(),
701 endpoint.security_mode());
702}
703
Paul Stewartced6a0b2011-11-08 15:32:04 -0800704ByteArrays WiFi::GetHiddenSSIDList() {
705 // Create a unique set of hidden SSIDs.
706 set<ByteArray> hidden_ssids_set;
707 for (vector<WiFiServiceRefPtr>::const_iterator it = services_.begin();
708 it != services_.end();
709 ++it) {
Paul Stewarta41e38d2011-11-11 07:47:29 -0800710 if ((*it)->hidden_ssid() && (*it)->favorite()) {
Paul Stewartced6a0b2011-11-08 15:32:04 -0800711 hidden_ssids_set.insert((*it)->ssid());
712 }
713 }
Paul Stewarta41e38d2011-11-11 07:47:29 -0800714 VLOG(2) << "Found " << hidden_ssids_set.size() << " hidden services";
Paul Stewartced6a0b2011-11-08 15:32:04 -0800715 ByteArrays hidden_ssids(hidden_ssids_set.begin(), hidden_ssids_set.end());
716 if (!hidden_ssids.empty()) {
717 // TODO(pstew): Devise a better method for time-sharing with SSIDs that do
718 // not fit in.
719 if (hidden_ssids.size() >= wpa_supplicant::kScanMaxSSIDsPerScan) {
720 hidden_ssids.erase(
721 hidden_ssids.begin() + wpa_supplicant::kScanMaxSSIDsPerScan - 1,
722 hidden_ssids.end());
723 }
724 // Add Broadcast SSID, signified by an empty ByteArray. If we specify
725 // SSIDs to wpa_supplicant, we need to explicitly specify the default
726 // behavior of doing a broadcast probe.
727 hidden_ssids.push_back(ByteArray());
728 }
729 return hidden_ssids;
730}
731
Paul Stewarta41e38d2011-11-11 07:47:29 -0800732bool WiFi::LoadHiddenServices(StoreInterface *storage) {
733 bool created_hidden_service = false;
734 set<string> groups = storage->GetGroupsWithKey(flimflam::kWifiHiddenSsid);
735 for (set<string>::iterator it = groups.begin(); it != groups.end(); ++it) {
736 bool is_hidden = false;
737 if (!storage->GetBool(*it, flimflam::kWifiHiddenSsid, &is_hidden)) {
738 VLOG(2) << "Storage group " << *it << " returned by GetGroupsWithKey "
739 << "failed for GetBool(" << flimflam::kWifiHiddenSsid
740 << ") -- possible non-bool key";
741 continue;
742 }
743 if (!is_hidden) {
744 continue;
745 }
746 string ssid_hex;
747 vector<uint8_t> ssid_bytes;
748 if (!storage->GetString(*it, flimflam::kSSIDProperty, &ssid_hex) ||
749 !base::HexStringToBytes(ssid_hex, &ssid_bytes)) {
750 VLOG(2) << "Hidden network is missing/invalid \""
751 << flimflam::kSSIDProperty << "\" property";
752 continue;
753 }
754 string device_address;
755 string network_mode;
756 string security;
757 // It is gross that we have to do this, but the only place we can
758 // get information about the service is from its storage name.
759 if (!WiFiService::ParseStorageIdentifier(*it, &device_address,
760 &network_mode, &security) ||
761 device_address != address()) {
762 VLOG(2) << "Hidden network has unparsable storage identifier \""
763 << *it << "\"";
764 continue;
765 }
766 if (FindService(ssid_bytes, network_mode, security).get()) {
767 // If service already exists, we have nothing to do, since the
768 // service has already loaded its configuration from storage.
769 // This is guaranteed to happen in both cases where Load() is
770 // called on a device (via a ConfigureDevice() call on the
771 // profile):
772 // - In RegisterDevice() the Device hasn't been started yet,
773 // so it has no services registered, except for those
774 // created by previous iterations of LoadHiddenService().
775 // The latter can happen if another profile in the Manager's
776 // stack defines the same ssid/mode/security. Even this
777 // case is okay, since even if the profiles differ
778 // materially on configuration and credentials, the "right"
779 // one will be configured in the course of the
780 // RegisterService() call below.
781 // - In PushProfile(), all registered services have been
782 // introduced to the profile via ConfigureService() prior
783 // to calling ConfigureDevice() on the profile.
784 continue;
785 }
786 WiFiServiceRefPtr service(new WiFiService(control_interface(),
787 dispatcher(),
Thieu Le3426c8f2012-01-11 17:35:11 -0800788 metrics(),
Paul Stewarta41e38d2011-11-11 07:47:29 -0800789 manager(),
790 this,
791 ssid_bytes,
792 network_mode,
793 security,
794 true));
795 services_.push_back(service);
796
797 // By registering the service, the rest of the configuration
798 // will be loaded from the profile into the service via ConfigureService().
799 manager()->RegisterService(service);
800
801 created_hidden_service = true;
802 }
803
804 // If we are idle and we created a service as a result of opening the
805 // profile, we should initiate a scan for our new hidden SSID.
806 if (running() && created_hidden_service &&
807 supplicant_state_ == wpa_supplicant::kInterfaceStateInactive) {
808 Scan(NULL);
809 }
810
811 return created_hidden_service;
812}
813
Paul Stewart66c86002012-01-30 18:00:52 -0800814void WiFi::ClearCachedCredentialsTask() {
815 supplicant_interface_proxy_->ClearCachedCredentials();
816 clear_cached_credentials_pending_ = false;
817}
818
mukesh agrawalb4bc57d2011-12-07 01:07:47 +0000819void WiFi::BSSAddedTask(
820 const ::DBus::Path &path,
821 const map<string, ::DBus::Variant> &properties) {
mukesh agrawalb4bc57d2011-12-07 01:07:47 +0000822 // Note: we assume that BSSIDs are unique across endpoints. This
823 // means that if an AP reuses the same BSSID for multiple SSIDs, we
824 // lose.
mukesh agrawalb20776f2012-02-10 16:00:36 -0800825 WiFiEndpointRefPtr endpoint(
826 new WiFiEndpoint(proxy_factory_, this, path, properties));
mukesh agrawalb4bc57d2011-12-07 01:07:47 +0000827 LOG(INFO) << "Found endpoint. "
mukesh agrawale9adda12012-02-09 18:33:48 -0800828 << "RPC path: " << path << ", "
mukesh agrawalb4bc57d2011-12-07 01:07:47 +0000829 << "ssid: " << endpoint->ssid_string() << ", "
830 << "bssid: " << endpoint->bssid_string() << ", "
831 << "signal: " << endpoint->signal_strength() << ", "
Thieu Lee41a72d2012-02-06 20:46:51 +0000832 << "security: " << endpoint->security_mode() << ", "
833 << "frequency: " << endpoint->frequency();
mukesh agrawalb4bc57d2011-12-07 01:07:47 +0000834
835 if (endpoint->ssid_string().empty()) {
836 // Don't bother trying to find or create a Service for an Endpoint
837 // without an SSID. We wouldn't be able to connect to it anyway.
838 return;
839 }
840
mukesh agrawalb3857612012-01-18 16:23:29 -0800841 if (endpoint->ssid()[0] == 0) {
842 // Assume that an SSID starting with NULL is bogus/misconfigured,
843 // and filter it out.
844 return;
845 }
846
mukesh agrawalb4bc57d2011-12-07 01:07:47 +0000847 WiFiServiceRefPtr service = FindServiceForEndpoint(*endpoint);
848 if (service) {
849 LOG(INFO) << "Assigned endpoint " << endpoint->bssid_string()
850 << " to service " << service->friendly_name() << ".";
851 service->AddEndpoint(endpoint);
852
853 if (manager()->HasService(service)) {
854 manager()->UpdateService(service);
855 } else {
856 DCHECK_EQ(1, service->NumEndpoints()); // Expect registered by now if >1.
857 manager()->RegisterService(service);
858 }
mukesh agrawale9adda12012-02-09 18:33:48 -0800859 } else {
860 const bool hidden_ssid = false;
861 service = CreateServiceForEndpoint(*endpoint, hidden_ssid);
862 LOG(INFO) << "New service " << service->GetRpcIdentifier()
863 << " (" << service->friendly_name() << ")";
864 service->AddEndpoint(endpoint);
865 manager()->RegisterService(service);
mukesh agrawalb4bc57d2011-12-07 01:07:47 +0000866 }
867
mukesh agrawale9adda12012-02-09 18:33:48 -0800868 // Do this last, to maintain the invariant that any Endpoint we
869 // know about has a corresponding Service.
mukesh agrawalb20776f2012-02-10 16:00:36 -0800870 //
871 // TODO(quiche): Write test to verify correct behavior in the case
872 // where we get multiple BSSAdded events for a single endpoint.
873 // (Old Endpoint's refcount should fall to zero, and old Endpoint
874 // should be destroyed.)
mukesh agrawale9adda12012-02-09 18:33:48 -0800875 endpoint_by_rpcid_[path] = endpoint;
mukesh agrawalb20776f2012-02-10 16:00:36 -0800876 endpoint->Start();
mukesh agrawalb4bc57d2011-12-07 01:07:47 +0000877}
878
879void WiFi::BSSRemovedTask(const ::DBus::Path &path) {
880 EndpointMap::iterator i = endpoint_by_rpcid_.find(path);
881 if (i == endpoint_by_rpcid_.end()) {
882 LOG(WARNING) << "WiFi " << link_name()
883 << " could not find BSS " << path
884 << " to remove.";
885 return;
886 }
887
888 WiFiEndpointRefPtr endpoint = i->second;
889 CHECK(endpoint);
890 endpoint_by_rpcid_.erase(i);
891
mukesh agrawalb4bc57d2011-12-07 01:07:47 +0000892 WiFiServiceRefPtr service = FindServiceForEndpoint(*endpoint);
mukesh agrawale9adda12012-02-09 18:33:48 -0800893 CHECK(service) << "Can't find Service for Endpoint "
894 << path << " "
895 << "(with BSSID " << endpoint->bssid_string() << ").";
mukesh agrawal8a3188d2011-12-01 20:56:44 +0000896 VLOG(2) << "Removing Endpoint " << endpoint->bssid_string()
897 << " from Service " << service->friendly_name();
mukesh agrawalb4bc57d2011-12-07 01:07:47 +0000898 service->RemoveEndpoint(endpoint);
mukesh agrawalb4bc57d2011-12-07 01:07:47 +0000899
mukesh agrawal8a3188d2011-12-01 20:56:44 +0000900 bool disconnect_service = !service->HasEndpoints() &&
901 (service->IsConnecting() || service->IsConnected());
902 bool forget_service =
903 // Forget Services without Endpoints, except that we always keep
904 // hidden services around. (We need them around to populate the
905 // hidden SSIDs list.)
906 !service->HasEndpoints() && !service->hidden_ssid();
907 bool deregister_service =
908 // Only deregister a Service if we're forgetting it. Otherwise,
909 // Manager can't keep our configuration up-to-date (as Profiles
910 // change).
911 forget_service;
912
913 if (disconnect_service) {
914 DisconnectFrom(service);
915 }
916
917 if (deregister_service) {
918 manager()->DeregisterService(service);
919 } else {
920 manager()->UpdateService(service);
921 }
922
923 if (forget_service) {
924 vector<WiFiServiceRefPtr>::iterator it;
925 it = std::find(services_.begin(), services_.end(), service);
926 if (it != services_.end()) {
927 services_.erase(it);
928 }
929 }
mukesh agrawalb4bc57d2011-12-07 01:07:47 +0000930}
931
mukesh agrawal15908392011-11-16 18:29:25 +0000932void WiFi::PropertiesChangedTask(
933 const map<string, ::DBus::Variant> &properties) {
934 // TODO(quiche): Handle changes in other properties (e.g. signal
935 // strength).
936
937 // Note that order matters here. In particular, we want to process
938 // changes in the current BSS before changes in state. This is so
939 // that we update the state of the correct Endpoint/Service.
940
941 map<string, ::DBus::Variant>::const_iterator properties_it =
942 properties.find(wpa_supplicant::kInterfacePropertyCurrentBSS);
943 if (properties_it != properties.end()) {
944 CurrentBSSChanged(properties_it->second.reader().get_path());
945 }
946
947 properties_it = properties.find(wpa_supplicant::kInterfacePropertyState);
948 if (properties_it != properties.end()) {
949 StateChanged(properties_it->second.reader().get_string());
950 }
951}
952
mukesh agrawaldc42bb32011-07-28 10:40:26 -0700953void WiFi::ScanDoneTask() {
mukesh agrawal5c05b292012-03-07 10:12:52 -0800954 VLOG(2) << __func__ << " need_bss_flush_ " << need_bss_flush_;
955 if (need_bss_flush_) {
956 CHECK(supplicant_interface_proxy_ != NULL);
957 // Compute |max_age| relative to |resumed_at_|, to account for the
958 // time taken to scan.
959 struct timeval now;
960 uint32_t max_age;
961 time_->GetTimeMonotonic(&now);
962 max_age = kMaxBSSResumeAgeSeconds + (now.tv_sec - resumed_at_.tv_sec);
963 supplicant_interface_proxy_->FlushBSS(max_age);
964 need_bss_flush_ = false;
965 }
mukesh agrawalb54601c2011-06-07 17:39:22 -0700966 scan_pending_ = false;
mukesh agrawalb54601c2011-06-07 17:39:22 -0700967}
968
mukesh agrawal32399322011-09-01 10:53:43 -0700969void WiFi::ScanTask() {
970 VLOG(2) << "WiFi " << link_name() << " scan requested.";
Paul Stewarta41e38d2011-11-11 07:47:29 -0800971 map<string, DBus::Variant> scan_args;
mukesh agrawal6e277772011-09-29 15:04:23 -0700972 scan_args[wpa_supplicant::kPropertyScanType].writer().
973 append_string(wpa_supplicant::kScanTypeActive);
Paul Stewartced6a0b2011-11-08 15:32:04 -0800974
975 ByteArrays hidden_ssids = GetHiddenSSIDList();
976 if (!hidden_ssids.empty()) {
977 scan_args[wpa_supplicant::kPropertyScanSSIDs] =
978 DBusAdaptor::ByteArraysToVariant(hidden_ssids);
979 }
980
Gaurav Shahf8721ee2011-11-07 09:12:46 -0800981 // TODO(quiche): Indicate scanning in UI. crosbug.com/14887
Gaurav Shah10109f22011-11-11 20:16:22 -0800982 // FIXME(gauravsh): A scan can fail if, for example, wpa_supplicant
983 // was restarted. This is done by a few of the 802.1x tests.
984 // crosbug.com/25657
985 try {
986 supplicant_interface_proxy_->Scan(scan_args);
987 scan_pending_ = true;
988 } catch (const DBus::Error e) { // NOLINT
989 LOG(WARNING) << "Scan failed. Attempting to re-connect to the supplicant.";
Eric Shienbrood9a245532012-03-07 14:20:39 -0500990 EnabledStateChangedCallback null_callback;
991 Stop(NULL, null_callback);
992 Start(NULL, null_callback);
Gaurav Shah10109f22011-11-11 20:16:22 -0800993 }
mukesh agrawal32399322011-09-01 10:53:43 -0700994}
995
mukesh agrawal15908392011-11-16 18:29:25 +0000996void WiFi::StateChanged(const string &new_state) {
997 const string old_state = supplicant_state_;
mukesh agrawal7ec71312011-11-10 02:08:26 +0000998 supplicant_state_ = new_state;
mukesh agrawal15908392011-11-16 18:29:25 +0000999 LOG(INFO) << "WiFi " << link_name() << " " << __func__ << " "
1000 << old_state << " -> " << new_state;
1001
1002 WiFiService *affected_service;
1003 // Identify the service to which the state change applies. If
1004 // |pending_service_| is non-NULL, then the state change applies to
1005 // |pending_service_|. Otherwise, it applies to |current_service_|.
1006 //
1007 // This policy is driven by the fact that the |pending_service_|
1008 // doesn't become the |current_service_| until wpa_supplicant
1009 // reports a CurrentBSS change to the |pending_service_|. And the
mukesh agrawalc01f3982012-01-24 13:48:39 -08001010 // CurrentBSS change won't be reported until the |pending_service_|
mukesh agrawal15908392011-11-16 18:29:25 +00001011 // reaches the wpa_supplicant::kInterfaceStateCompleted state.
1012 affected_service =
1013 pending_service_.get() ? pending_service_.get() : current_service_.get();
1014 if (!affected_service) {
1015 VLOG(2) << "WiFi " << link_name() << " " << __func__
1016 << " with no service";
1017 return;
1018 }
1019
mukesh agrawalc01f3982012-01-24 13:48:39 -08001020 if (new_state == wpa_supplicant::kInterfaceStateCompleted &&
1021 !affected_service->IsConnected()) {
1022 if (AcquireIPConfig()) {
1023 LOG(INFO) << link_name() << " is up; should start L3!";
1024 affected_service->SetState(Service::kStateConfiguring);
1025 } else {
1026 LOG(ERROR) << "Unable to acquire DHCP config.";
1027 }
mukesh agrawal15908392011-11-16 18:29:25 +00001028 } else if (new_state == wpa_supplicant::kInterfaceStateAssociated) {
1029 affected_service->SetState(Service::kStateAssociating);
1030 } else if (new_state == wpa_supplicant::kInterfaceStateAuthenticating ||
1031 new_state == wpa_supplicant::kInterfaceStateAssociating ||
1032 new_state == wpa_supplicant::kInterfaceState4WayHandshake ||
1033 new_state == wpa_supplicant::kInterfaceStateGroupHandshake) {
1034 // Ignore transitions into these states from Completed, to avoid
1035 // bothering the user when roaming, or re-keying.
1036 if (old_state != wpa_supplicant::kInterfaceStateCompleted)
1037 affected_service->SetState(Service::kStateAssociating);
1038 // TOOD(quiche): On backwards transitions, we should probably set
1039 // a timeout for getting back into the completed state. At present,
1040 // we depend on wpa_supplicant eventually reporting that CurrentBSS
mukesh agrawal8a3188d2011-12-01 20:56:44 +00001041 // has changed. But there may be cases where that signal is not sent.
mukesh agrawal15908392011-11-16 18:29:25 +00001042 // (crosbug.com/23207)
1043 } else {
1044 // Other transitions do not affect Service state.
1045 //
1046 // Note in particular that we ignore a State change into
1047 // kInterfaceStateDisconnected, in favor of observing the corresponding
1048 // change in CurrentBSS.
1049 }
mukesh agrawal7ec71312011-11-10 02:08:26 +00001050}
1051
1052// Used by Manager.
mukesh agrawal7a4e4002011-09-06 11:26:05 -07001053WiFiServiceRefPtr WiFi::GetService(const KeyValueStore &args, Error *error) {
Darin Petkovb65c2452012-02-23 15:17:06 +01001054 CHECK_EQ(args.GetString(flimflam::kTypeProperty), flimflam::kTypeWifi);
mukesh agrawal7a4e4002011-09-06 11:26:05 -07001055
1056 if (args.ContainsString(flimflam::kModeProperty) &&
1057 args.GetString(flimflam::kModeProperty) !=
1058 flimflam::kModeManaged) {
1059 error->Populate(Error::kNotSupported, kManagerErrorUnsupportedServiceMode);
1060 return NULL;
1061 }
1062
1063 if (!args.ContainsString(flimflam::kSSIDProperty)) {
1064 error->Populate(Error::kInvalidArguments, kManagerErrorSSIDRequired);
1065 return NULL;
1066 }
1067
1068 string ssid = args.GetString(flimflam::kSSIDProperty);
1069 if (ssid.length() < 1) {
1070 error->Populate(Error::kInvalidNetworkName, kManagerErrorSSIDTooShort);
1071 return NULL;
1072 }
1073
1074 if (ssid.length() > IEEE_80211::kMaxSSIDLen) {
1075 error->Populate(Error::kInvalidNetworkName, kManagerErrorSSIDTooLong);
1076 return NULL;
1077 }
1078
1079 string security_method;
1080 if (args.ContainsString(flimflam::kSecurityProperty)) {
1081 security_method = args.GetString(flimflam::kSecurityProperty);
1082 } else {
1083 security_method = flimflam::kSecurityNone;
1084 }
1085
1086 if (security_method != flimflam::kSecurityNone &&
1087 security_method != flimflam::kSecurityWep &&
1088 security_method != flimflam::kSecurityPsk &&
1089 security_method != flimflam::kSecurityWpa &&
1090 security_method != flimflam::kSecurityRsn &&
1091 security_method != flimflam::kSecurity8021x) {
1092 error->Populate(Error::kNotSupported,
1093 kManagerErrorUnsupportedSecurityMode);
1094 return NULL;
1095 }
1096
1097 if ((security_method == flimflam::kSecurityWep ||
1098 security_method == flimflam::kSecurityPsk ||
1099 security_method == flimflam::kSecurityWpa ||
1100 security_method == flimflam::kSecurityRsn) &&
1101 !args.ContainsString(flimflam::kPassphraseProperty)) {
1102 error->Populate(Error::kInvalidArguments,
1103 kManagerErrorPassphraseRequired);
1104 return NULL;
1105 }
1106
Paul Stewart6ab23a92011-11-09 17:17:47 -08001107 bool hidden_ssid;
Paul Stewartced6a0b2011-11-08 15:32:04 -08001108 if (args.ContainsBool(flimflam::kWifiHiddenSsid)) {
1109 hidden_ssid = args.GetBool(flimflam::kWifiHiddenSsid);
Paul Stewart6ab23a92011-11-09 17:17:47 -08001110 } else {
1111 // If the service is not found, and the caller hasn't specified otherwise,
1112 // we assume this is is a hidden network.
1113 hidden_ssid = true;
Paul Stewartced6a0b2011-11-08 15:32:04 -08001114 }
1115
Paul Stewart6ab23a92011-11-09 17:17:47 -08001116 vector<uint8_t> ssid_bytes(ssid.begin(), ssid.end());
1117 WiFiServiceRefPtr service(FindService(ssid_bytes, flimflam::kModeManaged,
1118 security_method));
1119 if (!service.get()) {
mukesh agrawal1a056262011-10-05 14:36:54 -07001120 service = new WiFiService(control_interface(),
1121 dispatcher(),
Thieu Le3426c8f2012-01-11 17:35:11 -08001122 metrics(),
mukesh agrawal1a056262011-10-05 14:36:54 -07001123 manager(),
1124 this,
Paul Stewart6ab23a92011-11-09 17:17:47 -08001125 ssid_bytes,
mukesh agrawal1a056262011-10-05 14:36:54 -07001126 flimflam::kModeManaged,
Paul Stewartced6a0b2011-11-08 15:32:04 -08001127 security_method,
1128 hidden_ssid);
1129 services_.push_back(service);
mukesh agrawal261daca2011-12-02 18:56:56 +00001130 // NB: We do not register the newly created Service with the Manager.
1131 // The Service will be registered if/when we find Endpoints for it.
mukesh agrawal7a4e4002011-09-06 11:26:05 -07001132 }
1133
mukesh agrawal1a056262011-10-05 14:36:54 -07001134 if (security_method == flimflam::kSecurityWep ||
1135 security_method == flimflam::kSecurityPsk ||
1136 security_method == flimflam::kSecurityWpa ||
1137 security_method == flimflam::kSecurityRsn) {
1138 service->SetPassphrase(args.GetString(flimflam::kPassphraseProperty),
1139 error);
1140 if (error->IsFailure()) {
1141 return NULL;
1142 }
1143 }
1144
Paul Stewartcb59fed2012-03-21 21:14:46 -07001145 service->Configure(args, error);
mukesh agrawal7a4e4002011-09-06 11:26:05 -07001146
Paul Stewart7f61e522012-03-22 11:13:45 -07001147 // TODO(pstew): Schedule a task to forget up all non-hidden services that
1148 // have no endpoints like the one we may have just created. crosbug.com/28224
1149
mukesh agrawal7a4e4002011-09-06 11:26:05 -07001150 return service;
1151}
1152
mukesh agrawal16bc1b82012-02-09 18:38:26 -08001153// static
1154bool WiFi::SanitizeSSID(string *ssid) {
1155 CHECK(ssid);
1156
1157 size_t ssid_len = ssid->length();
1158 size_t i;
1159 bool changed = false;
1160
Gary Morainac1bdb42012-02-16 17:42:29 -08001161 for (i = 0; i < ssid_len; ++i) {
mukesh agrawal16bc1b82012-02-09 18:38:26 -08001162 if (!g_ascii_isprint((*ssid)[i])) {
1163 (*ssid)[i] = '?';
1164 changed = true;
1165 }
1166 }
1167
1168 return changed;
1169}
1170
mukesh agrawal4d0401c2012-01-06 16:05:31 -08001171void WiFi::HelpRegisterDerivedInt32(
1172 PropertyStore *store,
1173 const string &name,
1174 int32(WiFi::*get)(Error *error),
1175 void(WiFi::*set)(const int32 &value, Error *error)) {
1176 store->RegisterDerivedInt32(
1177 name,
1178 Int32Accessor(new CustomAccessor<WiFi, int32>(this, get, set)));
1179}
1180
1181void WiFi::HelpRegisterDerivedString(
1182 PropertyStore *store,
1183 const string &name,
1184 string(WiFi::*get)(Error *error),
1185 void(WiFi::*set)(const string &value, Error *error)) {
1186 store->RegisterDerivedString(
1187 name,
1188 StringAccessor(new CustomAccessor<WiFi, string>(this, get, set)));
1189}
1190
1191void WiFi::HelpRegisterDerivedUint16(
1192 PropertyStore *store,
1193 const string &name,
1194 uint16(WiFi::*get)(Error *error),
1195 void(WiFi::*set)(const uint16 &value, Error *error)) {
1196 store->RegisterDerivedUint16(
1197 name,
1198 Uint16Accessor(new CustomAccessor<WiFi, uint16>(this, get, set)));
1199}
1200
Gary Morainac1bdb42012-02-16 17:42:29 -08001201void WiFi::HandlePowerStateChange(PowerManager::SuspendState new_state) {
mukesh agrawal5c05b292012-03-07 10:12:52 -08001202 LOG(INFO) << __func__;
1203 if (new_state == PowerManagerProxyDelegate::kOn) {
1204 // We want to flush the BSS cache, but we don't want to conflict
1205 // with a running scan or an active connection attempt. So record
1206 // the need to flush, and take care of flushing when the next scan
1207 // completes.
1208 //
1209 // Note that supplicant will automatically expire old cache
1210 // entries (after, e.g., a BSS is not found in two consecutive
1211 // scans). However, our explicit flush accelerates re-association
1212 // in cases where a BSS disappeared while we were asleep. (See,
1213 // e.g. WiFiRoaming.005SuspendRoam.)
1214 time_->GetTimeMonotonic(&resumed_at_);
1215 need_bss_flush_ = true;
1216
1217 if (!scan_pending_ && IsIdle()) {
1218 // Not scanning/connecting/connected, so let's get things rolling.
1219 Scan(NULL);
1220 }
Gary Morainac1bdb42012-02-16 17:42:29 -08001221 }
1222}
1223
Paul Stewartb50f0b92011-05-16 16:31:42 -07001224} // namespace shill