WifiMonitor.java revision 82b91fd1a87ae9000bac54fb44981d5003958de1
1/*
2 * Copyright (C) 2008 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
17package com.android.server.wifi;
18
19import android.net.NetworkInfo;
20import android.net.wifi.SupplicantState;
21import android.net.wifi.WifiManager;
22import android.net.wifi.WifiSsid;
23import android.net.wifi.p2p.WifiP2pConfig;
24import android.net.wifi.p2p.WifiP2pDevice;
25import android.net.wifi.p2p.WifiP2pGroup;
26import android.net.wifi.p2p.WifiP2pProvDiscEvent;
27import android.net.wifi.p2p.nsd.WifiP2pServiceResponse;
28import android.os.Message;
29import android.os.SystemClock;
30import android.util.Log;
31
32import com.android.server.wifi.p2p.WifiP2pServiceImpl.P2pStatus;
33
34import com.android.internal.util.Protocol;
35import com.android.internal.util.StateMachine;
36
37import java.util.HashMap;
38import java.util.List;
39import java.util.regex.Matcher;
40import java.util.regex.Pattern;
41
42/**
43 * Listens for events from the wpa_supplicant server, and passes them on
44 * to the {@link StateMachine} for handling. Runs in its own thread.
45 *
46 * @hide
47 */
48public class WifiMonitor {
49
50    private static final boolean DBG = false;
51    private static final String TAG = "WifiMonitor";
52
53    /** Events we receive from the supplicant daemon */
54
55    private static final int CONNECTED    = 1;
56    private static final int DISCONNECTED = 2;
57    private static final int STATE_CHANGE = 3;
58    private static final int SCAN_RESULTS = 4;
59    private static final int LINK_SPEED   = 5;
60    private static final int TERMINATING  = 6;
61    private static final int DRIVER_STATE = 7;
62    private static final int EAP_FAILURE  = 8;
63    private static final int ASSOC_REJECT = 9;
64    private static final int SSID_TEMP_DISABLE = 10;
65    private static final int SSID_REENABLE = 11;
66    private static final int UNKNOWN      = 12;
67
68    /** All events coming from the supplicant start with this prefix */
69    private static final String EVENT_PREFIX_STR = "CTRL-EVENT-";
70    private static final int EVENT_PREFIX_LEN_STR = EVENT_PREFIX_STR.length();
71
72    /** All WPA events coming from the supplicant start with this prefix */
73    private static final String WPA_EVENT_PREFIX_STR = "WPA:";
74    private static final String PASSWORD_MAY_BE_INCORRECT_STR =
75       "pre-shared key may be incorrect";
76
77    /* WPS events */
78    private static final String WPS_SUCCESS_STR = "WPS-SUCCESS";
79
80    /* Format: WPS-FAIL msg=%d [config_error=%d] [reason=%d (%s)] */
81    private static final String WPS_FAIL_STR    = "WPS-FAIL";
82    private static final String WPS_FAIL_PATTERN =
83            "WPS-FAIL msg=\\d+(?: config_error=(\\d+))?(?: reason=(\\d+))?";
84
85    /* config error code values for config_error=%d */
86    private static final int CONFIG_MULTIPLE_PBC_DETECTED = 12;
87    private static final int CONFIG_AUTH_FAILURE = 18;
88
89    /* reason code values for reason=%d */
90    private static final int REASON_TKIP_ONLY_PROHIBITED = 1;
91    private static final int REASON_WEP_PROHIBITED = 2;
92
93    private static final String WPS_OVERLAP_STR = "WPS-OVERLAP-DETECTED";
94    private static final String WPS_TIMEOUT_STR = "WPS-TIMEOUT";
95
96    /* Hotspot 2.0 ANQP query events */
97    private static final String GAS_QUERY_PREFIX_STR = "GAS-QUERY-";
98    private static final String GAS_QUERY_START_STR = "GAS-QUERY-START";
99    private static final String GAS_QUERY_DONE_STR = "GAS-QUERY-DONE";
100    private static final String RX_HS20_ANQP_ICON_STR = "RX-HS20-ANQP-ICON";
101    private static final int RX_HS20_ANQP_ICON_STR_LEN = RX_HS20_ANQP_ICON_STR.length();
102
103    /* Hotspot 2.0 events */
104    private static final String HS20_PREFIX_STR = "HS20-";
105    private static final String HS20_SUB_REM_STR = "HS20-SUBSCRIPTION-REMEDIATION";
106    private static final String HS20_DEAUTH_STR = "HS20-DEAUTH-IMMINENT-NOTICE";
107
108    /**
109     * Names of events from wpa_supplicant (minus the prefix). In the
110     * format descriptions, * &quot;<code>x</code>&quot;
111     * designates a dynamic value that needs to be parsed out from the event
112     * string
113     */
114    /**
115     * <pre>
116     * CTRL-EVENT-CONNECTED - Connection to xx:xx:xx:xx:xx:xx completed
117     * </pre>
118     * <code>xx:xx:xx:xx:xx:xx</code> is the BSSID of the associated access point
119     */
120    private static final String CONNECTED_STR =    "CONNECTED";
121    /**
122     * <pre>
123     * CTRL-EVENT-DISCONNECTED - Disconnect event - remove keys
124     * </pre>
125     */
126    private static final String DISCONNECTED_STR = "DISCONNECTED";
127    /**
128     * <pre>
129     * CTRL-EVENT-STATE-CHANGE x
130     * </pre>
131     * <code>x</code> is the numerical value of the new state.
132     */
133    private static final String STATE_CHANGE_STR =  "STATE-CHANGE";
134    /**
135     * <pre>
136     * CTRL-EVENT-SCAN-RESULTS ready
137     * </pre>
138     */
139    private static final String SCAN_RESULTS_STR =  "SCAN-RESULTS";
140
141    /**
142     * <pre>
143     * CTRL-EVENT-LINK-SPEED x Mb/s
144     * </pre>
145     * {@code x} is the link speed in Mb/sec.
146     */
147    private static final String LINK_SPEED_STR = "LINK-SPEED";
148    /**
149     * <pre>
150     * CTRL-EVENT-TERMINATING - signal x
151     * </pre>
152     * <code>x</code> is the signal that caused termination.
153     */
154    private static final String TERMINATING_STR =  "TERMINATING";
155    /**
156     * <pre>
157     * CTRL-EVENT-DRIVER-STATE state
158     * </pre>
159     * <code>state</code> can be HANGED
160     */
161    private static final String DRIVER_STATE_STR = "DRIVER-STATE";
162    /**
163     * <pre>
164     * CTRL-EVENT-EAP-FAILURE EAP authentication failed
165     * </pre>
166     */
167    private static final String EAP_FAILURE_STR = "EAP-FAILURE";
168
169    /**
170     * This indicates an authentication failure on EAP FAILURE event
171     */
172    private static final String EAP_AUTH_FAILURE_STR = "EAP authentication failed";
173
174    /**
175     * This indicates an assoc reject event
176     */
177    private static final String ASSOC_REJECT_STR = "ASSOC-REJECT";
178
179    /**
180     * This indicates auth or association failure bad enough so as network got disabled
181     * - WPA_PSK auth failure suspecting shared key mismatch
182     * - failed multiple Associations
183     */
184    private static final String TEMP_DISABLED_STR = "SSID-TEMP-DISABLED";
185
186    /**
187     * This indicates a previously disabled SSID was reenabled by supplicant
188     */
189    private static final String REENABLED_STR = "SSID-REENABLED";
190
191
192    /**
193     * Regex pattern for extracting an Ethernet-style MAC address from a string.
194     * Matches a strings like the following:<pre>
195     * CTRL-EVENT-CONNECTED - Connection to 00:1e:58:ec:d5:6d completed (reauth) [id=1 id_str=]</pre>
196     */
197    private static Pattern mConnectedEventPattern =
198        Pattern.compile("((?:[0-9a-f]{2}:){5}[0-9a-f]{2}) .* \\[id=([0-9]+) ");
199
200    /** P2P events */
201    private static final String P2P_EVENT_PREFIX_STR = "P2P";
202
203    /* P2P-DEVICE-FOUND fa:7b:7a:42:02:13 p2p_dev_addr=fa:7b:7a:42:02:13 pri_dev_type=1-0050F204-1
204       name='p2p-TEST1' config_methods=0x188 dev_capab=0x27 group_capab=0x0 */
205    private static final String P2P_DEVICE_FOUND_STR = "P2P-DEVICE-FOUND";
206
207    /* P2P-DEVICE-LOST p2p_dev_addr=42:fc:89:e1:e2:27 */
208    private static final String P2P_DEVICE_LOST_STR = "P2P-DEVICE-LOST";
209
210    /* P2P-FIND-STOPPED */
211    private static final String P2P_FIND_STOPPED_STR = "P2P-FIND-STOPPED";
212
213    /* P2P-GO-NEG-REQUEST 42:fc:89:a8:96:09 dev_passwd_id=4 */
214    private static final String P2P_GO_NEG_REQUEST_STR = "P2P-GO-NEG-REQUEST";
215
216    private static final String P2P_GO_NEG_SUCCESS_STR = "P2P-GO-NEG-SUCCESS";
217
218    /* P2P-GO-NEG-FAILURE status=x */
219    private static final String P2P_GO_NEG_FAILURE_STR = "P2P-GO-NEG-FAILURE";
220
221    private static final String P2P_GROUP_FORMATION_SUCCESS_STR =
222            "P2P-GROUP-FORMATION-SUCCESS";
223
224    private static final String P2P_GROUP_FORMATION_FAILURE_STR =
225            "P2P-GROUP-FORMATION-FAILURE";
226
227    /* P2P-GROUP-STARTED p2p-wlan0-0 [client|GO] ssid="DIRECT-W8" freq=2437
228       [psk=2182b2e50e53f260d04f3c7b25ef33c965a3291b9b36b455a82d77fd82ca15bc|passphrase="fKG4jMe3"]
229       go_dev_addr=fa:7b:7a:42:02:13 [PERSISTENT] */
230    private static final String P2P_GROUP_STARTED_STR = "P2P-GROUP-STARTED";
231
232    /* P2P-GROUP-REMOVED p2p-wlan0-0 [client|GO] reason=REQUESTED */
233    private static final String P2P_GROUP_REMOVED_STR = "P2P-GROUP-REMOVED";
234
235    /* P2P-INVITATION-RECEIVED sa=fa:7b:7a:42:02:13 go_dev_addr=f8:7b:7a:42:02:13
236        bssid=fa:7b:7a:42:82:13 unknown-network */
237    private static final String P2P_INVITATION_RECEIVED_STR = "P2P-INVITATION-RECEIVED";
238
239    /* P2P-INVITATION-RESULT status=1 */
240    private static final String P2P_INVITATION_RESULT_STR = "P2P-INVITATION-RESULT";
241
242    /* P2P-PROV-DISC-PBC-REQ 42:fc:89:e1:e2:27 p2p_dev_addr=42:fc:89:e1:e2:27
243       pri_dev_type=1-0050F204-1 name='p2p-TEST2' config_methods=0x188 dev_capab=0x27
244       group_capab=0x0 */
245    private static final String P2P_PROV_DISC_PBC_REQ_STR = "P2P-PROV-DISC-PBC-REQ";
246
247    /* P2P-PROV-DISC-PBC-RESP 02:12:47:f2:5a:36 */
248    private static final String P2P_PROV_DISC_PBC_RSP_STR = "P2P-PROV-DISC-PBC-RESP";
249
250    /* P2P-PROV-DISC-ENTER-PIN 42:fc:89:e1:e2:27 p2p_dev_addr=42:fc:89:e1:e2:27
251       pri_dev_type=1-0050F204-1 name='p2p-TEST2' config_methods=0x188 dev_capab=0x27
252       group_capab=0x0 */
253    private static final String P2P_PROV_DISC_ENTER_PIN_STR = "P2P-PROV-DISC-ENTER-PIN";
254    /* P2P-PROV-DISC-SHOW-PIN 42:fc:89:e1:e2:27 44490607 p2p_dev_addr=42:fc:89:e1:e2:27
255       pri_dev_type=1-0050F204-1 name='p2p-TEST2' config_methods=0x188 dev_capab=0x27
256       group_capab=0x0 */
257    private static final String P2P_PROV_DISC_SHOW_PIN_STR = "P2P-PROV-DISC-SHOW-PIN";
258    /* P2P-PROV-DISC-FAILURE p2p_dev_addr=42:fc:89:e1:e2:27 */
259    private static final String P2P_PROV_DISC_FAILURE_STR = "P2P-PROV-DISC-FAILURE";
260
261    /*
262     * Protocol format is as follows.<br>
263     * See the Table.62 in the WiFi Direct specification for the detail.
264     * ______________________________________________________________
265     * |           Length(2byte)     | Type(1byte) | TransId(1byte)}|
266     * ______________________________________________________________
267     * | status(1byte)  |            vendor specific(variable)      |
268     *
269     * P2P-SERV-DISC-RESP 42:fc:89:e1:e2:27 1 0300000101
270     * length=3, service type=0(ALL Service), transaction id=1,
271     * status=1(service protocol type not available)<br>
272     *
273     * P2P-SERV-DISC-RESP 42:fc:89:e1:e2:27 1 0300020201
274     * length=3, service type=2(UPnP), transaction id=2,
275     * status=1(service protocol type not available)
276     *
277     * P2P-SERV-DISC-RESP 42:fc:89:e1:e2:27 1 990002030010757569643a3131323
278     * 2646534652d383537342d353961622d393332322d3333333435363738393034343a3
279     * a75726e3a736368656d61732d75706e702d6f72673a736572766963653a436f6e746
280     * 56e744469726563746f72793a322c757569643a36383539646564652d383537342d3
281     * 53961622d393333322d3132333435363738393031323a3a75706e703a726f6f74646
282     * 576696365
283     * length=153,type=2(UPnP),transaction id=3,status=0
284     *
285     * UPnP Protocol format is as follows.
286     * ______________________________________________________
287     * |  Version (1)  |          USN (Variable)            |
288     *
289     * version=0x10(UPnP1.0) data=usn:uuid:1122de4e-8574-59ab-9322-33345678
290     * 9044::urn:schemas-upnp-org:service:ContentDirectory:2,usn:uuid:6859d
291     * ede-8574-59ab-9332-123456789012::upnp:rootdevice
292     *
293     * P2P-SERV-DISC-RESP 58:17:0c:bc:dd:ca 21 1900010200045f6970
294     * 70c00c000c01094d795072696e746572c027
295     * length=25, type=1(Bonjour),transaction id=2,status=0
296     *
297     * Bonjour Protocol format is as follows.
298     * __________________________________________________________
299     * |DNS Name(Variable)|DNS Type(1)|Version(1)|RDATA(Variable)|
300     *
301     * DNS Name=_ipp._tcp.local.,DNS type=12(PTR), Version=1,
302     * RDATA=MyPrinter._ipp._tcp.local.
303     *
304     */
305    private static final String P2P_SERV_DISC_RESP_STR = "P2P-SERV-DISC-RESP";
306
307    private static final String HOST_AP_EVENT_PREFIX_STR = "AP";
308    /* AP-STA-CONNECTED 42:fc:89:a8:96:09 dev_addr=02:90:4c:a0:92:54 */
309    private static final String AP_STA_CONNECTED_STR = "AP-STA-CONNECTED";
310    /* AP-STA-DISCONNECTED 42:fc:89:a8:96:09 */
311    private static final String AP_STA_DISCONNECTED_STR = "AP-STA-DISCONNECTED";
312
313    /* Supplicant events reported to a state machine */
314    private static final int BASE = Protocol.BASE_WIFI_MONITOR;
315
316    /* Connection to supplicant established */
317    public static final int SUP_CONNECTION_EVENT                 = BASE + 1;
318    /* Connection to supplicant lost */
319    public static final int SUP_DISCONNECTION_EVENT              = BASE + 2;
320   /* Network connection completed */
321    public static final int NETWORK_CONNECTION_EVENT             = BASE + 3;
322    /* Network disconnection completed */
323    public static final int NETWORK_DISCONNECTION_EVENT          = BASE + 4;
324    /* Scan results are available */
325    public static final int SCAN_RESULTS_EVENT                   = BASE + 5;
326    /* Supplicate state changed */
327    public static final int SUPPLICANT_STATE_CHANGE_EVENT        = BASE + 6;
328    /* Password failure and EAP authentication failure */
329    public static final int AUTHENTICATION_FAILURE_EVENT         = BASE + 7;
330    /* WPS success detected */
331    public static final int WPS_SUCCESS_EVENT                    = BASE + 8;
332    /* WPS failure detected */
333    public static final int WPS_FAIL_EVENT                       = BASE + 9;
334     /* WPS overlap detected */
335    public static final int WPS_OVERLAP_EVENT                    = BASE + 10;
336     /* WPS timeout detected */
337    public static final int WPS_TIMEOUT_EVENT                    = BASE + 11;
338    /* Driver was hung */
339    public static final int DRIVER_HUNG_EVENT                    = BASE + 12;
340    /* SSID was disabled due to auth failure or excessive
341     * connection failures */
342    public static final int SSID_TEMP_DISABLED                   = BASE + 13;
343    /* SSID was reenabled */
344    public static final int SSID_REENABLED                       = BASE + 14;
345
346    /* P2P events */
347    public static final int P2P_DEVICE_FOUND_EVENT               = BASE + 21;
348    public static final int P2P_DEVICE_LOST_EVENT                = BASE + 22;
349    public static final int P2P_GO_NEGOTIATION_REQUEST_EVENT     = BASE + 23;
350    public static final int P2P_GO_NEGOTIATION_SUCCESS_EVENT     = BASE + 25;
351    public static final int P2P_GO_NEGOTIATION_FAILURE_EVENT     = BASE + 26;
352    public static final int P2P_GROUP_FORMATION_SUCCESS_EVENT    = BASE + 27;
353    public static final int P2P_GROUP_FORMATION_FAILURE_EVENT    = BASE + 28;
354    public static final int P2P_GROUP_STARTED_EVENT              = BASE + 29;
355    public static final int P2P_GROUP_REMOVED_EVENT              = BASE + 30;
356    public static final int P2P_INVITATION_RECEIVED_EVENT        = BASE + 31;
357    public static final int P2P_INVITATION_RESULT_EVENT          = BASE + 32;
358    public static final int P2P_PROV_DISC_PBC_REQ_EVENT          = BASE + 33;
359    public static final int P2P_PROV_DISC_PBC_RSP_EVENT          = BASE + 34;
360    public static final int P2P_PROV_DISC_ENTER_PIN_EVENT        = BASE + 35;
361    public static final int P2P_PROV_DISC_SHOW_PIN_EVENT         = BASE + 36;
362    public static final int P2P_FIND_STOPPED_EVENT               = BASE + 37;
363    public static final int P2P_SERV_DISC_RESP_EVENT             = BASE + 38;
364    public static final int P2P_PROV_DISC_FAILURE_EVENT          = BASE + 39;
365
366    /* hostap events */
367    public static final int AP_STA_DISCONNECTED_EVENT            = BASE + 41;
368    public static final int AP_STA_CONNECTED_EVENT               = BASE + 42;
369
370    /* Indicates assoc reject event */
371    public static final int ASSOCIATION_REJECTION_EVENT          = BASE + 43;
372
373    /* hotspot 2.0 ANQP events */
374    public static final int GAS_QUERY_START_EVENT                = BASE + 51;
375    public static final int GAS_QUERY_DONE_EVENT                 = BASE + 52;
376    public static final int RX_HS20_ANQP_ICON_EVENT              = BASE + 53;
377
378    /* hotspot 2.0 events */
379    public static final int HS20_REMEDIATION_EVENT               = BASE + 61;
380    public static final int HS20_DEAUTH_EVENT                    = BASE + 62;
381
382    /**
383     * This indicates a read error on the monitor socket conenction
384     */
385    private static final String WPA_RECV_ERROR_STR = "recv error";
386
387    /**
388     * Max errors before we close supplicant connection
389     */
390    private static final int MAX_RECV_ERRORS    = 10;
391
392    private final String mInterfaceName;
393    private final WifiNative mWifiNative;
394    private final StateMachine mStateMachine;
395    private StateMachine mStateMachine2;
396    private boolean mMonitoring;
397
398    // This is a global counter, since it's not monitor specific. However, the existing
399    // implementation forwards all "global" control events like CTRL-EVENT-TERMINATING
400    // to the p2p0 monitor. Is that expected ? It seems a bit surprising.
401    //
402    // TODO: If the p2p0 monitor isn't registered, the behaviour is even more surprising.
403    // The event will be dispatched to all monitors, and each of them will end up incrementing
404    // it in their dispatchXXX method. If we have 5 registered monitors (say), 2 consecutive
405    // recv errors will cause us to disconnect from the supplicant (instead of the intended 10).
406    //
407    // This variable is always accessed and modified under a WifiMonitorSingleton lock.
408    private static int sRecvErrors;
409
410    public WifiMonitor(StateMachine stateMachine, WifiNative wifiNative) {
411        if (DBG) Log.d(TAG, "Creating WifiMonitor");
412        mWifiNative = wifiNative;
413        mInterfaceName = wifiNative.mInterfaceName;
414        mStateMachine = stateMachine;
415        mStateMachine2 = null;
416        mMonitoring = false;
417
418        WifiMonitorSingleton.sInstance.registerInterfaceMonitor(mInterfaceName, this);
419    }
420
421    // TODO: temporary hack, should be handle by supplicant manager (new component in future)
422    public void setStateMachine2(StateMachine stateMachine) {
423        mStateMachine2 = stateMachine;
424    }
425
426    public void startMonitoring() {
427        WifiMonitorSingleton.sInstance.startMonitoring(mInterfaceName);
428    }
429
430    public void stopMonitoring() {
431        WifiMonitorSingleton.sInstance.stopMonitoring(mInterfaceName);
432    }
433
434    public void stopSupplicant() {
435        WifiMonitorSingleton.sInstance.stopSupplicant();
436    }
437
438    public void killSupplicant(boolean p2pSupported) {
439        WifiMonitorSingleton.sInstance.killSupplicant(p2pSupported);
440    }
441
442    private static class WifiMonitorSingleton {
443        private static final WifiMonitorSingleton sInstance = new WifiMonitorSingleton();
444
445        private final HashMap<String, WifiMonitor> mIfaceMap = new HashMap<String, WifiMonitor>();
446        private boolean mConnected = false;
447        private WifiNative mWifiNative;
448
449        private WifiMonitorSingleton() {
450        }
451
452        public synchronized void startMonitoring(String iface) {
453            WifiMonitor m = mIfaceMap.get(iface);
454            if (m == null) {
455                Log.e(TAG, "startMonitor called with unknown iface=" + iface);
456                return;
457            }
458
459            Log.d(TAG, "startMonitoring(" + iface + ") with mConnected = " + mConnected);
460
461            if (mConnected) {
462                m.mMonitoring = true;
463                m.mStateMachine.sendMessage(SUP_CONNECTION_EVENT);
464            } else {
465                if (DBG) Log.d(TAG, "connecting to supplicant");
466                int connectTries = 0;
467                while (true) {
468                    if (mWifiNative.connectToSupplicant()) {
469                        m.mMonitoring = true;
470                        m.mStateMachine.sendMessage(SUP_CONNECTION_EVENT);
471                        new MonitorThread(mWifiNative, this).start();
472                        mConnected = true;
473                        break;
474                    }
475                    if (connectTries++ < 5) {
476                        try {
477                            Thread.sleep(1000);
478                        } catch (InterruptedException ignore) {
479                        }
480                    } else {
481                        mIfaceMap.remove(iface);
482                        m.mStateMachine.sendMessage(SUP_DISCONNECTION_EVENT);
483                        Log.e(TAG, "startMonitoring(" + iface + ") failed!");
484                        break;
485                    }
486                }
487            }
488        }
489
490        public synchronized void stopMonitoring(String iface) {
491            WifiMonitor m = mIfaceMap.get(iface);
492            if (DBG) Log.d(TAG, "stopMonitoring(" + iface + ") = " + m.mStateMachine);
493            m.mMonitoring = false;
494            m.mStateMachine.sendMessage(SUP_DISCONNECTION_EVENT);
495        }
496
497        public synchronized void registerInterfaceMonitor(String iface, WifiMonitor m) {
498            if (DBG) Log.d(TAG, "registerInterface(" + iface + "+" + m.mStateMachine + ")");
499            mIfaceMap.put(iface, m);
500            if (mWifiNative == null) {
501                mWifiNative = m.mWifiNative;
502            }
503        }
504
505        public synchronized void unregisterInterfaceMonitor(String iface) {
506            // REVIEW: When should we call this? If this isn't called, then WifiMonitor
507            // objects will remain in the mIfaceMap; and won't ever get deleted
508
509            WifiMonitor m = mIfaceMap.remove(iface);
510            if (DBG) Log.d(TAG, "unregisterInterface(" + iface + "+" + m.mStateMachine + ")");
511        }
512
513        public synchronized void stopSupplicant() {
514            mWifiNative.stopSupplicant();
515        }
516
517        public synchronized void killSupplicant(boolean p2pSupported) {
518            WifiNative.killSupplicant(p2pSupported);
519            mConnected = false;
520            for (WifiMonitor m : mIfaceMap.values()) {
521                m.mMonitoring = false;
522            }
523        }
524
525        private synchronized boolean dispatchEvent(String eventStr) {
526            String iface;
527            if (eventStr.startsWith("IFNAME=")) {
528                int space = eventStr.indexOf(' ');
529                if (space != -1) {
530                    iface = eventStr.substring(7, space);
531                    if (!mIfaceMap.containsKey(iface) && iface.startsWith("p2p-")) {
532                        // p2p interfaces are created dynamically, but we have
533                        // only one P2p state machine monitoring all of them; look
534                        // for it explicitly, and send messages there ..
535                        iface = "p2p0";
536                    }
537                    eventStr = eventStr.substring(space + 1);
538                } else {
539                    // No point dispatching this event to any interface, the dispatched
540                    // event string will begin with "IFNAME=" which dispatchEvent can't really
541                    // do anything about.
542                    Log.e(TAG, "Dropping malformed event (unparsable iface): " + eventStr);
543                    return false;
544                }
545            } else {
546                // events without prefix belong to p2p0 monitor
547                iface = "p2p0";
548            }
549
550            if (DBG) Log.d(TAG, "Dispatching event to interface: " + iface);
551
552            WifiMonitor m = mIfaceMap.get(iface);
553            if (m != null) {
554                if (m.mMonitoring) {
555                    if (m.dispatchEvent(eventStr)) {
556                        mConnected = false;
557                        return true;
558                    }
559
560                    return false;
561                } else {
562                    if (DBG) Log.d(TAG, "Dropping event because (" + iface + ") is stopped");
563                    return false;
564                }
565            } else {
566                if (DBG) Log.d(TAG, "Sending to all monitors because there's no matching iface");
567                boolean done = false;
568                for (WifiMonitor monitor : mIfaceMap.values()) {
569                    if (monitor.mMonitoring && monitor.dispatchEvent(eventStr)) {
570                        done = true;
571                    }
572                }
573
574                if (done) {
575                    mConnected = false;
576                }
577
578                return done;
579            }
580        }
581    }
582
583    private static class MonitorThread extends Thread {
584        private final WifiNative mWifiNative;
585        private final WifiMonitorSingleton mWifiMonitorSingleton;
586
587        public MonitorThread(WifiNative wifiNative, WifiMonitorSingleton wifiMonitorSingleton) {
588            super("WifiMonitor");
589            mWifiNative = wifiNative;
590            mWifiMonitorSingleton = wifiMonitorSingleton;
591        }
592
593        public void run() {
594            //noinspection InfiniteLoopStatement
595            for (;;) {
596                String eventStr = mWifiNative.waitForEvent();
597
598                // Skip logging the common but mostly uninteresting scan-results event
599                if (DBG && eventStr.indexOf(SCAN_RESULTS_STR) == -1) {
600                    Log.d(TAG, "Event [" + eventStr + "]");
601                }
602
603                if (mWifiMonitorSingleton.dispatchEvent(eventStr)) {
604                    if (DBG) Log.d(TAG, "Disconnecting from the supplicant, no more events");
605                    break;
606                }
607            }
608        }
609    }
610
611    private void logDbg(String debug) {
612        long now = SystemClock.elapsedRealtimeNanos();
613        String ts = String.format("[%,d us] ", now/1000);
614        Log.e(TAG, ts+debug+ " stack:" + Thread.currentThread().getStackTrace()[2].getMethodName()
615                +" - "+ Thread.currentThread().getStackTrace()[3].getMethodName()
616                +" - "+ Thread.currentThread().getStackTrace()[4].getMethodName()
617                +" - "+ Thread.currentThread().getStackTrace()[5].getMethodName());
618
619    }
620
621    /* @return true if the event was supplicant disconnection */
622    private boolean dispatchEvent(String eventStr) {
623
624        if (DBG) logDbg("WifiMonitor dispatchEvent " + eventStr);
625
626        if (!eventStr.startsWith(EVENT_PREFIX_STR)) {
627            if (eventStr.startsWith(WPA_EVENT_PREFIX_STR) &&
628                    0 < eventStr.indexOf(PASSWORD_MAY_BE_INCORRECT_STR)) {
629               mStateMachine.sendMessage(AUTHENTICATION_FAILURE_EVENT);
630            } else if (eventStr.startsWith(WPS_SUCCESS_STR)) {
631                mStateMachine.sendMessage(WPS_SUCCESS_EVENT);
632            } else if (eventStr.startsWith(WPS_FAIL_STR)) {
633                handleWpsFailEvent(eventStr);
634            } else if (eventStr.startsWith(WPS_OVERLAP_STR)) {
635                mStateMachine.sendMessage(WPS_OVERLAP_EVENT);
636            } else if (eventStr.startsWith(WPS_TIMEOUT_STR)) {
637                mStateMachine.sendMessage(WPS_TIMEOUT_EVENT);
638            } else if (eventStr.startsWith(P2P_EVENT_PREFIX_STR)) {
639                handleP2pEvents(eventStr);
640            } else if (eventStr.startsWith(HOST_AP_EVENT_PREFIX_STR)) {
641                handleHostApEvents(eventStr);
642            } else if (eventStr.startsWith(GAS_QUERY_PREFIX_STR)) {
643                handleGasQueryEvents(eventStr);
644            } else if (eventStr.startsWith(RX_HS20_ANQP_ICON_STR)) {
645                if (mStateMachine2 != null)
646                    mStateMachine2.sendMessage(RX_HS20_ANQP_ICON_EVENT,
647                            eventStr.substring(RX_HS20_ANQP_ICON_STR_LEN + 1));
648            } else if (eventStr.startsWith(HS20_PREFIX_STR)) {
649                handleHs20Events(eventStr);
650            } else {
651                if (DBG) Log.w(TAG, "couldn't identify event type - " + eventStr);
652            }
653            return false;
654        }
655
656        String eventName = eventStr.substring(EVENT_PREFIX_LEN_STR);
657        int nameEnd = eventName.indexOf(' ');
658        if (nameEnd != -1)
659            eventName = eventName.substring(0, nameEnd);
660        if (eventName.length() == 0) {
661            if (DBG) Log.i(TAG, "Received wpa_supplicant event with empty event name");
662            return false;
663        }
664        /*
665        * Map event name into event enum
666        */
667        int event;
668        if (eventName.equals(CONNECTED_STR))
669            event = CONNECTED;
670        else if (eventName.equals(DISCONNECTED_STR))
671            event = DISCONNECTED;
672        else if (eventName.equals(STATE_CHANGE_STR))
673            event = STATE_CHANGE;
674        else if (eventName.equals(SCAN_RESULTS_STR))
675            event = SCAN_RESULTS;
676        else if (eventName.equals(LINK_SPEED_STR))
677            event = LINK_SPEED;
678        else if (eventName.equals(TERMINATING_STR))
679            event = TERMINATING;
680        else if (eventName.equals(DRIVER_STATE_STR))
681            event = DRIVER_STATE;
682        else if (eventName.equals(EAP_FAILURE_STR))
683            event = EAP_FAILURE;
684        else if (eventName.equals(ASSOC_REJECT_STR))
685            event = ASSOC_REJECT;
686        else if (eventName.equals(TEMP_DISABLED_STR)) {
687            event = SSID_TEMP_DISABLE;
688        } else if (eventName.equals(REENABLED_STR)) {
689            event = SSID_REENABLE;
690        }
691        else
692            event = UNKNOWN;
693
694        String eventData = eventStr;
695        if (event == DRIVER_STATE || event == LINK_SPEED)
696            eventData = eventData.split(" ")[1];
697        else if (event == STATE_CHANGE || event == EAP_FAILURE) {
698            int ind = eventStr.indexOf(" ");
699            if (ind != -1) {
700                eventData = eventStr.substring(ind + 1);
701            }
702        } else {
703            int ind = eventStr.indexOf(" - ");
704            if (ind != -1) {
705                eventData = eventStr.substring(ind + 3);
706            }
707        }
708
709        if ((event == SSID_TEMP_DISABLE)||(event == SSID_REENABLE)) {
710            String substr = null;
711            int netId = -1;
712            int ind = eventStr.indexOf(" ");
713            if (ind != -1) {
714                substr = eventStr.substring(ind + 1);
715            }
716            if (substr != null) {
717                String status[] = substr.split(" ");
718                for (String key : status) {
719                    if (key.regionMatches(0, "id=", 0, 3)) {
720                        int idx = 3;
721                        netId = 0;
722                        while (idx < key.length()) {
723                            char c = key.charAt(idx);
724                            if ((c >= 0x30) && (c <= 0x39)) {
725                                netId *= 10;
726                                netId += c - 0x30;
727                                idx++;
728                            } else {
729                                break;
730                            }
731                        }
732                    }
733                }
734            }
735            mStateMachine.sendMessage((event == SSID_TEMP_DISABLE)?
736                    SSID_TEMP_DISABLED:SSID_REENABLED, netId, 0, substr);
737        } else if (event == STATE_CHANGE) {
738            handleSupplicantStateChange(eventData);
739        } else if (event == DRIVER_STATE) {
740            handleDriverEvent(eventData);
741        } else if (event == TERMINATING) {
742            /**
743             * Close the supplicant connection if we see
744             * too many recv errors
745             */
746            if (eventData.startsWith(WPA_RECV_ERROR_STR)) {
747                if (++sRecvErrors > MAX_RECV_ERRORS) {
748                    if (DBG) {
749                        Log.d(TAG, "too many recv errors, closing connection");
750                    }
751                } else {
752                    return false;
753                }
754            }
755
756            // notify and exit
757            mStateMachine.sendMessage(SUP_DISCONNECTION_EVENT);
758            return true;
759        } else if (event == EAP_FAILURE) {
760            if (eventData.startsWith(EAP_AUTH_FAILURE_STR)) {
761                logDbg("WifiMonitor send auth failure (EAP_AUTH_FAILURE) ");
762                mStateMachine.sendMessage(AUTHENTICATION_FAILURE_EVENT);
763            }
764        } else if (event == ASSOC_REJECT) {
765            mStateMachine.sendMessage(ASSOCIATION_REJECTION_EVENT);
766        } else {
767            handleEvent(event, eventData);
768        }
769        sRecvErrors = 0;
770        return false;
771    }
772
773    private void handleDriverEvent(String state) {
774        if (state == null) {
775            return;
776        }
777        if (state.equals("HANGED")) {
778            mStateMachine.sendMessage(DRIVER_HUNG_EVENT);
779        }
780    }
781
782    /**
783     * Handle all supplicant events except STATE-CHANGE
784     * @param event the event type
785     * @param remainder the rest of the string following the
786     * event name and &quot;&#8195;&#8212;&#8195;&quot;
787     */
788    void handleEvent(int event, String remainder) {
789        switch (event) {
790            case DISCONNECTED:
791                handleNetworkStateChange(NetworkInfo.DetailedState.DISCONNECTED, remainder);
792                break;
793
794            case CONNECTED:
795                handleNetworkStateChange(NetworkInfo.DetailedState.CONNECTED, remainder);
796                break;
797
798            case SCAN_RESULTS:
799                mStateMachine.sendMessage(SCAN_RESULTS_EVENT);
800                break;
801
802            case UNKNOWN:
803                break;
804        }
805    }
806
807    private void handleWpsFailEvent(String dataString) {
808        final Pattern p = Pattern.compile(WPS_FAIL_PATTERN);
809        Matcher match = p.matcher(dataString);
810        int reason = 0;
811        if (match.find()) {
812            String cfgErrStr = match.group(1);
813            String reasonStr = match.group(2);
814
815            if (reasonStr != null) {
816                int reasonInt = Integer.parseInt(reasonStr);
817                switch(reasonInt) {
818                    case REASON_TKIP_ONLY_PROHIBITED:
819                        mStateMachine.sendMessage(mStateMachine.obtainMessage(WPS_FAIL_EVENT,
820                                WifiManager.WPS_TKIP_ONLY_PROHIBITED, 0));
821                        return;
822                    case REASON_WEP_PROHIBITED:
823                        mStateMachine.sendMessage(mStateMachine.obtainMessage(WPS_FAIL_EVENT,
824                                WifiManager.WPS_WEP_PROHIBITED, 0));
825                        return;
826                    default:
827                        reason = reasonInt;
828                        break;
829                }
830            }
831            if (cfgErrStr != null) {
832                int cfgErrInt = Integer.parseInt(cfgErrStr);
833                switch(cfgErrInt) {
834                    case CONFIG_AUTH_FAILURE:
835                        mStateMachine.sendMessage(mStateMachine.obtainMessage(WPS_FAIL_EVENT,
836                                WifiManager.WPS_AUTH_FAILURE, 0));
837                        return;
838                    case CONFIG_MULTIPLE_PBC_DETECTED:
839                        mStateMachine.sendMessage(mStateMachine.obtainMessage(WPS_FAIL_EVENT,
840                                WifiManager.WPS_OVERLAP_ERROR, 0));
841                        return;
842                    default:
843                        if (reason == 0) reason = cfgErrInt;
844                        break;
845                }
846            }
847        }
848        //For all other errors, return a generic internal error
849        mStateMachine.sendMessage(mStateMachine.obtainMessage(WPS_FAIL_EVENT,
850                WifiManager.ERROR, reason));
851    }
852
853    /* <event> status=<err> and the special case of <event> reason=FREQ_CONFLICT */
854    private P2pStatus p2pError(String dataString) {
855        P2pStatus err = P2pStatus.UNKNOWN;
856        String[] tokens = dataString.split(" ");
857        if (tokens.length < 2) return err;
858        String[] nameValue = tokens[1].split("=");
859        if (nameValue.length != 2) return err;
860
861        /* Handle the special case of reason=FREQ+CONFLICT */
862        if (nameValue[1].equals("FREQ_CONFLICT")) {
863            return P2pStatus.NO_COMMON_CHANNEL;
864        }
865        try {
866            err = P2pStatus.valueOf(Integer.parseInt(nameValue[1]));
867        } catch (NumberFormatException e) {
868            e.printStackTrace();
869        }
870        return err;
871    }
872
873    /**
874     * Handle p2p events
875     */
876    private void handleP2pEvents(String dataString) {
877        if (dataString.startsWith(P2P_DEVICE_FOUND_STR)) {
878            mStateMachine.sendMessage(P2P_DEVICE_FOUND_EVENT, new WifiP2pDevice(dataString));
879        } else if (dataString.startsWith(P2P_DEVICE_LOST_STR)) {
880            mStateMachine.sendMessage(P2P_DEVICE_LOST_EVENT, new WifiP2pDevice(dataString));
881        } else if (dataString.startsWith(P2P_FIND_STOPPED_STR)) {
882            mStateMachine.sendMessage(P2P_FIND_STOPPED_EVENT);
883        } else if (dataString.startsWith(P2P_GO_NEG_REQUEST_STR)) {
884            mStateMachine.sendMessage(P2P_GO_NEGOTIATION_REQUEST_EVENT,
885                    new WifiP2pConfig(dataString));
886        } else if (dataString.startsWith(P2P_GO_NEG_SUCCESS_STR)) {
887            mStateMachine.sendMessage(P2P_GO_NEGOTIATION_SUCCESS_EVENT);
888        } else if (dataString.startsWith(P2P_GO_NEG_FAILURE_STR)) {
889            mStateMachine.sendMessage(P2P_GO_NEGOTIATION_FAILURE_EVENT, p2pError(dataString));
890        } else if (dataString.startsWith(P2P_GROUP_FORMATION_SUCCESS_STR)) {
891            mStateMachine.sendMessage(P2P_GROUP_FORMATION_SUCCESS_EVENT);
892        } else if (dataString.startsWith(P2P_GROUP_FORMATION_FAILURE_STR)) {
893            mStateMachine.sendMessage(P2P_GROUP_FORMATION_FAILURE_EVENT, p2pError(dataString));
894        } else if (dataString.startsWith(P2P_GROUP_STARTED_STR)) {
895            mStateMachine.sendMessage(P2P_GROUP_STARTED_EVENT, new WifiP2pGroup(dataString));
896        } else if (dataString.startsWith(P2P_GROUP_REMOVED_STR)) {
897            mStateMachine.sendMessage(P2P_GROUP_REMOVED_EVENT, new WifiP2pGroup(dataString));
898        } else if (dataString.startsWith(P2P_INVITATION_RECEIVED_STR)) {
899            mStateMachine.sendMessage(P2P_INVITATION_RECEIVED_EVENT,
900                    new WifiP2pGroup(dataString));
901        } else if (dataString.startsWith(P2P_INVITATION_RESULT_STR)) {
902            mStateMachine.sendMessage(P2P_INVITATION_RESULT_EVENT, p2pError(dataString));
903        } else if (dataString.startsWith(P2P_PROV_DISC_PBC_REQ_STR)) {
904            mStateMachine.sendMessage(P2P_PROV_DISC_PBC_REQ_EVENT,
905                    new WifiP2pProvDiscEvent(dataString));
906        } else if (dataString.startsWith(P2P_PROV_DISC_PBC_RSP_STR)) {
907            mStateMachine.sendMessage(P2P_PROV_DISC_PBC_RSP_EVENT,
908                    new WifiP2pProvDiscEvent(dataString));
909        } else if (dataString.startsWith(P2P_PROV_DISC_ENTER_PIN_STR)) {
910            mStateMachine.sendMessage(P2P_PROV_DISC_ENTER_PIN_EVENT,
911                    new WifiP2pProvDiscEvent(dataString));
912        } else if (dataString.startsWith(P2P_PROV_DISC_SHOW_PIN_STR)) {
913            mStateMachine.sendMessage(P2P_PROV_DISC_SHOW_PIN_EVENT,
914                    new WifiP2pProvDiscEvent(dataString));
915        } else if (dataString.startsWith(P2P_PROV_DISC_FAILURE_STR)) {
916            mStateMachine.sendMessage(P2P_PROV_DISC_FAILURE_EVENT);
917        } else if (dataString.startsWith(P2P_SERV_DISC_RESP_STR)) {
918            List<WifiP2pServiceResponse> list = WifiP2pServiceResponse.newInstance(dataString);
919            if (list != null) {
920                mStateMachine.sendMessage(P2P_SERV_DISC_RESP_EVENT, list);
921            } else {
922                Log.e(TAG, "Null service resp " + dataString);
923            }
924        }
925    }
926
927    /**
928     * Handle hostap events
929     */
930    private void handleHostApEvents(String dataString) {
931        String[] tokens = dataString.split(" ");
932        /* AP-STA-CONNECTED 42:fc:89:a8:96:09 p2p_dev_addr=02:90:4c:a0:92:54 */
933        if (tokens[0].equals(AP_STA_CONNECTED_STR)) {
934            mStateMachine.sendMessage(AP_STA_CONNECTED_EVENT, new WifiP2pDevice(dataString));
935            /* AP-STA-DISCONNECTED 42:fc:89:a8:96:09 p2p_dev_addr=02:90:4c:a0:92:54 */
936        } else if (tokens[0].equals(AP_STA_DISCONNECTED_STR)) {
937            mStateMachine.sendMessage(AP_STA_DISCONNECTED_EVENT, new WifiP2pDevice(dataString));
938        }
939    }
940
941    /**
942     * Handle ANQP events
943     */
944    private void handleGasQueryEvents(String dataString) {
945        // hs20
946        if (mStateMachine2 == null) return;
947        if (dataString.startsWith(GAS_QUERY_START_STR)) {
948            mStateMachine2.sendMessage(GAS_QUERY_START_EVENT);
949        } else if (dataString.startsWith(GAS_QUERY_DONE_STR)) {
950            String[] dataTokens = dataString.split(" ");
951            String bssid = null;
952            int success = 0;
953            for (String token : dataTokens) {
954                String[] nameValue = token.split("=");
955                if (nameValue.length != 2) {
956                    continue;
957                }
958                if (nameValue[0].equals("addr")) {
959                    bssid = nameValue[1];
960                    continue;
961                }
962                if (nameValue[0].equals("result"))  {
963                    success = nameValue[1].equals("SUCCESS") ? 1 : 0;
964                    continue;
965                }
966            }
967            mStateMachine2.sendMessage(GAS_QUERY_DONE_EVENT, success, 0, bssid);
968        } else {
969            if (DBG) Log.d(TAG, "Unknown GAS query event: " + dataString);
970        }
971    }
972
973    /**
974     * Handle HS20 events
975     */
976    private void handleHs20Events(String dataString) {
977        if (mStateMachine2 == null) return;
978        if (dataString.startsWith(HS20_SUB_REM_STR)) {
979            // format: HS20-SUBSCRIPTION-REMEDIATION osu_method, url
980            String[] dataTokens = dataString.split(" ");
981            int method = -1;
982            String url = null;
983            if (dataTokens.length >= 3) {
984                method = Integer.parseInt(dataTokens[1]);
985                url = dataTokens[2];
986            }
987            mStateMachine2.sendMessage(HS20_REMEDIATION_EVENT, method, 0, url);
988        } else if (dataString.startsWith(HS20_DEAUTH_STR)) {
989            // format: HS20-DEAUTH-IMMINENT-NOTICE code, delay, url
990            int code = -1;
991            int delay = -1;
992            String url = null;
993            String[] dataTokens = dataString.split(" ");
994            if (dataTokens.length >= 4) {
995                code = Integer.parseInt(dataTokens[1]);
996                delay = Integer.parseInt(dataTokens[2]);
997                url = dataTokens[3];
998            }
999            mStateMachine2.sendMessage(HS20_DEAUTH_EVENT, code, delay, url);
1000        } else {
1001            if (DBG) Log.d(TAG, "Unknown HS20 event: " + dataString);
1002        }
1003    }
1004
1005    /**
1006     * Handle the supplicant STATE-CHANGE event
1007     * @param dataString New supplicant state string in the format:
1008     * id=network-id state=new-state
1009     */
1010    private void handleSupplicantStateChange(String dataString) {
1011        WifiSsid wifiSsid = null;
1012        int index = dataString.lastIndexOf("SSID=");
1013        if (index != -1) {
1014            wifiSsid = WifiSsid.createFromAsciiEncoded(
1015                    dataString.substring(index + 5));
1016        }
1017        String[] dataTokens = dataString.split(" ");
1018
1019        String BSSID = null;
1020        int networkId = -1;
1021        int newState  = -1;
1022        for (String token : dataTokens) {
1023            String[] nameValue = token.split("=");
1024            if (nameValue.length != 2) {
1025                continue;
1026            }
1027
1028            if (nameValue[0].equals("BSSID")) {
1029                BSSID = nameValue[1];
1030                continue;
1031            }
1032
1033            int value;
1034            try {
1035                value = Integer.parseInt(nameValue[1]);
1036            } catch (NumberFormatException e) {
1037                continue;
1038            }
1039
1040            if (nameValue[0].equals("id")) {
1041                networkId = value;
1042            } else if (nameValue[0].equals("state")) {
1043                newState = value;
1044            }
1045        }
1046
1047        if (newState == -1) return;
1048
1049        SupplicantState newSupplicantState = SupplicantState.INVALID;
1050        for (SupplicantState state : SupplicantState.values()) {
1051            if (state.ordinal() == newState) {
1052                newSupplicantState = state;
1053                break;
1054            }
1055        }
1056        if (newSupplicantState == SupplicantState.INVALID) {
1057            Log.w(TAG, "Invalid supplicant state: " + newState);
1058        }
1059        notifySupplicantStateChange(networkId, wifiSsid, BSSID, newSupplicantState);
1060    }
1061
1062    private void handleNetworkStateChange(NetworkInfo.DetailedState newState, String data) {
1063        String BSSID = null;
1064        int networkId = -1;
1065        if (newState == NetworkInfo.DetailedState.CONNECTED) {
1066            Matcher match = mConnectedEventPattern.matcher(data);
1067            if (!match.find()) {
1068                if (DBG) Log.d(TAG, "Could not find BSSID in CONNECTED event string");
1069            } else {
1070                BSSID = match.group(1);
1071                try {
1072                    networkId = Integer.parseInt(match.group(2));
1073                } catch (NumberFormatException e) {
1074                    networkId = -1;
1075                }
1076            }
1077            notifyNetworkStateChange(newState, BSSID, networkId);
1078        }
1079    }
1080
1081    /**
1082     * Send the state machine a notification that the state of Wifi connectivity
1083     * has changed.
1084     * @param newState the new network state
1085     * @param BSSID when the new state is {@link NetworkInfo.DetailedState#CONNECTED},
1086     * this is the MAC address of the access point. Otherwise, it
1087     * is {@code null}.
1088     * @param netId the configured network on which the state change occurred
1089     */
1090    void notifyNetworkStateChange(NetworkInfo.DetailedState newState, String BSSID, int netId) {
1091        if (newState == NetworkInfo.DetailedState.CONNECTED) {
1092            Message m = mStateMachine.obtainMessage(NETWORK_CONNECTION_EVENT,
1093                    netId, 0, BSSID);
1094            mStateMachine.sendMessage(m);
1095        } else {
1096            Message m = mStateMachine.obtainMessage(NETWORK_DISCONNECTION_EVENT,
1097                    netId, 0, BSSID);
1098            mStateMachine.sendMessage(m);
1099        }
1100    }
1101
1102    /**
1103     * Send the state machine a notification that the state of the supplicant
1104     * has changed.
1105     * @param networkId the configured network on which the state change occurred
1106     * @param wifiSsid network name
1107     * @param BSSID network address
1108     * @param newState the new {@code SupplicantState}
1109     */
1110    void notifySupplicantStateChange(int networkId, WifiSsid wifiSsid, String BSSID,
1111            SupplicantState newState) {
1112        mStateMachine.sendMessage(mStateMachine.obtainMessage(SUPPLICANT_STATE_CHANGE_EVENT,
1113                new StateChangeResult(networkId, wifiSsid, BSSID, newState)));
1114    }
1115}
1116