Vectorize website settings icons in omnibox
[chromium-blink-merge.git] / components / wifi / wifi_service_win.cc
blob2716136b34e51fa4738477a3a072c41be3fb95db
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 "components/wifi/network_properties.h"
25 #include "third_party/libxml/chromium/libxml_utils.h"
27 namespace {
28 const wchar_t kNwCategoryWizardRegKey[] =
29 L"Software\\Microsoft\\Windows NT\\CurrentVersion\\Network\\"
30 L"NwCategoryWizard";
31 const wchar_t kNwCategoryWizardRegValue[] = L"Show";
32 const wchar_t kNwCategoryWizardSavedRegValue[] = L"ShowSaved";
33 const wchar_t kNwCategoryWizardDeleteRegValue[] = L"ShowDelete";
34 const wchar_t kWlanApiDll[] = L"wlanapi.dll";
36 // Created Profile Dictionary keys
37 const char kProfileXmlKey[] = "xml";
38 const char kProfileSharedKey[] = "shared";
40 // WlanApi function names
41 const char kWlanConnect[] = "WlanConnect";
42 const char kWlanCloseHandle[] = "WlanCloseHandle";
43 const char kWlanDeleteProfile[] = "WlanDeleteProfile";
44 const char kWlanDisconnect[] = "WlanDisconnect";
45 const char kWlanEnumInterfaces[] = "WlanEnumInterfaces";
46 const char kWlanFreeMemory[] = "WlanFreeMemory";
47 const char kWlanGetAvailableNetworkList[] = "WlanGetAvailableNetworkList";
48 const char kWlanGetNetworkBssList[] = "WlanGetNetworkBssList";
49 const char kWlanGetProfile[] = "WlanGetProfile";
50 const char kWlanOpenHandle[] = "WlanOpenHandle";
51 const char kWlanQueryInterface[] = "WlanQueryInterface";
52 const char kWlanRegisterNotification[] = "WlanRegisterNotification";
53 const char kWlanSaveTemporaryProfile[] = "WlanSaveTemporaryProfile";
54 const char kWlanScan[] = "WlanScan";
55 const char kWlanSetProfile[] = "WlanSetProfile";
57 // WlanApi function definitions
58 typedef DWORD(WINAPI* WlanConnectFunction)(
59 HANDLE hClientHandle,
60 CONST GUID* pInterfaceGuid,
61 CONST PWLAN_CONNECTION_PARAMETERS pConnectionParameters,
62 PVOID pReserved);
64 typedef DWORD (WINAPI* WlanCloseHandleFunction)(
65 HANDLE hClientHandle,
66 PVOID pReserved);
68 typedef DWORD(WINAPI* WlanDeleteProfileFunction)(HANDLE hClientHandle,
69 const GUID* pInterfaceGuid,
70 LPCWSTR strProfileName,
71 PVOID pReserved);
73 typedef DWORD(WINAPI* WlanDisconnectFunction)(HANDLE hClientHandle,
74 CONST GUID* pInterfaceGuid,
75 PVOID pReserved);
77 typedef DWORD(WINAPI* WlanEnumInterfacesFunction)(
78 HANDLE hClientHandle,
79 PVOID pReserved,
80 PWLAN_INTERFACE_INFO_LIST* ppInterfaceList);
82 typedef VOID (WINAPI* WlanFreeMemoryFunction)(
83 _In_ PVOID pMemory);
85 typedef DWORD(WINAPI* WlanGetAvailableNetworkListFunction)(
86 HANDLE hClientHandle,
87 CONST GUID* pInterfaceGuid,
88 DWORD dwFlags,
89 PVOID pReserved,
90 PWLAN_AVAILABLE_NETWORK_LIST* ppAvailableNetworkList);
92 typedef DWORD (WINAPI* WlanGetNetworkBssListFunction)(
93 HANDLE hClientHandle,
94 const GUID* pInterfaceGuid,
95 const PDOT11_SSID pDot11Ssid,
96 DOT11_BSS_TYPE dot11BssType,
97 BOOL bSecurityEnabled,
98 PVOID pReserved,
99 PWLAN_BSS_LIST* ppWlanBssList);
101 typedef DWORD(WINAPI* WlanGetProfileFunction)(HANDLE hClientHandle,
102 CONST GUID* pInterfaceGuid,
103 LPCWSTR strProfileName,
104 PVOID pReserved,
105 LPWSTR* pstrProfileXml,
106 DWORD* pdwFlags,
107 DWORD* pdwGrantedAccess);
109 typedef DWORD (WINAPI* WlanOpenHandleFunction)(
110 DWORD dwClientVersion,
111 PVOID pReserved,
112 PDWORD pdwNegotiatedVersion,
113 PHANDLE phClientHandle);
115 typedef DWORD(WINAPI* WlanQueryInterfaceFunction)(
116 HANDLE hClientHandle,
117 const GUID* pInterfaceGuid,
118 WLAN_INTF_OPCODE OpCode,
119 PVOID pReserved,
120 PDWORD pdwDataSize,
121 PVOID* ppData,
122 PWLAN_OPCODE_VALUE_TYPE pWlanOpcodeValueType);
124 typedef DWORD (WINAPI* WlanRegisterNotificationFunction)(
125 HANDLE hClientHandle,
126 DWORD dwNotifSource,
127 BOOL bIgnoreDuplicate,
128 WLAN_NOTIFICATION_CALLBACK funcCallback,
129 PVOID pCallbackContext,
130 PVOID pReserved,
131 PDWORD pdwPrevNotifSource);
133 typedef DWORD (WINAPI* WlanSaveTemporaryProfileFunction)(
134 HANDLE hClientHandle,
135 CONST GUID* pInterfaceGuid,
136 LPCWSTR strProfileName,
137 LPCWSTR strAllUserProfileSecurity,
138 DWORD dwFlags,
139 BOOL bOverWrite,
140 PVOID pReserved);
142 typedef DWORD(WINAPI* WlanScanFunction)(HANDLE hClientHandle,
143 CONST GUID* pInterfaceGuid,
144 CONST PDOT11_SSID pDot11Ssid,
145 CONST PWLAN_RAW_DATA pIeData,
146 PVOID pReserved);
148 typedef DWORD(WINAPI* WlanSetProfileFunction)(HANDLE hClientHandle,
149 const GUID* pInterfaceGuid,
150 DWORD dwFlags,
151 LPCWSTR strProfileXml,
152 LPCWSTR strAllUserProfileSecurity,
153 BOOL bOverwrite,
154 PVOID pReserved,
155 DWORD* pdwReasonCode);
157 // Values for WLANProfile XML.
158 const char kAuthenticationOpen[] = "open";
159 const char kAuthenticationWepPsk[] = "WEP";
160 const char kAuthenticationWpaPsk[] = "WPAPSK";
161 const char kAuthenticationWpa2Psk[] = "WPA2PSK";
162 const char kEncryptionAES[] = "AES";
163 const char kEncryptionNone[] = "none";
164 const char kEncryptionTKIP[] = "TKIP";
165 const char kEncryptionWEP[] = "WEP";
166 const char kKeyTypeNetwork[] = "networkKey";
167 const char kKeyTypePassphrase[] = "passPhrase";
169 } // namespace
171 namespace wifi {
173 // Implementation of WiFiService for Windows.
174 class WiFiServiceImpl : public WiFiService {
175 public:
176 WiFiServiceImpl();
177 ~WiFiServiceImpl() override;
179 // WiFiService interface implementation.
180 void Initialize(
181 scoped_refptr<base::SequencedTaskRunner> task_runner) override;
183 void UnInitialize() override;
185 void GetProperties(const std::string& network_guid,
186 base::DictionaryValue* properties,
187 std::string* error) override;
189 void GetManagedProperties(const std::string& network_guid,
190 base::DictionaryValue* managed_properties,
191 std::string* error) override;
193 void GetState(const std::string& network_guid,
194 base::DictionaryValue* properties,
195 std::string* error) override;
197 void SetProperties(const std::string& network_guid,
198 scoped_ptr<base::DictionaryValue> properties,
199 std::string* error) override;
201 void CreateNetwork(bool shared,
202 scoped_ptr<base::DictionaryValue> properties,
203 std::string* network_guid,
204 std::string* error) override;
206 void GetVisibleNetworks(const std::string& network_type,
207 base::ListValue* network_list,
208 bool include_details) override;
210 void RequestNetworkScan() override;
212 void StartConnect(const std::string& network_guid,
213 std::string* error) override;
215 void StartDisconnect(const std::string& network_guid,
216 std::string* error) override;
218 void GetKeyFromSystem(const std::string& network_guid,
219 std::string* key_data,
220 std::string* error) override;
222 void SetEventObservers(
223 scoped_refptr<base::SingleThreadTaskRunner> task_runner,
224 const NetworkGuidListCallback& networks_changed_observer,
225 const NetworkGuidListCallback& network_list_changed_observer) override;
227 void RequestConnectedNetworkUpdate() override {}
229 void GetConnectedNetworkSSID(std::string* ssid, std::string* error) override;
231 private:
232 typedef int32 EncryptionType;
233 enum EncryptionTypeEnum {
234 kEncryptionTypeAny = 0,
235 kEncryptionTypeAES = 1,
236 kEncryptionTypeTKIP = 2
239 // Static callback for Windows WLAN_NOTIFICATION. Calls OnWlanNotification
240 // on WiFiServiceImpl passed back as |context|.
241 static void __stdcall OnWlanNotificationCallback(
242 PWLAN_NOTIFICATION_DATA wlan_notification_data,
243 PVOID context);
245 // Callback for Windows WLAN_NOTIFICATION. Called on random thread from
246 // OnWlanNotificationCallback. Handles network connectivity and scan complete
247 // notification and posts tasks to main thread.
248 void OnWlanNotification(PWLAN_NOTIFICATION_DATA wlan_notification_data);
250 // Handles NetworkScanComplete notification on main thread. Sends
251 // |NetworkListChanged| event with new list of visible networks.
252 void OnNetworkScanCompleteOnMainThread();
254 // Wait up to |kMaxAttempts| with |kAttemptDelayMs| delay for connection
255 // to network with |network_guid|. Reset DHCP and Notify that |NetworkChanged|
256 // upon success.
257 void WaitForNetworkConnect(const std::string& network_guid, int attempt);
259 // Check |error_code| and if is not |ERROR_SUCCESS|, then store |error_name|
260 // into |error|.
261 bool CheckError(DWORD error_code,
262 const std::string& error_name,
263 std::string* error) const;
265 // Return |iterator| to network identified by |network_guid| in |networks|
266 // list.
267 NetworkList::iterator FindNetwork(NetworkList& networks,
268 const std::string& network_guid);
270 // Save currently connected network profile so it can be re-connected later.
271 DWORD SaveCurrentConnectedNetwork(const NetworkProperties& properties);
273 // Sort networks, so connected/connecting is up front, then by type:
274 // Ethernet, WiFi, Cellular, VPN
275 static void SortNetworks(NetworkList* networks);
277 // Open a WLAN client handle, register for WLAN notifications.
278 DWORD OpenClientHandle();
280 // Reset DHCP on wireless network to work around an issue when Windows
281 // takes forever to connect to the network, e.g. after Chromecast
282 // device reset.
283 DWORD ResetDHCP();
285 // Find |adapter_index_map| by |interface_guid| for DHCP reset.
286 DWORD FindAdapterIndexMapByGUID(const GUID& interface_guid,
287 IP_ADAPTER_INDEX_MAP* adapter_index_map);
289 // Avoid the network location wizard to pop up when network is connected.
290 // Preserve current value in |saved_nw_category_wizard_|.
291 DWORD DisableNwCategoryWizard();
293 // Restore network location wizard to value saved by DisableNwCategoryWizard.
294 DWORD RestoreNwCategoryWizard();
296 // Ensure that |client_| handle is initialized.
297 DWORD EnsureInitialized();
299 // Close |client_| handle if it is open.
300 DWORD CloseClientHandle();
302 // Get |profile_name| from unique |network_guid|.
303 base::string16 ProfileNameFromGUID(const std::string& network_guid) const {
304 return base::UTF8ToUTF16(network_guid);
307 // Get |dot11_ssid| from unique |network_guid|.
308 DOT11_SSID SSIDFromGUID(const std::string& network_guid) const;
310 // Get unique |network_guid| string based on |dot11_ssid|.
311 std::string GUIDFromSSID(const DOT11_SSID& dot11_ssid) const {
312 return std::string(reinterpret_cast<const char*>(dot11_ssid.ucSSID),
313 dot11_ssid.uSSIDLength);
316 // Get network |ssid| string based on |wlan|.
317 std::string SSIDFromWLAN(const WLAN_AVAILABLE_NETWORK& wlan) const {
318 return GUIDFromSSID(wlan.dot11Ssid);
321 // Get unique |network_guid| string based on |wlan|.
322 std::string GUIDFromWLAN(const WLAN_AVAILABLE_NETWORK& wlan) const {
323 return SSIDFromWLAN(wlan);
326 // Deduce |onc::wifi| security from |alg|.
327 std::string SecurityFromDot11AuthAlg(DOT11_AUTH_ALGORITHM alg) const;
329 // Deduce |onc::connection_state| from |wlan_state|.
330 std::string ConnectionStateFromInterfaceState(
331 WLAN_INTERFACE_STATE wlan_state) const;
333 // Convert |EncryptionType| into WPA(2) encryption type string.
334 std::string WpaEncryptionFromEncryptionType(
335 EncryptionType encryption_type) const;
337 // Deduce WLANProfile |authEncryption| values from |onc::wifi| security.
338 bool AuthEncryptionFromSecurity(const std::string& security,
339 EncryptionType encryption_type,
340 std::string* authentication,
341 std::string* encryption,
342 std::string* key_type) const;
344 // Populate |properties| based on |wlan|.
345 void NetworkPropertiesFromAvailableNetwork(const WLAN_AVAILABLE_NETWORK& wlan,
346 NetworkProperties* properties);
348 // Update |properties| based on bss info from |wlan_bss_list|. If |bssid| in
349 // |properties| is not empty, then it is not changed and |frequency| is set
350 // based on that bssid.
351 void UpdateNetworkPropertiesFromBssList(const std::string& network_guid,
352 const WLAN_BSS_LIST& wlan_bss_list,
353 NetworkProperties* properties);
355 // Get the list of visible wireless networks.
356 DWORD GetVisibleNetworkList(NetworkList* network_list);
358 // Get properties of the network currently used (connected or in transition)
359 // by interface. Populate |current_properties| on success.
360 DWORD GetCurrentProperties(NetworkProperties* current_properties);
362 // Get the SSID of the network currently used (connected or in transition)
363 // by interface. Populate |ssid| on success. This is a stripped down version
364 // of GetCurrentProperties that doesn't use the BSS list;
365 DWORD GetCurrentSSID(std::string* ssid);
367 // Connect to network |network_guid| using previosly stored profile if exists,
368 // or just network sid. If |frequency| is not |kFrequencyUnknown| then
369 // connects only to BSS which uses that frequency and returns
370 // |ERROR_NOT_FOUND| if such BSS cannot be found.
371 DWORD Connect(const std::string& network_guid, Frequency frequency);
373 // Disconnect from currently connected network if any.
374 DWORD Disconnect();
376 // Get desired connection freqency if it was set using |SetProperties|.
377 // Default to |kFrequencyAny|.
378 Frequency GetFrequencyToConnect(const std::string& network_guid) const;
380 // Get DOT11_BSSID_LIST of desired BSSIDs to connect to |ssid| network on
381 // given |frequency|.
382 DWORD GetDesiredBssList(DOT11_SSID& ssid,
383 Frequency frequency,
384 scoped_ptr<DOT11_BSSID_LIST>* desired_list);
386 // Normalizes |frequency_in_mhz| into one of |Frequency| values.
387 Frequency GetNormalizedFrequency(int frequency_in_mhz) const;
389 // Create |profile_xml| based on |network_properties|. If |encryption_type|
390 // is |kEncryptionTypeAny| applies the type most suitable for parameters in
391 // |network_properties|.
392 bool CreateProfile(const NetworkProperties& network_properties,
393 EncryptionType encryption_type,
394 std::string* profile_xml);
396 // Save temporary wireless profile for |network_guid|.
397 DWORD SaveTempProfile(const std::string& network_guid);
399 // Get previously stored |profile_xml| for |network_guid|.
400 // If |get_plaintext_key| is true, and process has sufficient privileges, then
401 // <sharedKey> data in |profile_xml| will be unprotected.
402 DWORD GetProfile(const std::string& network_guid,
403 bool get_plaintext_key,
404 std::string* profile_xml);
406 // Set |profile_xml| to current user or all users depending on |shared| flag.
407 // If |overwrite| is false, then returns an error if profile exists.
408 DWORD SetProfile(bool shared, const std::string& profile_xml, bool overwrite);
410 // Return true if there is previously stored profile xml for |network_guid|.
411 bool HaveProfile(const std::string& network_guid);
413 // Delete profile that was created, but failed to connect.
414 DWORD DeleteCreatedProfile(const std::string& network_guid);
416 // Notify |network_list_changed_observer_| that list of visible networks has
417 // changed to |networks|.
418 void NotifyNetworkListChanged(const NetworkList& networks);
420 // Notify |networks_changed_observer_| that network |network_guid| status has
421 // changed.
422 void NotifyNetworkChanged(const std::string& network_guid);
424 // Load WlanApi.dll from SystemDirectory and get Api function pointers.
425 DWORD LoadWlanLibrary();
426 // Instance of WlanApi.dll.
427 HINSTANCE wlan_api_library_;
428 // WlanApi function pointers
429 WlanConnectFunction WlanConnect_function_;
430 WlanCloseHandleFunction WlanCloseHandle_function_;
431 WlanDeleteProfileFunction WlanDeleteProfile_function_;
432 WlanDisconnectFunction WlanDisconnect_function_;
433 WlanEnumInterfacesFunction WlanEnumInterfaces_function_;
434 WlanFreeMemoryFunction WlanFreeMemory_function_;
435 WlanGetAvailableNetworkListFunction WlanGetAvailableNetworkList_function_;
436 // WlanGetNetworkBssList function may not be avaiable on Windows XP.
437 WlanGetNetworkBssListFunction WlanGetNetworkBssList_function_;
438 WlanGetProfileFunction WlanGetProfile_function_;
439 WlanOpenHandleFunction WlanOpenHandle_function_;
440 WlanQueryInterfaceFunction WlanQueryInterface_function_;
441 WlanRegisterNotificationFunction WlanRegisterNotification_function_;
442 WlanScanFunction WlanScan_function_;
443 WlanSetProfileFunction WlanSetProfile_function_;
444 // WlanSaveTemporaryProfile function may not be avaiable on Windows XP.
445 WlanSaveTemporaryProfileFunction WlanSaveTemporaryProfile_function_;
447 // WLAN service handle.
448 HANDLE client_;
449 // GUID of the currently connected interface, if any, otherwise the GUID of
450 // one of the WLAN interfaces.
451 GUID interface_guid_;
452 // Temporary storage of network properties indexed by |network_guid|. Persist
453 // only in memory.
454 base::DictionaryValue connect_properties_;
455 // Preserved WLAN profile xml.
456 std::map<std::string, std::string> saved_profiles_xml_;
457 // Created WLAN Profiles, indexed by |network_guid|. Contains xml with TKIP
458 // encryption type saved by |CreateNetwork| if applicable. Profile has to be
459 // deleted if connection fails. Implicitly created profiles have to be deleted
460 // if connection succeeds. Persist only in memory.
461 base::DictionaryValue created_profiles_;
462 // Observer to get notified when network(s) have changed (e.g. connect).
463 NetworkGuidListCallback networks_changed_observer_;
464 // Observer to get notified when network list has changed (scan complete).
465 NetworkGuidListCallback network_list_changed_observer_;
466 // Saved value of network location wizard show value.
467 scoped_ptr<DWORD> saved_nw_category_wizard_;
468 // Task runner to post events on UI thread.
469 scoped_refptr<base::SingleThreadTaskRunner> event_task_runner_;
470 // Task runner for worker tasks.
471 scoped_refptr<base::SequencedTaskRunner> task_runner_;
472 // If |false|, then |networks_changed_observer_| is not notified.
473 bool enable_notify_network_changed_;
474 // Number of attempts to check that network has connected successfully.
475 static const int kMaxAttempts = 100;
476 // Delay between attempts to check that network has connected successfully.
477 static const int kAttemptDelayMs = 100;
478 DISALLOW_COPY_AND_ASSIGN(WiFiServiceImpl);
481 WiFiServiceImpl::WiFiServiceImpl()
482 : wlan_api_library_(NULL),
483 WlanConnect_function_(NULL),
484 WlanCloseHandle_function_(NULL),
485 WlanDeleteProfile_function_(NULL),
486 WlanDisconnect_function_(NULL),
487 WlanEnumInterfaces_function_(NULL),
488 WlanFreeMemory_function_(NULL),
489 WlanGetAvailableNetworkList_function_(NULL),
490 WlanGetNetworkBssList_function_(NULL),
491 WlanGetProfile_function_(NULL),
492 WlanOpenHandle_function_(NULL),
493 WlanRegisterNotification_function_(NULL),
494 WlanScan_function_(NULL),
495 WlanSetProfile_function_(NULL),
496 WlanSaveTemporaryProfile_function_(NULL),
497 client_(NULL),
498 enable_notify_network_changed_(true) {
501 WiFiServiceImpl::~WiFiServiceImpl() { UnInitialize(); }
503 void WiFiServiceImpl::Initialize(
504 scoped_refptr<base::SequencedTaskRunner> task_runner) {
505 DCHECK(!client_);
506 task_runner_.swap(task_runner);
507 // Restore NwCategoryWizard in case if we crashed during connect.
508 RestoreNwCategoryWizard();
509 OpenClientHandle();
512 void WiFiServiceImpl::UnInitialize() {
513 CloseClientHandle();
516 void WiFiServiceImpl::GetProperties(const std::string& network_guid,
517 base::DictionaryValue* properties,
518 std::string* error) {
519 DWORD error_code = EnsureInitialized();
520 if (CheckError(error_code, kErrorWiFiService, error))
521 return;
523 NetworkProperties connected_properties;
524 error_code = GetCurrentProperties(&connected_properties);
525 if (error_code == ERROR_SUCCESS &&
526 connected_properties.guid == network_guid) {
527 properties->Swap(connected_properties.ToValue(false).get());
528 return;
531 NetworkList network_list;
532 error_code = GetVisibleNetworkList(&network_list);
533 if (error_code == ERROR_SUCCESS) {
534 NetworkList::const_iterator it = FindNetwork(network_list, network_guid);
535 if (it != network_list.end()) {
536 DVLOG(1) << "Get Properties: " << network_guid << ":"
537 << it->connection_state;
538 properties->Swap(it->ToValue(false).get());
539 return;
541 error_code = ERROR_NOT_FOUND;
544 CheckError(error_code, kErrorWiFiService, error);
547 void WiFiServiceImpl::GetManagedProperties(
548 const std::string& network_guid,
549 base::DictionaryValue* managed_properties,
550 std::string* error) {
551 CheckError(ERROR_CALL_NOT_IMPLEMENTED, kErrorWiFiService, error);
554 void WiFiServiceImpl::GetState(const std::string& network_guid,
555 base::DictionaryValue* properties,
556 std::string* error) {
557 CheckError(ERROR_CALL_NOT_IMPLEMENTED, kErrorWiFiService, error);
560 void WiFiServiceImpl::SetProperties(
561 const std::string& network_guid,
562 scoped_ptr<base::DictionaryValue> properties,
563 std::string* error) {
564 // Temporary preserve WiFi properties (desired frequency, wifi password) to
565 // use in StartConnect.
566 DCHECK(properties.get());
567 if (!properties->HasKey(onc::network_type::kWiFi)) {
568 DVLOG(0) << "Missing WiFi properties:" << *properties;
569 *error = kErrorWiFiService;
570 return;
573 base::DictionaryValue* existing_properties;
574 // If the network properties already exist, don't override previously set
575 // properties, unless they are set in |properties|.
576 if (connect_properties_.GetDictionaryWithoutPathExpansion(
577 network_guid, &existing_properties)) {
578 existing_properties->MergeDictionary(properties.get());
579 } else {
580 connect_properties_.SetWithoutPathExpansion(network_guid,
581 properties.release());
585 void WiFiServiceImpl::CreateNetwork(
586 bool shared,
587 scoped_ptr<base::DictionaryValue> properties,
588 std::string* network_guid,
589 std::string* error) {
590 DWORD error_code = EnsureInitialized();
591 if (CheckError(error_code, kErrorWiFiService, error))
592 return;
594 NetworkProperties network_properties;
595 if (!network_properties.UpdateFromValue(*properties)) {
596 CheckError(ERROR_INVALID_DATA, kErrorWiFiService, error);
597 return;
600 network_properties.guid = network_properties.ssid;
601 std::string profile_xml;
602 if (!CreateProfile(network_properties, kEncryptionTypeAny, &profile_xml)) {
603 CheckError(ERROR_INVALID_DATA, kErrorWiFiService, error);
604 return;
607 error_code = SetProfile(shared, profile_xml, false);
608 if (CheckError(error_code, kErrorWiFiService, error)) {
609 DVLOG(0) << profile_xml;
610 return;
613 // WAP and WAP2 networks could use either AES or TKIP encryption type.
614 // Preserve alternative profile to use in case if connection with default
615 // encryption type fails.
616 std::string tkip_profile_xml;
617 if (!CreateProfile(network_properties,
618 kEncryptionTypeTKIP,
619 &tkip_profile_xml)) {
620 CheckError(ERROR_INVALID_DATA, kErrorWiFiService, error);
621 return;
624 if (tkip_profile_xml != profile_xml) {
625 scoped_ptr<base::DictionaryValue> tkip_profile(new base::DictionaryValue());
626 tkip_profile->SetString(kProfileXmlKey, tkip_profile_xml);
627 tkip_profile->SetBoolean(kProfileSharedKey, shared);
628 created_profiles_.SetWithoutPathExpansion(network_properties.guid,
629 tkip_profile.release());
632 *network_guid = network_properties.guid;
635 void WiFiServiceImpl::GetVisibleNetworks(const std::string& network_type,
636 base::ListValue* network_list,
637 bool include_details) {
638 if (!network_type.empty() &&
639 network_type != onc::network_type::kAllTypes &&
640 network_type != onc::network_type::kWiFi) {
641 return;
644 DWORD error = EnsureInitialized();
645 if (error == ERROR_SUCCESS) {
646 NetworkList networks;
647 error = GetVisibleNetworkList(&networks);
648 if (error == ERROR_SUCCESS && !networks.empty()) {
649 SortNetworks(&networks);
650 for (NetworkList::const_iterator it = networks.begin();
651 it != networks.end();
652 ++it) {
653 scoped_ptr<base::DictionaryValue> network(
654 it->ToValue(!include_details));
655 network_list->Append(network.release());
661 void WiFiServiceImpl::RequestNetworkScan() {
662 DWORD error = EnsureInitialized();
663 if (error == ERROR_SUCCESS) {
664 WlanScan_function_(client_, &interface_guid_, NULL, NULL, NULL);
668 void WiFiServiceImpl::StartConnect(const std::string& network_guid,
669 std::string* error) {
670 DVLOG(1) << "Start Connect: " << network_guid;
671 DWORD error_code = EnsureInitialized();
672 if (CheckError(error_code, kErrorWiFiService, error))
673 return;
675 // Check, if the network is already connected on desired frequency.
676 Frequency frequency = GetFrequencyToConnect(network_guid);
677 NetworkProperties properties;
678 GetCurrentProperties(&properties);
679 bool already_connected =
680 network_guid == properties.guid &&
681 properties.connection_state == onc::connection_state::kConnected &&
682 (frequency == kFrequencyAny || frequency == properties.frequency);
684 // Connect only if network |network_guid| is not connected already.
685 if (!already_connected) {
686 SaveCurrentConnectedNetwork(properties);
687 error_code = Connect(network_guid, frequency);
689 if (error_code == ERROR_SUCCESS) {
690 // Notify that previously connected network has changed.
691 NotifyNetworkChanged(properties.guid);
692 // Start waiting for network connection state change.
693 if (!networks_changed_observer_.is_null()) {
694 DisableNwCategoryWizard();
695 // Disable automatic network change notifications as they get fired
696 // when network is just connected, but not yet accessible (doesn't
697 // have valid IP address).
698 enable_notify_network_changed_ = false;
699 WaitForNetworkConnect(network_guid, 0);
700 return;
702 } else if (error_code == ERROR_ACCESS_DENIED) {
703 CheckError(error_code, kErrorNotConfigured, error);
704 } else {
705 CheckError(error_code, kErrorWiFiService, error);
709 void WiFiServiceImpl::StartDisconnect(const std::string& network_guid,
710 std::string* error) {
711 DVLOG(1) << "Start Disconnect: " << network_guid;
712 DWORD error_code = EnsureInitialized();
713 if (CheckError(error_code, kErrorWiFiService, error))
714 return;
716 // Check, if the network is currently connected.
717 NetworkProperties properties;
718 GetCurrentProperties(&properties);
719 if (network_guid == properties.guid) {
720 if (properties.connection_state == onc::connection_state::kConnected)
721 SaveCurrentConnectedNetwork(properties);
722 error_code = Disconnect();
723 if (error_code == ERROR_SUCCESS) {
724 NotifyNetworkChanged(network_guid);
725 return;
728 CheckError(error_code, kErrorWiFiService, error);
731 void WiFiServiceImpl::GetKeyFromSystem(const std::string& network_guid,
732 std::string* key_data,
733 std::string* error) {
734 DWORD error_code = EnsureInitialized();
735 if (CheckError(error_code, kErrorWiFiService, error))
736 return;
738 std::string profile_xml;
739 error_code = GetProfile(network_guid, true, &profile_xml);
740 if (CheckError(error_code, kErrorWiFiService, error))
741 return;
743 const char kSharedKeyElement[] = "sharedKey";
744 const char kProtectedElement[] = "protected";
745 const char kKeyMaterialElement[] = "keyMaterial";
747 // Quick check to verify presence of <sharedKey> element.
748 if (profile_xml.find(kSharedKeyElement) == std::string::npos) {
749 *error = kErrorWiFiService;
750 return;
753 XmlReader reader;
754 if (reader.Load(profile_xml)) {
755 while (reader.Read()) {
756 reader.SkipToElement();
757 if (reader.NodeName() == kSharedKeyElement) {
758 while (reader.Read()) {
759 reader.SkipToElement();
760 if (reader.NodeName() == kKeyMaterialElement) {
761 reader.ReadElementContent(key_data);
762 } else if (reader.NodeName() == kProtectedElement) {
763 std::string protected_data;
764 reader.ReadElementContent(&protected_data);
765 // Without UAC privilege escalation call to |GetProfile| with
766 // |WLAN_PROFILE_GET_PLAINTEXT_KEY| flag returns success, but has
767 // protected keyMaterial. Report an error in this case.
768 if (protected_data != "false") {
769 *error = kErrorWiFiService;
770 break;
774 return;
779 // Did not find passphrase in the profile.
780 *error = kErrorWiFiService;
783 void WiFiServiceImpl::SetEventObservers(
784 scoped_refptr<base::SingleThreadTaskRunner> task_runner,
785 const NetworkGuidListCallback& networks_changed_observer,
786 const NetworkGuidListCallback& network_list_changed_observer) {
787 DWORD error_code = EnsureInitialized();
788 if (error_code != ERROR_SUCCESS)
789 return;
790 event_task_runner_.swap(task_runner);
791 if (!networks_changed_observer_.is_null() ||
792 !network_list_changed_observer_.is_null()) {
793 // Stop listening to WLAN notifications.
794 WlanRegisterNotification_function_(client_,
795 WLAN_NOTIFICATION_SOURCE_NONE,
796 FALSE,
797 OnWlanNotificationCallback,
798 this,
799 NULL,
800 NULL);
802 networks_changed_observer_ = networks_changed_observer;
803 network_list_changed_observer_ = network_list_changed_observer;
804 if (!networks_changed_observer_.is_null() ||
805 !network_list_changed_observer_.is_null()) {
806 // Start listening to WLAN notifications.
807 WlanRegisterNotification_function_(client_,
808 WLAN_NOTIFICATION_SOURCE_ALL,
809 FALSE,
810 OnWlanNotificationCallback,
811 this,
812 NULL,
813 NULL);
817 void WiFiServiceImpl::GetConnectedNetworkSSID(std::string* ssid,
818 std::string* error) {
819 DWORD error_code = EnsureInitialized();
820 if (CheckError(error_code, kErrorWiFiService, error))
821 return;
822 std::string current_ssid;
823 error_code = GetCurrentSSID(&current_ssid);
824 if (CheckError(error_code, kErrorWiFiService, error))
825 return;
826 *ssid = current_ssid;
829 void WiFiServiceImpl::OnWlanNotificationCallback(
830 PWLAN_NOTIFICATION_DATA wlan_notification_data,
831 PVOID context) {
832 WiFiServiceImpl* service = reinterpret_cast<WiFiServiceImpl*>(context);
833 service->OnWlanNotification(wlan_notification_data);
836 void WiFiServiceImpl::OnWlanNotification(
837 PWLAN_NOTIFICATION_DATA wlan_notification_data) {
838 if (event_task_runner_.get() == NULL)
839 return;
840 switch (wlan_notification_data->NotificationCode) {
841 case wlan_notification_acm_disconnected:
842 case wlan_notification_acm_connection_complete:
843 case wlan_notification_acm_connection_attempt_fail: {
844 PWLAN_CONNECTION_NOTIFICATION_DATA wlan_connection_data =
845 reinterpret_cast<PWLAN_CONNECTION_NOTIFICATION_DATA>(
846 wlan_notification_data->pData);
847 event_task_runner_->PostTask(
848 FROM_HERE, base::Bind(&WiFiServiceImpl::NotifyNetworkChanged,
849 base::Unretained(this),
850 GUIDFromSSID(wlan_connection_data->dot11Ssid)));
851 break;
853 case wlan_notification_acm_scan_complete:
854 case wlan_notification_acm_interface_removal:
855 event_task_runner_->PostTask(
856 FROM_HERE,
857 base::Bind(&WiFiServiceImpl::OnNetworkScanCompleteOnMainThread,
858 base::Unretained(this)));
859 break;
863 void WiFiServiceImpl::OnNetworkScanCompleteOnMainThread() {
864 NetworkList networks;
865 // Get current list of visible networks and notify that network list has
866 // changed.
867 DWORD error = GetVisibleNetworkList(&networks);
868 if (error != ERROR_SUCCESS)
869 networks.clear();
870 NotifyNetworkListChanged(networks);
873 void WiFiServiceImpl::WaitForNetworkConnect(const std::string& network_guid,
874 int attempt) {
875 // If network didn't get connected in |kMaxAttempts|, then try to connect
876 // using different profile if it was created recently.
877 if (attempt > kMaxAttempts) {
878 LOG(ERROR) << kMaxAttempts << " attempts exceeded waiting for connect to "
879 << network_guid;
881 base::DictionaryValue* created_profile = NULL;
882 // Check, whether this connection is using newly created profile.
883 if (created_profiles_.GetDictionaryWithoutPathExpansion(
884 network_guid, &created_profile)) {
885 std::string tkip_profile_xml;
886 bool shared = false;
887 // Check, if this connection there is alternative TKIP profile xml that
888 // should be tried. If there is, then set it up and try to connect again.
889 if (created_profile->GetString(kProfileXmlKey, &tkip_profile_xml) &&
890 created_profile->GetBoolean(kProfileSharedKey, &shared)) {
891 // Remove TKIP profile xml, so it will not be tried again.
892 created_profile->Remove(kProfileXmlKey, NULL);
893 created_profile->Remove(kProfileSharedKey, NULL);
894 DWORD error_code = SetProfile(shared, tkip_profile_xml, true);
895 if (error_code == ERROR_SUCCESS) {
896 // Try to connect with new profile.
897 error_code = Connect(network_guid,
898 GetFrequencyToConnect(network_guid));
899 if (error_code == ERROR_SUCCESS) {
900 // Start waiting again.
901 WaitForNetworkConnect(network_guid, 0);
902 return;
903 } else {
904 LOG(ERROR) << "Failed to set created profile for " << network_guid
905 << " error=" << error_code;
908 } else {
909 // Connection has failed, so delete bad created profile.
910 DWORD error_code = DeleteCreatedProfile(network_guid);
911 if (error_code != ERROR_SUCCESS) {
912 LOG(ERROR) << "Failed to delete created profile for " << network_guid
913 << " error=" << error_code;
917 // Restore automatic network change notifications and stop waiting.
918 enable_notify_network_changed_ = true;
919 RestoreNwCategoryWizard();
920 return;
922 NetworkProperties current_properties;
923 DWORD error = GetCurrentProperties(&current_properties);
924 if (network_guid == current_properties.guid &&
925 current_properties.connection_state ==
926 onc::connection_state::kConnected) {
927 DVLOG(1) << "WiFi Connected, Reset DHCP: " << network_guid;
928 // Even though wireless network is now connected, it may still be unusable,
929 // e.g. after Chromecast device reset. Reset DHCP on wireless network to
930 // work around this issue.
931 error = ResetDHCP();
932 if (error != ERROR_SUCCESS)
933 LOG(ERROR) << error;
934 // There is no need to keep created profile as network is connected.
935 created_profiles_.RemoveWithoutPathExpansion(network_guid, NULL);
936 // Restore previously suppressed notifications.
937 enable_notify_network_changed_ = true;
938 RestoreNwCategoryWizard();
939 NotifyNetworkChanged(network_guid);
940 } else {
941 // Continue waiting for network connection state change.
942 task_runner_->PostDelayedTask(
943 FROM_HERE,
944 base::Bind(&WiFiServiceImpl::WaitForNetworkConnect,
945 base::Unretained(this),
946 network_guid,
947 ++attempt),
948 base::TimeDelta::FromMilliseconds(kAttemptDelayMs));
952 bool WiFiServiceImpl::CheckError(DWORD error_code,
953 const std::string& error_name,
954 std::string* error) const {
955 if (error_code != ERROR_SUCCESS) {
956 DLOG(ERROR) << "WiFiService Error " << error_code << ": " << error_name;
957 *error = error_name;
958 return true;
960 return false;
963 NetworkList::iterator WiFiServiceImpl::FindNetwork(
964 NetworkList& networks,
965 const std::string& network_guid) {
966 for (NetworkList::iterator it = networks.begin(); it != networks.end();
967 ++it) {
968 if (it->guid == network_guid)
969 return it;
971 return networks.end();
974 DWORD WiFiServiceImpl::SaveCurrentConnectedNetwork(
975 const NetworkProperties& current_properties) {
976 DWORD error = ERROR_SUCCESS;
977 // Save currently connected network.
978 if (!current_properties.guid.empty() &&
979 current_properties.connection_state ==
980 onc::connection_state::kConnected) {
981 error = SaveTempProfile(current_properties.guid);
983 return error;
986 void WiFiServiceImpl::SortNetworks(NetworkList* networks) {
987 networks->sort(NetworkProperties::OrderByType);
990 DWORD WiFiServiceImpl::LoadWlanLibrary() {
991 // Use an absolute path to load the DLL to avoid DLL preloading attacks.
992 base::FilePath path;
993 if (!PathService::Get(base::DIR_SYSTEM, &path)) {
994 LOG(ERROR) << "Unable to get system path.";
995 return ERROR_NOT_FOUND;
997 wlan_api_library_ = ::LoadLibraryEx(path.Append(kWlanApiDll).value().c_str(),
998 NULL,
999 LOAD_WITH_ALTERED_SEARCH_PATH);
1000 if (!wlan_api_library_) {
1001 LOG(ERROR) << "Unable to load WlanApi.dll.";
1002 return ERROR_NOT_FOUND;
1005 // Initialize WlanApi function pointers
1006 WlanConnect_function_ =
1007 reinterpret_cast<WlanConnectFunction>(
1008 ::GetProcAddress(wlan_api_library_, kWlanConnect));
1009 WlanCloseHandle_function_ =
1010 reinterpret_cast<WlanCloseHandleFunction>(
1011 ::GetProcAddress(wlan_api_library_, kWlanCloseHandle));
1012 WlanDeleteProfile_function_ =
1013 reinterpret_cast<WlanDeleteProfileFunction>(
1014 ::GetProcAddress(wlan_api_library_, kWlanDeleteProfile));
1015 WlanDisconnect_function_ =
1016 reinterpret_cast<WlanDisconnectFunction>(
1017 ::GetProcAddress(wlan_api_library_, kWlanDisconnect));
1018 WlanEnumInterfaces_function_ =
1019 reinterpret_cast<WlanEnumInterfacesFunction>(
1020 ::GetProcAddress(wlan_api_library_, kWlanEnumInterfaces));
1021 WlanFreeMemory_function_ =
1022 reinterpret_cast<WlanFreeMemoryFunction>(
1023 ::GetProcAddress(wlan_api_library_, kWlanFreeMemory));
1024 WlanGetAvailableNetworkList_function_ =
1025 reinterpret_cast<WlanGetAvailableNetworkListFunction>(
1026 ::GetProcAddress(wlan_api_library_, kWlanGetAvailableNetworkList));
1027 WlanGetNetworkBssList_function_ =
1028 reinterpret_cast<WlanGetNetworkBssListFunction>(
1029 ::GetProcAddress(wlan_api_library_, kWlanGetNetworkBssList));
1030 WlanGetProfile_function_ =
1031 reinterpret_cast<WlanGetProfileFunction>(
1032 ::GetProcAddress(wlan_api_library_, kWlanGetProfile));
1033 WlanOpenHandle_function_ =
1034 reinterpret_cast<WlanOpenHandleFunction>(
1035 ::GetProcAddress(wlan_api_library_, kWlanOpenHandle));
1036 WlanQueryInterface_function_ =
1037 reinterpret_cast<WlanQueryInterfaceFunction>(
1038 ::GetProcAddress(wlan_api_library_, kWlanQueryInterface));
1039 WlanRegisterNotification_function_ =
1040 reinterpret_cast<WlanRegisterNotificationFunction>(
1041 ::GetProcAddress(wlan_api_library_, kWlanRegisterNotification));
1042 WlanSaveTemporaryProfile_function_ =
1043 reinterpret_cast<WlanSaveTemporaryProfileFunction>(
1044 ::GetProcAddress(wlan_api_library_, kWlanSaveTemporaryProfile));
1045 WlanScan_function_ =
1046 reinterpret_cast<WlanScanFunction>(
1047 ::GetProcAddress(wlan_api_library_, kWlanScan));
1048 WlanSetProfile_function_ =
1049 reinterpret_cast<WlanSetProfileFunction>(
1050 ::GetProcAddress(wlan_api_library_, kWlanSetProfile));
1052 if (!WlanConnect_function_ ||
1053 !WlanCloseHandle_function_ ||
1054 !WlanDeleteProfile_function_ ||
1055 !WlanDisconnect_function_ ||
1056 !WlanEnumInterfaces_function_ ||
1057 !WlanFreeMemory_function_ ||
1058 !WlanGetAvailableNetworkList_function_ ||
1059 !WlanGetProfile_function_ ||
1060 !WlanOpenHandle_function_ ||
1061 !WlanQueryInterface_function_ ||
1062 !WlanRegisterNotification_function_ ||
1063 !WlanScan_function_ ||
1064 !WlanSetProfile_function_) {
1065 LOG(ERROR) << "Unable to find required WlanApi function.";
1066 FreeLibrary(wlan_api_library_);
1067 wlan_api_library_ = NULL;
1068 return ERROR_NOT_FOUND;
1071 // Some WlanApi functions may not be available on XP.
1072 if (!WlanGetNetworkBssList_function_ ||
1073 !WlanSaveTemporaryProfile_function_) {
1074 DVLOG(1) << "WlanApi function is not be available on XP.";
1077 return ERROR_SUCCESS;
1080 DWORD WiFiServiceImpl::OpenClientHandle() {
1081 DWORD error = LoadWlanLibrary();
1082 DWORD service_version = 0;
1084 if (error != ERROR_SUCCESS)
1085 return error;
1087 // Open a handle to the service.
1088 error = WlanOpenHandle_function_(1, NULL, &service_version, &client_);
1090 PWLAN_INTERFACE_INFO_LIST interface_list = NULL;
1091 if (error == ERROR_SUCCESS) {
1092 // Enumerate wireless interfaces.
1093 error = WlanEnumInterfaces_function_(client_, NULL, &interface_list);
1094 if (error == ERROR_SUCCESS) {
1095 if (interface_list != NULL && interface_list->dwNumberOfItems != 0) {
1096 // Remember first interface just in case if none are connected.
1097 interface_guid_ = interface_list->InterfaceInfo[0].InterfaceGuid;
1098 // Try to find a connected interface.
1099 for (DWORD itf = 0; itf < interface_list->dwNumberOfItems; ++itf) {
1100 if (interface_list->InterfaceInfo[itf].isState ==
1101 wlan_interface_state_connected) {
1102 // Found connected interface, remember it!
1103 interface_guid_ = interface_list->InterfaceInfo[itf].InterfaceGuid;
1104 break;
1107 } else {
1108 error = ERROR_NOINTERFACE;
1111 // Clean up..
1112 if (interface_list != NULL)
1113 WlanFreeMemory_function_(interface_list);
1115 return error;
1118 DWORD WiFiServiceImpl::ResetDHCP() {
1119 IP_ADAPTER_INDEX_MAP adapter_index_map = {0};
1120 DWORD error = FindAdapterIndexMapByGUID(interface_guid_, &adapter_index_map);
1121 if (error != ERROR_SUCCESS) {
1122 LOG(ERROR) << error;
1123 return error;
1125 error = ::IpReleaseAddress(&adapter_index_map);
1126 if (error != ERROR_SUCCESS) {
1127 if (error != ERROR_ADDRESS_NOT_ASSOCIATED) {
1128 LOG(ERROR) << error;
1129 return error;
1131 DVLOG(1) << "Ignoring IpReleaseAddress Error: " << error;
1133 error = ::IpRenewAddress(&adapter_index_map);
1134 if (error != ERROR_SUCCESS)
1135 LOG(ERROR) << error;
1136 return error;
1139 DWORD WiFiServiceImpl::FindAdapterIndexMapByGUID(
1140 const GUID& interface_guid,
1141 IP_ADAPTER_INDEX_MAP* adapter_index_map) {
1142 base::string16 guid_string;
1143 const int kGUIDSize = 39;
1144 ::StringFromGUID2(
1145 interface_guid, base::WriteInto(&guid_string, kGUIDSize), kGUIDSize);
1147 ULONG buffer_length = 0;
1148 DWORD error = ::GetInterfaceInfo(NULL, &buffer_length);
1149 if (error == ERROR_INSUFFICIENT_BUFFER) {
1150 scoped_ptr<unsigned char[]> buffer(new unsigned char[buffer_length]);
1151 IP_INTERFACE_INFO* interface_info =
1152 reinterpret_cast<IP_INTERFACE_INFO*>(buffer.get());
1153 error = GetInterfaceInfo(interface_info, &buffer_length);
1154 if (error == ERROR_SUCCESS) {
1155 for (int adapter = 0; adapter < interface_info->NumAdapters; ++adapter) {
1156 if (base::EndsWith(
1157 interface_info->Adapter[adapter].Name, guid_string,
1158 base::CompareCase::INSENSITIVE_ASCII)) {
1159 *adapter_index_map = interface_info->Adapter[adapter];
1160 break;
1165 return error;
1168 DWORD WiFiServiceImpl::DisableNwCategoryWizard() {
1169 base::win::RegKey nw_category_wizard;
1170 DWORD error = nw_category_wizard.Open(HKEY_CURRENT_USER,
1171 kNwCategoryWizardRegKey,
1172 KEY_READ | KEY_SET_VALUE);
1173 if (error == ERROR_SUCCESS) {
1174 // Save current value if present.
1175 if (nw_category_wizard.HasValue(kNwCategoryWizardRegValue)) {
1176 DWORD saved = 0u;
1177 error = nw_category_wizard.ReadValueDW(kNwCategoryWizardRegValue,
1178 &saved);
1179 if (error == ERROR_SUCCESS) {
1180 error = nw_category_wizard.WriteValue(kNwCategoryWizardSavedRegValue,
1181 saved);
1183 } else {
1184 // Mark that temporary value has to be deleted.
1185 error = nw_category_wizard.WriteValue(kNwCategoryWizardDeleteRegValue,
1186 1u);
1189 // Disable network location wizard.
1190 error = nw_category_wizard.WriteValue(kNwCategoryWizardRegValue,
1191 static_cast<DWORD>(0));
1194 return error;
1197 DWORD WiFiServiceImpl::RestoreNwCategoryWizard() {
1198 base::win::RegKey nw_category_wizard;
1199 DWORD error = nw_category_wizard.Open(HKEY_CURRENT_USER,
1200 kNwCategoryWizardRegKey,
1201 KEY_SET_VALUE);
1202 if (error == ERROR_SUCCESS) {
1203 // Restore saved value if present.
1204 if (nw_category_wizard.HasValue(kNwCategoryWizardSavedRegValue)) {
1205 DWORD saved = 0u;
1206 error = nw_category_wizard.ReadValueDW(kNwCategoryWizardSavedRegValue,
1207 &saved);
1208 if (error == ERROR_SUCCESS) {
1209 error = nw_category_wizard.WriteValue(kNwCategoryWizardRegValue,
1210 saved);
1211 error = nw_category_wizard.DeleteValue(kNwCategoryWizardSavedRegValue);
1213 } else if (nw_category_wizard.HasValue(kNwCategoryWizardDeleteRegValue)) {
1214 error = nw_category_wizard.DeleteValue(kNwCategoryWizardRegValue);
1215 error = nw_category_wizard.DeleteValue(kNwCategoryWizardDeleteRegValue);
1219 return error;
1222 DWORD WiFiServiceImpl::EnsureInitialized() {
1223 if (client_ != NULL)
1224 return ERROR_SUCCESS;
1225 return ERROR_NOINTERFACE;
1228 DWORD WiFiServiceImpl::CloseClientHandle() {
1229 DWORD error = ERROR_SUCCESS;
1230 if (client_ != NULL) {
1231 error = WlanCloseHandle_function_(client_, NULL);
1232 client_ = NULL;
1234 if (wlan_api_library_ != NULL) {
1235 WlanConnect_function_ = NULL;
1236 WlanCloseHandle_function_ = NULL;
1237 WlanDeleteProfile_function_ = NULL;
1238 WlanDisconnect_function_ = NULL;
1239 WlanEnumInterfaces_function_ = NULL;
1240 WlanFreeMemory_function_ = NULL;
1241 WlanGetAvailableNetworkList_function_ = NULL;
1242 WlanGetNetworkBssList_function_ = NULL;
1243 WlanGetProfile_function_ = NULL;
1244 WlanOpenHandle_function_ = NULL;
1245 WlanRegisterNotification_function_ = NULL;
1246 WlanSaveTemporaryProfile_function_ = NULL;
1247 WlanScan_function_ = NULL;
1248 WlanSetProfile_function_ = NULL;
1249 ::FreeLibrary(wlan_api_library_);
1250 wlan_api_library_ = NULL;
1252 return error;
1255 DOT11_SSID WiFiServiceImpl::SSIDFromGUID(
1256 const std::string& network_guid) const {
1257 DOT11_SSID ssid = {0};
1258 if (network_guid.length() <= DOT11_SSID_MAX_LENGTH) {
1259 ssid.uSSIDLength = static_cast<ULONG>(network_guid.length());
1260 strncpy(reinterpret_cast<char*>(ssid.ucSSID),
1261 network_guid.c_str(),
1262 ssid.uSSIDLength);
1263 } else {
1264 NOTREACHED();
1266 return ssid;
1269 std::string WiFiServiceImpl::SecurityFromDot11AuthAlg(
1270 DOT11_AUTH_ALGORITHM alg) const {
1271 switch (alg) {
1272 case DOT11_AUTH_ALGO_RSNA:
1273 return onc::wifi::kWPA_EAP;
1274 case DOT11_AUTH_ALGO_RSNA_PSK:
1275 return onc::wifi::kWPA_PSK;
1276 case DOT11_AUTH_ALGO_80211_SHARED_KEY:
1277 return onc::wifi::kWEP_PSK;
1278 case DOT11_AUTH_ALGO_80211_OPEN:
1279 return onc::wifi::kSecurityNone;
1280 default:
1281 return onc::wifi::kWPA_EAP;
1285 std::string WiFiServiceImpl::ConnectionStateFromInterfaceState(
1286 WLAN_INTERFACE_STATE wlan_state) const {
1287 switch (wlan_state) {
1288 case wlan_interface_state_connected:
1289 // TODO(mef): Even if |wlan_state| is connected, the network may still
1290 // not be reachable, and should be resported as |kConnecting|.
1291 return onc::connection_state::kConnected;
1292 case wlan_interface_state_associating:
1293 case wlan_interface_state_discovering:
1294 case wlan_interface_state_authenticating:
1295 return onc::connection_state::kConnecting;
1296 default:
1297 return onc::connection_state::kNotConnected;
1301 void WiFiServiceImpl::NetworkPropertiesFromAvailableNetwork(
1302 const WLAN_AVAILABLE_NETWORK& wlan,
1303 NetworkProperties* properties) {
1304 // TODO(mef): It would be nice for the connection states in
1305 // getVisibleNetworks and getProperties results to be consistent.
1306 if (wlan.dwFlags & WLAN_AVAILABLE_NETWORK_CONNECTED) {
1307 properties->connection_state = onc::connection_state::kConnected;
1308 } else {
1309 properties->connection_state = onc::connection_state::kNotConnected;
1312 properties->ssid = SSIDFromWLAN(wlan);
1313 properties->name = properties->ssid;
1314 properties->guid = GUIDFromWLAN(wlan);
1315 properties->type = onc::network_type::kWiFi;
1316 properties->security =
1317 SecurityFromDot11AuthAlg(wlan.dot11DefaultAuthAlgorithm);
1318 properties->signal_strength = wlan.wlanSignalQuality;
1321 void WiFiServiceImpl::UpdateNetworkPropertiesFromBssList(
1322 const std::string& network_guid,
1323 const WLAN_BSS_LIST& wlan_bss_list,
1324 NetworkProperties* properties) {
1325 if (network_guid.empty())
1326 return;
1328 DOT11_SSID ssid = SSIDFromGUID(network_guid);
1329 for (size_t bss = 0; bss < wlan_bss_list.dwNumberOfItems; ++bss) {
1330 const WLAN_BSS_ENTRY& bss_entry(wlan_bss_list.wlanBssEntries[bss]);
1331 if (bss_entry.dot11Ssid.uSSIDLength == ssid.uSSIDLength &&
1332 0 == memcmp(bss_entry.dot11Ssid.ucSSID,
1333 ssid.ucSSID,
1334 bss_entry.dot11Ssid.uSSIDLength)) {
1335 std::string bssid = NetworkProperties::MacAddressAsString(
1336 bss_entry.dot11Bssid);
1337 Frequency frequency = GetNormalizedFrequency(
1338 bss_entry.ulChCenterFrequency / 1000);
1339 properties->frequency_set.insert(frequency);
1340 if (properties->bssid.empty() || properties->bssid == bssid) {
1341 properties->frequency = frequency;
1342 properties->bssid = bssid;
1348 // Get the list of visible wireless networks
1349 DWORD WiFiServiceImpl::GetVisibleNetworkList(NetworkList* network_list) {
1350 if (client_ == NULL) {
1351 NOTREACHED();
1352 return ERROR_NOINTERFACE;
1355 DWORD error = ERROR_SUCCESS;
1356 PWLAN_AVAILABLE_NETWORK_LIST available_network_list = NULL;
1357 PWLAN_BSS_LIST bss_list = NULL;
1359 error = WlanGetAvailableNetworkList_function_(
1360 client_,
1361 &interface_guid_,
1362 WLAN_AVAILABLE_NETWORK_INCLUDE_ALL_MANUAL_HIDDEN_PROFILES,
1363 NULL,
1364 &available_network_list);
1366 std::set<std::string> network_guids;
1368 if (error == ERROR_SUCCESS &&
1369 available_network_list &&
1370 WlanGetNetworkBssList_function_) {
1371 // TODO(mef): WlanGetNetworkBssList is not available on XP. If XP support is
1372 // needed, then different method of getting BSS (e.g. OID query) will have
1373 // to be used.
1374 error = WlanGetNetworkBssList_function_(client_,
1375 &interface_guid_,
1376 NULL,
1377 dot11_BSS_type_any,
1378 FALSE,
1379 NULL,
1380 &bss_list);
1381 if (error == ERROR_SUCCESS && NULL != bss_list) {
1382 for (DWORD i = 0; i < available_network_list->dwNumberOfItems; ++i) {
1383 NetworkProperties network_properties;
1384 NetworkPropertiesFromAvailableNetwork(
1385 available_network_list->Network[i],
1386 &network_properties);
1387 UpdateNetworkPropertiesFromBssList(network_properties.guid,
1388 *bss_list,
1389 &network_properties);
1390 // Check for duplicate network guids.
1391 if (network_guids.count(network_properties.guid)) {
1392 // There should be no difference between properties except for
1393 // |connection_state|, so mark it as |kConnected| if either one is.
1394 if (network_properties.connection_state ==
1395 onc::connection_state::kConnected) {
1396 NetworkList::iterator previous_network_properties =
1397 FindNetwork(*network_list, network_properties.guid);
1398 DCHECK(previous_network_properties != network_list->end());
1399 previous_network_properties->connection_state =
1400 network_properties.connection_state;
1402 } else {
1403 network_list->push_back(network_properties);
1405 network_guids.insert(network_properties.guid);
1410 // Clean up.
1411 if (available_network_list != NULL) {
1412 WlanFreeMemory_function_(available_network_list);
1414 if (bss_list != NULL) {
1415 WlanFreeMemory_function_(bss_list);
1417 return error;
1420 DWORD WiFiServiceImpl::GetCurrentProperties(NetworkProperties* properties) {
1421 if (client_ == NULL) {
1422 NOTREACHED();
1423 return ERROR_NOINTERFACE;
1426 // TODO(mef): WlanGetNetworkBssList is not available on XP. If XP support is
1427 // needed, then different method of getting BSS (e.g. OID query) will have
1428 // to be used.
1429 if (WlanGetNetworkBssList_function_ == NULL)
1430 return ERROR_NOINTERFACE;
1432 DWORD error = ERROR_SUCCESS;
1433 DWORD data_size = 0;
1434 PWLAN_CONNECTION_ATTRIBUTES wlan_connection_attributes = NULL;
1435 PWLAN_BSS_LIST bss_list = NULL;
1436 error = WlanQueryInterface_function_(
1437 client_,
1438 &interface_guid_,
1439 wlan_intf_opcode_current_connection,
1440 NULL,
1441 &data_size,
1442 reinterpret_cast<PVOID*>(&wlan_connection_attributes),
1443 NULL);
1444 if (error == ERROR_SUCCESS &&
1445 wlan_connection_attributes != NULL) {
1446 WLAN_ASSOCIATION_ATTRIBUTES& connected_wlan =
1447 wlan_connection_attributes->wlanAssociationAttributes;
1449 properties->connection_state = ConnectionStateFromInterfaceState(
1450 wlan_connection_attributes->isState);
1451 properties->ssid = GUIDFromSSID(connected_wlan.dot11Ssid);
1452 properties->name = properties->ssid;
1453 properties->guid = GUIDFromSSID(connected_wlan.dot11Ssid);
1454 properties->type = onc::network_type::kWiFi;
1455 properties->bssid = NetworkProperties::MacAddressAsString(
1456 connected_wlan.dot11Bssid);
1457 properties->security = SecurityFromDot11AuthAlg(
1458 wlan_connection_attributes->wlanSecurityAttributes.dot11AuthAlgorithm);
1459 properties->signal_strength = connected_wlan.wlanSignalQuality;
1461 error = WlanGetNetworkBssList_function_(client_,
1462 &interface_guid_,
1463 &connected_wlan.dot11Ssid,
1464 connected_wlan.dot11BssType,
1465 FALSE,
1466 NULL,
1467 &bss_list);
1468 if (error == ERROR_SUCCESS && NULL != bss_list) {
1469 UpdateNetworkPropertiesFromBssList(properties->guid,
1470 *bss_list,
1471 properties);
1475 // Clean up.
1476 if (wlan_connection_attributes != NULL)
1477 WlanFreeMemory_function_(wlan_connection_attributes);
1479 if (bss_list != NULL)
1480 WlanFreeMemory_function_(bss_list);
1482 return error;
1486 DWORD WiFiServiceImpl::GetCurrentSSID(std::string* ssid) {
1487 if (client_ == NULL) {
1488 NOTREACHED();
1489 return ERROR_NOINTERFACE;
1491 DWORD error = ERROR_SUCCESS;
1492 DWORD data_size = 0;
1493 PWLAN_CONNECTION_ATTRIBUTES wlan_connection_attributes = NULL;
1494 error = WlanQueryInterface_function_(
1495 client_,
1496 &interface_guid_,
1497 wlan_intf_opcode_current_connection,
1498 NULL,
1499 &data_size,
1500 reinterpret_cast<PVOID*>(&wlan_connection_attributes),
1501 NULL);
1502 if (error == ERROR_SUCCESS &&
1503 wlan_connection_attributes != NULL) {
1504 WLAN_ASSOCIATION_ATTRIBUTES& connected_wlan =
1505 wlan_connection_attributes->wlanAssociationAttributes;
1506 *ssid = GUIDFromSSID(connected_wlan.dot11Ssid);
1509 // Clean up.
1510 if (wlan_connection_attributes != NULL)
1511 WlanFreeMemory_function_(wlan_connection_attributes);
1513 return error;
1516 Frequency WiFiServiceImpl::GetFrequencyToConnect(
1517 const std::string& network_guid) const {
1518 // Check whether desired frequency is set in |connect_properties_|.
1519 const base::DictionaryValue* properties;
1520 if (connect_properties_.GetDictionaryWithoutPathExpansion(network_guid,
1521 &properties)) {
1522 const base::DictionaryValue* wifi;
1523 if (properties->GetDictionary(onc::network_type::kWiFi, &wifi)) {
1524 int frequency;
1525 if (wifi->GetInteger(onc::wifi::kFrequency, &frequency))
1526 return GetNormalizedFrequency(frequency);
1529 return kFrequencyAny;
1532 DWORD WiFiServiceImpl::GetDesiredBssList(
1533 DOT11_SSID& ssid,
1534 Frequency frequency,
1535 scoped_ptr<DOT11_BSSID_LIST>* desired_list) {
1536 if (client_ == NULL) {
1537 NOTREACHED();
1538 return ERROR_NOINTERFACE;
1541 desired_list->reset();
1543 if (frequency == kFrequencyAny)
1544 return ERROR_SUCCESS;
1546 // TODO(mef): WlanGetNetworkBssList is not available on XP. If XP support is
1547 // needed, then different method of getting BSS (e.g. OID query) will have
1548 // to be used.
1549 if (!WlanGetNetworkBssList_function_)
1550 return ERROR_NOT_SUPPORTED;
1552 DWORD error = ERROR_SUCCESS;
1553 PWLAN_BSS_LIST bss_list = NULL;
1555 error = WlanGetNetworkBssList_function_(client_,
1556 &interface_guid_,
1557 &ssid,
1558 dot11_BSS_type_infrastructure,
1559 FALSE,
1560 NULL,
1561 &bss_list);
1562 if (error == ERROR_SUCCESS && NULL != bss_list) {
1563 unsigned int best_quality = 0u;
1564 size_t best_index = 0;
1565 Frequency bss_frequency;
1567 // Go through bss_list and find best quality BSSID with matching frequency.
1568 for (size_t bss = 0; bss < bss_list->dwNumberOfItems; ++bss) {
1569 const WLAN_BSS_ENTRY& bss_entry(bss_list->wlanBssEntries[bss]);
1570 if (bss_entry.dot11Ssid.uSSIDLength != ssid.uSSIDLength ||
1571 0 != memcmp(bss_entry.dot11Ssid.ucSSID,
1572 ssid.ucSSID,
1573 bss_entry.dot11Ssid.uSSIDLength))
1574 continue;
1576 bss_frequency = GetNormalizedFrequency(
1577 bss_entry.ulChCenterFrequency / 1000);
1578 if (bss_frequency == frequency &&
1579 bss_entry.uLinkQuality > best_quality) {
1580 best_quality = bss_entry.uLinkQuality;
1581 best_index = bss;
1585 // If any matching BSS were found, prepare the header.
1586 if (best_quality > 0) {
1587 const WLAN_BSS_ENTRY& bss_entry(bss_list->wlanBssEntries[best_index]);
1588 scoped_ptr<DOT11_BSSID_LIST> selected_list(new DOT11_BSSID_LIST);
1590 selected_list->Header.Revision = DOT11_BSSID_LIST_REVISION_1;
1591 selected_list->Header.Size = sizeof(DOT11_BSSID_LIST);
1592 selected_list->Header.Type = NDIS_OBJECT_TYPE_DEFAULT;
1593 selected_list->uNumOfEntries = 1;
1594 selected_list->uTotalNumOfEntries = 1;
1595 std::copy(bss_entry.dot11Bssid,
1596 bss_entry.dot11Bssid+sizeof(bss_entry.dot11Bssid),
1597 selected_list->BSSIDs[0]);
1598 desired_list->swap(selected_list);
1599 DVLOG(1) << "Quality: " << best_quality << " BSS: "
1600 << NetworkProperties::MacAddressAsString(bss_entry.dot11Bssid);
1601 } else {
1602 error = ERROR_NOT_FOUND;
1606 // Clean up.
1607 if (bss_list != NULL) {
1608 WlanFreeMemory_function_(bss_list);
1610 return error;
1613 Frequency WiFiServiceImpl::GetNormalizedFrequency(int frequency_in_mhz) const {
1614 if (frequency_in_mhz == 0)
1615 return kFrequencyAny;
1616 if (frequency_in_mhz < 3000)
1617 return kFrequency2400;
1618 return kFrequency5000;
1621 DWORD WiFiServiceImpl::Connect(const std::string& network_guid,
1622 Frequency frequency) {
1623 if (client_ == NULL) {
1624 NOTREACHED();
1625 return ERROR_NOINTERFACE;
1628 DWORD error = ERROR_SUCCESS;
1629 DOT11_SSID ssid = SSIDFromGUID(network_guid);
1630 scoped_ptr<DOT11_BSSID_LIST> desired_bss_list;
1631 error = GetDesiredBssList(ssid, frequency, &desired_bss_list);
1632 if (error == ERROR_SUCCESS) {
1633 if (HaveProfile(network_guid)) {
1634 base::string16 profile_name = ProfileNameFromGUID(network_guid);
1635 WLAN_CONNECTION_PARAMETERS wlan_params = {
1636 wlan_connection_mode_profile,
1637 profile_name.c_str(),
1638 NULL,
1639 desired_bss_list.get(),
1640 dot11_BSS_type_any,
1642 error = WlanConnect_function_(
1643 client_, &interface_guid_, &wlan_params, NULL);
1644 } else {
1645 // If network is available, but is not open security, then it cannot be
1646 // connected without profile, so return 'access denied' error.
1647 scoped_ptr<base::DictionaryValue> properties (new base::DictionaryValue);
1648 const base::DictionaryValue* wifi;
1649 std::string wifi_security;
1650 std::string error_string;
1651 GetProperties(network_guid, properties.get(), &error_string);
1652 if (error_string.empty() &&
1653 properties->GetDictionary(onc::network_type::kWiFi, &wifi) &&
1654 wifi->GetString(onc::wifi::kSecurity, &wifi_security) &&
1655 wifi_security != onc::wifi::kSecurityNone) {
1656 error = ERROR_ACCESS_DENIED;
1657 LOG(ERROR) << error;
1658 return error;
1660 WLAN_CONNECTION_PARAMETERS wlan_params = {
1661 wlan_connection_mode_discovery_unsecure,
1662 NULL,
1663 &ssid,
1664 desired_bss_list.get(),
1665 dot11_BSS_type_infrastructure,
1667 error = WlanConnect_function_(
1668 client_, &interface_guid_, &wlan_params, NULL);
1672 return error;
1675 DWORD WiFiServiceImpl::Disconnect() {
1676 if (client_ == NULL) {
1677 NOTREACHED();
1678 return ERROR_NOINTERFACE;
1681 DWORD error = ERROR_SUCCESS;
1682 error = WlanDisconnect_function_(client_, &interface_guid_, NULL);
1683 return error;
1686 DWORD WiFiServiceImpl::SaveTempProfile(const std::string& network_guid) {
1687 if (client_ == NULL) {
1688 NOTREACHED();
1689 return ERROR_NOINTERFACE;
1692 DWORD error = ERROR_SUCCESS;
1693 base::string16 profile_name = ProfileNameFromGUID(network_guid);
1694 // TODO(mef): WlanSaveTemporaryProfile is not available on XP. If XP support
1695 // is needed, then different method of saving network profile will have to be
1696 // used.
1697 if (WlanSaveTemporaryProfile_function_) {
1698 error = WlanSaveTemporaryProfile_function_(client_,
1699 &interface_guid_,
1700 profile_name.c_str(),
1701 NULL,
1702 WLAN_PROFILE_USER,
1703 true,
1704 NULL);
1705 } else {
1706 error = ERROR_NOT_SUPPORTED;
1708 return error;
1711 DWORD WiFiServiceImpl::GetProfile(const std::string& network_guid,
1712 bool get_plaintext_key,
1713 std::string* profile_xml) {
1714 if (client_ == NULL) {
1715 NOTREACHED();
1716 return ERROR_NOINTERFACE;
1719 DWORD error = ERROR_SUCCESS;
1720 base::string16 profile_name = ProfileNameFromGUID(network_guid);
1721 DWORD flags = get_plaintext_key ? WLAN_PROFILE_GET_PLAINTEXT_KEY : 0;
1722 LPWSTR str_profile_xml = NULL;
1723 error = WlanGetProfile_function_(client_,
1724 &interface_guid_,
1725 profile_name.c_str(),
1726 NULL,
1727 &str_profile_xml,
1728 &flags,
1729 NULL);
1731 if (error == ERROR_SUCCESS && str_profile_xml != NULL) {
1732 *profile_xml = base::UTF16ToUTF8(str_profile_xml);
1734 // Clean up.
1735 if (str_profile_xml != NULL) {
1736 WlanFreeMemory_function_(str_profile_xml);
1739 return error;
1742 DWORD WiFiServiceImpl::SetProfile(bool shared,
1743 const std::string& profile_xml,
1744 bool overwrite) {
1745 DWORD error_code = ERROR_SUCCESS;
1747 base::string16 profile_xml16(base::UTF8ToUTF16(profile_xml));
1748 DWORD reason_code = 0u;
1750 error_code = WlanSetProfile_function_(client_,
1751 &interface_guid_,
1752 shared ? 0 : WLAN_PROFILE_USER,
1753 profile_xml16.c_str(),
1754 NULL,
1755 overwrite,
1756 NULL,
1757 &reason_code);
1758 return error_code;
1761 bool WiFiServiceImpl::HaveProfile(const std::string& network_guid) {
1762 std::string profile_xml;
1763 return GetProfile(network_guid, false, &profile_xml) == ERROR_SUCCESS;
1767 DWORD WiFiServiceImpl::DeleteCreatedProfile(const std::string& network_guid) {
1768 base::DictionaryValue* created_profile = NULL;
1769 DWORD error_code = ERROR_SUCCESS;
1770 // Check, whether this connection is using new created profile, and remove it.
1771 if (created_profiles_.GetDictionaryWithoutPathExpansion(
1772 network_guid, &created_profile)) {
1773 // Connection has failed, so delete it.
1774 base::string16 profile_name = ProfileNameFromGUID(network_guid);
1775 error_code = WlanDeleteProfile_function_(client_,
1776 &interface_guid_,
1777 profile_name.c_str(),
1778 NULL);
1779 created_profiles_.RemoveWithoutPathExpansion(network_guid, NULL);
1781 return error_code;
1784 std::string WiFiServiceImpl::WpaEncryptionFromEncryptionType(
1785 EncryptionType encryption_type) const {
1786 if (encryption_type == kEncryptionTypeTKIP)
1787 return kEncryptionTKIP;
1788 return kEncryptionAES;
1791 bool WiFiServiceImpl::AuthEncryptionFromSecurity(
1792 const std::string& security,
1793 EncryptionType encryption_type,
1794 std::string* authentication,
1795 std::string* encryption,
1796 std::string* key_type) const {
1797 if (security == onc::wifi::kSecurityNone) {
1798 *authentication = kAuthenticationOpen;
1799 *encryption = kEncryptionNone;
1800 } else if (security == onc::wifi::kWEP_PSK) {
1801 *authentication = kAuthenticationWepPsk;
1802 *encryption = kEncryptionWEP;
1803 *key_type = kKeyTypeNetwork;
1804 } else if (security == onc::wifi::kWPA_PSK) {
1805 *authentication = kAuthenticationWpaPsk;
1806 *encryption = WpaEncryptionFromEncryptionType(encryption_type);
1807 *key_type = kKeyTypePassphrase;
1808 } else if (security == onc::wifi::kWPA2_PSK) {
1809 *authentication = kAuthenticationWpa2Psk;
1810 *encryption = WpaEncryptionFromEncryptionType(encryption_type);
1811 *key_type = kKeyTypePassphrase;
1812 } else {
1813 return false;
1815 return true;
1818 bool WiFiServiceImpl::CreateProfile(
1819 const NetworkProperties& network_properties,
1820 EncryptionType encryption_type,
1821 std::string* profile_xml) {
1822 // Get authentication and encryption values from security.
1823 std::string authentication;
1824 std::string encryption;
1825 std::string key_type;
1826 bool valid = AuthEncryptionFromSecurity(network_properties.security,
1827 encryption_type,
1828 &authentication,
1829 &encryption,
1830 &key_type);
1831 if (!valid)
1832 return valid;
1834 // Generate profile XML.
1835 XmlWriter xml_writer;
1836 xml_writer.StartWriting();
1837 xml_writer.StartElement("WLANProfile");
1838 xml_writer.AddAttribute(
1839 "xmlns",
1840 "http://www.microsoft.com/networking/WLAN/profile/v1");
1841 xml_writer.WriteElement("name", network_properties.guid);
1842 xml_writer.StartElement("SSIDConfig");
1843 xml_writer.StartElement("SSID");
1844 xml_writer.WriteElement("name", network_properties.ssid);
1845 xml_writer.EndElement(); // Ends "SSID" element.
1846 xml_writer.EndElement(); // Ends "SSIDConfig" element.
1847 xml_writer.WriteElement("connectionType", "ESS");
1848 xml_writer.WriteElement("connectionMode", "manual");
1849 xml_writer.StartElement("MSM");
1850 xml_writer.StartElement("security");
1851 xml_writer.StartElement("authEncryption");
1852 xml_writer.WriteElement("authentication", authentication);
1853 xml_writer.WriteElement("encryption", encryption);
1854 xml_writer.WriteElement("useOneX", "false");
1855 xml_writer.EndElement(); // Ends "authEncryption" element.
1856 if (!key_type.empty()) {
1857 xml_writer.StartElement("sharedKey");
1858 xml_writer.WriteElement("keyType", key_type);
1859 xml_writer.WriteElement("protected", "false");
1860 xml_writer.WriteElement("keyMaterial", network_properties.password);
1861 xml_writer.EndElement(); // Ends "sharedKey" element.
1863 xml_writer.EndElement(); // Ends "security" element.
1864 xml_writer.EndElement(); // Ends "MSM" element.
1865 xml_writer.EndElement(); // Ends "WLANProfile" element.
1866 xml_writer.StopWriting();
1867 *profile_xml = xml_writer.GetWrittenString();
1869 return true;
1872 void WiFiServiceImpl::NotifyNetworkListChanged(const NetworkList& networks) {
1873 if (network_list_changed_observer_.is_null())
1874 return;
1876 NetworkGuidList current_networks;
1877 for (NetworkList::const_iterator it = networks.begin();
1878 it != networks.end();
1879 ++it) {
1880 current_networks.push_back(it->guid);
1883 event_task_runner_->PostTask(
1884 FROM_HERE, base::Bind(network_list_changed_observer_, current_networks));
1887 void WiFiServiceImpl::NotifyNetworkChanged(const std::string& network_guid) {
1888 if (enable_notify_network_changed_ && !networks_changed_observer_.is_null()) {
1889 DVLOG(1) << "NotifyNetworkChanged: " << network_guid;
1890 NetworkGuidList changed_networks(1, network_guid);
1891 event_task_runner_->PostTask(
1892 FROM_HERE, base::Bind(networks_changed_observer_, changed_networks));
1896 WiFiService* WiFiService::Create() { return new WiFiServiceImpl(); }
1898 } // namespace wifi