1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "components/wifi/wifi_service.h"
8 #import <CoreWLAN/CoreWLAN.h>
9 #import <SystemConfiguration/SystemConfiguration.h>
11 #include "base/bind.h"
12 #include "base/mac/foundation_util.h"
13 #include "base/mac/scoped_cftyperef.h"
14 #include "base/mac/scoped_nsobject.h"
15 #include "base/message_loop/message_loop.h"
16 #include "base/strings/sys_string_conversions.h"
17 #include "components/onc/onc_constants.h"
19 #if !defined(MAC_OS_X_VERSION_10_7) || \
20 MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_7
22 // Local definitions of API added in Mac OS X 10.7
24 @interface CWInterface (LionAPI)
25 - (BOOL)associateToNetwork:(CWNetwork*)network
26 password:(NSString*)password
27 error:(NSError**)error;
28 - (NSSet*)scanForNetworksWithName:(NSString*)networkName
29 error:(NSError**)error;
33 kCWChannelBandUnknown = 0,
34 kCWChannelBand2GHz = 1,
35 kCWChannelBand5GHz = 2,
38 @interface CWChannel : NSObject
39 @property(readonly) CWChannelBand channelBand;
42 @interface CWNetwork (LionAPI)
43 @property(readonly) CWChannel* wlanChannel;
50 const char kErrorAssociateToNetwork[] = "Error.AssociateToNetwork";
51 const char kErrorInvalidData[] = "Error.InvalidData";
52 const char kErrorNotConnected[] = "Error.NotConnected";
53 const char kErrorNotFound[] = "Error.NotFound";
54 const char kErrorNotImplemented[] = "Error.NotImplemented";
55 const char kErrorScanForNetworksWithName[] = "Error.ScanForNetworksWithName";
57 // Implementation of WiFiService for Mac OS X.
58 class WiFiServiceMac : public WiFiService {
61 virtual ~WiFiServiceMac();
63 // WiFiService interface implementation.
64 virtual void Initialize(
65 scoped_refptr<base::SequencedTaskRunner> task_runner) OVERRIDE;
67 virtual void UnInitialize() OVERRIDE;
69 virtual void GetProperties(const std::string& network_guid,
70 base::DictionaryValue* properties,
71 std::string* error) OVERRIDE;
73 virtual void GetManagedProperties(const std::string& network_guid,
74 base::DictionaryValue* managed_properties,
75 std::string* error) OVERRIDE;
77 virtual void GetState(const std::string& network_guid,
78 base::DictionaryValue* properties,
79 std::string* error) OVERRIDE;
81 virtual void SetProperties(const std::string& network_guid,
82 scoped_ptr<base::DictionaryValue> properties,
83 std::string* error) OVERRIDE;
85 virtual void CreateNetwork(bool shared,
86 scoped_ptr<base::DictionaryValue> properties,
87 std::string* network_guid,
88 std::string* error) OVERRIDE;
90 virtual void GetVisibleNetworks(const std::string& network_type,
91 base::ListValue* network_list) OVERRIDE;
93 virtual void RequestNetworkScan() OVERRIDE;
95 virtual void StartConnect(const std::string& network_guid,
96 std::string* error) OVERRIDE;
98 virtual void StartDisconnect(const std::string& network_guid,
99 std::string* error) OVERRIDE;
101 virtual void GetKeyFromSystem(const std::string& network_guid,
102 std::string* key_data,
103 std::string* error) OVERRIDE;
105 virtual void SetEventObservers(
106 scoped_refptr<base::MessageLoopProxy> message_loop_proxy,
107 const NetworkGuidListCallback& networks_changed_observer,
108 const NetworkGuidListCallback& network_list_changed_observer) OVERRIDE;
110 virtual void RequestConnectedNetworkUpdate() OVERRIDE;
113 // Checks |ns_error| and if is not |nil|, then stores |error_name|
115 bool CheckError(NSError* ns_error,
116 const char* error_name,
117 std::string* error) const;
119 // Gets |ssid| from unique |network_guid|.
120 NSString* SSIDFromGUID(const std::string& network_guid) const {
121 return base::SysUTF8ToNSString(network_guid);
124 // Gets unique |network_guid| string based on |ssid|.
125 std::string GUIDFromSSID(NSString* ssid) const {
126 return base::SysNSStringToUTF8(ssid);
129 // Populates |properties| from |network|.
130 void NetworkPropertiesFromCWNetwork(const CWNetwork* network,
131 NetworkProperties* properties) const;
133 // Converts |CWSecurityMode| into onc::wifi::k{WPA|WEP}* security constant.
134 std::string SecurityFromCWSecurityMode(CWSecurityMode security) const;
136 // Converts |CWChannelBand| into WiFiService::Frequency constant.
137 Frequency FrequencyFromCWChannelBand(CWChannelBand band) const;
139 // Gets current |onc::connection_state| for given |network_guid|.
140 std::string GetNetworkConnectionState(const std::string& network_guid) const;
142 // Updates |networks_| with the list of visible wireless networks.
143 void UpdateNetworks();
145 // Find network by |network_guid| and return iterator to its entry in
147 NetworkList::iterator FindNetwork(const std::string& network_guid);
149 // Handles notification from |wlan_observer_|.
150 void OnWlanObserverNotification();
152 // Notifies |network_list_changed_observer_| that list of visible networks has
153 // changed to |networks|.
154 void NotifyNetworkListChanged(const NetworkList& networks);
156 // Notifies |networks_changed_observer_| that network |network_guid|
157 // connection state has changed.
158 void NotifyNetworkChanged(const std::string& network_guid);
160 // Default interface.
161 base::scoped_nsobject<CWInterface> interface_;
162 // WLAN Notifications observer. |this| doesn't own this reference.
165 // Observer to get notified when network(s) have changed (e.g. connect).
166 NetworkGuidListCallback networks_changed_observer_;
167 // Observer to get notified when network list has changed.
168 NetworkGuidListCallback network_list_changed_observer_;
169 // MessageLoopProxy to which events should be posted.
170 scoped_refptr<base::MessageLoopProxy> message_loop_proxy_;
171 // Task runner for worker tasks.
172 scoped_refptr<base::SequencedTaskRunner> task_runner_;
173 // Cached list of visible networks. Updated by |UpdateNetworks|.
174 NetworkList networks_;
175 // Guid of last known connected network.
176 std::string connected_network_guid_;
177 // Temporary storage of network properties indexed by |network_guid|.
178 base::DictionaryValue network_properties_;
180 DISALLOW_COPY_AND_ASSIGN(WiFiServiceMac);
183 WiFiServiceMac::WiFiServiceMac() : wlan_observer_(nil) {
186 WiFiServiceMac::~WiFiServiceMac() {
189 void WiFiServiceMac::Initialize(
190 scoped_refptr<base::SequencedTaskRunner> task_runner) {
191 task_runner_.swap(task_runner);
192 interface_.reset([[CWInterface interface] retain]);
194 DVLOG(1) << "Failed to initialize default interface.";
199 respondsToSelector:@selector(associateToNetwork:password:error:)]) {
200 DVLOG(1) << "CWInterface does not support associateToNetwork.";
206 void WiFiServiceMac::UnInitialize() {
208 [[NSNotificationCenter defaultCenter] removeObserver:wlan_observer_];
212 void WiFiServiceMac::GetProperties(const std::string& network_guid,
213 base::DictionaryValue* properties,
214 std::string* error) {
215 NetworkList::iterator it = FindNetwork(network_guid);
216 if (it == networks_.end()) {
217 DVLOG(1) << "Network not found:" << network_guid;
218 *error = kErrorNotFound;
222 it->connection_state = GetNetworkConnectionState(network_guid);
223 scoped_ptr<base::DictionaryValue> network(it->ToValue(false));
224 properties->Swap(network.get());
225 DVLOG(1) << *properties;
228 void WiFiServiceMac::GetManagedProperties(
229 const std::string& network_guid,
230 base::DictionaryValue* managed_properties,
231 std::string* error) {
232 *error = kErrorNotImplemented;
235 void WiFiServiceMac::GetState(const std::string& network_guid,
236 base::DictionaryValue* properties,
237 std::string* error) {
238 *error = kErrorNotImplemented;
241 void WiFiServiceMac::SetProperties(
242 const std::string& network_guid,
243 scoped_ptr<base::DictionaryValue> properties,
244 std::string* error) {
245 network_properties_.SetWithoutPathExpansion(network_guid,
246 properties.release());
249 void WiFiServiceMac::CreateNetwork(
251 scoped_ptr<base::DictionaryValue> properties,
252 std::string* network_guid,
253 std::string* error) {
254 WiFiService::NetworkProperties network_properties;
255 if (!network_properties.UpdateFromValue(*properties)) {
256 *error = kErrorInvalidData;
260 std::string guid = network_properties.ssid;
261 if (FindNetwork(guid) != networks_.end()) {
262 *error = kErrorInvalidData;
265 network_properties_.SetWithoutPathExpansion(guid,
266 properties.release());
267 *network_guid = guid;
270 void WiFiServiceMac::GetVisibleNetworks(const std::string& network_type,
271 base::ListValue* network_list) {
272 if (!network_type.empty() &&
273 network_type != onc::network_type::kAllTypes &&
274 network_type != onc::network_type::kWiFi) {
278 if (networks_.empty())
281 for (WiFiService::NetworkList::const_iterator it = networks_.begin();
282 it != networks_.end();
284 scoped_ptr<base::DictionaryValue> network(it->ToValue(true));
285 network_list->Append(network.release());
289 void WiFiServiceMac::RequestNetworkScan() {
290 DVLOG(1) << "*** RequestNetworkScan";
294 void WiFiServiceMac::StartConnect(const std::string& network_guid,
295 std::string* error) {
296 NSError* ns_error = nil;
298 DVLOG(1) << "*** StartConnect: " << network_guid;
299 // Remember previously connected network.
300 std::string connected_network_guid = GUIDFromSSID([interface_ ssid]);
301 // Check whether desired network is already connected.
302 if (network_guid == connected_network_guid)
305 NSSet* networks = [interface_
306 scanForNetworksWithName:SSIDFromGUID(network_guid)
309 if (CheckError(ns_error, kErrorScanForNetworksWithName, error))
312 CWNetwork* network = [networks anyObject];
313 if (network == nil) {
314 // System can't find the network, remove it from the |networks_| and notify
316 NetworkList::iterator it = FindNetwork(connected_network_guid);
317 if (it != networks_.end()) {
319 // Notify observers that list has changed.
320 NotifyNetworkListChanged(networks_);
323 *error = kErrorNotFound;
327 // Check whether WiFi Password is set in |network_properties_|.
328 base::DictionaryValue* properties;
329 base::DictionaryValue* wifi;
330 std::string passphrase;
331 NSString* ns_password = nil;
332 if (network_properties_.GetDictionaryWithoutPathExpansion(network_guid,
334 properties->GetDictionary(onc::network_type::kWiFi, &wifi) &&
335 wifi->GetString(onc::wifi::kPassphrase, &passphrase)) {
336 ns_password = base::SysUTF8ToNSString(passphrase);
339 // Number of attempts to associate to network.
340 static const int kMaxAssociationAttempts = 3;
341 // Try to associate to network several times if timeout or PMK error occurs.
342 for (int i = 0; i < kMaxAssociationAttempts; ++i) {
343 // Nil out the PMK to prevent stale data from causing invalid PMK error
344 // (CoreWLANTypes -3924).
345 [interface_ setPairwiseMasterKey:nil error:&ns_error];
346 if (![interface_ associateToNetwork:network
349 NSInteger error_code = [ns_error code];
350 if (error_code != kCWTimeoutErr && error_code != kCWInvalidPMKErr) {
355 CheckError(ns_error, kErrorAssociateToNetwork, error);
358 void WiFiServiceMac::StartDisconnect(const std::string& network_guid,
359 std::string* error) {
360 DVLOG(1) << "*** StartDisconnect: " << network_guid;
362 if (network_guid == GUIDFromSSID([interface_ ssid])) {
363 // Power-cycle the interface to disconnect from current network and connect
364 // to default network.
365 NSError* ns_error = nil;
366 [interface_ setPower:NO error:&ns_error];
367 CheckError(ns_error, kErrorAssociateToNetwork, error);
368 [interface_ setPower:YES error:&ns_error];
369 CheckError(ns_error, kErrorAssociateToNetwork, error);
371 *error = kErrorNotConnected;
375 void WiFiServiceMac::GetKeyFromSystem(const std::string& network_guid,
376 std::string* key_data,
377 std::string* error) {
378 static const char kAirPortServiceName[] = "AirPort";
380 UInt32 password_length = 0;
381 void *password_data = NULL;
382 OSStatus status = SecKeychainFindGenericPassword(NULL,
383 strlen(kAirPortServiceName),
385 network_guid.length(),
386 network_guid.c_str(),
390 if (status != errSecSuccess) {
391 *error = kErrorNotFound;
396 *key_data = std::string(reinterpret_cast<char*>(password_data),
398 SecKeychainItemFreeContent(NULL, password_data);
402 void WiFiServiceMac::SetEventObservers(
403 scoped_refptr<base::MessageLoopProxy> message_loop_proxy,
404 const NetworkGuidListCallback& networks_changed_observer,
405 const NetworkGuidListCallback& network_list_changed_observer) {
406 message_loop_proxy_.swap(message_loop_proxy);
407 networks_changed_observer_ = networks_changed_observer;
408 network_list_changed_observer_ = network_list_changed_observer;
410 // Remove previous OS notifications observer.
411 if (wlan_observer_) {
412 [[NSNotificationCenter defaultCenter] removeObserver:wlan_observer_];
413 wlan_observer_ = nil;
416 // Subscribe to OS notifications.
417 if (!networks_changed_observer_.is_null()) {
418 void (^ns_observer) (NSNotification* notification) =
419 ^(NSNotification* notification) {
420 DVLOG(1) << "Received CWSSIDDidChangeNotification";
421 task_runner_->PostTask(
423 base::Bind(&WiFiServiceMac::OnWlanObserverNotification,
424 base::Unretained(this)));
427 wlan_observer_ = [[NSNotificationCenter defaultCenter]
428 addObserverForName:kCWSSIDDidChangeNotification
431 usingBlock:ns_observer];
435 void WiFiServiceMac::RequestConnectedNetworkUpdate() {
436 OnWlanObserverNotification();
439 std::string WiFiServiceMac::GetNetworkConnectionState(
440 const std::string& network_guid) const {
441 if (network_guid != GUIDFromSSID([interface_ ssid]))
442 return onc::connection_state::kNotConnected;
444 // Check whether WiFi network is reachable.
445 struct sockaddr_in local_wifi_address;
446 bzero(&local_wifi_address, sizeof(local_wifi_address));
447 local_wifi_address.sin_len = sizeof(local_wifi_address);
448 local_wifi_address.sin_family = AF_INET;
449 local_wifi_address.sin_addr.s_addr = htonl(IN_LINKLOCALNETNUM);
450 base::ScopedCFTypeRef<SCNetworkReachabilityRef> reachability(
451 SCNetworkReachabilityCreateWithAddress(
453 reinterpret_cast<const struct sockaddr*>(&local_wifi_address)));
454 SCNetworkReachabilityFlags flags = 0u;
455 if (SCNetworkReachabilityGetFlags(reachability, &flags) &&
456 (flags & kSCNetworkReachabilityFlagsReachable) &&
457 (flags & kSCNetworkReachabilityFlagsIsDirect)) {
458 // Network is reachable, report is as |kConnected|.
459 return onc::connection_state::kConnected;
461 // Network is not reachable yet, so it must be |kConnecting|.
462 return onc::connection_state::kConnecting;
465 void WiFiServiceMac::UpdateNetworks() {
466 NSError* ns_error = nil;
467 NSSet* cw_networks = [interface_ scanForNetworksWithName:nil
472 std::string connected_bssid = base::SysNSStringToUTF8([interface_ bssid]);
473 std::map<std::string, NetworkProperties*> network_properties_map;
476 // There is one |cw_network| per BSS in |cw_networks|, so go through the set
477 // and combine them, paying attention to supported frequencies.
478 for (CWNetwork* cw_network in cw_networks) {
479 std::string network_guid = GUIDFromSSID([cw_network ssid]);
480 bool update_all_properties = false;
482 if (network_properties_map.find(network_guid) ==
483 network_properties_map.end()) {
484 networks_.push_back(NetworkProperties());
485 network_properties_map[network_guid] = &networks_.back();
486 update_all_properties = true;
488 // If current network is connected, use its properties for this network.
489 if (base::SysNSStringToUTF8([cw_network bssid]) == connected_bssid)
490 update_all_properties = true;
492 NetworkProperties* properties = network_properties_map.at(network_guid);
493 if (update_all_properties) {
494 NetworkPropertiesFromCWNetwork(cw_network, properties);
496 properties->frequency_set.insert(FrequencyFromCWChannelBand(
497 [[cw_network wlanChannel] channelBand]));
500 // Sort networks, so connected/connecting is up front.
501 networks_.sort(NetworkProperties::OrderByType);
502 // Notify observers that list has changed.
503 NotifyNetworkListChanged(networks_);
506 bool WiFiServiceMac::CheckError(NSError* ns_error,
507 const char* error_name,
508 std::string* error) const {
509 if (ns_error != nil) {
510 DLOG(ERROR) << "*** Error:" << error_name << ":" << [ns_error code];
517 void WiFiServiceMac::NetworkPropertiesFromCWNetwork(
518 const CWNetwork* network,
519 NetworkProperties* properties) const {
520 std::string network_guid = GUIDFromSSID([network ssid]);
522 properties->connection_state = GetNetworkConnectionState(network_guid);
523 properties->ssid = base::SysNSStringToUTF8([network ssid]);
524 properties->name = properties->ssid;
525 properties->guid = network_guid;
526 properties->type = onc::network_type::kWiFi;
528 properties->bssid = base::SysNSStringToUTF8([network bssid]);
529 properties->frequency = FrequencyFromCWChannelBand(
530 static_cast<CWChannelBand>([[network wlanChannel] channelBand]));
531 properties->frequency_set.insert(properties->frequency);
532 properties->security = SecurityFromCWSecurityMode(
533 static_cast<CWSecurityMode>([[network securityMode] intValue]));
535 properties->signal_strength = [[network rssi] intValue];
538 std::string WiFiServiceMac::SecurityFromCWSecurityMode(
539 CWSecurityMode security) const {
541 case kCWSecurityModeWPA_Enterprise:
542 case kCWSecurityModeWPA2_Enterprise:
543 return onc::wifi::kWPA_EAP;
544 case kCWSecurityModeWPA_PSK:
545 case kCWSecurityModeWPA2_PSK:
546 return onc::wifi::kWPA_PSK;
547 case kCWSecurityModeWEP:
548 return onc::wifi::kWEP_PSK;
549 case kCWSecurityModeOpen:
550 return onc::wifi::kNone;
551 // TODO(mef): Figure out correct mapping.
552 case kCWSecurityModeWPS:
553 case kCWSecurityModeDynamicWEP:
554 return onc::wifi::kWPA_EAP;
556 return onc::wifi::kWPA_EAP;
560 WiFiService::Frequency WiFiServiceMac::FrequencyFromCWChannelBand(
561 CWChannelBand band) const {
562 return band == kCWChannelBand2GHz ? kFrequency2400 : kFrequency5000;
565 WiFiService::NetworkList::iterator WiFiServiceMac::FindNetwork(
566 const std::string& network_guid) {
567 for (NetworkList::iterator it = networks_.begin();
568 it != networks_.end();
570 if (it->guid == network_guid)
573 return networks_.end();
576 void WiFiServiceMac::OnWlanObserverNotification() {
577 std::string connected_network_guid = GUIDFromSSID([interface_ ssid]);
578 DVLOG(1) << " *** Got Notification: " << connected_network_guid;
579 // Connected network has changed, mark previous one disconnected.
580 if (connected_network_guid != connected_network_guid_) {
581 // Update connection_state of newly connected network.
582 NetworkList::iterator it = FindNetwork(connected_network_guid_);
583 if (it != networks_.end()) {
584 it->connection_state = onc::connection_state::kNotConnected;
585 NotifyNetworkChanged(connected_network_guid_);
587 connected_network_guid_ = connected_network_guid;
590 if (!connected_network_guid.empty()) {
591 // Update connection_state of newly connected network.
592 NetworkList::iterator it = FindNetwork(connected_network_guid);
593 if (it != networks_.end()) {
594 it->connection_state = GetNetworkConnectionState(connected_network_guid);
596 // Can't find |connected_network_guid| in |networks_|, try to update it.
599 // Notify that network is connecting.
600 NotifyNetworkChanged(connected_network_guid);
601 // Further network change notification will be sent by detector.
605 void WiFiServiceMac::NotifyNetworkListChanged(const NetworkList& networks) {
606 if (network_list_changed_observer_.is_null())
609 NetworkGuidList current_networks;
610 for (NetworkList::const_iterator it = networks.begin();
611 it != networks.end();
613 current_networks.push_back(it->guid);
616 message_loop_proxy_->PostTask(
618 base::Bind(network_list_changed_observer_, current_networks));
621 void WiFiServiceMac::NotifyNetworkChanged(const std::string& network_guid) {
622 if (networks_changed_observer_.is_null())
625 DVLOG(1) << "NotifyNetworkChanged: " << network_guid;
626 NetworkGuidList changed_networks(1, network_guid);
627 message_loop_proxy_->PostTask(
629 base::Bind(networks_changed_observer_, changed_networks));
633 WiFiService* WiFiService::Create() { return new WiFiServiceMac(); }