• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 
17 package com.android.server.wifi;
18 
19 import android.net.NetworkInfo;
20 import android.net.wifi.SupplicantState;
21 import android.net.wifi.WifiEnterpriseConfig;
22 import android.net.wifi.WifiManager;
23 import android.net.wifi.WifiSsid;
24 import android.net.wifi.p2p.WifiP2pConfig;
25 import android.net.wifi.p2p.WifiP2pDevice;
26 import android.net.wifi.p2p.WifiP2pGroup;
27 import android.net.wifi.p2p.WifiP2pProvDiscEvent;
28 import android.net.wifi.p2p.nsd.WifiP2pServiceResponse;
29 import android.os.Handler;
30 import android.os.Message;
31 import android.text.TextUtils;
32 import android.util.ArraySet;
33 import android.util.Base64;
34 import android.util.LocalLog;
35 import android.util.Log;
36 import android.util.SparseArray;
37 
38 import com.android.server.wifi.hotspot2.IconEvent;
39 import com.android.server.wifi.hotspot2.Utils;
40 import com.android.server.wifi.p2p.WifiP2pServiceImpl.P2pStatus;
41 
42 import com.android.internal.util.Protocol;
43 import com.android.internal.util.StateMachine;
44 
45 import java.io.IOException;
46 import java.util.HashMap;
47 import java.util.LinkedHashMap;
48 import java.util.List;
49 import java.util.Map;
50 import java.util.Set;
51 import java.util.regex.Matcher;
52 import 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  */
60 public 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();
getInstance()529     public static WifiMonitor getInstance() {
530         return sWifiMonitor;
531     }
532 
533     private final WifiNative mWifiNative;
WifiMonitor()534     private WifiMonitor() {
535         mWifiNative = WifiNative.getWlanNativeInterface();
536     }
537 
538     private int mRecvErrors = 0;
539 
enableVerboseLogging(int verbose)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<>();
registerHandler(String iface, int what, Handler handler)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<>();
isMonitoring(String iface)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 
setMonitoring(String iface, boolean enabled)577     private void setMonitoring(String iface, boolean enabled) {
578         mMonitoringMap.put(iface, enabled);
579     }
setMonitoringNone()580     private void setMonitoringNone() {
581         for (String iface : mMonitoringMap.keySet()) {
582             setMonitoring(iface, false);
583         }
584     }
585 
586 
ensureConnectedLocked()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(mWifiNative.getLocalLog()).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 
startMonitoring(String iface)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 
stopMonitoring(String iface)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 
stopSupplicant()634     public synchronized void stopSupplicant() {
635         mWifiNative.stopSupplicant();
636     }
637 
killSupplicant(boolean p2pSupported)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      */
sendMessage(String iface, int what)658     private void sendMessage(String iface, int what) {
659         sendMessage(iface, Message.obtain(null, what));
660     }
661 
sendMessage(String iface, int what, Object obj)662     private void sendMessage(String iface, int what, Object obj) {
663         sendMessage(iface, Message.obtain(null, what, obj));
664     }
665 
sendMessage(String iface, int what, int arg1)666     private void sendMessage(String iface, int what, int arg1) {
667         sendMessage(iface, Message.obtain(null, what, arg1, 0));
668     }
669 
sendMessage(String iface, int what, int arg1, int arg2)670     private void sendMessage(String iface, int what, int arg1, int arg2) {
671         sendMessage(iface, Message.obtain(null, what, arg1, arg2));
672     }
673 
sendMessage(String iface, int what, int arg1, int arg2, Object obj)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 
sendMessage(String iface, Message message)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 
sendMessage(Handler handler, Message message)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;
727 
MonitorThread(LocalLog localLog)728         public MonitorThread(LocalLog localLog) {
729             super("WifiMonitor");
730             mLocalLog = localLog;
731         }
732 
run()733         public void run() {
734             if (DBG) {
735                 Log.d(TAG, "MonitorThread start with mConnected=" + mConnected);
736             }
737             //noinspection InfiniteLoopStatement
738             for (;;) {
739                 if (!mConnected) {
740                     if (DBG) Log.d(TAG, "MonitorThread exit because mConnected is false");
741                     break;
742                 }
743                 String eventStr = mWifiNative.waitForEvent();
744 
745                 // Skip logging the common but mostly uninteresting events
746                 if (!eventStr.contains(BSS_ADDED_STR) && !eventStr.contains(BSS_REMOVED_STR)) {
747                     if (DBG) Log.d(TAG, "Event [" + eventStr + "]");
748                     mLocalLog.log("Event [" + eventStr + "]");
749                 }
750 
751                 if (dispatchEvent(eventStr)) {
752                     if (DBG) Log.d(TAG, "Disconnecting from the supplicant, no more events");
753                     break;
754                 }
755             }
756         }
757     }
758 
dispatchEvent(String eventStr)759     private synchronized boolean dispatchEvent(String eventStr) {
760         String iface;
761         // IFNAME=wlan0 ANQP-QUERY-DONE addr=18:cf:5e:26:a4:88 result=SUCCESS
762         if (eventStr.startsWith("IFNAME=")) {
763             int space = eventStr.indexOf(' ');
764             if (space != -1) {
765                 iface = eventStr.substring(7, space);
766                 if (!mHandlerMap.containsKey(iface) && iface.startsWith("p2p-")) {
767                     // p2p interfaces are created dynamically, but we have
768                     // only one P2p state machine monitoring all of them; look
769                     // for it explicitly, and send messages there ..
770                     iface = "p2p0";
771                 }
772                 eventStr = eventStr.substring(space + 1);
773             } else {
774                 // No point dispatching this event to any interface, the dispatched
775                 // event string will begin with "IFNAME=" which dispatchEvent can't really
776                 // do anything about.
777                 Log.e(TAG, "Dropping malformed event (unparsable iface): " + eventStr);
778                 return false;
779             }
780         } else {
781             // events without prefix belong to p2p0 monitor
782             iface = "p2p0";
783         }
784 
785         if (VDBG) Log.d(TAG, "Dispatching event to interface: " + iface);
786 
787         if (dispatchEvent(eventStr, iface)) {
788             mConnected = false;
789             return true;
790         }
791         return false;
792     }
793 
794     private Map<String, Long> mLastConnectBSSIDs = new HashMap<String, Long>() {
795         public Long get(String iface) {
796             Long value = super.get(iface);
797             if (value != null) {
798                 return value;
799             }
800             return 0L;
801         }
802     };
803 
804     /* @return true if the event was supplicant disconnection */
dispatchEvent(String eventStr, String iface)805     private boolean dispatchEvent(String eventStr, String iface) {
806         if (DBG) {
807             // Dont log CTRL-EVENT-BSS-ADDED which are too verbose and not handled
808             if (eventStr != null && !eventStr.contains("CTRL-EVENT-BSS-ADDED")) {
809                 Log.d(TAG, iface + " cnt=" + Integer.toString(eventLogCounter)
810                         + " dispatchEvent: " + eventStr);
811             }
812         }
813 
814         if (!eventStr.startsWith(EVENT_PREFIX_STR)) {
815             if (eventStr.startsWith(WPS_SUCCESS_STR)) {
816                 sendMessage(iface, WPS_SUCCESS_EVENT);
817             } else if (eventStr.startsWith(WPS_FAIL_STR)) {
818                 handleWpsFailEvent(eventStr, iface);
819             } else if (eventStr.startsWith(WPS_OVERLAP_STR)) {
820                 sendMessage(iface, WPS_OVERLAP_EVENT);
821             } else if (eventStr.startsWith(WPS_TIMEOUT_STR)) {
822                 sendMessage(iface, WPS_TIMEOUT_EVENT);
823             } else if (eventStr.startsWith(P2P_EVENT_PREFIX_STR)) {
824                 handleP2pEvents(eventStr, iface);
825             } else if (eventStr.startsWith(HOST_AP_EVENT_PREFIX_STR)) {
826                 handleHostApEvents(eventStr, iface);
827             } else if (eventStr.startsWith(ANQP_DONE_STR)) {
828                 try {
829                     handleAnqpResult(eventStr, iface);
830                 }
831                 catch (IllegalArgumentException iae) {
832                     Log.e(TAG, "Bad ANQP event string: '" + eventStr + "': " + iae);
833                 }
834             } else if (eventStr.startsWith(HS20_ICON_STR)) {
835                 try {
836                     handleIconResult(eventStr, iface);
837                 }
838                 catch (IllegalArgumentException iae) {
839                     Log.e(TAG, "Bad Icon event string: '" + eventStr + "': " + iae);
840                 }
841             }
842             else if (eventStr.startsWith(HS20_SUB_REM_STR)) {
843                 // Tack on the last connected BSSID so we have some idea what AP the WNM pertains to
844                 handleWnmFrame(String.format("%012x %s",
845                                 mLastConnectBSSIDs.get(iface), eventStr), iface);
846             } else if (eventStr.startsWith(HS20_DEAUTH_STR)) {
847                 handleWnmFrame(String.format("%012x %s",
848                                 mLastConnectBSSIDs.get(iface), eventStr), iface);
849             } else if (eventStr.startsWith(REQUEST_PREFIX_STR)) {
850                 handleRequests(eventStr, iface);
851             } else if (eventStr.startsWith(TARGET_BSSID_STR)) {
852                 handleTargetBSSIDEvent(eventStr, iface);
853             } else if (eventStr.startsWith(ASSOCIATED_WITH_STR)) {
854                 handleAssociatedBSSIDEvent(eventStr, iface);
855             } else if (eventStr.startsWith(AUTH_EVENT_PREFIX_STR) &&
856                     eventStr.endsWith(AUTH_TIMEOUT_STR)) {
857                 sendMessage(iface, AUTHENTICATION_FAILURE_EVENT);
858             } else {
859                 if (DBG) Log.w(TAG, "couldn't identify event type - " + eventStr);
860             }
861             eventLogCounter++;
862             return false;
863         }
864 
865         String eventName = eventStr.substring(EVENT_PREFIX_LEN_STR);
866         int nameEnd = eventName.indexOf(' ');
867         if (nameEnd != -1)
868             eventName = eventName.substring(0, nameEnd);
869         if (eventName.length() == 0) {
870             if (DBG) Log.i(TAG, "Received wpa_supplicant event with empty event name");
871             eventLogCounter++;
872             return false;
873         }
874         /*
875         * Map event name into event enum
876         */
877         int event;
878         if (eventName.equals(CONNECTED_STR)) {
879             event = CONNECTED;
880             long bssid = -1L;
881             int prefix = eventStr.indexOf(ConnectPrefix);
882             if (prefix >= 0) {
883                 int suffix = eventStr.indexOf(ConnectSuffix);
884                 if (suffix > prefix) {
885                     try {
886                         bssid = Utils.parseMac(
887                                 eventStr.substring(prefix + ConnectPrefix.length(), suffix));
888                     } catch (IllegalArgumentException iae) {
889                         bssid = -1L;
890                     }
891                 }
892             }
893             mLastConnectBSSIDs.put(iface, bssid);
894             if (bssid == -1L) {
895                 Log.w(TAG, "Failed to parse out BSSID from '" + eventStr + "'");
896             }
897         }
898         else if (eventName.equals(DISCONNECTED_STR))
899             event = DISCONNECTED;
900         else if (eventName.equals(STATE_CHANGE_STR))
901             event = STATE_CHANGE;
902         else if (eventName.equals(SCAN_RESULTS_STR))
903             event = SCAN_RESULTS;
904         else if (eventName.equals(SCAN_FAILED_STR))
905             event = SCAN_FAILED;
906         else if (eventName.equals(LINK_SPEED_STR))
907             event = LINK_SPEED;
908         else if (eventName.equals(TERMINATING_STR))
909             event = TERMINATING;
910         else if (eventName.equals(DRIVER_STATE_STR))
911             event = DRIVER_STATE;
912         else if (eventName.equals(EAP_FAILURE_STR))
913             event = EAP_FAILURE;
914         else if (eventName.equals(ASSOC_REJECT_STR))
915             event = ASSOC_REJECT;
916         else if (eventName.equals(TEMP_DISABLED_STR)) {
917             event = SSID_TEMP_DISABLE;
918         } else if (eventName.equals(REENABLED_STR)) {
919             event = SSID_REENABLE;
920         } else if (eventName.equals(BSS_ADDED_STR)) {
921             event = BSS_ADDED;
922         } else if (eventName.equals(BSS_REMOVED_STR)) {
923             event = BSS_REMOVED;
924         } else
925             event = UNKNOWN;
926 
927         String eventData = eventStr;
928         if (event == DRIVER_STATE || event == LINK_SPEED)
929             eventData = eventData.split(" ")[1];
930         else if (event == STATE_CHANGE || event == EAP_FAILURE) {
931             int ind = eventStr.indexOf(" ");
932             if (ind != -1) {
933                 eventData = eventStr.substring(ind + 1);
934             }
935         } else {
936             int ind = eventStr.indexOf(" - ");
937             if (ind != -1) {
938                 eventData = eventStr.substring(ind + 3);
939             }
940         }
941 
942         if ((event == SSID_TEMP_DISABLE)||(event == SSID_REENABLE)) {
943             String substr = null;
944             int netId = -1;
945             int ind = eventStr.indexOf(" ");
946             if (ind != -1) {
947                 substr = eventStr.substring(ind + 1);
948             }
949             if (substr != null) {
950                 String status[] = substr.split(" ");
951                 for (String key : status) {
952                     if (key.regionMatches(0, "id=", 0, 3)) {
953                         int idx = 3;
954                         netId = 0;
955                         while (idx < key.length()) {
956                             char c = key.charAt(idx);
957                             if ((c >= 0x30) && (c <= 0x39)) {
958                                 netId *= 10;
959                                 netId += c - 0x30;
960                                 idx++;
961                             } else {
962                                 break;
963                             }
964                         }
965                     }
966                 }
967             }
968             sendMessage(iface, (event == SSID_TEMP_DISABLE)?
969                     SSID_TEMP_DISABLED:SSID_REENABLED, netId, 0, substr);
970         } else if (event == STATE_CHANGE) {
971             handleSupplicantStateChange(eventData, iface);
972         } else if (event == DRIVER_STATE) {
973             handleDriverEvent(eventData, iface);
974         } else if (event == TERMINATING) {
975             /**
976              * Close the supplicant connection if we see
977              * too many recv errors
978              */
979             if (eventData.startsWith(WPA_RECV_ERROR_STR)) {
980                 if (++mRecvErrors > MAX_RECV_ERRORS) {
981                     if (DBG) {
982                         Log.d(TAG, "too many recv errors, closing connection");
983                     }
984                 } else {
985                     eventLogCounter++;
986                     return false;
987                 }
988             }
989 
990             // Notify and exit
991             sendMessage(null, SUP_DISCONNECTION_EVENT, eventLogCounter);
992             return true;
993         } else if (event == EAP_FAILURE) {
994             if (eventData.startsWith(EAP_AUTH_FAILURE_STR)) {
995                 sendMessage(iface, AUTHENTICATION_FAILURE_EVENT, eventLogCounter);
996             }
997         } else if (event == ASSOC_REJECT) {
998             Matcher match = mAssocRejectEventPattern.matcher(eventData);
999             String BSSID = "";
1000             int status = -1;
1001             if (!match.find()) {
1002                 if (DBG) Log.d(TAG, "Assoc Reject: Could not parse assoc reject string");
1003             } else {
1004                 int groupNumber = match.groupCount();
1005                 int statusGroupNumber = -1;
1006                 if (groupNumber == 2) {
1007                     BSSID = match.group(1);
1008                     statusGroupNumber = 2;
1009                 } else {
1010                     // Under such case Supplicant does not report BSSID
1011                     BSSID = null;
1012                     statusGroupNumber = 1;
1013                 }
1014                 try {
1015                     status = Integer.parseInt(match.group(statusGroupNumber));
1016                 } catch (NumberFormatException e) {
1017                     status = -1;
1018                 }
1019             }
1020             sendMessage(iface, ASSOCIATION_REJECTION_EVENT, eventLogCounter, status, BSSID);
1021         } else if (event == BSS_ADDED && !VDBG) {
1022             // Ignore that event - it is not handled, and dont log it as it is too verbose
1023         } else if (event == BSS_REMOVED && !VDBG) {
1024             // Ignore that event - it is not handled, and dont log it as it is too verbose
1025         }  else {
1026             handleEvent(event, eventData, iface);
1027         }
1028         mRecvErrors = 0;
1029         eventLogCounter++;
1030         return false;
1031     }
1032 
handleDriverEvent(String state, String iface)1033     private void handleDriverEvent(String state, String iface) {
1034         if (state == null) {
1035             return;
1036         }
1037         if (state.equals("HANGED")) {
1038             sendMessage(iface, DRIVER_HUNG_EVENT);
1039         }
1040     }
1041 
1042     /**
1043      * Handle all supplicant events except STATE-CHANGE
1044      * @param event the event type
1045      * @param remainder the rest of the string following the
1046      * event name and &quot;&#8195;&#8212;&#8195;&quot;
1047      */
handleEvent(int event, String remainder, String iface)1048     private void handleEvent(int event, String remainder, String iface) {
1049         if (DBG) {
1050             Log.d(TAG, "handleEvent " + Integer.toString(event) + " " + remainder);
1051         }
1052         switch (event) {
1053             case DISCONNECTED:
1054                 handleNetworkStateChange(NetworkInfo.DetailedState.DISCONNECTED, remainder, iface);
1055                 break;
1056 
1057             case CONNECTED:
1058                 handleNetworkStateChange(NetworkInfo.DetailedState.CONNECTED, remainder, iface);
1059                 break;
1060 
1061             case SCAN_RESULTS:
1062                 sendMessage(iface, SCAN_RESULTS_EVENT);
1063                 break;
1064 
1065             case SCAN_FAILED:
1066                 sendMessage(iface, SCAN_FAILED_EVENT);
1067                 break;
1068 
1069             case UNKNOWN:
1070                 if (DBG) {
1071                     Log.w(TAG, "handleEvent unknown: " + Integer.toString(event) + " " + remainder);
1072                 }
1073                 break;
1074             default:
1075                 break;
1076         }
1077     }
1078 
handleTargetBSSIDEvent(String eventStr, String iface)1079     private void handleTargetBSSIDEvent(String eventStr, String iface) {
1080         String BSSID = null;
1081         Matcher match = mTargetBSSIDPattern.matcher(eventStr);
1082         if (match.find()) {
1083             BSSID = match.group(1);
1084         }
1085         sendMessage(iface, WifiStateMachine.CMD_TARGET_BSSID, eventLogCounter, 0, BSSID);
1086     }
1087 
handleAssociatedBSSIDEvent(String eventStr, String iface)1088     private void handleAssociatedBSSIDEvent(String eventStr, String iface) {
1089         String BSSID = null;
1090         Matcher match = mAssociatedPattern.matcher(eventStr);
1091         if (match.find()) {
1092             BSSID = match.group(1);
1093         }
1094         sendMessage(iface, WifiStateMachine.CMD_ASSOCIATED_BSSID, eventLogCounter, 0, BSSID);
1095     }
1096 
1097 
handleWpsFailEvent(String dataString, String iface)1098     private void handleWpsFailEvent(String dataString, String iface) {
1099         final Pattern p = Pattern.compile(WPS_FAIL_PATTERN);
1100         Matcher match = p.matcher(dataString);
1101         int reason = 0;
1102         if (match.find()) {
1103             String cfgErrStr = match.group(1);
1104             String reasonStr = match.group(2);
1105 
1106             if (reasonStr != null) {
1107                 int reasonInt = Integer.parseInt(reasonStr);
1108                 switch(reasonInt) {
1109                     case REASON_TKIP_ONLY_PROHIBITED:
1110                         sendMessage(iface, WPS_FAIL_EVENT, WifiManager.WPS_TKIP_ONLY_PROHIBITED);
1111                         return;
1112                     case REASON_WEP_PROHIBITED:
1113                         sendMessage(iface, WPS_FAIL_EVENT, WifiManager.WPS_WEP_PROHIBITED);
1114                         return;
1115                     default:
1116                         reason = reasonInt;
1117                         break;
1118                 }
1119             }
1120             if (cfgErrStr != null) {
1121                 int cfgErrInt = Integer.parseInt(cfgErrStr);
1122                 switch(cfgErrInt) {
1123                     case CONFIG_AUTH_FAILURE:
1124                         sendMessage(iface, WPS_FAIL_EVENT, WifiManager.WPS_AUTH_FAILURE);
1125                         return;
1126                     case CONFIG_MULTIPLE_PBC_DETECTED:
1127                         sendMessage(iface, WPS_FAIL_EVENT, WifiManager.WPS_OVERLAP_ERROR);
1128                         return;
1129                     default:
1130                         if (reason == 0) reason = cfgErrInt;
1131                         break;
1132                 }
1133             }
1134         }
1135         //For all other errors, return a generic internal error
1136         sendMessage(iface, WPS_FAIL_EVENT, WifiManager.ERROR, reason);
1137     }
1138 
1139     /* <event> status=<err> and the special case of <event> reason=FREQ_CONFLICT */
p2pError(String dataString)1140     private P2pStatus p2pError(String dataString) {
1141         P2pStatus err = P2pStatus.UNKNOWN;
1142         String[] tokens = dataString.split(" ");
1143         if (tokens.length < 2) return err;
1144         String[] nameValue = tokens[1].split("=");
1145         if (nameValue.length != 2) return err;
1146 
1147         /* Handle the special case of reason=FREQ+CONFLICT */
1148         if (nameValue[1].equals("FREQ_CONFLICT")) {
1149             return P2pStatus.NO_COMMON_CHANNEL;
1150         }
1151         try {
1152             err = P2pStatus.valueOf(Integer.parseInt(nameValue[1]));
1153         } catch (NumberFormatException e) {
1154             e.printStackTrace();
1155         }
1156         return err;
1157     }
1158 
getWifiP2pDevice(String dataString)1159     private WifiP2pDevice getWifiP2pDevice(String dataString) {
1160         try {
1161             return new WifiP2pDevice(dataString);
1162         } catch (IllegalArgumentException e) {
1163             return null;
1164         }
1165     }
1166 
getWifiP2pGroup(String dataString)1167     private WifiP2pGroup getWifiP2pGroup(String dataString) {
1168         try {
1169             return new WifiP2pGroup(dataString);
1170         } catch (IllegalArgumentException e) {
1171             return null;
1172         }
1173     }
1174 
1175     /**
1176      * Handle p2p events
1177      */
handleP2pEvents(String dataString, String iface)1178     private void handleP2pEvents(String dataString, String iface) {
1179         if (dataString.startsWith(P2P_DEVICE_FOUND_STR)) {
1180             WifiP2pDevice device = getWifiP2pDevice(dataString);
1181             if (device != null) sendMessage(iface, P2P_DEVICE_FOUND_EVENT, device);
1182         } else if (dataString.startsWith(P2P_DEVICE_LOST_STR)) {
1183             WifiP2pDevice device = getWifiP2pDevice(dataString);
1184             if (device != null) sendMessage(iface, P2P_DEVICE_LOST_EVENT, device);
1185         } else if (dataString.startsWith(P2P_FIND_STOPPED_STR)) {
1186             sendMessage(iface, P2P_FIND_STOPPED_EVENT);
1187         } else if (dataString.startsWith(P2P_GO_NEG_REQUEST_STR)) {
1188             sendMessage(iface, P2P_GO_NEGOTIATION_REQUEST_EVENT, new WifiP2pConfig(dataString));
1189         } else if (dataString.startsWith(P2P_GO_NEG_SUCCESS_STR)) {
1190             sendMessage(iface, P2P_GO_NEGOTIATION_SUCCESS_EVENT);
1191         } else if (dataString.startsWith(P2P_GO_NEG_FAILURE_STR)) {
1192             sendMessage(iface, P2P_GO_NEGOTIATION_FAILURE_EVENT, p2pError(dataString));
1193         } else if (dataString.startsWith(P2P_GROUP_FORMATION_SUCCESS_STR)) {
1194             sendMessage(iface, P2P_GROUP_FORMATION_SUCCESS_EVENT);
1195         } else if (dataString.startsWith(P2P_GROUP_FORMATION_FAILURE_STR)) {
1196             sendMessage(iface, P2P_GROUP_FORMATION_FAILURE_EVENT, p2pError(dataString));
1197         } else if (dataString.startsWith(P2P_GROUP_STARTED_STR)) {
1198             WifiP2pGroup group = getWifiP2pGroup(dataString);
1199             if (group != null) sendMessage(iface, P2P_GROUP_STARTED_EVENT, group);
1200         } else if (dataString.startsWith(P2P_GROUP_REMOVED_STR)) {
1201             WifiP2pGroup group = getWifiP2pGroup(dataString);
1202             if (group != null) sendMessage(iface, P2P_GROUP_REMOVED_EVENT, group);
1203         } else if (dataString.startsWith(P2P_INVITATION_RECEIVED_STR)) {
1204             sendMessage(iface, P2P_INVITATION_RECEIVED_EVENT, new WifiP2pGroup(dataString));
1205         } else if (dataString.startsWith(P2P_INVITATION_RESULT_STR)) {
1206             sendMessage(iface, P2P_INVITATION_RESULT_EVENT, p2pError(dataString));
1207         } else if (dataString.startsWith(P2P_PROV_DISC_PBC_REQ_STR)) {
1208             sendMessage(iface, P2P_PROV_DISC_PBC_REQ_EVENT, new WifiP2pProvDiscEvent(dataString));
1209         } else if (dataString.startsWith(P2P_PROV_DISC_PBC_RSP_STR)) {
1210             sendMessage(iface, P2P_PROV_DISC_PBC_RSP_EVENT, new WifiP2pProvDiscEvent(dataString));
1211         } else if (dataString.startsWith(P2P_PROV_DISC_ENTER_PIN_STR)) {
1212             sendMessage(iface, P2P_PROV_DISC_ENTER_PIN_EVENT, new WifiP2pProvDiscEvent(dataString));
1213         } else if (dataString.startsWith(P2P_PROV_DISC_SHOW_PIN_STR)) {
1214             sendMessage(iface, P2P_PROV_DISC_SHOW_PIN_EVENT, new WifiP2pProvDiscEvent(dataString));
1215         } else if (dataString.startsWith(P2P_PROV_DISC_FAILURE_STR)) {
1216             sendMessage(iface, P2P_PROV_DISC_FAILURE_EVENT);
1217         } else if (dataString.startsWith(P2P_SERV_DISC_RESP_STR)) {
1218             List<WifiP2pServiceResponse> list = WifiP2pServiceResponse.newInstance(dataString);
1219             if (list != null) {
1220                 sendMessage(iface, P2P_SERV_DISC_RESP_EVENT, list);
1221             } else {
1222                 Log.e(TAG, "Null service resp " + dataString);
1223             }
1224         }
1225     }
1226 
1227     /**
1228      * Handle hostap events
1229      */
handleHostApEvents(String dataString, String iface)1230     private void handleHostApEvents(String dataString, String iface) {
1231         String[] tokens = dataString.split(" ");
1232         /* AP-STA-CONNECTED 42:fc:89:a8:96:09 p2p_dev_addr=02:90:4c:a0:92:54 */
1233         if (tokens[0].equals(AP_STA_CONNECTED_STR)) {
1234             sendMessage(iface, AP_STA_CONNECTED_EVENT, new WifiP2pDevice(dataString));
1235             /* AP-STA-DISCONNECTED 42:fc:89:a8:96:09 p2p_dev_addr=02:90:4c:a0:92:54 */
1236         } else if (tokens[0].equals(AP_STA_DISCONNECTED_STR)) {
1237             sendMessage(iface, AP_STA_DISCONNECTED_EVENT, new WifiP2pDevice(dataString));
1238         }
1239     }
1240 
1241     private static final String ADDR_STRING = "addr=";
1242     private static final String RESULT_STRING = "result=";
1243 
1244     // ANQP-QUERY-DONE addr=18:cf:5e:26:a4:88 result=SUCCESS
1245 
handleAnqpResult(String eventStr, String iface)1246     private void handleAnqpResult(String eventStr, String iface) {
1247         int addrPos = eventStr.indexOf(ADDR_STRING);
1248         int resPos = eventStr.indexOf(RESULT_STRING);
1249         if (addrPos < 0 || resPos < 0) {
1250             throw new IllegalArgumentException("Unexpected ANQP result notification");
1251         }
1252         int eoaddr = eventStr.indexOf(' ', addrPos + ADDR_STRING.length());
1253         if (eoaddr < 0) {
1254             eoaddr = eventStr.length();
1255         }
1256         int eoresult = eventStr.indexOf(' ', resPos + RESULT_STRING.length());
1257         if (eoresult < 0) {
1258             eoresult = eventStr.length();
1259         }
1260 
1261         try {
1262             long bssid = Utils.parseMac(eventStr.substring(addrPos + ADDR_STRING.length(), eoaddr));
1263             int result = eventStr.substring(
1264                     resPos + RESULT_STRING.length(), eoresult).equalsIgnoreCase("success") ? 1 : 0;
1265 
1266             sendMessage(iface, ANQP_DONE_EVENT, result, 0, bssid);
1267         }
1268         catch (IllegalArgumentException iae) {
1269             Log.e(TAG, "Bad MAC address in ANQP response: " + iae.getMessage());
1270         }
1271     }
1272 
handleIconResult(String eventStr, String iface)1273     private void handleIconResult(String eventStr, String iface) {
1274         // RX-HS20-ICON c0:c5:20:27:d1:e8 <file> <size>
1275         String[] segments = eventStr.split(" ");
1276         if (segments.length != 4) {
1277             throw new IllegalArgumentException("Incorrect number of segments");
1278         }
1279 
1280         try {
1281             String bssid = segments[1];
1282             String fileName = segments[2];
1283             int size = Integer.parseInt(segments[3]);
1284             sendMessage(iface, RX_HS20_ANQP_ICON_EVENT,
1285                     new IconEvent(Utils.parseMac(bssid), fileName, size));
1286         }
1287         catch (NumberFormatException nfe) {
1288             throw new IllegalArgumentException("Bad numeral");
1289         }
1290     }
1291 
handleWnmFrame(String eventStr, String iface)1292     private void handleWnmFrame(String eventStr, String iface) {
1293         try {
1294             WnmData wnmData = WnmData.buildWnmData(eventStr);
1295             sendMessage(iface, HS20_REMEDIATION_EVENT, wnmData);
1296         } catch (IOException | NumberFormatException e) {
1297             Log.w(TAG, "Bad WNM event: '" + eventStr + "'");
1298         }
1299     }
1300 
1301     /**
1302      * Handle Supplicant Requests
1303      */
handleRequests(String dataString, String iface)1304     private void handleRequests(String dataString, String iface) {
1305         String SSID = null;
1306         int reason = -2;
1307         String requestName = dataString.substring(REQUEST_PREFIX_LEN_STR);
1308         if (TextUtils.isEmpty(requestName)) {
1309             return;
1310         }
1311         if (requestName.startsWith(IDENTITY_STR)) {
1312             Matcher match = mRequestIdentityPattern.matcher(requestName);
1313             if (match.find()) {
1314                 SSID = match.group(2);
1315                 try {
1316                     reason = Integer.parseInt(match.group(1));
1317                 } catch (NumberFormatException e) {
1318                     reason = -1;
1319                 }
1320             } else {
1321                 Log.e(TAG, "didn't find SSID " + requestName);
1322             }
1323             sendMessage(iface, SUP_REQUEST_IDENTITY, eventLogCounter, reason, SSID);
1324         } else if (requestName.startsWith(SIM_STR)) {
1325             Matcher matchGsm = mRequestGsmAuthPattern.matcher(requestName);
1326             Matcher matchUmts = mRequestUmtsAuthPattern.matcher(requestName);
1327             WifiStateMachine.SimAuthRequestData data =
1328                     new WifiStateMachine.SimAuthRequestData();
1329             if (matchGsm.find()) {
1330                 data.networkId = Integer.parseInt(matchGsm.group(1));
1331                 data.protocol = WifiEnterpriseConfig.Eap.SIM;
1332                 data.ssid = matchGsm.group(4);
1333                 data.data = matchGsm.group(2).split(":");
1334                 sendMessage(iface, SUP_REQUEST_SIM_AUTH, data);
1335             } else if (matchUmts.find()) {
1336                 data.networkId = Integer.parseInt(matchUmts.group(1));
1337                 data.protocol = WifiEnterpriseConfig.Eap.AKA;
1338                 data.ssid = matchUmts.group(4);
1339                 data.data = new String[2];
1340                 data.data[0] = matchUmts.group(2);
1341                 data.data[1] = matchUmts.group(3);
1342                 sendMessage(iface, SUP_REQUEST_SIM_AUTH, data);
1343             } else {
1344                 Log.e(TAG, "couldn't parse SIM auth request - " + requestName);
1345             }
1346 
1347         } else {
1348             if (DBG) Log.w(TAG, "couldn't identify request type - " + dataString);
1349         }
1350     }
1351 
1352     /**
1353      * Handle the supplicant STATE-CHANGE event
1354      * @param dataString New supplicant state string in the format:
1355      * id=network-id state=new-state
1356      */
handleSupplicantStateChange(String dataString, String iface)1357     private void handleSupplicantStateChange(String dataString, String iface) {
1358         WifiSsid wifiSsid = null;
1359         int index = dataString.lastIndexOf("SSID=");
1360         if (index != -1) {
1361             wifiSsid = WifiSsid.createFromAsciiEncoded(
1362                     dataString.substring(index + 5));
1363         }
1364         String[] dataTokens = dataString.split(" ");
1365 
1366         String BSSID = null;
1367         int networkId = -1;
1368         int newState  = -1;
1369         for (String token : dataTokens) {
1370             String[] nameValue = token.split("=");
1371             if (nameValue.length != 2) {
1372                 continue;
1373             }
1374 
1375             if (nameValue[0].equals("BSSID")) {
1376                 BSSID = nameValue[1];
1377                 continue;
1378             }
1379 
1380             int value;
1381             try {
1382                 value = Integer.parseInt(nameValue[1]);
1383             } catch (NumberFormatException e) {
1384                 continue;
1385             }
1386 
1387             if (nameValue[0].equals("id")) {
1388                 networkId = value;
1389             } else if (nameValue[0].equals("state")) {
1390                 newState = value;
1391             }
1392         }
1393 
1394         if (newState == -1) return;
1395 
1396         SupplicantState newSupplicantState = SupplicantState.INVALID;
1397         for (SupplicantState state : SupplicantState.values()) {
1398             if (state.ordinal() == newState) {
1399                 newSupplicantState = state;
1400                 break;
1401             }
1402         }
1403         if (newSupplicantState == SupplicantState.INVALID) {
1404             Log.w(TAG, "Invalid supplicant state: " + newState);
1405         }
1406         sendMessage(iface, SUPPLICANT_STATE_CHANGE_EVENT, eventLogCounter, 0,
1407                 new StateChangeResult(networkId, wifiSsid, BSSID, newSupplicantState));
1408     }
1409 
handleNetworkStateChange(NetworkInfo.DetailedState newState, String data, String iface)1410     private void handleNetworkStateChange(NetworkInfo.DetailedState newState, String data,
1411             String iface) {
1412         String BSSID = null;
1413         int networkId = -1;
1414         int reason = 0;
1415         int ind = -1;
1416         int local = 0;
1417         Matcher match;
1418         if (newState == NetworkInfo.DetailedState.CONNECTED) {
1419             match = mConnectedEventPattern.matcher(data);
1420             if (!match.find()) {
1421                if (DBG) Log.d(TAG, "handleNetworkStateChange: Couldnt find BSSID in event string");
1422             } else {
1423                 BSSID = match.group(1);
1424                 try {
1425                     networkId = Integer.parseInt(match.group(2));
1426                 } catch (NumberFormatException e) {
1427                     networkId = -1;
1428                 }
1429             }
1430             sendMessage(iface, NETWORK_CONNECTION_EVENT, networkId, reason, BSSID);
1431         } else if (newState == NetworkInfo.DetailedState.DISCONNECTED) {
1432             match = mDisconnectedEventPattern.matcher(data);
1433             if (!match.find()) {
1434                if (DBG) Log.d(TAG, "handleNetworkStateChange: Could not parse disconnect string");
1435             } else {
1436                 BSSID = match.group(1);
1437                 try {
1438                     reason = Integer.parseInt(match.group(2));
1439                 } catch (NumberFormatException e) {
1440                     reason = -1;
1441                 }
1442                 try {
1443                     local = Integer.parseInt(match.group(3));
1444                 } catch (NumberFormatException e) {
1445                     local = -1;
1446                 }
1447             }
1448             if (DBG) Log.d(TAG, "WifiMonitor notify network disconnect: "
1449                     + BSSID
1450                     + " reason=" + Integer.toString(reason));
1451             sendMessage(iface, NETWORK_DISCONNECTION_EVENT, local, reason, BSSID);
1452         }
1453     }
1454 }
1455