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