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