Make sure webrtc::VideoSource is released when WebRtcVideoTrackAdapter is destroyed.
[chromium-blink-merge.git] / components / wifi / wifi_service_win.cc
blobfe9f7d03e73215f993ec44394fa555858da550e9
1 // Copyright 2013 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"
7 #include <iphlpapi.h>
8 #include <objbase.h>
9 #include <wlanapi.h>
11 #include <set>
13 #include "base/base_paths_win.h"
14 #include "base/bind.h"
15 #include "base/files/file_path.h"
16 #include "base/memory/ref_counted.h"
17 #include "base/message_loop/message_loop.h"
18 #include "base/path_service.h"
19 #include "base/strings/string16.h"
20 #include "base/strings/string_util.h"
21 #include "base/strings/utf_string_conversions.h"
22 #include "base/win/registry.h"
23 #include "components/onc/onc_constants.h"
24 #include "third_party/libxml/chromium/libxml_utils.h"
26 namespace {
27 const wchar_t kNwCategoryWizardRegKey[] =
28 L"Software\\Microsoft\\Windows NT\\CurrentVersion\\Network\\"
29 L"NwCategoryWizard";
30 const wchar_t kNwCategoryWizardRegValue[] = L"Show";
31 const wchar_t kNwCategoryWizardSavedRegValue[] = L"ShowSaved";
32 const wchar_t kNwCategoryWizardDeleteRegValue[] = L"ShowDelete";
33 const wchar_t kWlanApiDll[] = L"wlanapi.dll";
35 // Created Profile Dictionary keys
36 const char kProfileXmlKey[] = "xml";
37 const char kProfileSharedKey[] = "shared";
39 // WlanApi function names
40 const char kWlanConnect[] = "WlanConnect";
41 const char kWlanCloseHandle[] = "WlanCloseHandle";
42 const char kWlanDeleteProfile[] = "WlanDeleteProfile";
43 const char kWlanDisconnect[] = "WlanDisconnect";
44 const char kWlanEnumInterfaces[] = "WlanEnumInterfaces";
45 const char kWlanFreeMemory[] = "WlanFreeMemory";
46 const char kWlanGetAvailableNetworkList[] = "WlanGetAvailableNetworkList";
47 const char kWlanGetNetworkBssList[] = "WlanGetNetworkBssList";
48 const char kWlanGetProfile[] = "WlanGetProfile";
49 const char kWlanOpenHandle[] = "WlanOpenHandle";
50 const char kWlanQueryInterface[] = "WlanQueryInterface";
51 const char kWlanRegisterNotification[] = "WlanRegisterNotification";
52 const char kWlanSaveTemporaryProfile[] = "WlanSaveTemporaryProfile";
53 const char kWlanScan[] = "WlanScan";
54 const char kWlanSetProfile[] = "WlanSetProfile";
56 // WlanApi function definitions
57 typedef DWORD(WINAPI* WlanConnectFunction)(
58 HANDLE hClientHandle,
59 CONST GUID* pInterfaceGuid,
60 CONST PWLAN_CONNECTION_PARAMETERS pConnectionParameters,
61 PVOID pReserved);
63 typedef DWORD (WINAPI* WlanCloseHandleFunction)(
64 HANDLE hClientHandle,
65 PVOID pReserved);
67 typedef DWORD(WINAPI* WlanDeleteProfileFunction)(HANDLE hClientHandle,
68 const GUID* pInterfaceGuid,
69 LPCWSTR strProfileName,
70 PVOID pReserved);
72 typedef DWORD(WINAPI* WlanDisconnectFunction)(HANDLE hClientHandle,
73 CONST GUID* pInterfaceGuid,
74 PVOID pReserved);
76 typedef DWORD(WINAPI* WlanEnumInterfacesFunction)(
77 HANDLE hClientHandle,
78 PVOID pReserved,
79 PWLAN_INTERFACE_INFO_LIST* ppInterfaceList);
81 typedef VOID (WINAPI* WlanFreeMemoryFunction)(
82 _In_ PVOID pMemory);
84 typedef DWORD(WINAPI* WlanGetAvailableNetworkListFunction)(
85 HANDLE hClientHandle,
86 CONST GUID* pInterfaceGuid,
87 DWORD dwFlags,
88 PVOID pReserved,
89 PWLAN_AVAILABLE_NETWORK_LIST* ppAvailableNetworkList);
91 typedef DWORD (WINAPI* WlanGetNetworkBssListFunction)(
92 HANDLE hClientHandle,
93 const GUID* pInterfaceGuid,
94 const PDOT11_SSID pDot11Ssid,
95 DOT11_BSS_TYPE dot11BssType,
96 BOOL bSecurityEnabled,
97 PVOID pReserved,
98 PWLAN_BSS_LIST* ppWlanBssList);
100 typedef DWORD(WINAPI* WlanGetProfileFunction)(HANDLE hClientHandle,
101 CONST GUID* pInterfaceGuid,
102 LPCWSTR strProfileName,
103 PVOID pReserved,
104 LPWSTR* pstrProfileXml,
105 DWORD* pdwFlags,
106 DWORD* pdwGrantedAccess);
108 typedef DWORD (WINAPI* WlanOpenHandleFunction)(
109 DWORD dwClientVersion,
110 PVOID pReserved,
111 PDWORD pdwNegotiatedVersion,
112 PHANDLE phClientHandle);
114 typedef DWORD(WINAPI* WlanQueryInterfaceFunction)(
115 HANDLE hClientHandle,
116 const GUID* pInterfaceGuid,
117 WLAN_INTF_OPCODE OpCode,
118 PVOID pReserved,
119 PDWORD pdwDataSize,
120 PVOID* ppData,
121 PWLAN_OPCODE_VALUE_TYPE pWlanOpcodeValueType);
123 typedef DWORD (WINAPI* WlanRegisterNotificationFunction)(
124 HANDLE hClientHandle,
125 DWORD dwNotifSource,
126 BOOL bIgnoreDuplicate,
127 WLAN_NOTIFICATION_CALLBACK funcCallback,
128 PVOID pCallbackContext,
129 PVOID pReserved,
130 PDWORD pdwPrevNotifSource);
132 typedef DWORD (WINAPI* WlanSaveTemporaryProfileFunction)(
133 HANDLE hClientHandle,
134 CONST GUID* pInterfaceGuid,
135 LPCWSTR strProfileName,
136 LPCWSTR strAllUserProfileSecurity,
137 DWORD dwFlags,
138 BOOL bOverWrite,
139 PVOID pReserved);
141 typedef DWORD(WINAPI* WlanScanFunction)(HANDLE hClientHandle,
142 CONST GUID* pInterfaceGuid,
143 CONST PDOT11_SSID pDot11Ssid,
144 CONST PWLAN_RAW_DATA pIeData,
145 PVOID pReserved);
147 typedef DWORD(WINAPI* WlanSetProfileFunction)(HANDLE hClientHandle,
148 const GUID* pInterfaceGuid,
149 DWORD dwFlags,
150 LPCWSTR strProfileXml,
151 LPCWSTR strAllUserProfileSecurity,
152 BOOL bOverwrite,
153 PVOID pReserved,
154 DWORD* pdwReasonCode);
156 // Values for WLANProfile XML.
157 const char kAuthenticationOpen[] = "open";
158 const char kAuthenticationWepPsk[] = "WEP";
159 const char kAuthenticationWpaPsk[] = "WPAPSK";
160 const char kAuthenticationWpa2Psk[] = "WPA2PSK";
161 const char kEncryptionAES[] = "AES";
162 const char kEncryptionNone[] = "none";
163 const char kEncryptionTKIP[] = "TKIP";
164 const char kEncryptionWEP[] = "WEP";
165 const char kKeyTypeNetwork[] = "networkKey";
166 const char kKeyTypePassphrase[] = "passPhrase";
168 } // namespace
170 namespace wifi {
172 // Implementation of WiFiService for Windows.
173 class WiFiServiceImpl : public WiFiService {
174 public:
175 WiFiServiceImpl();
176 virtual ~WiFiServiceImpl();
178 // WiFiService interface implementation.
179 virtual void Initialize(
180 scoped_refptr<base::SequencedTaskRunner> task_runner) OVERRIDE;
182 virtual void UnInitialize() OVERRIDE;
184 virtual void GetProperties(const std::string& network_guid,
185 base::DictionaryValue* properties,
186 std::string* error) OVERRIDE;
188 virtual void GetManagedProperties(const std::string& network_guid,
189 base::DictionaryValue* managed_properties,
190 std::string* error) OVERRIDE;
192 virtual void GetState(const std::string& network_guid,
193 base::DictionaryValue* properties,
194 std::string* error) OVERRIDE;
196 virtual void SetProperties(const std::string& network_guid,
197 scoped_ptr<base::DictionaryValue> properties,
198 std::string* error) OVERRIDE;
200 virtual void CreateNetwork(bool shared,
201 scoped_ptr<base::DictionaryValue> properties,
202 std::string* network_guid,
203 std::string* error) OVERRIDE;
205 virtual void GetVisibleNetworks(const std::string& network_type,
206 base::ListValue* network_list) OVERRIDE;
208 virtual void RequestNetworkScan() OVERRIDE;
210 virtual void StartConnect(const std::string& network_guid,
211 std::string* error) OVERRIDE;
213 virtual void StartDisconnect(const std::string& network_guid,
214 std::string* error) OVERRIDE;
216 virtual void GetKeyFromSystem(const std::string& network_guid,
217 std::string* key_data,
218 std::string* error) OVERRIDE;
220 virtual void SetEventObservers(
221 scoped_refptr<base::MessageLoopProxy> message_loop_proxy,
222 const NetworkGuidListCallback& networks_changed_observer,
223 const NetworkGuidListCallback& network_list_changed_observer) OVERRIDE;
225 virtual void RequestConnectedNetworkUpdate() OVERRIDE {}
227 private:
228 typedef int32 EncryptionType;
229 enum EncryptionTypeEnum {
230 kEncryptionTypeAny = 0,
231 kEncryptionTypeAES = 1,
232 kEncryptionTypeTKIP = 2
235 // Static callback for Windows WLAN_NOTIFICATION. Calls OnWlanNotification
236 // on WiFiServiceImpl passed back as |context|.
237 static void __stdcall OnWlanNotificationCallback(
238 PWLAN_NOTIFICATION_DATA wlan_notification_data,
239 PVOID context);
241 // Callback for Windows WLAN_NOTIFICATION. Called on random thread from
242 // OnWlanNotificationCallback. Handles network connectivity and scan complete
243 // notification and posts tasks to main thread.
244 void OnWlanNotification(PWLAN_NOTIFICATION_DATA wlan_notification_data);
246 // Handles NetworkScanComplete notification on main thread. Sends
247 // |NetworkListChanged| event with new list of visible networks.
248 void OnNetworkScanCompleteOnMainThread();
250 // Wait up to |kMaxAttempts| with |kAttemptDelayMs| delay for connection
251 // to network with |network_guid|. Reset DHCP and Notify that |NetworkChanged|
252 // upon success.
253 void WaitForNetworkConnect(const std::string& network_guid, int attempt);
255 // Check |error_code| and if is not |ERROR_SUCCESS|, then store |error_name|
256 // into |error|.
257 bool CheckError(DWORD error_code,
258 const std::string& error_name,
259 std::string* error) const;
261 // Return |iterator| to network identified by |network_guid| in |networks|
262 // list.
263 NetworkList::iterator FindNetwork(NetworkList& networks,
264 const std::string& network_guid);
266 // Save currently connected network profile so it can be re-connected later.
267 DWORD SaveCurrentConnectedNetwork(const NetworkProperties& properties);
269 // Sort networks, so connected/connecting is up front, then by type:
270 // Ethernet, WiFi, Cellular, VPN
271 static void SortNetworks(NetworkList* networks);
273 // Open a WLAN client handle, register for WLAN notifications.
274 DWORD OpenClientHandle();
276 // Reset DHCP on wireless network to work around an issue when Windows
277 // takes forever to connect to the network, e.g. after Chromecast
278 // device reset.
279 DWORD ResetDHCP();
281 // Find |adapter_index_map| by |interface_guid| for DHCP reset.
282 DWORD FindAdapterIndexMapByGUID(const GUID& interface_guid,
283 IP_ADAPTER_INDEX_MAP* adapter_index_map);
285 // Avoid the network location wizard to pop up when network is connected.
286 // Preserve current value in |saved_nw_category_wizard_|.
287 DWORD DisableNwCategoryWizard();
289 // Restore network location wizard to value saved by DisableNwCategoryWizard.
290 DWORD RestoreNwCategoryWizard();
292 // Ensure that |client_| handle is initialized.
293 DWORD EnsureInitialized();
295 // Close |client_| handle if it is open.
296 DWORD CloseClientHandle();
298 // Get |profile_name| from unique |network_guid|.
299 base::string16 ProfileNameFromGUID(const std::string& network_guid) const {
300 return base::UTF8ToUTF16(network_guid);
303 // Get |dot11_ssid| from unique |network_guid|.
304 DOT11_SSID SSIDFromGUID(const std::string& network_guid) const;
306 // Get unique |network_guid| string based on |dot11_ssid|.
307 std::string GUIDFromSSID(const DOT11_SSID& dot11_ssid) const {
308 return std::string(reinterpret_cast<const char*>(dot11_ssid.ucSSID),
309 dot11_ssid.uSSIDLength);
312 // Get network |ssid| string based on |wlan|.
313 std::string SSIDFromWLAN(const WLAN_AVAILABLE_NETWORK& wlan) const {
314 return GUIDFromSSID(wlan.dot11Ssid);
317 // Get unique |network_guid| string based on |wlan|.
318 std::string GUIDFromWLAN(const WLAN_AVAILABLE_NETWORK& wlan) const {
319 return SSIDFromWLAN(wlan);
322 // Deduce |onc::wifi| security from |alg|.
323 std::string SecurityFromDot11AuthAlg(DOT11_AUTH_ALGORITHM alg) const;
325 // Deduce |onc::connection_state| from |wlan_state|.
326 std::string ConnectionStateFromInterfaceState(
327 WLAN_INTERFACE_STATE wlan_state) const;
329 // Convert |EncryptionType| into WPA(2) encryption type string.
330 std::string WpaEncryptionFromEncryptionType(
331 EncryptionType encryption_type) const;
333 // Deduce WLANProfile |authEncryption| values from |onc::wifi| security.
334 bool AuthEncryptionFromSecurity(const std::string& security,
335 EncryptionType encryption_type,
336 std::string* authentication,
337 std::string* encryption,
338 std::string* key_type) const;
340 // Populate |properties| based on |wlan|.
341 void NetworkPropertiesFromAvailableNetwork(const WLAN_AVAILABLE_NETWORK& wlan,
342 NetworkProperties* properties);
344 // Update |properties| based on bss info from |wlan_bss_list|. If |bssid| in
345 // |properties| is not empty, then it is not changed and |frequency| is set
346 // based on that bssid.
347 void UpdateNetworkPropertiesFromBssList(const std::string& network_guid,
348 const WLAN_BSS_LIST& wlan_bss_list,
349 NetworkProperties* properties);
351 // Get the list of visible wireless networks.
352 DWORD GetVisibleNetworkList(NetworkList* network_list);
354 // Get properties of the network currently used (connected or in transition)
355 // by interface. Populate |current_properties| on success.
356 DWORD GetCurrentProperties(NetworkProperties* current_properties);
358 // Connect to network |network_guid| using previosly stored profile if exists,
359 // or just network sid. If |frequency| is not |kFrequencyUnknown| then
360 // connects only to BSS which uses that frequency and returns
361 // |ERROR_NOT_FOUND| if such BSS cannot be found.
362 DWORD Connect(const std::string& network_guid, Frequency frequency);
364 // Disconnect from currently connected network if any.
365 DWORD Disconnect();
367 // Get desired connection freqency if it was set using |SetProperties|.
368 // Default to |kFrequencyAny|.
369 Frequency GetFrequencyToConnect(const std::string& network_guid) const;
371 // Get DOT11_BSSID_LIST of desired BSSIDs to connect to |ssid| network on
372 // given |frequency|.
373 DWORD GetDesiredBssList(DOT11_SSID& ssid,
374 Frequency frequency,
375 scoped_ptr<DOT11_BSSID_LIST>* desired_list);
377 // Normalizes |frequency_in_mhz| into one of |Frequency| values.
378 Frequency GetNormalizedFrequency(int frequency_in_mhz) const;
380 // Create |profile_xml| based on |network_properties|. If |encryption_type|
381 // is |kEncryptionTypeAny| applies the type most suitable for parameters in
382 // |network_properties|.
383 bool CreateProfile(const NetworkProperties& network_properties,
384 EncryptionType encryption_type,
385 std::string* profile_xml);
387 // Save temporary wireless profile for |network_guid|.
388 DWORD SaveTempProfile(const std::string& network_guid);
390 // Get previously stored |profile_xml| for |network_guid|.
391 // If |get_plaintext_key| is true, and process has sufficient privileges, then
392 // <sharedKey> data in |profile_xml| will be unprotected.
393 DWORD GetProfile(const std::string& network_guid,
394 bool get_plaintext_key,
395 std::string* profile_xml);
397 // Set |profile_xml| to current user or all users depending on |shared| flag.
398 // If |overwrite| is false, then returns an error if profile exists.
399 DWORD SetProfile(bool shared, const std::string& profile_xml, bool overwrite);
401 // Return true if there is previously stored profile xml for |network_guid|.
402 bool HaveProfile(const std::string& network_guid);
404 // Delete profile that was created, but failed to connect.
405 DWORD DeleteCreatedProfile(const std::string& network_guid);
407 // Notify |network_list_changed_observer_| that list of visible networks has
408 // changed to |networks|.
409 void NotifyNetworkListChanged(const NetworkList& networks);
411 // Notify |networks_changed_observer_| that network |network_guid| status has
412 // changed.
413 void NotifyNetworkChanged(const std::string& network_guid);
415 // Load WlanApi.dll from SystemDirectory and get Api function pointers.
416 DWORD LoadWlanLibrary();
417 // Instance of WlanApi.dll.
418 HINSTANCE wlan_api_library_;
419 // WlanApi function pointers
420 WlanConnectFunction WlanConnect_function_;
421 WlanCloseHandleFunction WlanCloseHandle_function_;
422 WlanDeleteProfileFunction WlanDeleteProfile_function_;
423 WlanDisconnectFunction WlanDisconnect_function_;
424 WlanEnumInterfacesFunction WlanEnumInterfaces_function_;
425 WlanFreeMemoryFunction WlanFreeMemory_function_;
426 WlanGetAvailableNetworkListFunction WlanGetAvailableNetworkList_function_;
427 // WlanGetNetworkBssList function may not be avaiable on Windows XP.
428 WlanGetNetworkBssListFunction WlanGetNetworkBssList_function_;
429 WlanGetProfileFunction WlanGetProfile_function_;
430 WlanOpenHandleFunction WlanOpenHandle_function_;
431 WlanQueryInterfaceFunction WlanQueryInterface_function_;
432 WlanRegisterNotificationFunction WlanRegisterNotification_function_;
433 WlanScanFunction WlanScan_function_;
434 WlanSetProfileFunction WlanSetProfile_function_;
435 // WlanSaveTemporaryProfile function may not be avaiable on Windows XP.
436 WlanSaveTemporaryProfileFunction WlanSaveTemporaryProfile_function_;
438 // WLAN service handle.
439 HANDLE client_;
440 // GUID of the currently connected interface, if any, otherwise the GUID of
441 // one of the WLAN interfaces.
442 GUID interface_guid_;
443 // Temporary storage of network properties indexed by |network_guid|. Persist
444 // only in memory.
445 base::DictionaryValue connect_properties_;
446 // Preserved WLAN profile xml.
447 std::map<std::string, std::string> saved_profiles_xml_;
448 // Created WLAN Profiles, indexed by |network_guid|. Contains xml with TKIP
449 // encryption type saved by |CreateNetwork| if applicable. Profile has to be
450 // deleted if connection fails. Implicitly created profiles have to be deleted
451 // if connection succeeds. Persist only in memory.
452 base::DictionaryValue created_profiles_;
453 // Observer to get notified when network(s) have changed (e.g. connect).
454 NetworkGuidListCallback networks_changed_observer_;
455 // Observer to get notified when network list has changed (scan complete).
456 NetworkGuidListCallback network_list_changed_observer_;
457 // Saved value of network location wizard show value.
458 scoped_ptr<DWORD> saved_nw_category_wizard_;
459 // MessageLoopProxy to post events on UI thread.
460 scoped_refptr<base::MessageLoopProxy> message_loop_proxy_;
461 // Task runner for worker tasks.
462 scoped_refptr<base::SequencedTaskRunner> task_runner_;
463 // If |false|, then |networks_changed_observer_| is not notified.
464 bool enable_notify_network_changed_;
465 // Number of attempts to check that network has connected successfully.
466 static const int kMaxAttempts = 100;
467 // Delay between attempts to check that network has connected successfully.
468 static const int kAttemptDelayMs = 100;
469 DISALLOW_COPY_AND_ASSIGN(WiFiServiceImpl);
472 WiFiServiceImpl::WiFiServiceImpl()
473 : wlan_api_library_(NULL),
474 WlanConnect_function_(NULL),
475 WlanCloseHandle_function_(NULL),
476 WlanDeleteProfile_function_(NULL),
477 WlanDisconnect_function_(NULL),
478 WlanEnumInterfaces_function_(NULL),
479 WlanFreeMemory_function_(NULL),
480 WlanGetAvailableNetworkList_function_(NULL),
481 WlanGetNetworkBssList_function_(NULL),
482 WlanGetProfile_function_(NULL),
483 WlanOpenHandle_function_(NULL),
484 WlanRegisterNotification_function_(NULL),
485 WlanSaveTemporaryProfile_function_(NULL),
486 WlanScan_function_(NULL),
487 WlanSetProfile_function_(NULL),
488 client_(NULL),
489 enable_notify_network_changed_(true) {}
491 WiFiServiceImpl::~WiFiServiceImpl() { UnInitialize(); }
493 void WiFiServiceImpl::Initialize(
494 scoped_refptr<base::SequencedTaskRunner> task_runner) {
495 DCHECK(!client_);
496 task_runner_.swap(task_runner);
497 // Restore NwCategoryWizard in case if we crashed during connect.
498 RestoreNwCategoryWizard();
499 OpenClientHandle();
502 void WiFiServiceImpl::UnInitialize() {
503 CloseClientHandle();
506 void WiFiServiceImpl::GetProperties(const std::string& network_guid,
507 base::DictionaryValue* properties,
508 std::string* error) {
509 DWORD error_code = EnsureInitialized();
510 if (CheckError(error_code, kErrorWiFiService, error))
511 return;
513 NetworkProperties connected_properties;
514 error_code = GetCurrentProperties(&connected_properties);
515 if (error_code == ERROR_SUCCESS &&
516 connected_properties.guid == network_guid) {
517 properties->Swap(connected_properties.ToValue(false).get());
518 return;
521 NetworkList network_list;
522 error_code = GetVisibleNetworkList(&network_list);
523 if (error_code == ERROR_SUCCESS) {
524 NetworkList::const_iterator it = FindNetwork(network_list, network_guid);
525 if (it != network_list.end()) {
526 DVLOG(1) << "Get Properties: " << network_guid << ":"
527 << it->connection_state;
528 properties->Swap(it->ToValue(false).get());
529 return;
531 error_code = ERROR_NOT_FOUND;
534 CheckError(error_code, kErrorWiFiService, error);
537 void WiFiServiceImpl::GetManagedProperties(
538 const std::string& network_guid,
539 base::DictionaryValue* managed_properties,
540 std::string* error) {
541 CheckError(ERROR_CALL_NOT_IMPLEMENTED, kErrorWiFiService, error);
544 void WiFiServiceImpl::GetState(const std::string& network_guid,
545 base::DictionaryValue* properties,
546 std::string* error) {
547 CheckError(ERROR_CALL_NOT_IMPLEMENTED, kErrorWiFiService, error);
550 void WiFiServiceImpl::SetProperties(
551 const std::string& network_guid,
552 scoped_ptr<base::DictionaryValue> properties,
553 std::string* error) {
554 // Temporary preserve WiFi properties (desired frequency, wifi password) to
555 // use in StartConnect.
556 DCHECK(properties.get());
557 if (!properties->HasKey(onc::network_type::kWiFi)) {
558 DVLOG(0) << "Missing WiFi properties:" << *properties;
559 *error = kErrorWiFiService;
560 return;
563 base::DictionaryValue* existing_properties;
564 // If the network properties already exist, don't override previously set
565 // properties, unless they are set in |properties|.
566 if (connect_properties_.GetDictionaryWithoutPathExpansion(
567 network_guid, &existing_properties)) {
568 existing_properties->MergeDictionary(properties.get());
569 } else {
570 connect_properties_.SetWithoutPathExpansion(network_guid,
571 properties.release());
575 void WiFiServiceImpl::CreateNetwork(
576 bool shared,
577 scoped_ptr<base::DictionaryValue> properties,
578 std::string* network_guid,
579 std::string* error) {
580 DWORD error_code = EnsureInitialized();
581 if (CheckError(error_code, kErrorWiFiService, error))
582 return;
584 WiFiService::NetworkProperties network_properties;
585 if (!network_properties.UpdateFromValue(*properties)) {
586 CheckError(ERROR_INVALID_DATA, kErrorWiFiService, error);
587 return;
590 network_properties.guid = network_properties.ssid;
591 std::string profile_xml;
592 if (!CreateProfile(network_properties, kEncryptionTypeAny, &profile_xml)) {
593 CheckError(ERROR_INVALID_DATA, kErrorWiFiService, error);
594 return;
597 error_code = SetProfile(shared, profile_xml, false);
598 if (CheckError(error_code, kErrorWiFiService, error)) {
599 DVLOG(0) << profile_xml;
600 return;
603 // WAP and WAP2 networks could use either AES or TKIP encryption type.
604 // Preserve alternative profile to use in case if connection with default
605 // encryption type fails.
606 std::string tkip_profile_xml;
607 if (!CreateProfile(network_properties,
608 kEncryptionTypeTKIP,
609 &tkip_profile_xml)) {
610 CheckError(ERROR_INVALID_DATA, kErrorWiFiService, error);
611 return;
614 if (tkip_profile_xml != profile_xml) {
615 scoped_ptr<base::DictionaryValue> tkip_profile(new base::DictionaryValue());
616 tkip_profile->SetString(kProfileXmlKey, tkip_profile_xml);
617 tkip_profile->SetBoolean(kProfileSharedKey, shared);
618 created_profiles_.SetWithoutPathExpansion(network_properties.guid,
619 tkip_profile.release());
622 *network_guid = network_properties.guid;
625 void WiFiServiceImpl::GetVisibleNetworks(const std::string& network_type,
626 base::ListValue* network_list) {
627 if (!network_type.empty() &&
628 network_type != onc::network_type::kAllTypes &&
629 network_type != onc::network_type::kWiFi) {
630 return;
633 DWORD error = EnsureInitialized();
634 if (error == ERROR_SUCCESS) {
635 NetworkList networks;
636 error = GetVisibleNetworkList(&networks);
637 if (error == ERROR_SUCCESS && !networks.empty()) {
638 SortNetworks(&networks);
639 for (WiFiService::NetworkList::const_iterator it = networks.begin();
640 it != networks.end();
641 ++it) {
642 scoped_ptr<base::DictionaryValue> network(it->ToValue(true));
643 network_list->Append(network.release());
649 void WiFiServiceImpl::RequestNetworkScan() {
650 DWORD error = EnsureInitialized();
651 if (error == ERROR_SUCCESS) {
652 WlanScan_function_(client_, &interface_guid_, NULL, NULL, NULL);
656 void WiFiServiceImpl::StartConnect(const std::string& network_guid,
657 std::string* error) {
658 DVLOG(1) << "Start Connect: " << network_guid;
659 DWORD error_code = EnsureInitialized();
660 if (CheckError(error_code, kErrorWiFiService, error))
661 return;
663 // Check, if the network is already connected on desired frequency.
664 Frequency frequency = GetFrequencyToConnect(network_guid);
665 NetworkProperties properties;
666 GetCurrentProperties(&properties);
667 bool already_connected =
668 network_guid == properties.guid &&
669 properties.connection_state == onc::connection_state::kConnected &&
670 (frequency == kFrequencyAny || frequency == properties.frequency);
672 // Connect only if network |network_guid| is not connected already.
673 if (!already_connected) {
674 SaveCurrentConnectedNetwork(properties);
675 error_code = Connect(network_guid, frequency);
677 if (error_code == ERROR_SUCCESS) {
678 // Notify that previously connected network has changed.
679 NotifyNetworkChanged(properties.guid);
680 // Start waiting for network connection state change.
681 if (!networks_changed_observer_.is_null()) {
682 DisableNwCategoryWizard();
683 // Disable automatic network change notifications as they get fired
684 // when network is just connected, but not yet accessible (doesn't
685 // have valid IP address).
686 enable_notify_network_changed_ = false;
687 WaitForNetworkConnect(network_guid, 0);
688 return;
690 } else if (error_code == ERROR_ACCESS_DENIED) {
691 CheckError(error_code, kErrorNotConfigured, error);
692 } else {
693 CheckError(error_code, kErrorWiFiService, error);
697 void WiFiServiceImpl::StartDisconnect(const std::string& network_guid,
698 std::string* error) {
699 DVLOG(1) << "Start Disconnect: " << network_guid;
700 DWORD error_code = EnsureInitialized();
701 if (CheckError(error_code, kErrorWiFiService, error))
702 return;
704 // Check, if the network is currently connected.
705 NetworkProperties properties;
706 GetCurrentProperties(&properties);
707 if (network_guid == properties.guid) {
708 if (properties.connection_state == onc::connection_state::kConnected)
709 SaveCurrentConnectedNetwork(properties);
710 error_code = Disconnect();
711 if (error_code == ERROR_SUCCESS) {
712 NotifyNetworkChanged(network_guid);
713 return;
716 CheckError(error_code, kErrorWiFiService, error);
719 void WiFiServiceImpl::GetKeyFromSystem(const std::string& network_guid,
720 std::string* key_data,
721 std::string* error) {
722 DWORD error_code = EnsureInitialized();
723 if (CheckError(error_code, kErrorWiFiService, error))
724 return;
726 std::string profile_xml;
727 error_code = GetProfile(network_guid, true, &profile_xml);
728 if (CheckError(error_code, kErrorWiFiService, error))
729 return;
731 const char kSharedKeyElement[] = "sharedKey";
732 const char kProtectedElement[] = "protected";
733 const char kKeyMaterialElement[] = "keyMaterial";
735 // Quick check to verify presence of <sharedKey> element.
736 if (profile_xml.find(kSharedKeyElement) == std::string::npos) {
737 *error = kErrorWiFiService;
738 return;
741 XmlReader reader;
742 if (reader.Load(profile_xml)) {
743 while (reader.Read()) {
744 reader.SkipToElement();
745 if (reader.NodeName() == kSharedKeyElement) {
746 while (reader.Read()) {
747 reader.SkipToElement();
748 if (reader.NodeName() == kKeyMaterialElement) {
749 reader.ReadElementContent(key_data);
750 } else if (reader.NodeName() == kProtectedElement) {
751 std::string protected_data;
752 reader.ReadElementContent(&protected_data);
753 // Without UAC privilege escalation call to |GetProfile| with
754 // |WLAN_PROFILE_GET_PLAINTEXT_KEY| flag returns success, but has
755 // protected keyMaterial. Report an error in this case.
756 if (protected_data != "false") {
757 *error = kErrorWiFiService;
758 break;
762 return;
767 // Did not find passphrase in the profile.
768 *error = kErrorWiFiService;
771 void WiFiServiceImpl::SetEventObservers(
772 scoped_refptr<base::MessageLoopProxy> message_loop_proxy,
773 const NetworkGuidListCallback& networks_changed_observer,
774 const NetworkGuidListCallback& network_list_changed_observer) {
775 DWORD error_code = EnsureInitialized();
776 if (error_code != ERROR_SUCCESS)
777 return;
778 message_loop_proxy_.swap(message_loop_proxy);
779 if (!networks_changed_observer_.is_null() ||
780 !network_list_changed_observer_.is_null()) {
781 // Stop listening to WLAN notifications.
782 WlanRegisterNotification_function_(client_,
783 WLAN_NOTIFICATION_SOURCE_NONE,
784 FALSE,
785 OnWlanNotificationCallback,
786 this,
787 NULL,
788 NULL);
790 networks_changed_observer_ = networks_changed_observer;
791 network_list_changed_observer_ = network_list_changed_observer;
792 if (!networks_changed_observer_.is_null() ||
793 !network_list_changed_observer_.is_null()) {
794 // Start listening to WLAN notifications.
795 WlanRegisterNotification_function_(client_,
796 WLAN_NOTIFICATION_SOURCE_ALL,
797 FALSE,
798 OnWlanNotificationCallback,
799 this,
800 NULL,
801 NULL);
805 void WiFiServiceImpl::OnWlanNotificationCallback(
806 PWLAN_NOTIFICATION_DATA wlan_notification_data,
807 PVOID context) {
808 WiFiServiceImpl* service = reinterpret_cast<WiFiServiceImpl*>(context);
809 service->OnWlanNotification(wlan_notification_data);
812 void WiFiServiceImpl::OnWlanNotification(
813 PWLAN_NOTIFICATION_DATA wlan_notification_data) {
814 if (message_loop_proxy_ == NULL)
815 return;
816 switch (wlan_notification_data->NotificationCode) {
817 case wlan_notification_acm_disconnected:
818 case wlan_notification_acm_connection_complete:
819 case wlan_notification_acm_connection_attempt_fail: {
820 PWLAN_CONNECTION_NOTIFICATION_DATA wlan_connection_data =
821 reinterpret_cast<PWLAN_CONNECTION_NOTIFICATION_DATA>(
822 wlan_notification_data->pData);
823 message_loop_proxy_->PostTask(
824 FROM_HERE,
825 base::Bind(&WiFiServiceImpl::NotifyNetworkChanged,
826 base::Unretained(this),
827 GUIDFromSSID(wlan_connection_data->dot11Ssid)));
828 break;
830 case wlan_notification_acm_scan_complete:
831 message_loop_proxy_->PostTask(
832 FROM_HERE,
833 base::Bind(&WiFiServiceImpl::OnNetworkScanCompleteOnMainThread,
834 base::Unretained(this)));
835 break;
839 void WiFiServiceImpl::OnNetworkScanCompleteOnMainThread() {
840 NetworkList networks;
841 // Get current list of visible networks and notify that network list has
842 // changed.
843 DWORD error = GetVisibleNetworkList(&networks);
844 DCHECK(error == ERROR_SUCCESS);
845 if (error == ERROR_SUCCESS)
846 NotifyNetworkListChanged(networks);
849 void WiFiServiceImpl::WaitForNetworkConnect(const std::string& network_guid,
850 int attempt) {
851 // If network didn't get connected in |kMaxAttempts|, then try to connect
852 // using different profile if it was created recently.
853 if (attempt > kMaxAttempts) {
854 LOG(ERROR) << kMaxAttempts << " attempts exceeded waiting for connect to "
855 << network_guid;
857 base::DictionaryValue* created_profile = NULL;
858 // Check, whether this connection is using newly created profile.
859 if (created_profiles_.GetDictionaryWithoutPathExpansion(
860 network_guid, &created_profile)) {
861 std::string tkip_profile_xml;
862 bool shared = false;
863 // Check, if this connection there is alternative TKIP profile xml that
864 // should be tried. If there is, then set it up and try to connect again.
865 if (created_profile->GetString(kProfileXmlKey, &tkip_profile_xml) &&
866 created_profile->GetBoolean(kProfileSharedKey, &shared)) {
867 // Remove TKIP profile xml, so it will not be tried again.
868 created_profile->Remove(kProfileXmlKey, NULL);
869 created_profile->Remove(kProfileSharedKey, NULL);
870 DWORD error_code = SetProfile(shared, tkip_profile_xml, true);
871 if (error_code == ERROR_SUCCESS) {
872 // Try to connect with new profile.
873 error_code = Connect(network_guid,
874 GetFrequencyToConnect(network_guid));
875 if (error_code == ERROR_SUCCESS) {
876 // Start waiting again.
877 WaitForNetworkConnect(network_guid, 0);
878 return;
879 } else {
880 LOG(ERROR) << "Failed to set created profile for " << network_guid
881 << " error=" << error_code;
884 } else {
885 // Connection has failed, so delete bad created profile.
886 DWORD error_code = DeleteCreatedProfile(network_guid);
887 if (error_code != ERROR_SUCCESS) {
888 LOG(ERROR) << "Failed to delete created profile for " << network_guid
889 << " error=" << error_code;
893 // Restore automatic network change notifications and stop waiting.
894 enable_notify_network_changed_ = true;
895 RestoreNwCategoryWizard();
896 return;
898 NetworkProperties current_properties;
899 DWORD error = GetCurrentProperties(&current_properties);
900 if (network_guid == current_properties.guid &&
901 current_properties.connection_state ==
902 onc::connection_state::kConnected) {
903 DVLOG(1) << "WiFi Connected, Reset DHCP: " << network_guid;
904 // Even though wireless network is now connected, it may still be unusable,
905 // e.g. after Chromecast device reset. Reset DHCP on wireless network to
906 // work around this issue.
907 error = ResetDHCP();
908 if (error != ERROR_SUCCESS)
909 LOG(ERROR) << error;
910 // There is no need to keep created profile as network is connected.
911 created_profiles_.RemoveWithoutPathExpansion(network_guid, NULL);
912 // Restore previously suppressed notifications.
913 enable_notify_network_changed_ = true;
914 RestoreNwCategoryWizard();
915 NotifyNetworkChanged(network_guid);
916 } else {
917 // Continue waiting for network connection state change.
918 task_runner_->PostDelayedTask(
919 FROM_HERE,
920 base::Bind(&WiFiServiceImpl::WaitForNetworkConnect,
921 base::Unretained(this),
922 network_guid,
923 ++attempt),
924 base::TimeDelta::FromMilliseconds(kAttemptDelayMs));
928 bool WiFiServiceImpl::CheckError(DWORD error_code,
929 const std::string& error_name,
930 std::string* error) const {
931 if (error_code != ERROR_SUCCESS) {
932 DLOG(ERROR) << "WiFiService Error " << error_code << ": " << error_name;
933 *error = error_name;
934 return true;
936 return false;
939 WiFiService::NetworkList::iterator WiFiServiceImpl::FindNetwork(
940 NetworkList& networks,
941 const std::string& network_guid) {
942 for (NetworkList::iterator it = networks.begin(); it != networks.end();
943 ++it) {
944 if (it->guid == network_guid)
945 return it;
947 return networks.end();
950 DWORD WiFiServiceImpl::SaveCurrentConnectedNetwork(
951 const NetworkProperties& current_properties) {
952 DWORD error = ERROR_SUCCESS;
953 // Save currently connected network.
954 if (!current_properties.guid.empty() &&
955 current_properties.connection_state ==
956 onc::connection_state::kConnected) {
957 error = SaveTempProfile(current_properties.guid);
959 return error;
962 void WiFiServiceImpl::SortNetworks(NetworkList* networks) {
963 networks->sort(NetworkProperties::OrderByType);
966 DWORD WiFiServiceImpl::LoadWlanLibrary() {
967 // Use an absolute path to load the DLL to avoid DLL preloading attacks.
968 base::FilePath path;
969 if (!PathService::Get(base::DIR_SYSTEM, &path)) {
970 LOG(ERROR) << "Unable to get system path.";
971 return ERROR_NOT_FOUND;
973 wlan_api_library_ = ::LoadLibraryEx(path.Append(kWlanApiDll).value().c_str(),
974 NULL,
975 LOAD_WITH_ALTERED_SEARCH_PATH);
976 if (!wlan_api_library_) {
977 LOG(ERROR) << "Unable to load WlanApi.dll.";
978 return ERROR_NOT_FOUND;
981 // Initialize WlanApi function pointers
982 WlanConnect_function_ =
983 reinterpret_cast<WlanConnectFunction>(
984 ::GetProcAddress(wlan_api_library_, kWlanConnect));
985 WlanCloseHandle_function_ =
986 reinterpret_cast<WlanCloseHandleFunction>(
987 ::GetProcAddress(wlan_api_library_, kWlanCloseHandle));
988 WlanDeleteProfile_function_ =
989 reinterpret_cast<WlanDeleteProfileFunction>(
990 ::GetProcAddress(wlan_api_library_, kWlanDeleteProfile));
991 WlanDisconnect_function_ =
992 reinterpret_cast<WlanDisconnectFunction>(
993 ::GetProcAddress(wlan_api_library_, kWlanDisconnect));
994 WlanEnumInterfaces_function_ =
995 reinterpret_cast<WlanEnumInterfacesFunction>(
996 ::GetProcAddress(wlan_api_library_, kWlanEnumInterfaces));
997 WlanFreeMemory_function_ =
998 reinterpret_cast<WlanFreeMemoryFunction>(
999 ::GetProcAddress(wlan_api_library_, kWlanFreeMemory));
1000 WlanGetAvailableNetworkList_function_ =
1001 reinterpret_cast<WlanGetAvailableNetworkListFunction>(
1002 ::GetProcAddress(wlan_api_library_, kWlanGetAvailableNetworkList));
1003 WlanGetNetworkBssList_function_ =
1004 reinterpret_cast<WlanGetNetworkBssListFunction>(
1005 ::GetProcAddress(wlan_api_library_, kWlanGetNetworkBssList));
1006 WlanGetProfile_function_ =
1007 reinterpret_cast<WlanGetProfileFunction>(
1008 ::GetProcAddress(wlan_api_library_, kWlanGetProfile));
1009 WlanOpenHandle_function_ =
1010 reinterpret_cast<WlanOpenHandleFunction>(
1011 ::GetProcAddress(wlan_api_library_, kWlanOpenHandle));
1012 WlanQueryInterface_function_ =
1013 reinterpret_cast<WlanQueryInterfaceFunction>(
1014 ::GetProcAddress(wlan_api_library_, kWlanQueryInterface));
1015 WlanRegisterNotification_function_ =
1016 reinterpret_cast<WlanRegisterNotificationFunction>(
1017 ::GetProcAddress(wlan_api_library_, kWlanRegisterNotification));
1018 WlanSaveTemporaryProfile_function_ =
1019 reinterpret_cast<WlanSaveTemporaryProfileFunction>(
1020 ::GetProcAddress(wlan_api_library_, kWlanSaveTemporaryProfile));
1021 WlanScan_function_ =
1022 reinterpret_cast<WlanScanFunction>(
1023 ::GetProcAddress(wlan_api_library_, kWlanScan));
1024 WlanSetProfile_function_ =
1025 reinterpret_cast<WlanSetProfileFunction>(
1026 ::GetProcAddress(wlan_api_library_, kWlanSetProfile));
1028 if (!WlanConnect_function_ ||
1029 !WlanCloseHandle_function_ ||
1030 !WlanDeleteProfile_function_ ||
1031 !WlanDisconnect_function_ ||
1032 !WlanEnumInterfaces_function_ ||
1033 !WlanFreeMemory_function_ ||
1034 !WlanGetAvailableNetworkList_function_ ||
1035 !WlanGetProfile_function_ ||
1036 !WlanOpenHandle_function_ ||
1037 !WlanQueryInterface_function_ ||
1038 !WlanRegisterNotification_function_ ||
1039 !WlanScan_function_ ||
1040 !WlanSetProfile_function_) {
1041 LOG(ERROR) << "Unable to find required WlanApi function.";
1042 FreeLibrary(wlan_api_library_);
1043 wlan_api_library_ = NULL;
1044 return ERROR_NOT_FOUND;
1047 // Some WlanApi functions may not be available on XP.
1048 if (!WlanGetNetworkBssList_function_ ||
1049 !WlanSaveTemporaryProfile_function_) {
1050 DVLOG(1) << "WlanApi function is not be available on XP.";
1053 return ERROR_SUCCESS;
1056 DWORD WiFiServiceImpl::OpenClientHandle() {
1057 DWORD error = LoadWlanLibrary();
1058 DWORD service_version = 0;
1060 if (error != ERROR_SUCCESS)
1061 return error;
1063 // Open a handle to the service.
1064 error = WlanOpenHandle_function_(1, NULL, &service_version, &client_);
1066 PWLAN_INTERFACE_INFO_LIST interface_list = NULL;
1067 if (error == ERROR_SUCCESS) {
1068 // Enumerate wireless interfaces.
1069 error = WlanEnumInterfaces_function_(client_, NULL, &interface_list);
1070 if (error == ERROR_SUCCESS) {
1071 if (interface_list != NULL && interface_list->dwNumberOfItems != 0) {
1072 // Remember first interface just in case if none are connected.
1073 interface_guid_ = interface_list->InterfaceInfo[0].InterfaceGuid;
1074 // Try to find a connected interface.
1075 for (DWORD itf = 0; itf < interface_list->dwNumberOfItems; ++itf) {
1076 if (interface_list->InterfaceInfo[itf].isState ==
1077 wlan_interface_state_connected) {
1078 // Found connected interface, remember it!
1079 interface_guid_ = interface_list->InterfaceInfo[itf].InterfaceGuid;
1080 break;
1083 } else {
1084 error = ERROR_NOINTERFACE;
1087 // Clean up..
1088 if (interface_list != NULL)
1089 WlanFreeMemory_function_(interface_list);
1091 return error;
1094 DWORD WiFiServiceImpl::ResetDHCP() {
1095 IP_ADAPTER_INDEX_MAP adapter_index_map = {0};
1096 DWORD error = FindAdapterIndexMapByGUID(interface_guid_, &adapter_index_map);
1097 if (error != ERROR_SUCCESS) {
1098 LOG(ERROR) << error;
1099 return error;
1101 error = ::IpReleaseAddress(&adapter_index_map);
1102 if (error != ERROR_SUCCESS) {
1103 if (error != ERROR_ADDRESS_NOT_ASSOCIATED) {
1104 LOG(ERROR) << error;
1105 return error;
1107 DVLOG(1) << "Ignoring IpReleaseAddress Error: " << error;
1109 error = ::IpRenewAddress(&adapter_index_map);
1110 if (error != ERROR_SUCCESS)
1111 LOG(ERROR) << error;
1112 return error;
1115 DWORD WiFiServiceImpl::FindAdapterIndexMapByGUID(
1116 const GUID& interface_guid,
1117 IP_ADAPTER_INDEX_MAP* adapter_index_map) {
1118 base::string16 guid_string;
1119 const int kGUIDSize = 39;
1120 ::StringFromGUID2(
1121 interface_guid, WriteInto(&guid_string, kGUIDSize), kGUIDSize);
1123 ULONG buffer_length = 0;
1124 DWORD error = ::GetInterfaceInfo(NULL, &buffer_length);
1125 if (error == ERROR_INSUFFICIENT_BUFFER) {
1126 scoped_ptr<unsigned char[]> buffer(new unsigned char[buffer_length]);
1127 IP_INTERFACE_INFO* interface_info =
1128 reinterpret_cast<IP_INTERFACE_INFO*>(buffer.get());
1129 error = GetInterfaceInfo(interface_info, &buffer_length);
1130 if (error == ERROR_SUCCESS) {
1131 for (int adapter = 0; adapter < interface_info->NumAdapters; ++adapter) {
1132 if (EndsWith(
1133 interface_info->Adapter[adapter].Name, guid_string, false)) {
1134 *adapter_index_map = interface_info->Adapter[adapter];
1135 break;
1140 return error;
1143 DWORD WiFiServiceImpl::DisableNwCategoryWizard() {
1144 base::win::RegKey nw_category_wizard;
1145 DWORD error = nw_category_wizard.Open(HKEY_CURRENT_USER,
1146 kNwCategoryWizardRegKey,
1147 KEY_READ | KEY_SET_VALUE);
1148 if (error == ERROR_SUCCESS) {
1149 // Save current value if present.
1150 if (nw_category_wizard.HasValue(kNwCategoryWizardRegValue)) {
1151 DWORD saved = 0u;
1152 error = nw_category_wizard.ReadValueDW(kNwCategoryWizardRegValue,
1153 &saved);
1154 if (error == ERROR_SUCCESS) {
1155 error = nw_category_wizard.WriteValue(kNwCategoryWizardSavedRegValue,
1156 saved);
1158 } else {
1159 // Mark that temporary value has to be deleted.
1160 error = nw_category_wizard.WriteValue(kNwCategoryWizardDeleteRegValue,
1161 1u);
1164 // Disable network location wizard.
1165 error = nw_category_wizard.WriteValue(kNwCategoryWizardRegValue,
1166 static_cast<DWORD>(0));
1169 return error;
1172 DWORD WiFiServiceImpl::RestoreNwCategoryWizard() {
1173 base::win::RegKey nw_category_wizard;
1174 DWORD error = nw_category_wizard.Open(HKEY_CURRENT_USER,
1175 kNwCategoryWizardRegKey,
1176 KEY_SET_VALUE);
1177 if (error == ERROR_SUCCESS) {
1178 // Restore saved value if present.
1179 if (nw_category_wizard.HasValue(kNwCategoryWizardSavedRegValue)) {
1180 DWORD saved = 0u;
1181 error = nw_category_wizard.ReadValueDW(kNwCategoryWizardSavedRegValue,
1182 &saved);
1183 if (error == ERROR_SUCCESS) {
1184 error = nw_category_wizard.WriteValue(kNwCategoryWizardRegValue,
1185 saved);
1186 error = nw_category_wizard.DeleteValue(kNwCategoryWizardSavedRegValue);
1188 } else if (nw_category_wizard.HasValue(kNwCategoryWizardDeleteRegValue)) {
1189 error = nw_category_wizard.DeleteValue(kNwCategoryWizardRegValue);
1190 error = nw_category_wizard.DeleteValue(kNwCategoryWizardDeleteRegValue);
1194 return error;
1197 DWORD WiFiServiceImpl::EnsureInitialized() {
1198 if (client_ != NULL)
1199 return ERROR_SUCCESS;
1200 return ERROR_NOINTERFACE;
1203 DWORD WiFiServiceImpl::CloseClientHandle() {
1204 DWORD error = ERROR_SUCCESS;
1205 if (client_ != NULL) {
1206 error = WlanCloseHandle_function_(client_, NULL);
1207 client_ = NULL;
1209 if (wlan_api_library_ != NULL) {
1210 WlanConnect_function_ = NULL;
1211 WlanCloseHandle_function_ = NULL;
1212 WlanDeleteProfile_function_ = NULL;
1213 WlanDisconnect_function_ = NULL;
1214 WlanEnumInterfaces_function_ = NULL;
1215 WlanFreeMemory_function_ = NULL;
1216 WlanGetAvailableNetworkList_function_ = NULL;
1217 WlanGetNetworkBssList_function_ = NULL;
1218 WlanGetProfile_function_ = NULL;
1219 WlanOpenHandle_function_ = NULL;
1220 WlanRegisterNotification_function_ = NULL;
1221 WlanSaveTemporaryProfile_function_ = NULL;
1222 WlanScan_function_ = NULL;
1223 WlanSetProfile_function_ = NULL;
1224 ::FreeLibrary(wlan_api_library_);
1225 wlan_api_library_ = NULL;
1227 return error;
1230 DOT11_SSID WiFiServiceImpl::SSIDFromGUID(
1231 const std::string& network_guid) const {
1232 DOT11_SSID ssid = {0};
1233 if (network_guid.length() <= DOT11_SSID_MAX_LENGTH) {
1234 ssid.uSSIDLength = static_cast<ULONG>(network_guid.length());
1235 strncpy(reinterpret_cast<char*>(ssid.ucSSID),
1236 network_guid.c_str(),
1237 ssid.uSSIDLength);
1238 } else {
1239 NOTREACHED();
1241 return ssid;
1244 std::string WiFiServiceImpl::SecurityFromDot11AuthAlg(
1245 DOT11_AUTH_ALGORITHM alg) const {
1246 switch (alg) {
1247 case DOT11_AUTH_ALGO_RSNA:
1248 return onc::wifi::kWPA_EAP;
1249 case DOT11_AUTH_ALGO_RSNA_PSK:
1250 return onc::wifi::kWPA_PSK;
1251 case DOT11_AUTH_ALGO_80211_SHARED_KEY:
1252 return onc::wifi::kWEP_PSK;
1253 case DOT11_AUTH_ALGO_80211_OPEN:
1254 return onc::wifi::kNone;
1255 default:
1256 return onc::wifi::kWPA_EAP;
1260 std::string WiFiServiceImpl::ConnectionStateFromInterfaceState(
1261 WLAN_INTERFACE_STATE wlan_state) const {
1262 switch (wlan_state) {
1263 case wlan_interface_state_connected:
1264 // TODO(mef): Even if |wlan_state| is connected, the network may still
1265 // not be reachable, and should be resported as |kConnecting|.
1266 return onc::connection_state::kConnected;
1267 case wlan_interface_state_associating:
1268 case wlan_interface_state_discovering:
1269 case wlan_interface_state_authenticating:
1270 return onc::connection_state::kConnecting;
1271 default:
1272 return onc::connection_state::kNotConnected;
1276 void WiFiServiceImpl::NetworkPropertiesFromAvailableNetwork(
1277 const WLAN_AVAILABLE_NETWORK& wlan,
1278 NetworkProperties* properties) {
1279 // TODO(mef): It would be nice for the connection states in
1280 // getVisibleNetworks and getProperties results to be consistent.
1281 if (wlan.dwFlags & WLAN_AVAILABLE_NETWORK_CONNECTED) {
1282 properties->connection_state = onc::connection_state::kConnected;
1283 } else {
1284 properties->connection_state = onc::connection_state::kNotConnected;
1287 properties->ssid = SSIDFromWLAN(wlan);
1288 properties->name = properties->ssid;
1289 properties->guid = GUIDFromWLAN(wlan);
1290 properties->type = onc::network_type::kWiFi;
1291 properties->security =
1292 SecurityFromDot11AuthAlg(wlan.dot11DefaultAuthAlgorithm);
1293 properties->signal_strength = wlan.wlanSignalQuality;
1296 void WiFiServiceImpl::UpdateNetworkPropertiesFromBssList(
1297 const std::string& network_guid,
1298 const WLAN_BSS_LIST& wlan_bss_list,
1299 NetworkProperties* properties) {
1300 if (network_guid.empty())
1301 return;
1303 DOT11_SSID ssid = SSIDFromGUID(network_guid);
1304 for (size_t bss = 0; bss < wlan_bss_list.dwNumberOfItems; ++bss) {
1305 const WLAN_BSS_ENTRY& bss_entry(wlan_bss_list.wlanBssEntries[bss]);
1306 if (bss_entry.dot11Ssid.uSSIDLength == ssid.uSSIDLength &&
1307 0 == memcmp(bss_entry.dot11Ssid.ucSSID,
1308 ssid.ucSSID,
1309 bss_entry.dot11Ssid.uSSIDLength)) {
1310 std::string bssid = NetworkProperties::MacAddressAsString(
1311 bss_entry.dot11Bssid);
1312 Frequency frequency = GetNormalizedFrequency(
1313 bss_entry.ulChCenterFrequency / 1000);
1314 properties->frequency_set.insert(frequency);
1315 if (properties->bssid.empty() || properties->bssid == bssid) {
1316 properties->frequency = frequency;
1317 properties->bssid = bssid;
1323 // Get the list of visible wireless networks
1324 DWORD WiFiServiceImpl::GetVisibleNetworkList(NetworkList* network_list) {
1325 if (client_ == NULL) {
1326 NOTREACHED();
1327 return ERROR_NOINTERFACE;
1330 DWORD error = ERROR_SUCCESS;
1331 PWLAN_AVAILABLE_NETWORK_LIST available_network_list = NULL;
1332 PWLAN_BSS_LIST bss_list = NULL;
1334 error = WlanGetAvailableNetworkList_function_(
1335 client_,
1336 &interface_guid_,
1337 WLAN_AVAILABLE_NETWORK_INCLUDE_ALL_MANUAL_HIDDEN_PROFILES,
1338 NULL,
1339 &available_network_list);
1341 std::set<std::string> network_guids;
1343 if (error == ERROR_SUCCESS &&
1344 available_network_list &&
1345 WlanGetNetworkBssList_function_) {
1346 // TODO(mef): WlanGetNetworkBssList is not available on XP. If XP support is
1347 // needed, then different method of getting BSS (e.g. OID query) will have
1348 // to be used.
1349 error = WlanGetNetworkBssList_function_(client_,
1350 &interface_guid_,
1351 NULL,
1352 dot11_BSS_type_any,
1353 FALSE,
1354 NULL,
1355 &bss_list);
1356 if (error == ERROR_SUCCESS && NULL != bss_list) {
1357 for (DWORD i = 0; i < available_network_list->dwNumberOfItems; ++i) {
1358 NetworkProperties network_properties;
1359 NetworkPropertiesFromAvailableNetwork(
1360 available_network_list->Network[i],
1361 &network_properties);
1362 UpdateNetworkPropertiesFromBssList(network_properties.guid,
1363 *bss_list,
1364 &network_properties);
1365 // Check for duplicate network guids.
1366 if (network_guids.count(network_properties.guid)) {
1367 // There should be no difference between properties except for
1368 // |connection_state|, so mark it as |kConnected| if either one is.
1369 if (network_properties.connection_state ==
1370 onc::connection_state::kConnected) {
1371 NetworkList::iterator previous_network_properties =
1372 FindNetwork(*network_list, network_properties.guid);
1373 DCHECK(previous_network_properties != network_list->end());
1374 previous_network_properties->connection_state =
1375 network_properties.connection_state;
1377 } else {
1378 network_list->push_back(network_properties);
1380 network_guids.insert(network_properties.guid);
1385 // Clean up.
1386 if (available_network_list != NULL) {
1387 WlanFreeMemory_function_(available_network_list);
1389 if (bss_list != NULL) {
1390 WlanFreeMemory_function_(bss_list);
1392 return error;
1395 DWORD WiFiServiceImpl::GetCurrentProperties(NetworkProperties* properties) {
1396 if (client_ == NULL) {
1397 NOTREACHED();
1398 return ERROR_NOINTERFACE;
1401 // TODO(mef): WlanGetNetworkBssList is not available on XP. If XP support is
1402 // needed, then different method of getting BSS (e.g. OID query) will have
1403 // to be used.
1404 if (WlanGetNetworkBssList_function_ == NULL)
1405 return ERROR_NOINTERFACE;
1407 DWORD error = ERROR_SUCCESS;
1408 DWORD data_size = 0;
1409 PWLAN_CONNECTION_ATTRIBUTES wlan_connection_attributes = NULL;
1410 PWLAN_BSS_LIST bss_list = NULL;
1411 error = WlanQueryInterface_function_(
1412 client_,
1413 &interface_guid_,
1414 wlan_intf_opcode_current_connection,
1415 NULL,
1416 &data_size,
1417 reinterpret_cast<PVOID*>(&wlan_connection_attributes),
1418 NULL);
1419 if (error == ERROR_SUCCESS &&
1420 wlan_connection_attributes != NULL) {
1421 WLAN_ASSOCIATION_ATTRIBUTES& connected_wlan =
1422 wlan_connection_attributes->wlanAssociationAttributes;
1424 properties->connection_state = ConnectionStateFromInterfaceState(
1425 wlan_connection_attributes->isState);
1426 properties->ssid = GUIDFromSSID(connected_wlan.dot11Ssid);
1427 properties->name = properties->ssid;
1428 properties->guid = GUIDFromSSID(connected_wlan.dot11Ssid);
1429 properties->type = onc::network_type::kWiFi;
1430 properties->bssid = NetworkProperties::MacAddressAsString(
1431 connected_wlan.dot11Bssid);
1432 properties->security = SecurityFromDot11AuthAlg(
1433 wlan_connection_attributes->wlanSecurityAttributes.dot11AuthAlgorithm);
1434 properties->signal_strength = connected_wlan.wlanSignalQuality;
1436 error = WlanGetNetworkBssList_function_(client_,
1437 &interface_guid_,
1438 &connected_wlan.dot11Ssid,
1439 connected_wlan.dot11BssType,
1440 FALSE,
1441 NULL,
1442 &bss_list);
1443 if (error == ERROR_SUCCESS && NULL != bss_list) {
1444 UpdateNetworkPropertiesFromBssList(properties->guid,
1445 *bss_list,
1446 properties);
1450 // Clean up.
1451 if (wlan_connection_attributes != NULL)
1452 WlanFreeMemory_function_(wlan_connection_attributes);
1454 if (bss_list != NULL)
1455 WlanFreeMemory_function_(bss_list);
1457 return error;
1460 WiFiService::Frequency WiFiServiceImpl::GetFrequencyToConnect(
1461 const std::string& network_guid) const {
1462 // Check whether desired frequency is set in |connect_properties_|.
1463 const base::DictionaryValue* properties;
1464 const base::DictionaryValue* wifi;
1465 int frequency;
1466 if (connect_properties_.GetDictionaryWithoutPathExpansion(
1467 network_guid, &properties) &&
1468 properties->GetDictionary(onc::network_type::kWiFi, &wifi) &&
1469 wifi->GetInteger(onc::wifi::kFrequency, &frequency)) {
1470 return GetNormalizedFrequency(frequency);
1472 return kFrequencyAny;
1475 DWORD WiFiServiceImpl::GetDesiredBssList(
1476 DOT11_SSID& ssid,
1477 Frequency frequency,
1478 scoped_ptr<DOT11_BSSID_LIST>* desired_list) {
1479 if (client_ == NULL) {
1480 NOTREACHED();
1481 return ERROR_NOINTERFACE;
1484 desired_list->reset();
1486 if (frequency == kFrequencyAny)
1487 return ERROR_SUCCESS;
1489 // TODO(mef): WlanGetNetworkBssList is not available on XP. If XP support is
1490 // needed, then different method of getting BSS (e.g. OID query) will have
1491 // to be used.
1492 if (!WlanGetNetworkBssList_function_)
1493 return ERROR_NOT_SUPPORTED;
1495 DWORD error = ERROR_SUCCESS;
1496 PWLAN_BSS_LIST bss_list = NULL;
1498 error = WlanGetNetworkBssList_function_(client_,
1499 &interface_guid_,
1500 &ssid,
1501 dot11_BSS_type_infrastructure,
1502 FALSE,
1503 NULL,
1504 &bss_list);
1505 if (error == ERROR_SUCCESS && NULL != bss_list) {
1506 unsigned int best_quality = 0u;
1507 size_t best_index = 0;
1508 Frequency bss_frequency;
1510 // Go through bss_list and find best quality BSSID with matching frequency.
1511 for (size_t bss = 0; bss < bss_list->dwNumberOfItems; ++bss) {
1512 const WLAN_BSS_ENTRY& bss_entry(bss_list->wlanBssEntries[bss]);
1513 if (bss_entry.dot11Ssid.uSSIDLength != ssid.uSSIDLength ||
1514 0 != memcmp(bss_entry.dot11Ssid.ucSSID,
1515 ssid.ucSSID,
1516 bss_entry.dot11Ssid.uSSIDLength))
1517 continue;
1519 bss_frequency = GetNormalizedFrequency(
1520 bss_entry.ulChCenterFrequency / 1000);
1521 if (bss_frequency == frequency &&
1522 bss_entry.uLinkQuality > best_quality) {
1523 best_quality = bss_entry.uLinkQuality;
1524 best_index = bss;
1528 // If any matching BSS were found, prepare the header.
1529 if (best_quality > 0) {
1530 const WLAN_BSS_ENTRY& bss_entry(bss_list->wlanBssEntries[best_index]);
1531 scoped_ptr<DOT11_BSSID_LIST> selected_list(new DOT11_BSSID_LIST);
1533 selected_list->Header.Revision = DOT11_BSSID_LIST_REVISION_1;
1534 selected_list->Header.Size = sizeof(DOT11_BSSID_LIST);
1535 selected_list->Header.Type = NDIS_OBJECT_TYPE_DEFAULT;
1536 selected_list->uNumOfEntries = 1;
1537 selected_list->uTotalNumOfEntries = 1;
1538 std::copy(bss_entry.dot11Bssid,
1539 bss_entry.dot11Bssid+sizeof(bss_entry.dot11Bssid),
1540 selected_list->BSSIDs[0]);
1541 desired_list->swap(selected_list);
1542 DVLOG(1) << "Quality: " << best_quality << " BSS: "
1543 << NetworkProperties::MacAddressAsString(bss_entry.dot11Bssid);
1544 } else {
1545 error = ERROR_NOT_FOUND;
1549 // Clean up.
1550 if (bss_list != NULL) {
1551 WlanFreeMemory_function_(bss_list);
1553 return error;
1556 WiFiService::Frequency WiFiServiceImpl::GetNormalizedFrequency(
1557 int frequency_in_mhz) const {
1558 if (frequency_in_mhz == 0)
1559 return kFrequencyAny;
1560 if (frequency_in_mhz < 3000)
1561 return kFrequency2400;
1562 return kFrequency5000;
1565 DWORD WiFiServiceImpl::Connect(const std::string& network_guid,
1566 Frequency frequency) {
1567 if (client_ == NULL) {
1568 NOTREACHED();
1569 return ERROR_NOINTERFACE;
1572 DWORD error = ERROR_SUCCESS;
1573 DOT11_SSID ssid = SSIDFromGUID(network_guid);
1574 scoped_ptr<DOT11_BSSID_LIST> desired_bss_list;
1575 error = GetDesiredBssList(ssid, frequency, &desired_bss_list);
1576 if (error == ERROR_SUCCESS) {
1577 if (HaveProfile(network_guid)) {
1578 base::string16 profile_name = ProfileNameFromGUID(network_guid);
1579 WLAN_CONNECTION_PARAMETERS wlan_params = {
1580 wlan_connection_mode_profile,
1581 profile_name.c_str(),
1582 NULL,
1583 desired_bss_list.get(),
1584 dot11_BSS_type_any,
1586 error = WlanConnect_function_(
1587 client_, &interface_guid_, &wlan_params, NULL);
1588 } else {
1589 // If network is available, but is not open security, then it cannot be
1590 // connected without profile, so return 'access denied' error.
1591 scoped_ptr<base::DictionaryValue> properties (new base::DictionaryValue);
1592 const base::DictionaryValue* wifi;
1593 std::string wifi_security;
1594 std::string error_string;
1595 GetProperties(network_guid, properties.get(), &error_string);
1596 if (error_string.empty() &&
1597 properties->GetDictionary(onc::network_type::kWiFi, &wifi) &&
1598 wifi->GetString(onc::wifi::kSecurity, &wifi_security) &&
1599 wifi_security != onc::wifi::kNone) {
1600 error = ERROR_ACCESS_DENIED;
1601 LOG(ERROR) << error;
1602 return error;
1604 WLAN_CONNECTION_PARAMETERS wlan_params = {
1605 wlan_connection_mode_discovery_unsecure,
1606 NULL,
1607 &ssid,
1608 desired_bss_list.get(),
1609 dot11_BSS_type_infrastructure,
1611 error = WlanConnect_function_(
1612 client_, &interface_guid_, &wlan_params, NULL);
1616 return error;
1619 DWORD WiFiServiceImpl::Disconnect() {
1620 if (client_ == NULL) {
1621 NOTREACHED();
1622 return ERROR_NOINTERFACE;
1625 DWORD error = ERROR_SUCCESS;
1626 error = WlanDisconnect_function_(client_, &interface_guid_, NULL);
1627 return error;
1630 DWORD WiFiServiceImpl::SaveTempProfile(const std::string& network_guid) {
1631 if (client_ == NULL) {
1632 NOTREACHED();
1633 return ERROR_NOINTERFACE;
1636 DWORD error = ERROR_SUCCESS;
1637 base::string16 profile_name = ProfileNameFromGUID(network_guid);
1638 // TODO(mef): WlanSaveTemporaryProfile is not available on XP. If XP support
1639 // is needed, then different method of saving network profile will have to be
1640 // used.
1641 if (WlanSaveTemporaryProfile_function_) {
1642 error = WlanSaveTemporaryProfile_function_(client_,
1643 &interface_guid_,
1644 profile_name.c_str(),
1645 NULL,
1646 WLAN_PROFILE_USER,
1647 true,
1648 NULL);
1649 } else {
1650 error = ERROR_NOT_SUPPORTED;
1652 return error;
1655 DWORD WiFiServiceImpl::GetProfile(const std::string& network_guid,
1656 bool get_plaintext_key,
1657 std::string* profile_xml) {
1658 if (client_ == NULL) {
1659 NOTREACHED();
1660 return ERROR_NOINTERFACE;
1663 DWORD error = ERROR_SUCCESS;
1664 base::string16 profile_name = ProfileNameFromGUID(network_guid);
1665 DWORD flags = get_plaintext_key ? WLAN_PROFILE_GET_PLAINTEXT_KEY : 0;
1666 LPWSTR str_profile_xml = NULL;
1667 error = WlanGetProfile_function_(client_,
1668 &interface_guid_,
1669 profile_name.c_str(),
1670 NULL,
1671 &str_profile_xml,
1672 &flags,
1673 NULL);
1675 if (error == ERROR_SUCCESS && str_profile_xml != NULL) {
1676 *profile_xml = base::UTF16ToUTF8(str_profile_xml);
1678 // Clean up.
1679 if (str_profile_xml != NULL) {
1680 WlanFreeMemory_function_(str_profile_xml);
1683 return error;
1686 DWORD WiFiServiceImpl::SetProfile(bool shared,
1687 const std::string& profile_xml,
1688 bool overwrite) {
1689 DWORD error_code = ERROR_SUCCESS;
1691 base::string16 profile_xml16(base::UTF8ToUTF16(profile_xml));
1692 DWORD reason_code = 0u;
1694 error_code = WlanSetProfile_function_(client_,
1695 &interface_guid_,
1696 shared ? 0 : WLAN_PROFILE_USER,
1697 profile_xml16.c_str(),
1698 NULL,
1699 overwrite,
1700 NULL,
1701 &reason_code);
1702 return error_code;
1705 bool WiFiServiceImpl::HaveProfile(const std::string& network_guid) {
1706 DWORD error = ERROR_SUCCESS;
1707 std::string profile_xml;
1708 return GetProfile(network_guid, false, &profile_xml) == ERROR_SUCCESS;
1712 DWORD WiFiServiceImpl::DeleteCreatedProfile(const std::string& network_guid) {
1713 base::DictionaryValue* created_profile = NULL;
1714 DWORD error_code = ERROR_SUCCESS;
1715 // Check, whether this connection is using new created profile, and remove it.
1716 if (created_profiles_.GetDictionaryWithoutPathExpansion(
1717 network_guid, &created_profile)) {
1718 // Connection has failed, so delete it.
1719 base::string16 profile_name = ProfileNameFromGUID(network_guid);
1720 error_code = WlanDeleteProfile_function_(client_,
1721 &interface_guid_,
1722 profile_name.c_str(),
1723 NULL);
1724 created_profiles_.RemoveWithoutPathExpansion(network_guid, NULL);
1726 return error_code;
1729 std::string WiFiServiceImpl::WpaEncryptionFromEncryptionType(
1730 EncryptionType encryption_type) const {
1731 if (encryption_type == kEncryptionTypeTKIP)
1732 return kEncryptionTKIP;
1733 return kEncryptionAES;
1736 bool WiFiServiceImpl::AuthEncryptionFromSecurity(
1737 const std::string& security,
1738 EncryptionType encryption_type,
1739 std::string* authentication,
1740 std::string* encryption,
1741 std::string* key_type) const {
1742 if (security == onc::wifi::kNone) {
1743 *authentication = kAuthenticationOpen;
1744 *encryption = kEncryptionNone;
1745 } else if (security == onc::wifi::kWEP_PSK) {
1746 *authentication = kAuthenticationOpen;
1747 *encryption = kEncryptionWEP;
1748 *key_type = kKeyTypeNetwork;
1749 } else if (security == onc::wifi::kWPA_PSK) {
1750 *authentication = kAuthenticationWpaPsk;
1751 *encryption = WpaEncryptionFromEncryptionType(encryption_type);
1752 *key_type = kKeyTypePassphrase;
1753 } else if (security == onc::wifi::kWPA2_PSK) {
1754 *authentication = kAuthenticationWpa2Psk;
1755 *encryption = WpaEncryptionFromEncryptionType(encryption_type);
1756 *key_type = kKeyTypePassphrase;
1757 } else {
1758 return false;
1760 return true;
1763 bool WiFiServiceImpl::CreateProfile(
1764 const NetworkProperties& network_properties,
1765 EncryptionType encryption_type,
1766 std::string* profile_xml) {
1767 // Get authentication and encryption values from security.
1768 std::string authentication;
1769 std::string encryption;
1770 std::string key_type;
1771 bool valid = AuthEncryptionFromSecurity(network_properties.security,
1772 encryption_type,
1773 &authentication,
1774 &encryption,
1775 &key_type);
1776 if (!valid)
1777 return valid;
1779 // Generate profile XML.
1780 XmlWriter xml_writer;
1781 xml_writer.StartWriting();
1782 xml_writer.StartElement("WLANProfile");
1783 xml_writer.AddAttribute(
1784 "xmlns",
1785 "http://www.microsoft.com/networking/WLAN/profile/v1");
1786 xml_writer.WriteElement("name", network_properties.guid);
1787 xml_writer.StartElement("SSIDConfig");
1788 xml_writer.StartElement("SSID");
1789 xml_writer.WriteElement("name", network_properties.ssid);
1790 xml_writer.EndElement(); // Ends "SSID" element.
1791 xml_writer.EndElement(); // Ends "SSIDConfig" element.
1792 xml_writer.WriteElement("connectionType", "ESS");
1793 xml_writer.WriteElement("connectionMode", "manual");
1794 xml_writer.StartElement("MSM");
1795 xml_writer.StartElement("security");
1796 xml_writer.StartElement("authEncryption");
1797 xml_writer.WriteElement("authentication", authentication);
1798 xml_writer.WriteElement("encryption", encryption);
1799 xml_writer.WriteElement("useOneX", "false");
1800 xml_writer.EndElement(); // Ends "authEncryption" element.
1801 if (!key_type.empty()) {
1802 xml_writer.StartElement("sharedKey");
1803 xml_writer.WriteElement("keyType", key_type);
1804 xml_writer.WriteElement("protected", "false");
1805 xml_writer.WriteElement("keyMaterial", network_properties.password);
1806 xml_writer.EndElement(); // Ends "sharedKey" element.
1808 xml_writer.EndElement(); // Ends "security" element.
1809 xml_writer.EndElement(); // Ends "MSM" element.
1810 xml_writer.EndElement(); // Ends "WLANProfile" element.
1811 xml_writer.StopWriting();
1812 *profile_xml = xml_writer.GetWrittenString();
1814 return true;
1817 void WiFiServiceImpl::NotifyNetworkListChanged(const NetworkList& networks) {
1818 if (network_list_changed_observer_.is_null())
1819 return;
1821 NetworkGuidList current_networks;
1822 for (NetworkList::const_iterator it = networks.begin();
1823 it != networks.end();
1824 ++it) {
1825 current_networks.push_back(it->guid);
1828 message_loop_proxy_->PostTask(
1829 FROM_HERE,
1830 base::Bind(network_list_changed_observer_, current_networks));
1833 void WiFiServiceImpl::NotifyNetworkChanged(const std::string& network_guid) {
1834 if (enable_notify_network_changed_ && !networks_changed_observer_.is_null()) {
1835 DVLOG(1) << "NotifyNetworkChanged: " << network_guid;
1836 NetworkGuidList changed_networks(1, network_guid);
1837 message_loop_proxy_->PostTask(
1838 FROM_HERE,
1839 base::Bind(networks_changed_observer_, changed_networks));
1843 WiFiService* WiFiService::Create() { return new WiFiServiceImpl(); }
1845 } // namespace wifi