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