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