WifiMonitor.java revision ed9938883ae2dade81c8be6cd6ceaef3febd5239
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 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    void enableVerboseLogging(int verbose) {
422        if (verbose > 0) {
423            DBG = true;
424        } else {
425            DBG = false;
426        }
427    }
428
429        // TODO: temporary hack, should be handle by supplicant manager (new component in future)
430    public void setStateMachine2(StateMachine stateMachine) {
431        mStateMachine2 = stateMachine;
432    }
433
434    public void startMonitoring() {
435        WifiMonitorSingleton.sInstance.startMonitoring(mInterfaceName);
436    }
437
438    public void stopMonitoring() {
439        WifiMonitorSingleton.sInstance.stopMonitoring(mInterfaceName);
440    }
441
442    public void stopSupplicant() {
443        WifiMonitorSingleton.sInstance.stopSupplicant();
444    }
445
446    public void killSupplicant(boolean p2pSupported) {
447        WifiMonitorSingleton.sInstance.killSupplicant(p2pSupported);
448    }
449
450    private static class WifiMonitorSingleton {
451        private static final WifiMonitorSingleton sInstance = new WifiMonitorSingleton();
452
453        private final HashMap<String, WifiMonitor> mIfaceMap = new HashMap<String, WifiMonitor>();
454        private boolean mConnected = false;
455        private WifiNative mWifiNative;
456
457        private WifiMonitorSingleton() {
458        }
459
460        public synchronized void startMonitoring(String iface) {
461            WifiMonitor m = mIfaceMap.get(iface);
462            if (m == null) {
463                Log.e(TAG, "startMonitor called with unknown iface=" + iface);
464                return;
465            }
466
467            Log.d(TAG, "startMonitoring(" + iface + ") with mConnected = " + mConnected);
468
469            if (mConnected) {
470                m.mMonitoring = true;
471                m.mStateMachine.sendMessage(SUP_CONNECTION_EVENT);
472            } else {
473                if (DBG) Log.d(TAG, "connecting to supplicant");
474                int connectTries = 0;
475                while (true) {
476                    if (mWifiNative.connectToSupplicant()) {
477                        m.mMonitoring = true;
478                        m.mStateMachine.sendMessage(SUP_CONNECTION_EVENT);
479                        new MonitorThread(mWifiNative, this).start();
480                        mConnected = true;
481                        break;
482                    }
483                    if (connectTries++ < 5) {
484                        try {
485                            Thread.sleep(1000);
486                        } catch (InterruptedException ignore) {
487                        }
488                    } else {
489                        mIfaceMap.remove(iface);
490                        m.mStateMachine.sendMessage(SUP_DISCONNECTION_EVENT);
491                        Log.e(TAG, "startMonitoring(" + iface + ") failed!");
492                        break;
493                    }
494                }
495            }
496        }
497
498        public synchronized void stopMonitoring(String iface) {
499            WifiMonitor m = mIfaceMap.get(iface);
500            if (DBG) Log.d(TAG, "stopMonitoring(" + iface + ") = " + m.mStateMachine);
501            m.mMonitoring = false;
502            m.mStateMachine.sendMessage(SUP_DISCONNECTION_EVENT);
503        }
504
505        public synchronized void registerInterfaceMonitor(String iface, WifiMonitor m) {
506            if (DBG) Log.d(TAG, "registerInterface(" + iface + "+" + m.mStateMachine + ")");
507            mIfaceMap.put(iface, m);
508            if (mWifiNative == null) {
509                mWifiNative = m.mWifiNative;
510            }
511        }
512
513        public synchronized void unregisterInterfaceMonitor(String iface) {
514            // REVIEW: When should we call this? If this isn't called, then WifiMonitor
515            // objects will remain in the mIfaceMap; and won't ever get deleted
516
517            WifiMonitor m = mIfaceMap.remove(iface);
518            if (DBG) Log.d(TAG, "unregisterInterface(" + iface + "+" + m.mStateMachine + ")");
519        }
520
521        public synchronized void stopSupplicant() {
522            mWifiNative.stopSupplicant();
523        }
524
525        public synchronized void killSupplicant(boolean p2pSupported) {
526            WifiNative.killSupplicant(p2pSupported);
527            mConnected = false;
528            for (WifiMonitor m : mIfaceMap.values()) {
529                m.mMonitoring = false;
530            }
531        }
532
533        private synchronized boolean dispatchEvent(String eventStr) {
534            String iface;
535            if (eventStr.startsWith("IFNAME=")) {
536                int space = eventStr.indexOf(' ');
537                if (space != -1) {
538                    iface = eventStr.substring(7, space);
539                    if (!mIfaceMap.containsKey(iface) && iface.startsWith("p2p-")) {
540                        // p2p interfaces are created dynamically, but we have
541                        // only one P2p state machine monitoring all of them; look
542                        // for it explicitly, and send messages there ..
543                        iface = "p2p0";
544                    }
545                    eventStr = eventStr.substring(space + 1);
546                } else {
547                    // No point dispatching this event to any interface, the dispatched
548                    // event string will begin with "IFNAME=" which dispatchEvent can't really
549                    // do anything about.
550                    Log.e(TAG, "Dropping malformed event (unparsable iface): " + eventStr);
551                    return false;
552                }
553            } else {
554                // events without prefix belong to p2p0 monitor
555                iface = "p2p0";
556            }
557
558            if (DBG) Log.d(TAG, "Dispatching event to interface: " + iface);
559
560            WifiMonitor m = mIfaceMap.get(iface);
561            if (m != null) {
562                if (m.mMonitoring) {
563                    if (m.dispatchEvent(eventStr)) {
564                        mConnected = false;
565                        return true;
566                    }
567
568                    return false;
569                } else {
570                    if (DBG) Log.d(TAG, "Dropping event because (" + iface + ") is stopped");
571                    return false;
572                }
573            } else {
574                if (DBG) Log.d(TAG, "Sending to all monitors because there's no matching iface");
575                boolean done = false;
576                for (WifiMonitor monitor : mIfaceMap.values()) {
577                    if (monitor.mMonitoring && monitor.dispatchEvent(eventStr)) {
578                        done = true;
579                    }
580                }
581
582                if (done) {
583                    mConnected = false;
584                }
585
586                return done;
587            }
588        }
589    }
590
591    private static class MonitorThread extends Thread {
592        private final WifiNative mWifiNative;
593        private final WifiMonitorSingleton mWifiMonitorSingleton;
594
595        public MonitorThread(WifiNative wifiNative, WifiMonitorSingleton wifiMonitorSingleton) {
596            super("WifiMonitor");
597            mWifiNative = wifiNative;
598            mWifiMonitorSingleton = wifiMonitorSingleton;
599        }
600
601        public void run() {
602            //noinspection InfiniteLoopStatement
603            for (;;) {
604                String eventStr = mWifiNative.waitForEvent();
605
606                // Skip logging the common but mostly uninteresting scan-results event
607                if (DBG && eventStr.indexOf(SCAN_RESULTS_STR) == -1) {
608                    Log.d(TAG, "Event [" + eventStr + "]");
609                }
610
611                if (mWifiMonitorSingleton.dispatchEvent(eventStr)) {
612                    if (DBG) Log.d(TAG, "Disconnecting from the supplicant, no more events");
613                    break;
614                }
615            }
616        }
617    }
618
619    private void logDbg(String debug) {
620        long now = SystemClock.elapsedRealtimeNanos();
621        String ts = String.format("[%,d us] ", now/1000);
622        Log.e(TAG, ts+debug+ " stack:" + Thread.currentThread().getStackTrace()[2].getMethodName()
623                +" - "+ Thread.currentThread().getStackTrace()[3].getMethodName()
624                +" - "+ Thread.currentThread().getStackTrace()[4].getMethodName()
625                +" - "+ Thread.currentThread().getStackTrace()[5].getMethodName());
626
627    }
628
629    /* @return true if the event was supplicant disconnection */
630    private boolean dispatchEvent(String eventStr) {
631
632        if (DBG) logDbg("WifiMonitor dispatchEvent " + eventStr);
633
634        if (!eventStr.startsWith(EVENT_PREFIX_STR)) {
635            if (eventStr.startsWith(WPA_EVENT_PREFIX_STR) &&
636                    0 < eventStr.indexOf(PASSWORD_MAY_BE_INCORRECT_STR)) {
637               mStateMachine.sendMessage(AUTHENTICATION_FAILURE_EVENT);
638            } else if (eventStr.startsWith(WPS_SUCCESS_STR)) {
639                mStateMachine.sendMessage(WPS_SUCCESS_EVENT);
640            } else if (eventStr.startsWith(WPS_FAIL_STR)) {
641                handleWpsFailEvent(eventStr);
642            } else if (eventStr.startsWith(WPS_OVERLAP_STR)) {
643                mStateMachine.sendMessage(WPS_OVERLAP_EVENT);
644            } else if (eventStr.startsWith(WPS_TIMEOUT_STR)) {
645                mStateMachine.sendMessage(WPS_TIMEOUT_EVENT);
646            } else if (eventStr.startsWith(P2P_EVENT_PREFIX_STR)) {
647                handleP2pEvents(eventStr);
648            } else if (eventStr.startsWith(HOST_AP_EVENT_PREFIX_STR)) {
649                handleHostApEvents(eventStr);
650            } else if (eventStr.startsWith(GAS_QUERY_PREFIX_STR)) {
651                handleGasQueryEvents(eventStr);
652            } else if (eventStr.startsWith(RX_HS20_ANQP_ICON_STR)) {
653                if (mStateMachine2 != null)
654                    mStateMachine2.sendMessage(RX_HS20_ANQP_ICON_EVENT,
655                            eventStr.substring(RX_HS20_ANQP_ICON_STR_LEN + 1));
656            } else if (eventStr.startsWith(HS20_PREFIX_STR)) {
657                handleHs20Events(eventStr);
658            } else {
659                if (DBG) Log.w(TAG, "couldn't identify event type - " + eventStr);
660            }
661            return false;
662        }
663
664        String eventName = eventStr.substring(EVENT_PREFIX_LEN_STR);
665        int nameEnd = eventName.indexOf(' ');
666        if (nameEnd != -1)
667            eventName = eventName.substring(0, nameEnd);
668        if (eventName.length() == 0) {
669            if (DBG) Log.i(TAG, "Received wpa_supplicant event with empty event name");
670            return false;
671        }
672        /*
673        * Map event name into event enum
674        */
675        int event;
676        if (eventName.equals(CONNECTED_STR))
677            event = CONNECTED;
678        else if (eventName.equals(DISCONNECTED_STR))
679            event = DISCONNECTED;
680        else if (eventName.equals(STATE_CHANGE_STR))
681            event = STATE_CHANGE;
682        else if (eventName.equals(SCAN_RESULTS_STR))
683            event = SCAN_RESULTS;
684        else if (eventName.equals(LINK_SPEED_STR))
685            event = LINK_SPEED;
686        else if (eventName.equals(TERMINATING_STR))
687            event = TERMINATING;
688        else if (eventName.equals(DRIVER_STATE_STR))
689            event = DRIVER_STATE;
690        else if (eventName.equals(EAP_FAILURE_STR))
691            event = EAP_FAILURE;
692        else if (eventName.equals(ASSOC_REJECT_STR))
693            event = ASSOC_REJECT;
694        else if (eventName.equals(TEMP_DISABLED_STR)) {
695            event = SSID_TEMP_DISABLE;
696        } else if (eventName.equals(REENABLED_STR)) {
697            event = SSID_REENABLE;
698        }
699        else
700            event = UNKNOWN;
701
702        String eventData = eventStr;
703        if (event == DRIVER_STATE || event == LINK_SPEED)
704            eventData = eventData.split(" ")[1];
705        else if (event == STATE_CHANGE || event == EAP_FAILURE) {
706            int ind = eventStr.indexOf(" ");
707            if (ind != -1) {
708                eventData = eventStr.substring(ind + 1);
709            }
710        } else {
711            int ind = eventStr.indexOf(" - ");
712            if (ind != -1) {
713                eventData = eventStr.substring(ind + 3);
714            }
715        }
716
717        if ((event == SSID_TEMP_DISABLE)||(event == SSID_REENABLE)) {
718            String substr = null;
719            int netId = -1;
720            int ind = eventStr.indexOf(" ");
721            if (ind != -1) {
722                substr = eventStr.substring(ind + 1);
723            }
724            if (substr != null) {
725                String status[] = substr.split(" ");
726                for (String key : status) {
727                    if (key.regionMatches(0, "id=", 0, 3)) {
728                        int idx = 3;
729                        netId = 0;
730                        while (idx < key.length()) {
731                            char c = key.charAt(idx);
732                            if ((c >= 0x30) && (c <= 0x39)) {
733                                netId *= 10;
734                                netId += c - 0x30;
735                                idx++;
736                            } else {
737                                break;
738                            }
739                        }
740                    }
741                }
742            }
743            mStateMachine.sendMessage((event == SSID_TEMP_DISABLE)?
744                    SSID_TEMP_DISABLED:SSID_REENABLED, netId, 0, substr);
745        } else if (event == STATE_CHANGE) {
746            handleSupplicantStateChange(eventData);
747        } else if (event == DRIVER_STATE) {
748            handleDriverEvent(eventData);
749        } else if (event == TERMINATING) {
750            /**
751             * Close the supplicant connection if we see
752             * too many recv errors
753             */
754            if (eventData.startsWith(WPA_RECV_ERROR_STR)) {
755                if (++sRecvErrors > MAX_RECV_ERRORS) {
756                    if (DBG) {
757                        Log.d(TAG, "too many recv errors, closing connection");
758                    }
759                } else {
760                    return false;
761                }
762            }
763
764            // notify and exit
765            mStateMachine.sendMessage(SUP_DISCONNECTION_EVENT);
766            return true;
767        } else if (event == EAP_FAILURE) {
768            if (eventData.startsWith(EAP_AUTH_FAILURE_STR)) {
769                logDbg("WifiMonitor send auth failure (EAP_AUTH_FAILURE) ");
770                mStateMachine.sendMessage(AUTHENTICATION_FAILURE_EVENT);
771            }
772        } else if (event == ASSOC_REJECT) {
773            mStateMachine.sendMessage(ASSOCIATION_REJECTION_EVENT);
774        } else {
775            handleEvent(event, eventData);
776        }
777        sRecvErrors = 0;
778        return false;
779    }
780
781    private void handleDriverEvent(String state) {
782        if (state == null) {
783            return;
784        }
785        if (state.equals("HANGED")) {
786            mStateMachine.sendMessage(DRIVER_HUNG_EVENT);
787        }
788    }
789
790    /**
791     * Handle all supplicant events except STATE-CHANGE
792     * @param event the event type
793     * @param remainder the rest of the string following the
794     * event name and &quot;&#8195;&#8212;&#8195;&quot;
795     */
796    void handleEvent(int event, String remainder) {
797        switch (event) {
798            case DISCONNECTED:
799                handleNetworkStateChange(NetworkInfo.DetailedState.DISCONNECTED, remainder);
800                break;
801
802            case CONNECTED:
803                handleNetworkStateChange(NetworkInfo.DetailedState.CONNECTED, remainder);
804                break;
805
806            case SCAN_RESULTS:
807                mStateMachine.sendMessage(SCAN_RESULTS_EVENT);
808                break;
809
810            case UNKNOWN:
811                break;
812        }
813    }
814
815    private void handleWpsFailEvent(String dataString) {
816        final Pattern p = Pattern.compile(WPS_FAIL_PATTERN);
817        Matcher match = p.matcher(dataString);
818        int reason = 0;
819        if (match.find()) {
820            String cfgErrStr = match.group(1);
821            String reasonStr = match.group(2);
822
823            if (reasonStr != null) {
824                int reasonInt = Integer.parseInt(reasonStr);
825                switch(reasonInt) {
826                    case REASON_TKIP_ONLY_PROHIBITED:
827                        mStateMachine.sendMessage(mStateMachine.obtainMessage(WPS_FAIL_EVENT,
828                                WifiManager.WPS_TKIP_ONLY_PROHIBITED, 0));
829                        return;
830                    case REASON_WEP_PROHIBITED:
831                        mStateMachine.sendMessage(mStateMachine.obtainMessage(WPS_FAIL_EVENT,
832                                WifiManager.WPS_WEP_PROHIBITED, 0));
833                        return;
834                    default:
835                        reason = reasonInt;
836                        break;
837                }
838            }
839            if (cfgErrStr != null) {
840                int cfgErrInt = Integer.parseInt(cfgErrStr);
841                switch(cfgErrInt) {
842                    case CONFIG_AUTH_FAILURE:
843                        mStateMachine.sendMessage(mStateMachine.obtainMessage(WPS_FAIL_EVENT,
844                                WifiManager.WPS_AUTH_FAILURE, 0));
845                        return;
846                    case CONFIG_MULTIPLE_PBC_DETECTED:
847                        mStateMachine.sendMessage(mStateMachine.obtainMessage(WPS_FAIL_EVENT,
848                                WifiManager.WPS_OVERLAP_ERROR, 0));
849                        return;
850                    default:
851                        if (reason == 0) reason = cfgErrInt;
852                        break;
853                }
854            }
855        }
856        //For all other errors, return a generic internal error
857        mStateMachine.sendMessage(mStateMachine.obtainMessage(WPS_FAIL_EVENT,
858                WifiManager.ERROR, reason));
859    }
860
861    /* <event> status=<err> and the special case of <event> reason=FREQ_CONFLICT */
862    private P2pStatus p2pError(String dataString) {
863        P2pStatus err = P2pStatus.UNKNOWN;
864        String[] tokens = dataString.split(" ");
865        if (tokens.length < 2) return err;
866        String[] nameValue = tokens[1].split("=");
867        if (nameValue.length != 2) return err;
868
869        /* Handle the special case of reason=FREQ+CONFLICT */
870        if (nameValue[1].equals("FREQ_CONFLICT")) {
871            return P2pStatus.NO_COMMON_CHANNEL;
872        }
873        try {
874            err = P2pStatus.valueOf(Integer.parseInt(nameValue[1]));
875        } catch (NumberFormatException e) {
876            e.printStackTrace();
877        }
878        return err;
879    }
880
881    /**
882     * Handle p2p events
883     */
884    private void handleP2pEvents(String dataString) {
885        if (dataString.startsWith(P2P_DEVICE_FOUND_STR)) {
886            mStateMachine.sendMessage(P2P_DEVICE_FOUND_EVENT, new WifiP2pDevice(dataString));
887        } else if (dataString.startsWith(P2P_DEVICE_LOST_STR)) {
888            mStateMachine.sendMessage(P2P_DEVICE_LOST_EVENT, new WifiP2pDevice(dataString));
889        } else if (dataString.startsWith(P2P_FIND_STOPPED_STR)) {
890            mStateMachine.sendMessage(P2P_FIND_STOPPED_EVENT);
891        } else if (dataString.startsWith(P2P_GO_NEG_REQUEST_STR)) {
892            mStateMachine.sendMessage(P2P_GO_NEGOTIATION_REQUEST_EVENT,
893                    new WifiP2pConfig(dataString));
894        } else if (dataString.startsWith(P2P_GO_NEG_SUCCESS_STR)) {
895            mStateMachine.sendMessage(P2P_GO_NEGOTIATION_SUCCESS_EVENT);
896        } else if (dataString.startsWith(P2P_GO_NEG_FAILURE_STR)) {
897            mStateMachine.sendMessage(P2P_GO_NEGOTIATION_FAILURE_EVENT, p2pError(dataString));
898        } else if (dataString.startsWith(P2P_GROUP_FORMATION_SUCCESS_STR)) {
899            mStateMachine.sendMessage(P2P_GROUP_FORMATION_SUCCESS_EVENT);
900        } else if (dataString.startsWith(P2P_GROUP_FORMATION_FAILURE_STR)) {
901            mStateMachine.sendMessage(P2P_GROUP_FORMATION_FAILURE_EVENT, p2pError(dataString));
902        } else if (dataString.startsWith(P2P_GROUP_STARTED_STR)) {
903            mStateMachine.sendMessage(P2P_GROUP_STARTED_EVENT, new WifiP2pGroup(dataString));
904        } else if (dataString.startsWith(P2P_GROUP_REMOVED_STR)) {
905            mStateMachine.sendMessage(P2P_GROUP_REMOVED_EVENT, new WifiP2pGroup(dataString));
906        } else if (dataString.startsWith(P2P_INVITATION_RECEIVED_STR)) {
907            mStateMachine.sendMessage(P2P_INVITATION_RECEIVED_EVENT,
908                    new WifiP2pGroup(dataString));
909        } else if (dataString.startsWith(P2P_INVITATION_RESULT_STR)) {
910            mStateMachine.sendMessage(P2P_INVITATION_RESULT_EVENT, p2pError(dataString));
911        } else if (dataString.startsWith(P2P_PROV_DISC_PBC_REQ_STR)) {
912            mStateMachine.sendMessage(P2P_PROV_DISC_PBC_REQ_EVENT,
913                    new WifiP2pProvDiscEvent(dataString));
914        } else if (dataString.startsWith(P2P_PROV_DISC_PBC_RSP_STR)) {
915            mStateMachine.sendMessage(P2P_PROV_DISC_PBC_RSP_EVENT,
916                    new WifiP2pProvDiscEvent(dataString));
917        } else if (dataString.startsWith(P2P_PROV_DISC_ENTER_PIN_STR)) {
918            mStateMachine.sendMessage(P2P_PROV_DISC_ENTER_PIN_EVENT,
919                    new WifiP2pProvDiscEvent(dataString));
920        } else if (dataString.startsWith(P2P_PROV_DISC_SHOW_PIN_STR)) {
921            mStateMachine.sendMessage(P2P_PROV_DISC_SHOW_PIN_EVENT,
922                    new WifiP2pProvDiscEvent(dataString));
923        } else if (dataString.startsWith(P2P_PROV_DISC_FAILURE_STR)) {
924            mStateMachine.sendMessage(P2P_PROV_DISC_FAILURE_EVENT);
925        } else if (dataString.startsWith(P2P_SERV_DISC_RESP_STR)) {
926            List<WifiP2pServiceResponse> list = WifiP2pServiceResponse.newInstance(dataString);
927            if (list != null) {
928                mStateMachine.sendMessage(P2P_SERV_DISC_RESP_EVENT, list);
929            } else {
930                Log.e(TAG, "Null service resp " + dataString);
931            }
932        }
933    }
934
935    /**
936     * Handle hostap events
937     */
938    private void handleHostApEvents(String dataString) {
939        String[] tokens = dataString.split(" ");
940        /* AP-STA-CONNECTED 42:fc:89:a8:96:09 p2p_dev_addr=02:90:4c:a0:92:54 */
941        if (tokens[0].equals(AP_STA_CONNECTED_STR)) {
942            mStateMachine.sendMessage(AP_STA_CONNECTED_EVENT, new WifiP2pDevice(dataString));
943            /* AP-STA-DISCONNECTED 42:fc:89:a8:96:09 p2p_dev_addr=02:90:4c:a0:92:54 */
944        } else if (tokens[0].equals(AP_STA_DISCONNECTED_STR)) {
945            mStateMachine.sendMessage(AP_STA_DISCONNECTED_EVENT, new WifiP2pDevice(dataString));
946        }
947    }
948
949    /**
950     * Handle ANQP events
951     */
952    private void handleGasQueryEvents(String dataString) {
953        // hs20
954        if (mStateMachine2 == null) return;
955        if (dataString.startsWith(GAS_QUERY_START_STR)) {
956            mStateMachine2.sendMessage(GAS_QUERY_START_EVENT);
957        } else if (dataString.startsWith(GAS_QUERY_DONE_STR)) {
958            String[] dataTokens = dataString.split(" ");
959            String bssid = null;
960            int success = 0;
961            for (String token : dataTokens) {
962                String[] nameValue = token.split("=");
963                if (nameValue.length != 2) {
964                    continue;
965                }
966                if (nameValue[0].equals("addr")) {
967                    bssid = nameValue[1];
968                    continue;
969                }
970                if (nameValue[0].equals("result"))  {
971                    success = nameValue[1].equals("SUCCESS") ? 1 : 0;
972                    continue;
973                }
974            }
975            mStateMachine2.sendMessage(GAS_QUERY_DONE_EVENT, success, 0, bssid);
976        } else {
977            if (DBG) Log.d(TAG, "Unknown GAS query event: " + dataString);
978        }
979    }
980
981    /**
982     * Handle HS20 events
983     */
984    private void handleHs20Events(String dataString) {
985        if (mStateMachine2 == null) return;
986        if (dataString.startsWith(HS20_SUB_REM_STR)) {
987            // format: HS20-SUBSCRIPTION-REMEDIATION osu_method, url
988            String[] dataTokens = dataString.split(" ");
989            int method = -1;
990            String url = null;
991            if (dataTokens.length >= 3) {
992                method = Integer.parseInt(dataTokens[1]);
993                url = dataTokens[2];
994            }
995            mStateMachine2.sendMessage(HS20_REMEDIATION_EVENT, method, 0, url);
996        } else if (dataString.startsWith(HS20_DEAUTH_STR)) {
997            // format: HS20-DEAUTH-IMMINENT-NOTICE code, delay, url
998            int code = -1;
999            int delay = -1;
1000            String url = null;
1001            String[] dataTokens = dataString.split(" ");
1002            if (dataTokens.length >= 4) {
1003                code = Integer.parseInt(dataTokens[1]);
1004                delay = Integer.parseInt(dataTokens[2]);
1005                url = dataTokens[3];
1006            }
1007            mStateMachine2.sendMessage(HS20_DEAUTH_EVENT, code, delay, url);
1008        } else {
1009            if (DBG) Log.d(TAG, "Unknown HS20 event: " + dataString);
1010        }
1011    }
1012
1013    /**
1014     * Handle the supplicant STATE-CHANGE event
1015     * @param dataString New supplicant state string in the format:
1016     * id=network-id state=new-state
1017     */
1018    private void handleSupplicantStateChange(String dataString) {
1019        WifiSsid wifiSsid = null;
1020        int index = dataString.lastIndexOf("SSID=");
1021        if (index != -1) {
1022            wifiSsid = WifiSsid.createFromAsciiEncoded(
1023                    dataString.substring(index + 5));
1024        }
1025        String[] dataTokens = dataString.split(" ");
1026
1027        String BSSID = null;
1028        int networkId = -1;
1029        int newState  = -1;
1030        for (String token : dataTokens) {
1031            String[] nameValue = token.split("=");
1032            if (nameValue.length != 2) {
1033                continue;
1034            }
1035
1036            if (nameValue[0].equals("BSSID")) {
1037                BSSID = nameValue[1];
1038                continue;
1039            }
1040
1041            int value;
1042            try {
1043                value = Integer.parseInt(nameValue[1]);
1044            } catch (NumberFormatException e) {
1045                continue;
1046            }
1047
1048            if (nameValue[0].equals("id")) {
1049                networkId = value;
1050            } else if (nameValue[0].equals("state")) {
1051                newState = value;
1052            }
1053        }
1054
1055        if (newState == -1) return;
1056
1057        SupplicantState newSupplicantState = SupplicantState.INVALID;
1058        for (SupplicantState state : SupplicantState.values()) {
1059            if (state.ordinal() == newState) {
1060                newSupplicantState = state;
1061                break;
1062            }
1063        }
1064        if (newSupplicantState == SupplicantState.INVALID) {
1065            Log.w(TAG, "Invalid supplicant state: " + newState);
1066        }
1067        notifySupplicantStateChange(networkId, wifiSsid, BSSID, newSupplicantState);
1068    }
1069
1070    private void handleNetworkStateChange(NetworkInfo.DetailedState newState, String data) {
1071        String BSSID = null;
1072        int networkId = -1;
1073        if (newState == NetworkInfo.DetailedState.CONNECTED) {
1074            Matcher match = mConnectedEventPattern.matcher(data);
1075            if (!match.find()) {
1076                if (DBG) Log.d(TAG, "Could not find BSSID in CONNECTED event string");
1077            } else {
1078                BSSID = match.group(1);
1079                try {
1080                    networkId = Integer.parseInt(match.group(2));
1081                } catch (NumberFormatException e) {
1082                    networkId = -1;
1083                }
1084            }
1085            notifyNetworkStateChange(newState, BSSID, networkId);
1086        }
1087    }
1088
1089    /**
1090     * Send the state machine a notification that the state of Wifi connectivity
1091     * has changed.
1092     * @param newState the new network state
1093     * @param BSSID when the new state is {@link NetworkInfo.DetailedState#CONNECTED},
1094     * this is the MAC address of the access point. Otherwise, it
1095     * is {@code null}.
1096     * @param netId the configured network on which the state change occurred
1097     */
1098    void notifyNetworkStateChange(NetworkInfo.DetailedState newState, String BSSID, int netId) {
1099        if (newState == NetworkInfo.DetailedState.CONNECTED) {
1100            Message m = mStateMachine.obtainMessage(NETWORK_CONNECTION_EVENT,
1101                    netId, 0, BSSID);
1102            mStateMachine.sendMessage(m);
1103        } else {
1104            Message m = mStateMachine.obtainMessage(NETWORK_DISCONNECTION_EVENT,
1105                    netId, 0, BSSID);
1106            mStateMachine.sendMessage(m);
1107        }
1108    }
1109
1110    /**
1111     * Send the state machine a notification that the state of the supplicant
1112     * has changed.
1113     * @param networkId the configured network on which the state change occurred
1114     * @param wifiSsid network name
1115     * @param BSSID network address
1116     * @param newState the new {@code SupplicantState}
1117     */
1118    void notifySupplicantStateChange(int networkId, WifiSsid wifiSsid, String BSSID,
1119            SupplicantState newState) {
1120        mStateMachine.sendMessage(mStateMachine.obtainMessage(SUPPLICANT_STATE_CHANGE_EVENT,
1121                new StateChangeResult(networkId, wifiSsid, BSSID, newState)));
1122    }
1123}
1124