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