Upstream version 5.34.104.0
[platform/framework/web/crosswalk.git] / src / components / wifi / wifi_service_mac.mm
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.
4
5 #include "components/wifi/wifi_service.h"
6
7 #import <netinet/in.h>
8 #import <CoreWLAN/CoreWLAN.h>
9 #import <SystemConfiguration/SystemConfiguration.h>
10
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"
18
19 #if !defined(MAC_OS_X_VERSION_10_7) || \
20     MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_7
21
22 // Local definitions of API added in Mac OS X 10.7
23
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;
30 @end
31
32 enum CWChannelBand {
33   kCWChannelBandUnknown = 0,
34   kCWChannelBand2GHz = 1,
35   kCWChannelBand5GHz = 2,
36 };
37
38 @interface CWChannel : NSObject
39 @property(readonly) CWChannelBand channelBand;
40 @end
41
42 @interface CWNetwork (LionAPI)
43 @property(readonly) CWChannel* wlanChannel;
44 @end
45
46 #endif  // 10.7
47
48 namespace wifi {
49
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";
56
57 // Implementation of WiFiService for Mac OS X.
58 class WiFiServiceMac : public WiFiService {
59  public:
60   WiFiServiceMac();
61   virtual ~WiFiServiceMac();
62
63   // WiFiService interface implementation.
64   virtual void Initialize(
65       scoped_refptr<base::SequencedTaskRunner> task_runner) OVERRIDE;
66
67   virtual void UnInitialize() OVERRIDE;
68
69   virtual void GetProperties(const std::string& network_guid,
70                              base::DictionaryValue* properties,
71                              std::string* error) OVERRIDE;
72
73   virtual void GetManagedProperties(const std::string& network_guid,
74                                     base::DictionaryValue* managed_properties,
75                                     std::string* error) OVERRIDE;
76
77   virtual void GetState(const std::string& network_guid,
78                         base::DictionaryValue* properties,
79                         std::string* error) OVERRIDE;
80
81   virtual void SetProperties(const std::string& network_guid,
82                              scoped_ptr<base::DictionaryValue> properties,
83                              std::string* error) OVERRIDE;
84
85   virtual void CreateNetwork(bool shared,
86                              scoped_ptr<base::DictionaryValue> properties,
87                              std::string* network_guid,
88                              std::string* error) OVERRIDE;
89
90   virtual void GetVisibleNetworks(const std::string& network_type,
91                                   base::ListValue* network_list) OVERRIDE;
92
93   virtual void RequestNetworkScan() OVERRIDE;
94
95   virtual void StartConnect(const std::string& network_guid,
96                             std::string* error) OVERRIDE;
97
98   virtual void StartDisconnect(const std::string& network_guid,
99                                std::string* error) OVERRIDE;
100
101   virtual void GetKeyFromSystem(const std::string& network_guid,
102                                 std::string* key_data,
103                                 std::string* error) OVERRIDE;
104
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;
109
110   virtual void RequestConnectedNetworkUpdate() OVERRIDE;
111
112  private:
113   // Checks |ns_error| and if is not |nil|, then stores |error_name|
114   // into |error|.
115   bool CheckError(NSError* ns_error,
116                   const char* error_name,
117                   std::string* error) const;
118
119   // Gets |ssid| from unique |network_guid|.
120   NSString* SSIDFromGUID(const std::string& network_guid) const {
121     return base::SysUTF8ToNSString(network_guid);
122   }
123
124   // Gets unique |network_guid| string based on |ssid|.
125   std::string GUIDFromSSID(NSString* ssid) const {
126     return base::SysNSStringToUTF8(ssid);
127   }
128
129   // Populates |properties| from |network|.
130   void NetworkPropertiesFromCWNetwork(const CWNetwork* network,
131                                       NetworkProperties* properties) const;
132
133   // Converts |CWSecurityMode| into onc::wifi::k{WPA|WEP}* security constant.
134   std::string SecurityFromCWSecurityMode(CWSecurityMode security) const;
135
136   // Converts |CWChannelBand| into WiFiService::Frequency constant.
137   Frequency FrequencyFromCWChannelBand(CWChannelBand band) const;
138
139   // Gets current |onc::connection_state| for given |network_guid|.
140   std::string GetNetworkConnectionState(const std::string& network_guid) const;
141
142   // Updates |networks_| with the list of visible wireless networks.
143   void UpdateNetworks();
144
145   // Find network by |network_guid| and return iterator to its entry in
146   // |networks_|.
147   NetworkList::iterator FindNetwork(const std::string& network_guid);
148
149   // Handles notification from |wlan_observer_|.
150   void OnWlanObserverNotification();
151
152   // Notifies |network_list_changed_observer_| that list of visible networks has
153   // changed to |networks|.
154   void NotifyNetworkListChanged(const NetworkList& networks);
155
156   // Notifies |networks_changed_observer_| that network |network_guid|
157   // connection state has changed.
158   void NotifyNetworkChanged(const std::string& network_guid);
159
160   // Default interface.
161   base::scoped_nsobject<CWInterface> interface_;
162   // WLAN Notifications observer. |this| doesn't own this reference.
163   id wlan_observer_;
164
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_;
179
180   DISALLOW_COPY_AND_ASSIGN(WiFiServiceMac);
181 };
182
183 WiFiServiceMac::WiFiServiceMac() : wlan_observer_(nil) {
184 }
185
186 WiFiServiceMac::~WiFiServiceMac() {
187 }
188
189 void WiFiServiceMac::Initialize(
190   scoped_refptr<base::SequencedTaskRunner> task_runner) {
191   task_runner_.swap(task_runner);
192   interface_.reset([[CWInterface interface] retain]);
193   if (!interface_) {
194     DVLOG(1) << "Failed to initialize default interface.";
195     return;
196   }
197
198   if (![interface_
199           respondsToSelector:@selector(associateToNetwork:password:error:)]) {
200     DVLOG(1) << "CWInterface does not support associateToNetwork.";
201     interface_.reset();
202     return;
203   }
204 }
205
206 void WiFiServiceMac::UnInitialize() {
207   if (wlan_observer_)
208     [[NSNotificationCenter defaultCenter] removeObserver:wlan_observer_];
209   interface_.reset();
210 }
211
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;
219     return;
220   }
221
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;
226 }
227
228 void WiFiServiceMac::GetManagedProperties(
229     const std::string& network_guid,
230     base::DictionaryValue* managed_properties,
231     std::string* error) {
232   *error = kErrorNotImplemented;
233 }
234
235 void WiFiServiceMac::GetState(const std::string& network_guid,
236                               base::DictionaryValue* properties,
237                               std::string* error) {
238   *error = kErrorNotImplemented;
239 }
240
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());
247 }
248
249 void WiFiServiceMac::CreateNetwork(
250     bool shared,
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;
257     return;
258   }
259
260   std::string guid = network_properties.ssid;
261   if (FindNetwork(guid) != networks_.end()) {
262     *error = kErrorInvalidData;
263     return;
264   }
265   network_properties_.SetWithoutPathExpansion(guid,
266                                               properties.release());
267   *network_guid = guid;
268 }
269
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) {
275     return;
276   }
277
278   if (networks_.empty())
279     UpdateNetworks();
280
281   for (WiFiService::NetworkList::const_iterator it = networks_.begin();
282        it != networks_.end();
283        ++it) {
284     scoped_ptr<base::DictionaryValue> network(it->ToValue(true));
285     network_list->Append(network.release());
286   }
287 }
288
289 void WiFiServiceMac::RequestNetworkScan() {
290   DVLOG(1) << "*** RequestNetworkScan";
291   UpdateNetworks();
292 }
293
294 void WiFiServiceMac::StartConnect(const std::string& network_guid,
295                                   std::string* error) {
296   NSError* ns_error = nil;
297
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)
303     return;
304
305   NSSet* networks = [interface_
306       scanForNetworksWithName:SSIDFromGUID(network_guid)
307                         error:&ns_error];
308
309   if (CheckError(ns_error, kErrorScanForNetworksWithName, error))
310     return;
311
312   CWNetwork* network = [networks anyObject];
313   if (network == nil) {
314     // System can't find the network, remove it from the |networks_| and notify
315     // observers.
316     NetworkList::iterator it = FindNetwork(connected_network_guid);
317     if (it != networks_.end()) {
318       networks_.erase(it);
319       // Notify observers that list has changed.
320       NotifyNetworkListChanged(networks_);
321     }
322
323     *error = kErrorNotFound;
324     return;
325   }
326
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,
333                                                             &properties) &&
334       properties->GetDictionary(onc::network_type::kWiFi, &wifi) &&
335       wifi->GetString(onc::wifi::kPassphrase, &passphrase)) {
336     ns_password = base::SysUTF8ToNSString(passphrase);
337   }
338
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
347                               password:ns_password
348                                  error:&ns_error]) {
349       NSInteger error_code = [ns_error code];
350       if (error_code != kCWTimeoutErr && error_code != kCWInvalidPMKErr) {
351         break;
352       }
353     }
354   }
355   CheckError(ns_error, kErrorAssociateToNetwork, error);
356 }
357
358 void WiFiServiceMac::StartDisconnect(const std::string& network_guid,
359                                      std::string* error) {
360   DVLOG(1) << "*** StartDisconnect: " << network_guid;
361
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);
370   } else {
371     *error = kErrorNotConnected;
372   }
373 }
374
375 void WiFiServiceMac::GetKeyFromSystem(const std::string& network_guid,
376                                       std::string* key_data,
377                                       std::string* error) {
378   static const char kAirPortServiceName[] = "AirPort";
379
380   UInt32 password_length = 0;
381   void *password_data = NULL;
382   OSStatus status = SecKeychainFindGenericPassword(NULL,
383                                                    strlen(kAirPortServiceName),
384                                                    kAirPortServiceName,
385                                                    network_guid.length(),
386                                                    network_guid.c_str(),
387                                                    &password_length,
388                                                    &password_data,
389                                                    NULL);
390   if (status != errSecSuccess) {
391     *error = kErrorNotFound;
392     return;
393   }
394
395   if (password_data) {
396     *key_data = std::string(reinterpret_cast<char*>(password_data),
397                             password_length);
398     SecKeychainItemFreeContent(NULL, password_data);
399   }
400 }
401
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;
409
410   // Remove previous OS notifications observer.
411   if (wlan_observer_) {
412     [[NSNotificationCenter defaultCenter] removeObserver:wlan_observer_];
413     wlan_observer_ = nil;
414   }
415
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(
422                 FROM_HERE,
423                 base::Bind(&WiFiServiceMac::OnWlanObserverNotification,
424                            base::Unretained(this)));
425     };
426
427     wlan_observer_ = [[NSNotificationCenter defaultCenter]
428         addObserverForName:kCWSSIDDidChangeNotification
429                     object:nil
430                      queue:nil
431                 usingBlock:ns_observer];
432   }
433 }
434
435 void WiFiServiceMac::RequestConnectedNetworkUpdate() {
436   OnWlanObserverNotification();
437 }
438
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;
443
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(
452           kCFAllocatorDefault,
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;
460   }
461   // Network is not reachable yet, so it must be |kConnecting|.
462   return onc::connection_state::kConnecting;
463 }
464
465 void WiFiServiceMac::UpdateNetworks() {
466   NSError* ns_error = nil;
467   NSSet* cw_networks = [interface_ scanForNetworksWithName:nil
468                                                      error:&ns_error];
469   if (ns_error != nil)
470     return;
471
472   std::string connected_bssid = base::SysNSStringToUTF8([interface_ bssid]);
473   std::map<std::string, NetworkProperties*> network_properties_map;
474   networks_.clear();
475
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;
481
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;
487     }
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;
491
492     NetworkProperties* properties = network_properties_map.at(network_guid);
493     if (update_all_properties) {
494       NetworkPropertiesFromCWNetwork(cw_network, properties);
495     } else {
496       properties->frequency_set.insert(FrequencyFromCWChannelBand(
497           [[cw_network wlanChannel] channelBand]));
498     }
499   }
500   // Sort networks, so connected/connecting is up front.
501   networks_.sort(NetworkProperties::OrderByType);
502   // Notify observers that list has changed.
503   NotifyNetworkListChanged(networks_);
504 }
505
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];
511     *error = error_name;
512     return true;
513   }
514   return false;
515 }
516
517 void WiFiServiceMac::NetworkPropertiesFromCWNetwork(
518     const CWNetwork* network,
519     NetworkProperties* properties) const {
520   std::string network_guid = GUIDFromSSID([network ssid]);
521
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;
527
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]));
534
535   properties->signal_strength = [[network rssi] intValue];
536 }
537
538 std::string WiFiServiceMac::SecurityFromCWSecurityMode(
539     CWSecurityMode security) const {
540   switch (security) {
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;
555   }
556   return onc::wifi::kWPA_EAP;
557 }
558
559
560 WiFiService::Frequency WiFiServiceMac::FrequencyFromCWChannelBand(
561     CWChannelBand band) const {
562   return band == kCWChannelBand2GHz ? kFrequency2400 : kFrequency5000;
563 }
564
565 WiFiService::NetworkList::iterator WiFiServiceMac::FindNetwork(
566     const std::string& network_guid) {
567   for (NetworkList::iterator it = networks_.begin();
568        it != networks_.end();
569        ++it) {
570     if (it->guid == network_guid)
571       return it;
572   }
573   return networks_.end();
574 }
575
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_);
586     }
587     connected_network_guid_ = connected_network_guid;
588   }
589
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);
595     } else {
596       // Can't find |connected_network_guid| in |networks_|, try to update it.
597       UpdateNetworks();
598     }
599     // Notify that network is connecting.
600     NotifyNetworkChanged(connected_network_guid);
601     // Further network change notification will be sent by detector.
602   }
603 }
604
605 void WiFiServiceMac::NotifyNetworkListChanged(const NetworkList& networks) {
606   if (network_list_changed_observer_.is_null())
607     return;
608
609   NetworkGuidList current_networks;
610   for (NetworkList::const_iterator it = networks.begin();
611        it != networks.end();
612        ++it) {
613     current_networks.push_back(it->guid);
614   }
615
616   message_loop_proxy_->PostTask(
617       FROM_HERE,
618       base::Bind(network_list_changed_observer_, current_networks));
619 }
620
621 void WiFiServiceMac::NotifyNetworkChanged(const std::string& network_guid) {
622   if (networks_changed_observer_.is_null())
623     return;
624
625   DVLOG(1) << "NotifyNetworkChanged: " << network_guid;
626   NetworkGuidList changed_networks(1, network_guid);
627   message_loop_proxy_->PostTask(
628       FROM_HERE,
629       base::Bind(networks_changed_observer_, changed_networks));
630 }
631
632 // static
633 WiFiService* WiFiService::Create() { return new WiFiServiceMac(); }
634
635 }  // namespace wifi