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