WifiMonitor.java revision ede1310be531a84faa08f02c3fd243448dd936dd
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.WifiManager; 22import android.net.wifi.WifiSsid; 23import android.net.wifi.p2p.WifiP2pConfig; 24import android.net.wifi.p2p.WifiP2pDevice; 25import android.net.wifi.p2p.WifiP2pGroup; 26import android.net.wifi.p2p.WifiP2pProvDiscEvent; 27import android.net.wifi.p2p.nsd.WifiP2pServiceResponse; 28import android.os.Message; 29import android.os.SystemClock; 30import android.util.Log; 31 32import com.android.server.wifi.p2p.WifiP2pServiceImpl.P2pStatus; 33 34import com.android.internal.util.Protocol; 35import com.android.internal.util.StateMachine; 36 37import java.util.HashMap; 38import java.util.List; 39import java.util.regex.Matcher; 40import java.util.regex.Pattern; 41 42/** 43 * Listens for events from the wpa_supplicant server, and passes them on 44 * to the {@link StateMachine} for handling. Runs in its own thread. 45 * 46 * @hide 47 */ 48public class WifiMonitor { 49 50 private static final boolean DBG = false; 51 private static final String TAG = "WifiMonitor"; 52 53 /** Events we receive from the supplicant daemon */ 54 55 private static final int CONNECTED = 1; 56 private static final int DISCONNECTED = 2; 57 private static final int STATE_CHANGE = 3; 58 private static final int SCAN_RESULTS = 4; 59 private static final int LINK_SPEED = 5; 60 private static final int TERMINATING = 6; 61 private static final int DRIVER_STATE = 7; 62 private static final int EAP_FAILURE = 8; 63 private static final int ASSOC_REJECT = 9; 64 private static final int SSID_TEMP_DISABLE = 10; 65 private static final int SSID_REENABLE = 11; 66 private static final int UNKNOWN = 12; 67 68 /** All events coming from the supplicant start with this prefix */ 69 private static final String EVENT_PREFIX_STR = "CTRL-EVENT-"; 70 private static final int EVENT_PREFIX_LEN_STR = EVENT_PREFIX_STR.length(); 71 72 /** All WPA events coming from the supplicant start with this prefix */ 73 private static final String WPA_EVENT_PREFIX_STR = "WPA:"; 74 private static final String PASSWORD_MAY_BE_INCORRECT_STR = 75 "pre-shared key may be incorrect"; 76 77 /* WPS events */ 78 private static final String WPS_SUCCESS_STR = "WPS-SUCCESS"; 79 80 /* Format: WPS-FAIL msg=%d [config_error=%d] [reason=%d (%s)] */ 81 private static final String WPS_FAIL_STR = "WPS-FAIL"; 82 private static final String WPS_FAIL_PATTERN = 83 "WPS-FAIL msg=\\d+(?: config_error=(\\d+))?(?: reason=(\\d+))?"; 84 85 /* config error code values for config_error=%d */ 86 private static final int CONFIG_MULTIPLE_PBC_DETECTED = 12; 87 private static final int CONFIG_AUTH_FAILURE = 18; 88 89 /* reason code values for reason=%d */ 90 private static final int REASON_TKIP_ONLY_PROHIBITED = 1; 91 private static final int REASON_WEP_PROHIBITED = 2; 92 93 private static final String WPS_OVERLAP_STR = "WPS-OVERLAP-DETECTED"; 94 private static final String WPS_TIMEOUT_STR = "WPS-TIMEOUT"; 95 96 /** 97 * Names of events from wpa_supplicant (minus the prefix). In the 98 * format descriptions, * "<code>x</code>" 99 * designates a dynamic value that needs to be parsed out from the event 100 * string 101 */ 102 /** 103 * <pre> 104 * CTRL-EVENT-CONNECTED - Connection to xx:xx:xx:xx:xx:xx completed 105 * </pre> 106 * <code>xx:xx:xx:xx:xx:xx</code> is the BSSID of the associated access point 107 */ 108 private static final String CONNECTED_STR = "CONNECTED"; 109 /** 110 * <pre> 111 * CTRL-EVENT-DISCONNECTED - Disconnect event - remove keys 112 * </pre> 113 */ 114 private static final String DISCONNECTED_STR = "DISCONNECTED"; 115 /** 116 * <pre> 117 * CTRL-EVENT-STATE-CHANGE x 118 * </pre> 119 * <code>x</code> is the numerical value of the new state. 120 */ 121 private static final String STATE_CHANGE_STR = "STATE-CHANGE"; 122 /** 123 * <pre> 124 * CTRL-EVENT-SCAN-RESULTS ready 125 * </pre> 126 */ 127 private static final String SCAN_RESULTS_STR = "SCAN-RESULTS"; 128 129 /** 130 * <pre> 131 * CTRL-EVENT-LINK-SPEED x Mb/s 132 * </pre> 133 * {@code x} is the link speed in Mb/sec. 134 */ 135 private static final String LINK_SPEED_STR = "LINK-SPEED"; 136 /** 137 * <pre> 138 * CTRL-EVENT-TERMINATING - signal x 139 * </pre> 140 * <code>x</code> is the signal that caused termination. 141 */ 142 private static final String TERMINATING_STR = "TERMINATING"; 143 /** 144 * <pre> 145 * CTRL-EVENT-DRIVER-STATE state 146 * </pre> 147 * <code>state</code> can be HANGED 148 */ 149 private static final String DRIVER_STATE_STR = "DRIVER-STATE"; 150 /** 151 * <pre> 152 * CTRL-EVENT-EAP-FAILURE EAP authentication failed 153 * </pre> 154 */ 155 private static final String EAP_FAILURE_STR = "EAP-FAILURE"; 156 157 /** 158 * This indicates an authentication failure on EAP FAILURE event 159 */ 160 private static final String EAP_AUTH_FAILURE_STR = "EAP authentication failed"; 161 162 /** 163 * This indicates an assoc reject event 164 */ 165 private static final String ASSOC_REJECT_STR = "ASSOC-REJECT"; 166 167 /** 168 * This indicates auth or association failure bad enough so as network got disabled 169 * - WPA_PSK auth failure suspecting shared key mismatch 170 * - failed multiple Associations 171 */ 172 private static final String TEMP_DISABLED_STR = "SSID-TEMP-DISABLED"; 173 174 /** 175 * This indicates a previously disabled SSID was reenabled by supplicant 176 */ 177 private static final String REENABLED_STR = "SSID-REENABLED"; 178 179 180 /** 181 * Regex pattern for extracting an Ethernet-style MAC address from a string. 182 * Matches a strings like the following:<pre> 183 * CTRL-EVENT-CONNECTED - Connection to 00:1e:58:ec:d5:6d completed (reauth) [id=1 id_str=]</pre> 184 */ 185 private static Pattern mConnectedEventPattern = 186 Pattern.compile("((?:[0-9a-f]{2}:){5}[0-9a-f]{2}) .* \\[id=([0-9]+) "); 187 188 /** P2P events */ 189 private static final String P2P_EVENT_PREFIX_STR = "P2P"; 190 191 /* P2P-DEVICE-FOUND fa:7b:7a:42:02:13 p2p_dev_addr=fa:7b:7a:42:02:13 pri_dev_type=1-0050F204-1 192 name='p2p-TEST1' config_methods=0x188 dev_capab=0x27 group_capab=0x0 */ 193 private static final String P2P_DEVICE_FOUND_STR = "P2P-DEVICE-FOUND"; 194 195 /* P2P-DEVICE-LOST p2p_dev_addr=42:fc:89:e1:e2:27 */ 196 private static final String P2P_DEVICE_LOST_STR = "P2P-DEVICE-LOST"; 197 198 /* P2P-FIND-STOPPED */ 199 private static final String P2P_FIND_STOPPED_STR = "P2P-FIND-STOPPED"; 200 201 /* P2P-GO-NEG-REQUEST 42:fc:89:a8:96:09 dev_passwd_id=4 */ 202 private static final String P2P_GO_NEG_REQUEST_STR = "P2P-GO-NEG-REQUEST"; 203 204 private static final String P2P_GO_NEG_SUCCESS_STR = "P2P-GO-NEG-SUCCESS"; 205 206 /* P2P-GO-NEG-FAILURE status=x */ 207 private static final String P2P_GO_NEG_FAILURE_STR = "P2P-GO-NEG-FAILURE"; 208 209 private static final String P2P_GROUP_FORMATION_SUCCESS_STR = 210 "P2P-GROUP-FORMATION-SUCCESS"; 211 212 private static final String P2P_GROUP_FORMATION_FAILURE_STR = 213 "P2P-GROUP-FORMATION-FAILURE"; 214 215 /* P2P-GROUP-STARTED p2p-wlan0-0 [client|GO] ssid="DIRECT-W8" freq=2437 216 [psk=2182b2e50e53f260d04f3c7b25ef33c965a3291b9b36b455a82d77fd82ca15bc|passphrase="fKG4jMe3"] 217 go_dev_addr=fa:7b:7a:42:02:13 [PERSISTENT] */ 218 private static final String P2P_GROUP_STARTED_STR = "P2P-GROUP-STARTED"; 219 220 /* P2P-GROUP-REMOVED p2p-wlan0-0 [client|GO] reason=REQUESTED */ 221 private static final String P2P_GROUP_REMOVED_STR = "P2P-GROUP-REMOVED"; 222 223 /* P2P-INVITATION-RECEIVED sa=fa:7b:7a:42:02:13 go_dev_addr=f8:7b:7a:42:02:13 224 bssid=fa:7b:7a:42:82:13 unknown-network */ 225 private static final String P2P_INVITATION_RECEIVED_STR = "P2P-INVITATION-RECEIVED"; 226 227 /* P2P-INVITATION-RESULT status=1 */ 228 private static final String P2P_INVITATION_RESULT_STR = "P2P-INVITATION-RESULT"; 229 230 /* P2P-PROV-DISC-PBC-REQ 42:fc:89:e1:e2:27 p2p_dev_addr=42:fc:89:e1:e2:27 231 pri_dev_type=1-0050F204-1 name='p2p-TEST2' config_methods=0x188 dev_capab=0x27 232 group_capab=0x0 */ 233 private static final String P2P_PROV_DISC_PBC_REQ_STR = "P2P-PROV-DISC-PBC-REQ"; 234 235 /* P2P-PROV-DISC-PBC-RESP 02:12:47:f2:5a:36 */ 236 private static final String P2P_PROV_DISC_PBC_RSP_STR = "P2P-PROV-DISC-PBC-RESP"; 237 238 /* P2P-PROV-DISC-ENTER-PIN 42:fc:89:e1:e2:27 p2p_dev_addr=42:fc:89:e1:e2:27 239 pri_dev_type=1-0050F204-1 name='p2p-TEST2' config_methods=0x188 dev_capab=0x27 240 group_capab=0x0 */ 241 private static final String P2P_PROV_DISC_ENTER_PIN_STR = "P2P-PROV-DISC-ENTER-PIN"; 242 /* P2P-PROV-DISC-SHOW-PIN 42:fc:89:e1:e2:27 44490607 p2p_dev_addr=42:fc:89:e1:e2:27 243 pri_dev_type=1-0050F204-1 name='p2p-TEST2' config_methods=0x188 dev_capab=0x27 244 group_capab=0x0 */ 245 private static final String P2P_PROV_DISC_SHOW_PIN_STR = "P2P-PROV-DISC-SHOW-PIN"; 246 /* P2P-PROV-DISC-FAILURE p2p_dev_addr=42:fc:89:e1:e2:27 */ 247 private static final String P2P_PROV_DISC_FAILURE_STR = "P2P-PROV-DISC-FAILURE"; 248 249 /* 250 * Protocol format is as follows.<br> 251 * See the Table.62 in the WiFi Direct specification for the detail. 252 * ______________________________________________________________ 253 * | Length(2byte) | Type(1byte) | TransId(1byte)}| 254 * ______________________________________________________________ 255 * | status(1byte) | vendor specific(variable) | 256 * 257 * P2P-SERV-DISC-RESP 42:fc:89:e1:e2:27 1 0300000101 258 * length=3, service type=0(ALL Service), transaction id=1, 259 * status=1(service protocol type not available)<br> 260 * 261 * P2P-SERV-DISC-RESP 42:fc:89:e1:e2:27 1 0300020201 262 * length=3, service type=2(UPnP), transaction id=2, 263 * status=1(service protocol type not available) 264 * 265 * P2P-SERV-DISC-RESP 42:fc:89:e1:e2:27 1 990002030010757569643a3131323 266 * 2646534652d383537342d353961622d393332322d3333333435363738393034343a3 267 * a75726e3a736368656d61732d75706e702d6f72673a736572766963653a436f6e746 268 * 56e744469726563746f72793a322c757569643a36383539646564652d383537342d3 269 * 53961622d393333322d3132333435363738393031323a3a75706e703a726f6f74646 270 * 576696365 271 * length=153,type=2(UPnP),transaction id=3,status=0 272 * 273 * UPnP Protocol format is as follows. 274 * ______________________________________________________ 275 * | Version (1) | USN (Variable) | 276 * 277 * version=0x10(UPnP1.0) data=usn:uuid:1122de4e-8574-59ab-9322-33345678 278 * 9044::urn:schemas-upnp-org:service:ContentDirectory:2,usn:uuid:6859d 279 * ede-8574-59ab-9332-123456789012::upnp:rootdevice 280 * 281 * P2P-SERV-DISC-RESP 58:17:0c:bc:dd:ca 21 1900010200045f6970 282 * 70c00c000c01094d795072696e746572c027 283 * length=25, type=1(Bonjour),transaction id=2,status=0 284 * 285 * Bonjour Protocol format is as follows. 286 * __________________________________________________________ 287 * |DNS Name(Variable)|DNS Type(1)|Version(1)|RDATA(Variable)| 288 * 289 * DNS Name=_ipp._tcp.local.,DNS type=12(PTR), Version=1, 290 * RDATA=MyPrinter._ipp._tcp.local. 291 * 292 */ 293 private static final String P2P_SERV_DISC_RESP_STR = "P2P-SERV-DISC-RESP"; 294 295 private static final String HOST_AP_EVENT_PREFIX_STR = "AP"; 296 /* AP-STA-CONNECTED 42:fc:89:a8:96:09 dev_addr=02:90:4c:a0:92:54 */ 297 private static final String AP_STA_CONNECTED_STR = "AP-STA-CONNECTED"; 298 /* AP-STA-DISCONNECTED 42:fc:89:a8:96:09 */ 299 private static final String AP_STA_DISCONNECTED_STR = "AP-STA-DISCONNECTED"; 300 301 /* Supplicant events reported to a state machine */ 302 private static final int BASE = Protocol.BASE_WIFI_MONITOR; 303 304 /* Connection to supplicant established */ 305 public static final int SUP_CONNECTION_EVENT = BASE + 1; 306 /* Connection to supplicant lost */ 307 public static final int SUP_DISCONNECTION_EVENT = BASE + 2; 308 /* Network connection completed */ 309 public static final int NETWORK_CONNECTION_EVENT = BASE + 3; 310 /* Network disconnection completed */ 311 public static final int NETWORK_DISCONNECTION_EVENT = BASE + 4; 312 /* Scan results are available */ 313 public static final int SCAN_RESULTS_EVENT = BASE + 5; 314 /* Supplicate state changed */ 315 public static final int SUPPLICANT_STATE_CHANGE_EVENT = BASE + 6; 316 /* Password failure and EAP authentication failure */ 317 public static final int AUTHENTICATION_FAILURE_EVENT = BASE + 7; 318 /* WPS success detected */ 319 public static final int WPS_SUCCESS_EVENT = BASE + 8; 320 /* WPS failure detected */ 321 public static final int WPS_FAIL_EVENT = BASE + 9; 322 /* WPS overlap detected */ 323 public static final int WPS_OVERLAP_EVENT = BASE + 10; 324 /* WPS timeout detected */ 325 public static final int WPS_TIMEOUT_EVENT = BASE + 11; 326 /* Driver was hung */ 327 public static final int DRIVER_HUNG_EVENT = BASE + 12; 328 /* SSID was disabled due to auth failure or excessive 329 * connection failures */ 330 public static final int SSID_TEMP_DISABLED = BASE + 13; 331 /* SSID was reenabled */ 332 public static final int SSID_REENABLED = BASE + 14; 333 334 /* P2P events */ 335 public static final int P2P_DEVICE_FOUND_EVENT = BASE + 21; 336 public static final int P2P_DEVICE_LOST_EVENT = BASE + 22; 337 public static final int P2P_GO_NEGOTIATION_REQUEST_EVENT = BASE + 23; 338 public static final int P2P_GO_NEGOTIATION_SUCCESS_EVENT = BASE + 25; 339 public static final int P2P_GO_NEGOTIATION_FAILURE_EVENT = BASE + 26; 340 public static final int P2P_GROUP_FORMATION_SUCCESS_EVENT = BASE + 27; 341 public static final int P2P_GROUP_FORMATION_FAILURE_EVENT = BASE + 28; 342 public static final int P2P_GROUP_STARTED_EVENT = BASE + 29; 343 public static final int P2P_GROUP_REMOVED_EVENT = BASE + 30; 344 public static final int P2P_INVITATION_RECEIVED_EVENT = BASE + 31; 345 public static final int P2P_INVITATION_RESULT_EVENT = BASE + 32; 346 public static final int P2P_PROV_DISC_PBC_REQ_EVENT = BASE + 33; 347 public static final int P2P_PROV_DISC_PBC_RSP_EVENT = BASE + 34; 348 public static final int P2P_PROV_DISC_ENTER_PIN_EVENT = BASE + 35; 349 public static final int P2P_PROV_DISC_SHOW_PIN_EVENT = BASE + 36; 350 public static final int P2P_FIND_STOPPED_EVENT = BASE + 37; 351 public static final int P2P_SERV_DISC_RESP_EVENT = BASE + 38; 352 public static final int P2P_PROV_DISC_FAILURE_EVENT = BASE + 39; 353 354 /* hostap events */ 355 public static final int AP_STA_DISCONNECTED_EVENT = BASE + 41; 356 public static final int AP_STA_CONNECTED_EVENT = BASE + 42; 357 358 /* Indicates assoc reject event */ 359 public static final int ASSOCIATION_REJECTION_EVENT = BASE + 43; 360 361 /** 362 * This indicates a read error on the monitor socket conenction 363 */ 364 private static final String WPA_RECV_ERROR_STR = "recv error"; 365 366 /** 367 * Max errors before we close supplicant connection 368 */ 369 private static final int MAX_RECV_ERRORS = 10; 370 371 private final String mInterfaceName; 372 private final WifiNative mWifiNative; 373 private final StateMachine mStateMachine; 374 private boolean mMonitoring; 375 376 // This is a global counter, since it's not monitor specific. However, the existing 377 // implementation forwards all "global" control events like CTRL-EVENT-TERMINATING 378 // to the p2p0 monitor. Is that expected ? It seems a bit surprising. 379 // 380 // TODO: If the p2p0 monitor isn't registered, the behaviour is even more surprising. 381 // The event will be dispatched to all monitors, and each of them will end up incrementing 382 // it in their dispatchXXX method. If we have 5 registered monitors (say), 2 consecutive 383 // recv errors will cause us to disconnect from the supplicant (instead of the intended 10). 384 // 385 // This variable is always accessed and modified under a WifiMonitorSingleton lock. 386 private static int sRecvErrors; 387 388 public WifiMonitor(StateMachine wifiStateMachine, WifiNative wifiNative) { 389 if (DBG) Log.d(TAG, "Creating WifiMonitor"); 390 mWifiNative = wifiNative; 391 mInterfaceName = wifiNative.mInterfaceName; 392 mStateMachine = wifiStateMachine; 393 mMonitoring = false; 394 395 WifiMonitorSingleton.sInstance.registerInterfaceMonitor(mInterfaceName, this); 396 } 397 398 public void startMonitoring() { 399 WifiMonitorSingleton.sInstance.startMonitoring(mInterfaceName); 400 } 401 402 public void stopMonitoring() { 403 WifiMonitorSingleton.sInstance.stopMonitoring(mInterfaceName); 404 } 405 406 public void stopSupplicant() { 407 WifiMonitorSingleton.sInstance.stopSupplicant(); 408 } 409 410 public void killSupplicant(boolean p2pSupported) { 411 WifiMonitorSingleton.sInstance.killSupplicant(p2pSupported); 412 } 413 414 private static class WifiMonitorSingleton { 415 private static final WifiMonitorSingleton sInstance = new WifiMonitorSingleton(); 416 417 private final HashMap<String, WifiMonitor> mIfaceMap = new HashMap<String, WifiMonitor>(); 418 private boolean mConnected = false; 419 private WifiNative mWifiNative; 420 421 private WifiMonitorSingleton() { 422 } 423 424 public synchronized void startMonitoring(String iface) { 425 WifiMonitor m = mIfaceMap.get(iface); 426 if (m == null) { 427 Log.e(TAG, "startMonitor called with unknown iface=" + iface); 428 return; 429 } 430 431 Log.d(TAG, "startMonitoring(" + iface + ") with mConnected = " + mConnected); 432 433 if (mConnected) { 434 m.mMonitoring = true; 435 m.mStateMachine.sendMessage(SUP_CONNECTION_EVENT); 436 } else { 437 if (DBG) Log.d(TAG, "connecting to supplicant"); 438 int connectTries = 0; 439 while (true) { 440 if (mWifiNative.connectToSupplicant()) { 441 m.mMonitoring = true; 442 m.mStateMachine.sendMessage(SUP_CONNECTION_EVENT); 443 new MonitorThread(mWifiNative, this).start(); 444 mConnected = true; 445 break; 446 } 447 if (connectTries++ < 5) { 448 try { 449 Thread.sleep(1000); 450 } catch (InterruptedException ignore) { 451 } 452 } else { 453 mIfaceMap.remove(iface); 454 m.mStateMachine.sendMessage(SUP_DISCONNECTION_EVENT); 455 Log.e(TAG, "startMonitoring(" + iface + ") failed!"); 456 break; 457 } 458 } 459 } 460 } 461 462 public synchronized void stopMonitoring(String iface) { 463 WifiMonitor m = mIfaceMap.get(iface); 464 if (DBG) Log.d(TAG, "stopMonitoring(" + iface + ") = " + m.mStateMachine); 465 m.mMonitoring = false; 466 m.mStateMachine.sendMessage(SUP_DISCONNECTION_EVENT); 467 } 468 469 public synchronized void registerInterfaceMonitor(String iface, WifiMonitor m) { 470 if (DBG) Log.d(TAG, "registerInterface(" + iface + "+" + m.mStateMachine + ")"); 471 mIfaceMap.put(iface, m); 472 if (mWifiNative == null) { 473 mWifiNative = m.mWifiNative; 474 } 475 } 476 477 public synchronized void unregisterInterfaceMonitor(String iface) { 478 // REVIEW: When should we call this? If this isn't called, then WifiMonitor 479 // objects will remain in the mIfaceMap; and won't ever get deleted 480 481 WifiMonitor m = mIfaceMap.remove(iface); 482 if (DBG) Log.d(TAG, "unregisterInterface(" + iface + "+" + m.mStateMachine + ")"); 483 } 484 485 public synchronized void stopSupplicant() { 486 mWifiNative.stopSupplicant(); 487 } 488 489 public synchronized void killSupplicant(boolean p2pSupported) { 490 WifiNative.killSupplicant(p2pSupported); 491 mConnected = false; 492 for (WifiMonitor m : mIfaceMap.values()) { 493 m.mMonitoring = false; 494 } 495 } 496 497 private synchronized boolean dispatchEvent(String eventStr) { 498 String iface; 499 if (eventStr.startsWith("IFNAME=")) { 500 int space = eventStr.indexOf(' '); 501 if (space != -1) { 502 iface = eventStr.substring(7, space); 503 if (!mIfaceMap.containsKey(iface) && iface.startsWith("p2p-")) { 504 // p2p interfaces are created dynamically, but we have 505 // only one P2p state machine monitoring all of them; look 506 // for it explicitly, and send messages there .. 507 iface = "p2p0"; 508 } 509 eventStr = eventStr.substring(space + 1); 510 } else { 511 // No point dispatching this event to any interface, the dispatched 512 // event string will begin with "IFNAME=" which dispatchEvent can't really 513 // do anything about. 514 Log.e(TAG, "Dropping malformed event (unparsable iface): " + eventStr); 515 return false; 516 } 517 } else { 518 // events without prefix belong to p2p0 monitor 519 iface = "p2p0"; 520 } 521 522 if (DBG) Log.d(TAG, "Dispatching event to interface: " + iface); 523 524 WifiMonitor m = mIfaceMap.get(iface); 525 if (m != null) { 526 if (m.mMonitoring) { 527 if (m.dispatchEvent(eventStr)) { 528 mConnected = false; 529 return true; 530 } 531 532 return false; 533 } else { 534 if (DBG) Log.d(TAG, "Dropping event because (" + iface + ") is stopped"); 535 return false; 536 } 537 } else { 538 if (DBG) Log.d(TAG, "Sending to all monitors because there's no matching iface"); 539 boolean done = false; 540 for (WifiMonitor monitor : mIfaceMap.values()) { 541 if (monitor.mMonitoring && monitor.dispatchEvent(eventStr)) { 542 done = true; 543 } 544 } 545 546 if (done) { 547 mConnected = false; 548 } 549 550 return done; 551 } 552 } 553 } 554 555 private static class MonitorThread extends Thread { 556 private final WifiNative mWifiNative; 557 private final WifiMonitorSingleton mWifiMonitorSingleton; 558 559 public MonitorThread(WifiNative wifiNative, WifiMonitorSingleton wifiMonitorSingleton) { 560 super("WifiMonitor"); 561 mWifiNative = wifiNative; 562 mWifiMonitorSingleton = wifiMonitorSingleton; 563 } 564 565 public void run() { 566 //noinspection InfiniteLoopStatement 567 for (;;) { 568 String eventStr = mWifiNative.waitForEvent(); 569 570 // Skip logging the common but mostly uninteresting scan-results event 571 if (DBG && eventStr.indexOf(SCAN_RESULTS_STR) == -1) { 572 Log.d(TAG, "Event [" + eventStr + "]"); 573 } 574 575 if (mWifiMonitorSingleton.dispatchEvent(eventStr)) { 576 if (DBG) Log.d(TAG, "Disconnecting from the supplicant, no more events"); 577 break; 578 } 579 } 580 } 581 } 582 583 private void logDbg(String debug) { 584 long now = SystemClock.elapsedRealtimeNanos(); 585 String ts = String.format("[%,d us] ", now/1000); 586 Log.e(TAG, ts+debug+ " stack:" + Thread.currentThread().getStackTrace()[2].getMethodName() 587 +" - "+ Thread.currentThread().getStackTrace()[3].getMethodName() 588 +" - "+ Thread.currentThread().getStackTrace()[4].getMethodName() 589 +" - "+ Thread.currentThread().getStackTrace()[5].getMethodName()); 590 591 } 592 593 /* @return true if the event was supplicant disconnection */ 594 private boolean dispatchEvent(String eventStr) { 595 596 if (DBG) logDbg("WifiMonitor dispatchEvent " + eventStr); 597 598 if (!eventStr.startsWith(EVENT_PREFIX_STR)) { 599 if (eventStr.startsWith(WPA_EVENT_PREFIX_STR) && 600 0 < eventStr.indexOf(PASSWORD_MAY_BE_INCORRECT_STR)) { 601 mStateMachine.sendMessage(AUTHENTICATION_FAILURE_EVENT); 602 } else if (eventStr.startsWith(WPS_SUCCESS_STR)) { 603 mStateMachine.sendMessage(WPS_SUCCESS_EVENT); 604 } else if (eventStr.startsWith(WPS_FAIL_STR)) { 605 handleWpsFailEvent(eventStr); 606 } else if (eventStr.startsWith(WPS_OVERLAP_STR)) { 607 mStateMachine.sendMessage(WPS_OVERLAP_EVENT); 608 } else if (eventStr.startsWith(WPS_TIMEOUT_STR)) { 609 mStateMachine.sendMessage(WPS_TIMEOUT_EVENT); 610 } else if (eventStr.startsWith(P2P_EVENT_PREFIX_STR)) { 611 handleP2pEvents(eventStr); 612 } else if (eventStr.startsWith(HOST_AP_EVENT_PREFIX_STR)) { 613 handleHostApEvents(eventStr); 614 } 615 else { 616 if (DBG) Log.w(TAG, "couldn't identify event type - " + eventStr); 617 } 618 return false; 619 } 620 621 String eventName = eventStr.substring(EVENT_PREFIX_LEN_STR); 622 int nameEnd = eventName.indexOf(' '); 623 if (nameEnd != -1) 624 eventName = eventName.substring(0, nameEnd); 625 if (eventName.length() == 0) { 626 if (DBG) Log.i(TAG, "Received wpa_supplicant event with empty event name"); 627 return false; 628 } 629 /* 630 * Map event name into event enum 631 */ 632 int event; 633 if (eventName.equals(CONNECTED_STR)) 634 event = CONNECTED; 635 else if (eventName.equals(DISCONNECTED_STR)) 636 event = DISCONNECTED; 637 else if (eventName.equals(STATE_CHANGE_STR)) 638 event = STATE_CHANGE; 639 else if (eventName.equals(SCAN_RESULTS_STR)) 640 event = SCAN_RESULTS; 641 else if (eventName.equals(LINK_SPEED_STR)) 642 event = LINK_SPEED; 643 else if (eventName.equals(TERMINATING_STR)) 644 event = TERMINATING; 645 else if (eventName.equals(DRIVER_STATE_STR)) 646 event = DRIVER_STATE; 647 else if (eventName.equals(EAP_FAILURE_STR)) 648 event = EAP_FAILURE; 649 else if (eventName.equals(ASSOC_REJECT_STR)) 650 event = ASSOC_REJECT; 651 else if (eventName.equals(TEMP_DISABLED_STR)) { 652 event = SSID_TEMP_DISABLE; 653 } else if (eventName.equals(REENABLED_STR)) { 654 event = SSID_REENABLE; 655 } 656 else 657 event = UNKNOWN; 658 659 String eventData = eventStr; 660 if (event == DRIVER_STATE || event == LINK_SPEED) 661 eventData = eventData.split(" ")[1]; 662 else if (event == STATE_CHANGE || event == EAP_FAILURE) { 663 int ind = eventStr.indexOf(" "); 664 if (ind != -1) { 665 eventData = eventStr.substring(ind + 1); 666 } 667 } else { 668 int ind = eventStr.indexOf(" - "); 669 if (ind != -1) { 670 eventData = eventStr.substring(ind + 3); 671 } 672 } 673 674 if ((event == SSID_TEMP_DISABLE)||(event == SSID_REENABLE)) { 675 String substr = null; 676 int netId = -1; 677 int ind = eventStr.indexOf(" "); 678 if (ind != -1) { 679 substr = eventStr.substring(ind + 1); 680 } 681 if (substr != null) { 682 String status[] = substr.split(" "); 683 for (String key : status) { 684 if (key.regionMatches(0, "id=", 0, 3)) { 685 int idx = 3; 686 netId = 0; 687 while (idx < key.length()) { 688 char c = key.charAt(idx); 689 if ((c >= 0x30) && (c <= 0x39)) { 690 netId *= 10; 691 netId += c - 0x30; 692 idx++; 693 } else { 694 break; 695 } 696 } 697 } 698 } 699 } 700 mStateMachine.sendMessage((event == SSID_TEMP_DISABLE)? 701 SSID_TEMP_DISABLED:SSID_REENABLED, netId, 0, substr); 702 } else if (event == STATE_CHANGE) { 703 handleSupplicantStateChange(eventData); 704 } else if (event == DRIVER_STATE) { 705 handleDriverEvent(eventData); 706 } else if (event == TERMINATING) { 707 /** 708 * Close the supplicant connection if we see 709 * too many recv errors 710 */ 711 if (eventData.startsWith(WPA_RECV_ERROR_STR)) { 712 if (++sRecvErrors > MAX_RECV_ERRORS) { 713 if (DBG) { 714 Log.d(TAG, "too many recv errors, closing connection"); 715 } 716 } else { 717 return false; 718 } 719 } 720 721 // notify and exit 722 mStateMachine.sendMessage(SUP_DISCONNECTION_EVENT); 723 return true; 724 } else if (event == EAP_FAILURE) { 725 if (eventData.startsWith(EAP_AUTH_FAILURE_STR)) { 726 logDbg("WifiMonitor send auth failure (EAP_AUTH_FAILURE) "); 727 mStateMachine.sendMessage(AUTHENTICATION_FAILURE_EVENT); 728 } 729 } else if (event == ASSOC_REJECT) { 730 mStateMachine.sendMessage(ASSOCIATION_REJECTION_EVENT); 731 } else { 732 handleEvent(event, eventData); 733 } 734 sRecvErrors = 0; 735 return false; 736 } 737 738 private void handleDriverEvent(String state) { 739 if (state == null) { 740 return; 741 } 742 if (state.equals("HANGED")) { 743 mStateMachine.sendMessage(DRIVER_HUNG_EVENT); 744 } 745 } 746 747 /** 748 * Handle all supplicant events except STATE-CHANGE 749 * @param event the event type 750 * @param remainder the rest of the string following the 751 * event name and " — " 752 */ 753 void handleEvent(int event, String remainder) { 754 switch (event) { 755 case DISCONNECTED: 756 handleNetworkStateChange(NetworkInfo.DetailedState.DISCONNECTED, remainder); 757 break; 758 759 case CONNECTED: 760 handleNetworkStateChange(NetworkInfo.DetailedState.CONNECTED, remainder); 761 break; 762 763 case SCAN_RESULTS: 764 mStateMachine.sendMessage(SCAN_RESULTS_EVENT); 765 break; 766 767 case UNKNOWN: 768 break; 769 } 770 } 771 772 private void handleWpsFailEvent(String dataString) { 773 final Pattern p = Pattern.compile(WPS_FAIL_PATTERN); 774 Matcher match = p.matcher(dataString); 775 if (match.find()) { 776 String cfgErr = match.group(1); 777 String reason = match.group(2); 778 779 if (reason != null) { 780 switch(Integer.parseInt(reason)) { 781 case REASON_TKIP_ONLY_PROHIBITED: 782 mStateMachine.sendMessage(mStateMachine.obtainMessage(WPS_FAIL_EVENT, 783 WifiManager.WPS_TKIP_ONLY_PROHIBITED, 0)); 784 return; 785 case REASON_WEP_PROHIBITED: 786 mStateMachine.sendMessage(mStateMachine.obtainMessage(WPS_FAIL_EVENT, 787 WifiManager.WPS_WEP_PROHIBITED, 0)); 788 return; 789 } 790 } 791 if (cfgErr != null) { 792 switch(Integer.parseInt(cfgErr)) { 793 case CONFIG_AUTH_FAILURE: 794 mStateMachine.sendMessage(mStateMachine.obtainMessage(WPS_FAIL_EVENT, 795 WifiManager.WPS_AUTH_FAILURE, 0)); 796 return; 797 case CONFIG_MULTIPLE_PBC_DETECTED: 798 mStateMachine.sendMessage(mStateMachine.obtainMessage(WPS_FAIL_EVENT, 799 WifiManager.WPS_OVERLAP_ERROR, 0)); 800 return; 801 } 802 } 803 } 804 //For all other errors, return a generic internal error 805 mStateMachine.sendMessage(mStateMachine.obtainMessage(WPS_FAIL_EVENT, 806 WifiManager.ERROR, 0)); 807 } 808 809 /* <event> status=<err> and the special case of <event> reason=FREQ_CONFLICT */ 810 private P2pStatus p2pError(String dataString) { 811 P2pStatus err = P2pStatus.UNKNOWN; 812 String[] tokens = dataString.split(" "); 813 if (tokens.length < 2) return err; 814 String[] nameValue = tokens[1].split("="); 815 if (nameValue.length != 2) return err; 816 817 /* Handle the special case of reason=FREQ+CONFLICT */ 818 if (nameValue[1].equals("FREQ_CONFLICT")) { 819 return P2pStatus.NO_COMMON_CHANNEL; 820 } 821 try { 822 err = P2pStatus.valueOf(Integer.parseInt(nameValue[1])); 823 } catch (NumberFormatException e) { 824 e.printStackTrace(); 825 } 826 return err; 827 } 828 829 /** 830 * Handle p2p events 831 */ 832 private void handleP2pEvents(String dataString) { 833 if (dataString.startsWith(P2P_DEVICE_FOUND_STR)) { 834 mStateMachine.sendMessage(P2P_DEVICE_FOUND_EVENT, new WifiP2pDevice(dataString)); 835 } else if (dataString.startsWith(P2P_DEVICE_LOST_STR)) { 836 mStateMachine.sendMessage(P2P_DEVICE_LOST_EVENT, new WifiP2pDevice(dataString)); 837 } else if (dataString.startsWith(P2P_FIND_STOPPED_STR)) { 838 mStateMachine.sendMessage(P2P_FIND_STOPPED_EVENT); 839 } else if (dataString.startsWith(P2P_GO_NEG_REQUEST_STR)) { 840 mStateMachine.sendMessage(P2P_GO_NEGOTIATION_REQUEST_EVENT, 841 new WifiP2pConfig(dataString)); 842 } else if (dataString.startsWith(P2P_GO_NEG_SUCCESS_STR)) { 843 mStateMachine.sendMessage(P2P_GO_NEGOTIATION_SUCCESS_EVENT); 844 } else if (dataString.startsWith(P2P_GO_NEG_FAILURE_STR)) { 845 mStateMachine.sendMessage(P2P_GO_NEGOTIATION_FAILURE_EVENT, p2pError(dataString)); 846 } else if (dataString.startsWith(P2P_GROUP_FORMATION_SUCCESS_STR)) { 847 mStateMachine.sendMessage(P2P_GROUP_FORMATION_SUCCESS_EVENT); 848 } else if (dataString.startsWith(P2P_GROUP_FORMATION_FAILURE_STR)) { 849 mStateMachine.sendMessage(P2P_GROUP_FORMATION_FAILURE_EVENT, p2pError(dataString)); 850 } else if (dataString.startsWith(P2P_GROUP_STARTED_STR)) { 851 mStateMachine.sendMessage(P2P_GROUP_STARTED_EVENT, new WifiP2pGroup(dataString)); 852 } else if (dataString.startsWith(P2P_GROUP_REMOVED_STR)) { 853 mStateMachine.sendMessage(P2P_GROUP_REMOVED_EVENT, new WifiP2pGroup(dataString)); 854 } else if (dataString.startsWith(P2P_INVITATION_RECEIVED_STR)) { 855 mStateMachine.sendMessage(P2P_INVITATION_RECEIVED_EVENT, 856 new WifiP2pGroup(dataString)); 857 } else if (dataString.startsWith(P2P_INVITATION_RESULT_STR)) { 858 mStateMachine.sendMessage(P2P_INVITATION_RESULT_EVENT, p2pError(dataString)); 859 } else if (dataString.startsWith(P2P_PROV_DISC_PBC_REQ_STR)) { 860 mStateMachine.sendMessage(P2P_PROV_DISC_PBC_REQ_EVENT, 861 new WifiP2pProvDiscEvent(dataString)); 862 } else if (dataString.startsWith(P2P_PROV_DISC_PBC_RSP_STR)) { 863 mStateMachine.sendMessage(P2P_PROV_DISC_PBC_RSP_EVENT, 864 new WifiP2pProvDiscEvent(dataString)); 865 } else if (dataString.startsWith(P2P_PROV_DISC_ENTER_PIN_STR)) { 866 mStateMachine.sendMessage(P2P_PROV_DISC_ENTER_PIN_EVENT, 867 new WifiP2pProvDiscEvent(dataString)); 868 } else if (dataString.startsWith(P2P_PROV_DISC_SHOW_PIN_STR)) { 869 mStateMachine.sendMessage(P2P_PROV_DISC_SHOW_PIN_EVENT, 870 new WifiP2pProvDiscEvent(dataString)); 871 } else if (dataString.startsWith(P2P_PROV_DISC_FAILURE_STR)) { 872 mStateMachine.sendMessage(P2P_PROV_DISC_FAILURE_EVENT); 873 } else if (dataString.startsWith(P2P_SERV_DISC_RESP_STR)) { 874 List<WifiP2pServiceResponse> list = WifiP2pServiceResponse.newInstance(dataString); 875 if (list != null) { 876 mStateMachine.sendMessage(P2P_SERV_DISC_RESP_EVENT, list); 877 } else { 878 Log.e(TAG, "Null service resp " + dataString); 879 } 880 } 881 } 882 883 /** 884 * Handle hostap events 885 */ 886 private void handleHostApEvents(String dataString) { 887 String[] tokens = dataString.split(" "); 888 /* AP-STA-CONNECTED 42:fc:89:a8:96:09 p2p_dev_addr=02:90:4c:a0:92:54 */ 889 if (tokens[0].equals(AP_STA_CONNECTED_STR)) { 890 mStateMachine.sendMessage(AP_STA_CONNECTED_EVENT, new WifiP2pDevice(dataString)); 891 /* AP-STA-DISCONNECTED 42:fc:89:a8:96:09 p2p_dev_addr=02:90:4c:a0:92:54 */ 892 } else if (tokens[0].equals(AP_STA_DISCONNECTED_STR)) { 893 mStateMachine.sendMessage(AP_STA_DISCONNECTED_EVENT, new WifiP2pDevice(dataString)); 894 } 895 } 896 897 /** 898 * Handle the supplicant STATE-CHANGE event 899 * @param dataString New supplicant state string in the format: 900 * id=network-id state=new-state 901 */ 902 private void handleSupplicantStateChange(String dataString) { 903 WifiSsid wifiSsid = null; 904 int index = dataString.lastIndexOf("SSID="); 905 if (index != -1) { 906 wifiSsid = WifiSsid.createFromAsciiEncoded( 907 dataString.substring(index + 5)); 908 } 909 String[] dataTokens = dataString.split(" "); 910 911 String BSSID = null; 912 int networkId = -1; 913 int newState = -1; 914 for (String token : dataTokens) { 915 String[] nameValue = token.split("="); 916 if (nameValue.length != 2) { 917 continue; 918 } 919 920 if (nameValue[0].equals("BSSID")) { 921 BSSID = nameValue[1]; 922 continue; 923 } 924 925 int value; 926 try { 927 value = Integer.parseInt(nameValue[1]); 928 } catch (NumberFormatException e) { 929 continue; 930 } 931 932 if (nameValue[0].equals("id")) { 933 networkId = value; 934 } else if (nameValue[0].equals("state")) { 935 newState = value; 936 } 937 } 938 939 if (newState == -1) return; 940 941 SupplicantState newSupplicantState = SupplicantState.INVALID; 942 for (SupplicantState state : SupplicantState.values()) { 943 if (state.ordinal() == newState) { 944 newSupplicantState = state; 945 break; 946 } 947 } 948 if (newSupplicantState == SupplicantState.INVALID) { 949 Log.w(TAG, "Invalid supplicant state: " + newState); 950 } 951 notifySupplicantStateChange(networkId, wifiSsid, BSSID, newSupplicantState); 952 } 953 954 private void handleNetworkStateChange(NetworkInfo.DetailedState newState, String data) { 955 String BSSID = null; 956 int networkId = -1; 957 if (newState == NetworkInfo.DetailedState.CONNECTED) { 958 Matcher match = mConnectedEventPattern.matcher(data); 959 if (!match.find()) { 960 if (DBG) Log.d(TAG, "Could not find BSSID in CONNECTED event string"); 961 } else { 962 BSSID = match.group(1); 963 try { 964 networkId = Integer.parseInt(match.group(2)); 965 } catch (NumberFormatException e) { 966 networkId = -1; 967 } 968 } 969 notifyNetworkStateChange(newState, BSSID, networkId); 970 } 971 } 972 973 /** 974 * Send the state machine a notification that the state of Wifi connectivity 975 * has changed. 976 * @param newState the new network state 977 * @param BSSID when the new state is {@link NetworkInfo.DetailedState#CONNECTED}, 978 * this is the MAC address of the access point. Otherwise, it 979 * is {@code null}. 980 * @param netId the configured network on which the state change occurred 981 */ 982 void notifyNetworkStateChange(NetworkInfo.DetailedState newState, String BSSID, int netId) { 983 if (newState == NetworkInfo.DetailedState.CONNECTED) { 984 Message m = mStateMachine.obtainMessage(NETWORK_CONNECTION_EVENT, 985 netId, 0, BSSID); 986 mStateMachine.sendMessage(m); 987 } else { 988 Message m = mStateMachine.obtainMessage(NETWORK_DISCONNECTION_EVENT, 989 netId, 0, BSSID); 990 mStateMachine.sendMessage(m); 991 } 992 } 993 994 /** 995 * Send the state machine a notification that the state of the supplicant 996 * has changed. 997 * @param networkId the configured network on which the state change occurred 998 * @param wifiSsid network name 999 * @param BSSID network address 1000 * @param newState the new {@code SupplicantState} 1001 */ 1002 void notifySupplicantStateChange(int networkId, WifiSsid wifiSsid, String BSSID, 1003 SupplicantState newState) { 1004 mStateMachine.sendMessage(mStateMachine.obtainMessage(SUPPLICANT_STATE_CHANGE_EVENT, 1005 new StateChangeResult(networkId, wifiSsid, BSSID, newState))); 1006 } 1007} 1008