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