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