1 //
2 // Copyright (C) 2012 The Android Open Source Project
3 //
4 // Licensed under the Apache License, Version 2.0 (the "License");
5 // you may not use this file except in compliance with the License.
6 // You may obtain a copy of the License at
7 //
8 //      http://www.apache.org/licenses/LICENSE-2.0
9 //
10 // Unless required by applicable law or agreed to in writing, software
11 // distributed under the License is distributed on an "AS IS" BASIS,
12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 // See the License for the specific language governing permissions and
14 // limitations under the License.
15 //
16 
17 #ifndef SHILL_WIFI_WIFI_H_
18 #define SHILL_WIFI_WIFI_H_
19 
20 // A WiFi device represents a wireless network interface implemented as an IEEE
21 // 802.11 station.  An Access Point (AP) (or, more correctly, a Basic Service
22 // Set(BSS)) is represented by a WiFiEndpoint.  An AP provides a WiFiService,
23 // which is the same concept as Extended Service Set (ESS) in 802.11,
24 // identified by an SSID.  A WiFiService includes zero or more WiFiEndpoints
25 // that provide that service.
26 //
27 // A WiFi device interacts with a real device through WPA Supplicant.
28 // Wifi::Start() creates a connection to WPA Supplicant, represented by
29 // |supplicant_interface_proxy_|.  [1]
30 //
31 // A WiFi device becomes aware of WiFiEndpoints through BSSAdded signals from
32 // WPA Supplicant, which identifies them by a "path".  The WiFi object maintains
33 // an EndpointMap in |endpoint_by_rpcid_|, in which the key is the "path" and
34 // the value is a pointer to a WiFiEndpoint object.  When a WiFiEndpoint is
35 // added, it is associated with a WiFiService.
36 //
37 // The WiFi device connects to a WiFiService, not a WiFiEndpoint, through WPA
38 // Supplicant. It is the job of WPA Supplicant to select a BSS (aka
39 // WiFiEndpoint) to connect to.  The protocol for establishing a connection is
40 // as follows:
41 //
42 //  1.  The WiFi device sends AddNetwork to WPA Supplicant, which returns a
43 //  "network path" when done.
44 //
45 //  2.  The WiFi device sends SelectNetwork, indicating the network path
46 //  received in 1, to WPA Supplicant, which begins the process of associating
47 //  with an AP in the ESS.  At this point the WiFiService which is being
48 //  connected is called the |pending_service_|.
49 //
50 //  3.  During association to an EAP-TLS network, WPA Supplicant can send
51 //  multiple "Certification" events, which provide information about the
52 //  identity of the remote entity.
53 //
54 //  4.  When association is complete, WPA Supplicant sends a PropertiesChanged
55 //  signal to the WiFi device, indicating a change in the CurrentBSS.  The
56 //  WiFiService indicated by the new value of CurrentBSS is set as the
57 //  |current_service_|, and |pending_service_| is (normally) cleared.
58 //
59 // Some key things to notice are 1) WPA Supplicant does the work of selecting
60 // the AP (aka WiFiEndpoint) and it tells the WiFi device which AP it selected.
61 // 2) The process of connecting is asynchronous.  There is a |current_service_|
62 // to which the WiFi device is presently using and a |pending_service_| to which
63 // the WiFi device has initiated a connection.
64 //
65 // A WiFi device is notified that an AP has gone away via the BSSRemoved signal.
66 // When the last WiFiEndpoint of a WiFiService is removed, the WiFiService
67 // itself is deleted.
68 //
69 // TODO(gmorain): Add explanation of hidden SSIDs.
70 //
71 // WPA Supplicant's PropertiesChanged signal communicates changes in the state
72 // of WPA Supplicant's current service.  This state is stored in
73 // |supplicant_state_| and reflects WPA Supplicant's view of the state of the
74 // connection to an AP.  Changes in this state sometimes cause state changes in
75 // the WiFiService to which a WiFi device is connected.  For example, when WPA
76 // Supplicant signals the new state to be "completed", then the WiFiService
77 // state gets changed to "configuring".  State change notifications are not
78 // reliable because WPA Supplicant may coalesce state changes in quick
79 // succession so that only the last of the changes is signaled.
80 //
81 // Notes:
82 //
83 // 1.  Shill's definition of the interface is described in
84 // shill/dbus_proxies/supplicant-interface.xml, and the WPA Supplicant's
85 // description of the same interface is in
86 // third_party/wpa_supplicant/doc/dbus.doxygen.
87 
88 #include <time.h>
89 
90 #include <map>
91 #include <memory>
92 #include <set>
93 #include <string>
94 #include <vector>
95 
96 #include <base/callback_forward.h>
97 #include <base/cancelable_callback.h>
98 #include <base/files/file_path.h>
99 #include <base/memory/weak_ptr.h>
100 #include <gtest/gtest_prod.h>  // for FRIEND_TEST
101 #include <metrics/timer.h>
102 
103 #include "shill/device.h"
104 #include "shill/event_dispatcher.h"
105 #include "shill/key_value_store.h"
106 #include "shill/net/netlink_manager.h"
107 #include "shill/power_manager.h"
108 #include "shill/refptr_types.h"
109 #include "shill/service.h"
110 #include "shill/supplicant/supplicant_event_delegate_interface.h"
111 
112 namespace shill {
113 
114 class Error;
115 class GeolocationInfo;
116 class Mac80211Monitor;
117 class Metrics;
118 class NetlinkManager;
119 class NetlinkMessage;
120 class Nl80211Message;
121 class ScanSession;
122 class SupplicantEAPStateHandler;
123 class SupplicantInterfaceProxyInterface;
124 class SupplicantProcessProxyInterface;
125 class TDLSManager;
126 class WakeOnWiFi;
127 class WiFiProvider;
128 class WiFiService;
129 
130 // WiFi class. Specialization of Device for WiFi.
131 class WiFi : public Device, public SupplicantEventDelegateInterface {
132  public:
133   typedef std::set<uint32_t> FreqSet;
134 
135   WiFi(ControlInterface* control_interface,
136        EventDispatcher* dispatcher,
137        Metrics* metrics,
138        Manager* manager,
139        const std::string& link,
140        const std::string& address,
141        int interface_index);
142   ~WiFi() override;
143 
144   void Start(Error* error,
145              const EnabledStateChangedCallback& callback) override;
146   void Stop(Error* error, const EnabledStateChangedCallback& callback) override;
147   void Scan(ScanType scan_type, Error* error,
148             const std::string& reason) override;
149   void SetSchedScan(bool enable, Error* error) override;
150   // Callback for system suspend.
151   void OnBeforeSuspend(const ResultCallback& callback) override;
152   // Callback for dark resume.
153   void OnDarkResume(const ResultCallback& callback) override;
154   // Callback for system resume. If this WiFi device is idle, a scan
155   // is initiated. Additionally, the base class implementation is
156   // invoked unconditionally.
157   void OnAfterResume() override;
158   // Callback for when a service is configured with an IP.
159   void OnConnected() override;
160   // Callback for when a service fails to configure with an IP.
161   void OnIPConfigFailure() override;
162 
163   // Calls corresponding functions of |wake_on_wifi_|. Refer to wake_on_wifi.h
164   // for documentation.
165   void AddWakeOnPacketConnection(const std::string& ip_endpoint,
166                                  Error* error) override;
167   void RemoveWakeOnPacketConnection(const std::string& ip_endpoint,
168                                     Error* error) override;
169   void RemoveAllWakeOnPacketConnections(Error* error) override;
170 
171   // Implementation of SupplicantEventDelegateInterface.  These methods
172   // are called by SupplicantInterfaceProxy, in response to events from
173   // wpa_supplicant.
174   void BSSAdded(const std::string& BSS,
175                 const KeyValueStore& properties) override;
176   void BSSRemoved(const std::string& BSS) override;
177   void Certification(const KeyValueStore& properties) override;
178   void EAPEvent(
179       const std::string& status, const std::string& parameter) override;
180   void PropertiesChanged(const KeyValueStore& properties) override;
181   void ScanDone(const bool& success) override;
182   void TDLSDiscoverResponse(const std::string& peer_address) override;
183 
184   // Called by WiFiService.
185   virtual void ConnectTo(WiFiService* service);
186 
187   // After checking |service| state is active, initiate
188   // process of disconnecting.  Log and return if not active.
189   virtual void DisconnectFromIfActive(WiFiService* service);
190 
191   // If |service| is connected, initiate the process of disconnecting it.
192   // Otherwise, if it a pending or current service, discontinue the process
193   // of connecting and return |service| to the idle state.
194   virtual void DisconnectFrom(WiFiService* service);
195   virtual bool IsIdle() const;
196   // Clear any cached credentials wpa_supplicant may be holding for
197   // |service|.  This has a side-effect of disconnecting the service
198   // if it is connected.
199   virtual void ClearCachedCredentials(const WiFiService* service);
200 
201   // Called by WiFiEndpoint.
202   virtual void NotifyEndpointChanged(const WiFiEndpointConstRefPtr& endpoint);
203 
204   // Utility, used by WiFiService and WiFiEndpoint.
205   // Replace non-ASCII characters with '?'. Return true if one or more
206   // characters were changed.
207   static bool SanitizeSSID(std::string* ssid);
208 
209   // Formats |ssid| for logging purposes, to ease scrubbing.
210   static std::string LogSSID(const std::string& ssid);
211 
212   // Called by Linkmonitor (overridden from Device superclass).
213   void OnLinkMonitorFailure() override;
214 
215   // Called by Device when link becomes unreliable (overriden from Device
216   // superclass).
217   void OnUnreliableLink() override;
218 
IsCurrentService(const WiFiServiceRefPtr service)219   bool IsCurrentService(const WiFiServiceRefPtr service) {
220     return service.get() == current_service_.get();
221   }
222 
223   // Overridden from Device superclass
224   std::vector<GeolocationInfo> GetGeolocationObjects() const override;
225 
226   // Overridden from Device superclass
227   bool ShouldUseArpGateway() const override;
228 
229   // Called by a WiFiService when it disassociates itself from this Device.
230   virtual void DisassociateFromService(const WiFiServiceRefPtr& service);
231 
232   // Called by a WiFiService when it unloads to destroy its lease file.
233   virtual void DestroyServiceLease(const WiFiService& service);
234 
235   // Perform TDLS |operation| on |peer|.
236   std::string PerformTDLSOperation(const std::string& operation,
237                                    const std::string& peer,
238                                    Error* error) override;
239 
240   // Overridden from Device superclass.
241   bool IsTrafficMonitorEnabled() const override;
242 
243   // Remove all networks from WPA supplicant.
244   // Passed as a callback to |wake_on_wifi_| where it is used.
245   void RemoveSupplicantNetworks();
246 
247   bool RequestRoam(const std::string& addr, Error* error) override;
248 
249  private:
250   enum ScanMethod {
251     kScanMethodNone,
252     kScanMethodFull,
253     kScanMethodProgressive,
254     kScanMethodProgressiveErrorToFull,
255     kScanMethodProgressiveFinishedToFull
256   };
257   enum ScanState {
258     kScanIdle,
259     kScanScanning,
260     kScanBackgroundScanning,
261     kScanTransitionToConnecting,
262     kScanConnecting,
263     kScanConnected,
264     kScanFoundNothing
265   };
266 
267   // Result from a BSSAdded or BSSRemoved event.
268   struct ScanResult {
ScanResultScanResult269     ScanResult() : is_removal(false) {}
ScanResultScanResult270     ScanResult(const std::string& path_in,
271                const KeyValueStore& properties_in,
272                bool is_removal_in)
273         : path(path_in), properties(properties_in), is_removal(is_removal_in) {}
274     std::string path;
275     KeyValueStore properties;
276     bool is_removal;
277   };
278 
279   struct PendingScanResults {
PendingScanResultsPendingScanResults280     PendingScanResults() : is_complete(false) {}
PendingScanResultsPendingScanResults281     explicit PendingScanResults(const base::Closure& process_results_callback)
282         : is_complete(false), callback(process_results_callback) {}
283 
284     // List of pending scan results to process.
285     std::vector<ScanResult> results;
286 
287     // If true, denotes that the scan is complete (ScanDone() was called).
288     bool is_complete;
289 
290     // Cancelable closure used to process the scan results.
291     base::CancelableClosure callback;
292   };
293 
294   friend class WiFiObjectTest;  // access to supplicant_*_proxy_, link_up_
295   friend class WiFiTimerTest;  // kNumFastScanAttempts, kFastScanIntervalSeconds
296   friend class WiFiMainTest;  // ScanState, ScanMethod
297   FRIEND_TEST(WiFiMainTest, AppendBgscan);
298   FRIEND_TEST(WiFiMainTest, BackgroundScan);  // ScanMethod, ScanState
299   FRIEND_TEST(WiFiMainTest, ConnectToServiceNotPending);  // ScanState
300   FRIEND_TEST(WiFiMainTest, ConnectToWithError);  // ScanState
301   FRIEND_TEST(WiFiMainTest, ConnectWhileNotScanning);  // ScanState
302   FRIEND_TEST(WiFiMainTest, CurrentBSSChangedUpdateServiceEndpoint);
303   FRIEND_TEST(WiFiMainTest, DisconnectReasonUpdated);
304   FRIEND_TEST(WiFiMainTest, DisconnectReasonCleared);
305   FRIEND_TEST(WiFiMainTest, FlushBSSOnResume);  // kMaxBSSResumeAgeSeconds
306   FRIEND_TEST(WiFiMainTest, FullScanConnecting);  // ScanMethod, ScanState
307   FRIEND_TEST(WiFiMainTest, FullScanConnectingToConnected);
308   FRIEND_TEST(WiFiMainTest, FullScanDuringProgressive);  // ScanState
309   FRIEND_TEST(WiFiMainTest, FullScanFindsNothing);  // ScanMethod, ScanState
310   FRIEND_TEST(WiFiMainTest, InitialSupplicantState);  // kInterfaceStateUnknown
311   FRIEND_TEST(WiFiMainTest, LinkMonitorFailure);  // set_link_monitor()
312   FRIEND_TEST(WiFiMainTest, NoScansWhileConnecting_FullScan);  // ScanState
313   FRIEND_TEST(WiFiMainTest, NoScansWhileConnecting);  // ScanState
314   FRIEND_TEST(WiFiMainTest, PendingScanEvents);  // EndpointMap
315   FRIEND_TEST(WiFiMainTest, ProgressiveScanConnectingToConnected);
316   FRIEND_TEST(WiFiMainTest, ProgressiveScanConnectingToNotFound);
317   FRIEND_TEST(WiFiMainTest, ProgressiveScanDuringFull);  // ScanState
318   FRIEND_TEST(WiFiMainTest, ProgressiveScanError);  // ScanMethod, ScanState
319   FRIEND_TEST(WiFiMainTest, ProgressiveScanFound);  // ScanMethod, ScanState
320   FRIEND_TEST(WiFiMainTest, ProgressiveScanNotFound);  // ScanMethod, ScanState
321   FRIEND_TEST(WiFiMainTest, ScanRejected);  // ScanState
322   FRIEND_TEST(WiFiMainTest, ScanResults);             // EndpointMap
323   FRIEND_TEST(WiFiMainTest, ScanResultsWithUpdates);  // EndpointMap
324   FRIEND_TEST(WiFiMainTest, ScanStateHandleDisconnect);  // ScanState
325   FRIEND_TEST(WiFiMainTest, ScanStateNotScanningNoUma);  // ScanState
326   FRIEND_TEST(WiFiMainTest, ScanStateUma);  // ScanState, ScanMethod
327   FRIEND_TEST(WiFiMainTest, Stop);  // weak_ptr_factory_
328   FRIEND_TEST(WiFiMainTest, TimeoutPendingServiceWithEndpoints);
329   FRIEND_TEST(WiFiPropertyTest, BgscanMethodProperty);  // bgscan_method_
330   FRIEND_TEST(WiFiTimerTest, FastRescan);  // kFastScanIntervalSeconds
331   FRIEND_TEST(WiFiTimerTest, RequestStationInfo);  // kRequestStationInfoPeriod
332   // kPostWakeConnectivityReportDelayMilliseconds
333   FRIEND_TEST(WiFiTimerTest, ResumeDispatchesConnectivityReportTask);
334   // kFastScanIntervalSeconds
335   FRIEND_TEST(WiFiTimerTest, StartScanTimer_HaveFastScansRemaining);
336   FRIEND_TEST(WiFiMainTest, ParseWiphyIndex_Success);  // kDefaultWiphyIndex
337   // ScanMethod, ScanState
338   FRIEND_TEST(WiFiMainTest, ResetScanStateWhenScanFailed);
339   // kPostScanFailedDelayMilliseconds
340   FRIEND_TEST(WiFiTimerTest, ScanDoneDispatchesTasks);
341   // kMaxPassiveScanRetries, kMaxFreqsForPassiveScanRetries
342   FRIEND_TEST(WiFiMainTest, InitiateScanInDarkResume_Idle);
343 
344   typedef std::map<const std::string, WiFiEndpointRefPtr> EndpointMap;
345   typedef std::map<const WiFiService*, std::string> ReverseServiceMap;
346 
347   static const char* kDefaultBgscanMethod;
348   static const uint16_t kBackgroundScanIntervalSeconds;
349   static const uint16_t kDefaultBgscanShortIntervalSeconds;
350   static const int32_t kDefaultBgscanSignalThresholdDbm;
351   static const uint16_t kDefaultRoamThresholdDb;
352   static const uint16_t kDefaultScanIntervalSeconds;
353   static const time_t kMaxBSSResumeAgeSeconds;
354   static const char kInterfaceStateUnknown[];
355   // Delay between scans when supplicant finds "No suitable network".
356   static const time_t kRescanIntervalSeconds;
357   // Number of times to quickly attempt a scan after startup / disconnect.
358   static const int kNumFastScanAttempts;
359   static const int kFastScanIntervalSeconds;
360   static const int kPendingTimeoutSeconds;
361   static const int kReconnectTimeoutSeconds;
362   static const int kRequestStationInfoPeriodSeconds;
363   static const size_t kMinumumFrequenciesToScan;
364   static const float kDefaultFractionPerScan;
365   static const size_t kStuckQueueLengthThreshold;
366   // Number of milliseconds to wait after waking from suspend to report the
367   // connection status to metrics.
368   static const int kPostWakeConnectivityReportDelayMilliseconds;
369   // Used to instantiate |wiphy_index_| in WiFi. Assigned a large value so that
370   // any attempts to match the default value of |wiphy_index_| against an actual
371   // wiphy index reported in an NL80211 message will fail.
372   static const uint32_t kDefaultWiphyIndex;
373   // Number of milliseconds to wait after failing to launch a scan before
374   // resetting the scan state to idle.
375   static const int kPostScanFailedDelayMilliseconds;
376   // Used to distinguish between a disconnect reason explicitly set by
377   // supplicant and a default.
378   static const int kDefaultDisconnectReason;
379 
380   void GetPhyInfo();
381   void AppendBgscan(WiFiService* service,
382                     KeyValueStore* service_params) const;
383   std::string GetBgscanMethod(const int& argument, Error* error);
GetBgscanShortInterval(Error *)384   uint16_t GetBgscanShortInterval(Error* /* error */) {
385     return bgscan_short_interval_seconds_;
386   }
GetBgscanSignalThreshold(Error *)387   int32_t GetBgscanSignalThreshold(Error* /* error */) {
388     return bgscan_signal_threshold_dbm_;
389   }
390   // These methods can't be 'const' because they are passed to
391   // HelpRegisterDerivedUint16 which don't take const methods.
GetRoamThreshold(Error *)392   uint16_t GetRoamThreshold(Error* /* error */) /*const*/ {
393     return roam_threshold_db_;
394   }
GetScanInterval(Error *)395   uint16_t GetScanInterval(Error* /* error */) /*const*/ {
396     return scan_interval_seconds_;
397   }
398 
399   // RPC accessor for |link_statistics_|.
400   KeyValueStore GetLinkStatistics(Error* error);
401 
402   bool GetScanPending(Error* /* error */);
403   bool SetBgscanMethod(
404       const int& argument, const std::string& method, Error* error);
405   bool SetBgscanShortInterval(const uint16_t& seconds, Error* error);
406   bool SetBgscanSignalThreshold(const int32_t& dbm, Error* error);
407   bool SetRoamThreshold(const uint16_t& threshold, Error* /*error*/);
408   bool SetScanInterval(const uint16_t& seconds, Error* error);
409   void ClearBgscanMethod(const int& argument, Error* error);
410 
411   void CurrentBSSChanged(const std::string& new_bss);
412   void DisconnectReasonChanged(const int32_t new_disconnect_reason);
413   // Return the RPC identifier associated with the wpa_supplicant network
414   // entry created for |service|.  If one does not exist, an empty string
415   // is returned, and |error| is populated.
416   std::string FindNetworkRpcidForService(const WiFiService* service,
417                                          Error* error);
418   void HandleDisconnect();
419   // Update failure and state for disconnected service.
420   // Set failure for disconnected service if disconnect is not user-initiated
421   // and failure is not already set. Then set the state of the service back
422   // to idle, so it can be used for future connections.
423   void ServiceDisconnected(WiFiServiceRefPtr service);
424   void HandleRoam(const std::string& new_bssid);
425   void BSSAddedTask(const std::string& BSS,
426                     const KeyValueStore& properties);
427   void BSSRemovedTask(const std::string& BSS);
428   void CertificationTask(const KeyValueStore& properties);
429   void EAPEventTask(const std::string& status, const std::string& parameter);
430   void PropertiesChangedTask(const KeyValueStore& properties);
431   void ScanDoneTask();
432   void ScanFailedTask();
433   // UpdateScanStateAfterScanDone is spawned as a task from ScanDoneTask in
434   // order to guarantee that it is run after the start of any connections that
435   // result from a scan.  This works because supplicant sends all BSSAdded
436   // signals to shill before it sends a ScanDone signal.  The code that
437   // handles those signals launch tasks such that the tasks have the following
438   // dependencies (an arrow from X->Y indicates X is guaranteed to run before
439   // Y):
440   //
441   // [BSSAdded]-->[BssAddedTask]-->[SortServiceTask (calls ConnectTo)]
442   //     |              |                 |
443   //     V              V                 V
444   // [ScanDone]-->[ScanDoneTask]-->[UpdateScanStateAfterScanDone]
445   void UpdateScanStateAfterScanDone();
446   void ScanTask();
447   void StateChanged(const std::string& new_state);
448   // Heuristic check if a connection failure was due to bad credentials.
449   // Returns true and puts type of failure in |failure| if a credential
450   // problem is detected.
451   bool SuspectCredentials(WiFiServiceRefPtr service,
452                           Service::ConnectFailure* failure) const;
453   void HelpRegisterDerivedInt32(
454       PropertyStore* store,
455       const std::string& name,
456       int32_t(WiFi::*get)(Error* error),
457       bool(WiFi::*set)(const int32_t& value, Error* error));
458   void HelpRegisterDerivedUint16(
459       PropertyStore* store,
460       const std::string& name,
461       uint16_t(WiFi::*get)(Error* error),
462       bool(WiFi::*set)(const uint16_t& value, Error* error));
463   void HelpRegisterConstDerivedBool(
464       PropertyStore* store,
465       const std::string& name,
466       bool(WiFi::*get)(Error* error));
467 
468   // Disable a network entry in wpa_supplicant, and catch any exception
469   // that occurs.  Returns false if an exception occurred, true otherwise.
470   bool DisableNetwork(const std::string& network);
471   // Disable the wpa_supplicant network entry associated with |service|.
472   // Any cached credentials stored in wpa_supplicant related to this
473   // network entry will be preserved.  This will have the side-effect of
474   // disconnecting this service if it is currently connected.  Returns
475   // true if successful, otherwise returns false and populates |error|
476   // with the reason for failure.
477   virtual bool DisableNetworkForService(
478       const WiFiService* service, Error* error);
479   // Remove a network entry from wpa_supplicant, and catch any exception
480   // that occurs.  Returns false if an exception occurred, true otherwise.
481   bool RemoveNetwork(const std::string& network);
482   // Remove the wpa_supplicant network entry associated with |service|.
483   // Any cached credentials stored in wpa_supplicant related to this
484   // network entry will be removed.  This will have the side-effect of
485   // disconnecting this service if it is currently connected.  Returns
486   // true if successful, otherwise returns false and populates |error|
487   // with the reason for failure.
488   virtual bool RemoveNetworkForService(
489       const WiFiService* service, Error* error);
490   // Update disable_ht40 setting in wpa_supplicant for the given service.
491   void SetHT40EnableForService(const WiFiService* service, bool enable);
492   // Perform the next in a series of progressive scans.
493   void ProgressiveScanTask();
494   // Task to configure scheduled scan in wpa_supplicant.
495   void SetSchedScanTask(bool enable);
496   // Recovers from failed progressive scan.
497   void OnFailedProgressiveScan();
498   // Restart fast scanning after disconnection.
499   void RestartFastScanAttempts();
500   // Schedules a scan attempt at time |scan_interval_seconds_| in the
501   // future.  Cancels any currently pending scan timer.
502   void StartScanTimer();
503   // Cancels any currently pending scan timer.
504   void StopScanTimer();
505   // Initiates a scan, if idle. Reschedules the scan timer regardless.
506   void ScanTimerHandler();
507   // Abort any current scan (at the shill-level; let any request that's
508   // already gone out finish).
509   void AbortScan();
510   // Abort any current scan and start a new scan of type |type| if shill is
511   // currently idle.
512   void InitiateScan(ScanType scan_type);
513   // Suppresses manager auto-connects and flushes supplicant BSS cache, then
514   // triggers the passive scan. Meant for use in dark resume where we want to
515   // ensure that shill and supplicant do not use stale information to launch
516   // connection attempts.
517   void InitiateScanInDarkResume(const FreqSet& freqs);
518   // If |freqs| contains at least one frequency channel a passive scan is
519   // launched on all the frequencies in |freqs|. Otherwise, a passive scan is
520   // launched on all channels.
521   void TriggerPassiveScan(const FreqSet& freqs);
522   // Starts a timer in order to limit the length of an attempt to
523   // connect to a pending network.
524   void StartPendingTimer();
525   // Cancels any currently pending network timer.
526   void StopPendingTimer();
527   // Aborts a pending network that is taking too long to connect.
528   void PendingTimeoutHandler();
529   // Starts a timer in order to limit the length of an attempt to
530   // reconnect to the current network.
531   void StartReconnectTimer();
532   // Stops any pending reconnect timer.
533   void StopReconnectTimer();
534   // Disconnects from the current service that is taking too long
535   // to reconnect on its own.
536   void ReconnectTimeoutHandler();
537   // Sets the current pending service.  If the argument is non-NULL,
538   // the Pending timer is started and the associated service is set
539   // to "Associating", otherwise it is stopped.
540   void SetPendingService(const WiFiServiceRefPtr& service);
541 
542   void OnSupplicantAppear();
543   void OnSupplicantVanish();
544   // Called by ScopeLogger when WiFi debug scope is enabled/disabled.
545   void OnWiFiDebugScopeChanged(bool enabled);
546   // Enable or disable debugging for the current connection attempt.
547   void SetConnectionDebugging(bool enabled);
548   // Enable high bitrates for the current network.  High rates are disabled
549   // on the initial association and every reassociation afterward.
550   void EnableHighBitrates();
551 
552   // Request and retrieve information about the currently connected station.
553   void RequestStationInfo();
554   void OnReceivedStationInfo(const Nl80211Message& nl80211_message);
555   void StopRequestingStationInfo();
556 
557   void ConnectToSupplicant();
558 
559   void Restart();
560 
561   std::string GetServiceLeaseName(const WiFiService& service);
562 
563   // Netlink message handler for NL80211_CMD_NEW_WIPHY messages; copies
564   // device's supported frequencies from that message into
565   // |all_scan_frequencies_|.
566   void OnNewWiphy(const Nl80211Message& nl80211_message);
567 
568   void OnTriggerPassiveScanResponse(const Nl80211Message& netlink_message);
569 
570   void SetScanState(ScanState new_state,
571                     ScanMethod new_method,
572                     const char* reason);
573   void ReportScanResultToUma(ScanState state, ScanMethod method);
574   static std::string ScanStateString(ScanState state, ScanMethod type);
575 
576   // In addition to calling the implementations of these functions in Device,
577   // calls WakeOnWiFi::PrepareForWakeOnWiFiBeforeSuspend.
578   void OnIPConfigUpdated(const IPConfigRefPtr& ipconfig,
579                          bool new_lease_acquired) override;
580   void OnIPv6ConfigUpdated() override;
581 
582   // Returns true iff the WiFi device is connected to the current service.
583   bool IsConnectedToCurrentService();
584 
585   // Callback invoked to report whether this WiFi device is connected to
586   // a service after waking from suspend. Wraps around a Call the function
587   // with the same name in WakeOnWiFi.
588   void ReportConnectedToServiceAfterWake();
589 
590   // Add a scan result to the list of pending scan results, and post a task
591   // for handling these results if one is not already running.
592   void AddPendingScanResult(const std::string& path,
593                             const KeyValueStore& properties,
594                             bool is_removal);
595 
596   // Callback invoked to handle pending scan results from AddPendingScanResult.
597   void PendingScanResultsHandler();
598 
599   // Given a NL80211_CMD_NEW_WIPHY message |nl80211_message|, parses the
600   // wiphy index of the NIC and sets |wiphy_index_| with the parsed index.
601   // Returns true iff the wiphy index was parsed successfully, false otherwise.
602   bool ParseWiphyIndex(const Nl80211Message& nl80211_message);
603 
604   // Callback invoked when the kernel broadcasts a notification that a scan has
605   // started.
606   virtual void OnScanStarted(const NetlinkMessage& netlink_message);
607 
608   // Helper function for setting supplicant_interface_proxy_ pointer.
609   void SetSupplicantInterfaceProxy(
610       SupplicantInterfaceProxyInterface* supplicant_interface_proxy);
611 
612   // Pointer to the provider object that maintains WiFiService objects.
613   WiFiProvider* provider_;
614 
615   base::WeakPtrFactory<WiFi> weak_ptr_factory_;
616 
617   // Store cached copies of singletons for speed/ease of testing.
618   Time* time_;
619 
620   bool supplicant_present_;
621 
622   std::unique_ptr<SupplicantProcessProxyInterface> supplicant_process_proxy_;
623   std::unique_ptr<SupplicantInterfaceProxyInterface>
624       supplicant_interface_proxy_;
625   // wpa_supplicant's RPC path for this device/interface.
626   std::string supplicant_interface_path_;
627   // The rpcid used as the key is wpa_supplicant's D-Bus path for the
628   // Endpoint (BSS, in supplicant parlance).
629   EndpointMap endpoint_by_rpcid_;
630   // Map from Services to the D-Bus path for the corresponding wpa_supplicant
631   // Network.
632   ReverseServiceMap rpcid_by_service_;
633   // The Service we are presently connected to. May be nullptr is we're not
634   // not connected to any Service.
635   WiFiServiceRefPtr current_service_;
636   // The Service we're attempting to connect to. May be nullptr if we're
637   // not attempting to connect to a new Service. If non-NULL, should
638   // be distinct from |current_service_|. (A service should not
639   // simultaneously be both pending, and current.)
640   WiFiServiceRefPtr pending_service_;
641   std::string supplicant_state_;
642   std::string supplicant_bss_;
643   int32_t supplicant_disconnect_reason_;
644   std::string phy_name_;
645   // Indicates that we should flush supplicant's BSS cache after the
646   // next scan completes.
647   bool need_bss_flush_;
648   struct timeval resumed_at_;
649   // Executes when the (foreground) scan timer expires. Calls ScanTimerHandler.
650   base::CancelableClosure scan_timer_callback_;
651   // Executes when a pending service connect timer expires. Calls
652   // PendingTimeoutHandler.
653   base::CancelableClosure pending_timeout_callback_;
654   // Executes when a reconnecting service timer expires. Calls
655   // ReconnectTimeoutHandler.
656   base::CancelableClosure reconnect_timeout_callback_;
657   // Executes periodically while a service is connected, to update the
658   // signal strength from the currently connected AP.
659   base::CancelableClosure request_station_info_callback_;
660   // Executes when WPA supplicant reports that a scan has failed via a ScanDone
661   // signal.
662   base::CancelableClosure scan_failed_callback_;
663   // Number of remaining fast scans to be done during startup and disconnect.
664   int fast_scans_remaining_;
665   // Indicates that the current BSS has reached the completed state according
666   // to supplicant.
667   bool has_already_completed_;
668   // Indicates that the current BSS for a connected service has changed, which
669   // implies that a driver-based roam has been initiated.  If this roam
670   // succeeds, we should renew our lease.
671   bool is_roaming_in_progress_;
672   // Indicates that we are debugging a problematic connection.
673   bool is_debugging_connection_;
674   // Tracks the process of an EAP negotiation.
675   std::unique_ptr<SupplicantEAPStateHandler> eap_state_handler_;
676   // Tracks mac80211 state, to diagnose problems such as queue stalls.
677   std::unique_ptr<Mac80211Monitor> mac80211_monitor_;
678 
679   // Properties
680   std::string bgscan_method_;
681   uint16_t bgscan_short_interval_seconds_;
682   int32_t bgscan_signal_threshold_dbm_;
683   uint16_t roam_threshold_db_;
684   uint16_t scan_interval_seconds_;
685 
686   bool progressive_scan_enabled_;
687   std::string scan_configuration_;
688   NetlinkManager* netlink_manager_;
689   std::set<uint16_t> all_scan_frequencies_;
690   std::unique_ptr<ScanSession> scan_session_;
691   size_t min_frequencies_to_scan_;
692   size_t max_frequencies_to_scan_;
693   bool scan_all_frequencies_;
694 
695   // Holds the list of scan results waiting to be processed and a cancelable
696   // closure for processing the pending tasks in PendingScanResultsHandler().
697   std::unique_ptr<PendingScanResults> pending_scan_results_;
698 
699   // Fraction of previously seen scan frequencies to include in each
700   // progressive scan batch (since the frequencies are sorted, the sum of the
701   // fraction_per_scan_ over the scans in a session (* 100) is the percentile
702   // of the frequencies that have been scanned).
703   float fraction_per_scan_;
704 
705   ScanState scan_state_;
706   ScanMethod scan_method_;
707   chromeos_metrics::Timer scan_timer_;
708 
709   // Used to compute the number of bytes received since the link went up.
710   uint64_t receive_byte_count_at_connect_;
711 
712   // Used to report the current state of our wireless link.
713   KeyValueStore link_statistics_;
714 
715   // Wiphy interface index of this WiFi device.
716   uint32_t wiphy_index_;
717 
718   std::unique_ptr<WakeOnWiFi> wake_on_wifi_;
719 
720   std::unique_ptr<TDLSManager> tdls_manager_;
721 
722   DISALLOW_COPY_AND_ASSIGN(WiFi);
723 };
724 
725 }  // namespace shill
726 
727 #endif  // SHILL_WIFI_WIFI_H_
728