WifiNative.java revision 590f3fc2045389d5ef274c4b3bd6162d93b1a0ac
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.annotation.Nullable; 20import android.app.AlarmManager; 21import android.app.PendingIntent; 22import android.content.BroadcastReceiver; 23import android.content.Context; 24import android.content.Intent; 25import android.content.IntentFilter; 26import android.net.apf.ApfCapabilities; 27import android.net.wifi.RttManager; 28import android.net.wifi.RttManager.ResponderConfig; 29import android.net.wifi.ScanResult; 30import android.net.wifi.WifiConfiguration; 31import android.net.wifi.WifiEnterpriseConfig; 32import android.net.wifi.WifiLinkLayerStats; 33import android.net.wifi.WifiManager; 34import android.net.wifi.WifiScanner; 35import android.net.wifi.WifiSsid; 36import android.net.wifi.WifiWakeReasonAndCounts; 37import android.net.wifi.WpsInfo; 38import android.net.wifi.p2p.WifiP2pConfig; 39import android.net.wifi.p2p.WifiP2pGroup; 40import android.net.wifi.p2p.nsd.WifiP2pServiceInfo; 41import android.os.SystemClock; 42import android.os.SystemProperties; 43import android.text.TextUtils; 44import android.util.LocalLog; 45import android.util.Log; 46 47import com.android.internal.annotations.Immutable; 48import com.android.internal.util.HexDump; 49import com.android.server.connectivity.KeepalivePacketData; 50import com.android.server.wifi.hotspot2.NetworkDetail; 51import com.android.server.wifi.hotspot2.SupplicantBridge; 52import com.android.server.wifi.hotspot2.Utils; 53import com.android.server.wifi.util.FrameParser; 54import com.android.server.wifi.util.InformationElementUtil; 55 56import libcore.util.HexEncoding; 57 58import org.json.JSONException; 59import org.json.JSONObject; 60 61import java.io.PrintWriter; 62import java.io.StringWriter; 63import java.io.UnsupportedEncodingException; 64import java.net.URLDecoder; 65import java.net.URLEncoder; 66import java.nio.ByteBuffer; 67import java.nio.CharBuffer; 68import java.nio.charset.CharacterCodingException; 69import java.nio.charset.CharsetDecoder; 70import java.nio.charset.StandardCharsets; 71import java.util.ArrayList; 72import java.util.BitSet; 73import java.util.HashMap; 74import java.util.Iterator; 75import java.util.List; 76import java.util.Locale; 77import java.util.Map; 78import java.util.Set; 79 80 81/** 82 * Native calls for bring up/shut down of the supplicant daemon and for 83 * sending requests to the supplicant daemon 84 * 85 * waitForEvent() is called on the monitor thread for events. All other methods 86 * must be serialized from the framework. 87 * 88 * {@hide} 89 */ 90public class WifiNative { 91 private static boolean DBG = false; 92 93 // Must match wifi_hal.h 94 public static final int WIFI_SUCCESS = 0; 95 96 /** 97 * Hold this lock before calling supplicant or HAL methods 98 * it is required to mutually exclude access to the driver 99 */ 100 public static final Object sLock = new Object(); 101 102 private static final LocalLog sLocalLog = new LocalLog(16384); 103 104 public static LocalLog getLocalLog() { 105 return sLocalLog; 106 } 107 108 /* Register native functions */ 109 static { 110 /* Native functions are defined in libwifi-service.so */ 111 System.loadLibrary("wifi-service"); 112 registerNatives(); 113 } 114 115 private static native int registerNatives(); 116 117 /* 118 * Singleton WifiNative instances 119 */ 120 private static WifiNative wlanNativeInterface = 121 new WifiNative(SystemProperties.get("wifi.interface", "wlan0"), true); 122 public static WifiNative getWlanNativeInterface() { 123 return wlanNativeInterface; 124 } 125 126 private static WifiNative p2pNativeInterface = 127 // commands for p2p0 interface don't need prefix 128 new WifiNative(SystemProperties.get("wifi.direct.interface", "p2p0"), false); 129 public static WifiNative getP2pNativeInterface() { 130 return p2pNativeInterface; 131 } 132 133 134 private final String mTAG; 135 private final String mInterfaceName; 136 private final String mInterfacePrefix; 137 138 private Context mContext = null; 139 public void initContext(Context context) { 140 if (mContext == null && context != null) { 141 mContext = context; 142 } 143 } 144 145 private WifiNative(String interfaceName, 146 boolean requiresPrefix) { 147 mInterfaceName = interfaceName; 148 mTAG = "WifiNative-" + interfaceName; 149 150 if (requiresPrefix) { 151 mInterfacePrefix = "IFNAME=" + interfaceName + " "; 152 } else { 153 mInterfacePrefix = ""; 154 } 155 } 156 157 public String getInterfaceName() { 158 return mInterfaceName; 159 } 160 161 // Note this affects logging on for all interfaces 162 void enableVerboseLogging(int verbose) { 163 if (verbose > 0) { 164 DBG = true; 165 } else { 166 DBG = false; 167 } 168 } 169 170 private void localLog(String s) { 171 if (sLocalLog != null) sLocalLog.log(mInterfaceName + ": " + s); 172 } 173 174 175 176 /* 177 * Driver and Supplicant management 178 */ 179 private native static boolean loadDriverNative(); 180 public boolean loadDriver() { 181 synchronized (sLock) { 182 return loadDriverNative(); 183 } 184 } 185 186 private native static boolean isDriverLoadedNative(); 187 public boolean isDriverLoaded() { 188 synchronized (sLock) { 189 return isDriverLoadedNative(); 190 } 191 } 192 193 private native static boolean unloadDriverNative(); 194 public boolean unloadDriver() { 195 synchronized (sLock) { 196 return unloadDriverNative(); 197 } 198 } 199 200 private native static boolean startSupplicantNative(boolean p2pSupported); 201 public boolean startSupplicant(boolean p2pSupported) { 202 synchronized (sLock) { 203 return startSupplicantNative(p2pSupported); 204 } 205 } 206 207 /* Sends a kill signal to supplicant. To be used when we have lost connection 208 or when the supplicant is hung */ 209 private native static boolean killSupplicantNative(boolean p2pSupported); 210 public boolean killSupplicant(boolean p2pSupported) { 211 synchronized (sLock) { 212 return killSupplicantNative(p2pSupported); 213 } 214 } 215 216 private native static boolean connectToSupplicantNative(); 217 public boolean connectToSupplicant() { 218 synchronized (sLock) { 219 localLog(mInterfacePrefix + "connectToSupplicant"); 220 return connectToSupplicantNative(); 221 } 222 } 223 224 private native static void closeSupplicantConnectionNative(); 225 public void closeSupplicantConnection() { 226 synchronized (sLock) { 227 localLog(mInterfacePrefix + "closeSupplicantConnection"); 228 closeSupplicantConnectionNative(); 229 } 230 } 231 232 /** 233 * Wait for the supplicant to send an event, returning the event string. 234 * @return the event string sent by the supplicant. 235 */ 236 private native static String waitForEventNative(); 237 public String waitForEvent() { 238 // No synchronization necessary .. it is implemented in WifiMonitor 239 return waitForEventNative(); 240 } 241 242 243 /* 244 * Supplicant Command Primitives 245 */ 246 private native boolean doBooleanCommandNative(String command); 247 248 private native int doIntCommandNative(String command); 249 250 private native String doStringCommandNative(String command); 251 252 private boolean doBooleanCommand(String command) { 253 if (DBG) Log.d(mTAG, "doBoolean: " + command); 254 synchronized (sLock) { 255 String toLog = mInterfacePrefix + command; 256 boolean result = doBooleanCommandNative(mInterfacePrefix + command); 257 localLog(toLog + " -> " + result); 258 if (DBG) Log.d(mTAG, command + ": returned " + result); 259 return result; 260 } 261 } 262 263 private boolean doBooleanCommandWithoutLogging(String command) { 264 if (DBG) Log.d(mTAG, "doBooleanCommandWithoutLogging: " + command); 265 synchronized (sLock) { 266 boolean result = doBooleanCommandNative(mInterfacePrefix + command); 267 if (DBG) Log.d(mTAG, command + ": returned " + result); 268 return result; 269 } 270 } 271 272 private int doIntCommand(String command) { 273 if (DBG) Log.d(mTAG, "doInt: " + command); 274 synchronized (sLock) { 275 String toLog = mInterfacePrefix + command; 276 int result = doIntCommandNative(mInterfacePrefix + command); 277 localLog(toLog + " -> " + result); 278 if (DBG) Log.d(mTAG, " returned " + result); 279 return result; 280 } 281 } 282 283 private String doStringCommand(String command) { 284 if (DBG) { 285 //GET_NETWORK commands flood the logs 286 if (!command.startsWith("GET_NETWORK")) { 287 Log.d(mTAG, "doString: [" + command + "]"); 288 } 289 } 290 synchronized (sLock) { 291 String toLog = mInterfacePrefix + command; 292 String result = doStringCommandNative(mInterfacePrefix + command); 293 if (result == null) { 294 if (DBG) Log.d(mTAG, "doStringCommandNative no result"); 295 } else { 296 if (!command.startsWith("STATUS-")) { 297 localLog(toLog + " -> " + result); 298 } 299 if (DBG) Log.d(mTAG, " returned " + result.replace("\n", " ")); 300 } 301 return result; 302 } 303 } 304 305 private String doStringCommandWithoutLogging(String command) { 306 if (DBG) { 307 //GET_NETWORK commands flood the logs 308 if (!command.startsWith("GET_NETWORK")) { 309 Log.d(mTAG, "doString: [" + command + "]"); 310 } 311 } 312 synchronized (sLock) { 313 return doStringCommandNative(mInterfacePrefix + command); 314 } 315 } 316 317 public String doCustomSupplicantCommand(String command) { 318 return doStringCommand(command); 319 } 320 321 /* 322 * Wrappers for supplicant commands 323 */ 324 public boolean ping() { 325 String pong = doStringCommand("PING"); 326 return (pong != null && pong.equals("PONG")); 327 } 328 329 public void setSupplicantLogLevel(String level) { 330 doStringCommand("LOG_LEVEL " + level); 331 } 332 333 public String getFreqCapability() { 334 return doStringCommand("GET_CAPABILITY freq"); 335 } 336 337 /** 338 * Create a comma separate string from integer set. 339 * @param values List of integers. 340 * @return comma separated string. 341 */ 342 private static String createCSVStringFromIntegerSet(Set<Integer> values) { 343 StringBuilder list = new StringBuilder(); 344 boolean first = true; 345 for (Integer value : values) { 346 if (!first) { 347 list.append(","); 348 } 349 list.append(value); 350 first = false; 351 } 352 return list.toString(); 353 } 354 355 /** 356 * Start a scan using wpa_supplicant for the given frequencies. 357 * @param freqs list of frequencies to scan for, if null scan all supported channels. 358 * @param hiddenNetworkIds List of hidden networks to be scanned for. 359 */ 360 public boolean scan(Set<Integer> freqs, Set<Integer> hiddenNetworkIds) { 361 String freqList = null; 362 String hiddenNetworkIdList = null; 363 if (freqs != null && freqs.size() != 0) { 364 freqList = createCSVStringFromIntegerSet(freqs); 365 } 366 if (hiddenNetworkIds != null && hiddenNetworkIds.size() != 0) { 367 hiddenNetworkIdList = createCSVStringFromIntegerSet(hiddenNetworkIds); 368 } 369 return scanWithParams(freqList, hiddenNetworkIdList); 370 } 371 372 private boolean scanWithParams(String freqList, String hiddenNetworkIdList) { 373 StringBuilder scanCommand = new StringBuilder(); 374 scanCommand.append("SCAN TYPE=ONLY"); 375 if (freqList != null) { 376 scanCommand.append(" freq=" + freqList); 377 } 378 if (hiddenNetworkIdList != null) { 379 scanCommand.append(" scan_id=" + hiddenNetworkIdList); 380 } 381 return doBooleanCommand(scanCommand.toString()); 382 } 383 384 /* Does a graceful shutdown of supplicant. Is a common stop function for both p2p and sta. 385 * 386 * Note that underneath we use a harsh-sounding "terminate" supplicant command 387 * for a graceful stop and a mild-sounding "stop" interface 388 * to kill the process 389 */ 390 public boolean stopSupplicant() { 391 return doBooleanCommand("TERMINATE"); 392 } 393 394 public String listNetworks() { 395 return doStringCommand("LIST_NETWORKS"); 396 } 397 398 public String listNetworks(int last_id) { 399 return doStringCommand("LIST_NETWORKS LAST_ID=" + last_id); 400 } 401 402 public int addNetwork() { 403 return doIntCommand("ADD_NETWORK"); 404 } 405 406 public boolean setNetworkExtra(int netId, String name, Map<String, String> values) { 407 final String encoded; 408 try { 409 encoded = URLEncoder.encode(new JSONObject(values).toString(), "UTF-8"); 410 } catch (NullPointerException e) { 411 Log.e(TAG, "Unable to serialize networkExtra: " + e.toString()); 412 return false; 413 } catch (UnsupportedEncodingException e) { 414 Log.e(TAG, "Unable to serialize networkExtra: " + e.toString()); 415 return false; 416 } 417 return setNetworkVariable(netId, name, "\"" + encoded + "\""); 418 } 419 420 public boolean setNetworkVariable(int netId, String name, String value) { 421 if (TextUtils.isEmpty(name) || TextUtils.isEmpty(value)) return false; 422 if (name.equals(WifiConfiguration.pskVarName) 423 || name.equals(WifiEnterpriseConfig.PASSWORD_KEY)) { 424 return doBooleanCommandWithoutLogging("SET_NETWORK " + netId + " " + name + " " + value); 425 } else { 426 return doBooleanCommand("SET_NETWORK " + netId + " " + name + " " + value); 427 } 428 } 429 430 public Map<String, String> getNetworkExtra(int netId, String name) { 431 final String wrapped = getNetworkVariable(netId, name); 432 if (wrapped == null || !wrapped.startsWith("\"") || !wrapped.endsWith("\"")) { 433 return null; 434 } 435 try { 436 final String encoded = wrapped.substring(1, wrapped.length() - 1); 437 // This method reads a JSON dictionary that was written by setNetworkExtra(). However, 438 // on devices that upgraded from Marshmallow, it may encounter a legacy value instead - 439 // an FQDN stored as a plain string. If such a value is encountered, the JSONObject 440 // constructor will thrown a JSONException and the method will return null. 441 final JSONObject json = new JSONObject(URLDecoder.decode(encoded, "UTF-8")); 442 final Map<String, String> values = new HashMap<String, String>(); 443 final Iterator<?> it = json.keys(); 444 while (it.hasNext()) { 445 final String key = (String) it.next(); 446 final Object value = json.get(key); 447 if (value instanceof String) { 448 values.put(key, (String) value); 449 } 450 } 451 return values; 452 } catch (UnsupportedEncodingException e) { 453 Log.e(TAG, "Unable to deserialize networkExtra: " + e.toString()); 454 return null; 455 } catch (JSONException e) { 456 // This is not necessarily an error. This exception will also occur if we encounter a 457 // legacy FQDN stored as a plain string. We want to return null in this case as no JSON 458 // dictionary of extras was found. 459 return null; 460 } 461 } 462 463 public String getNetworkVariable(int netId, String name) { 464 if (TextUtils.isEmpty(name)) return null; 465 466 // GET_NETWORK will likely flood the logs ... 467 return doStringCommandWithoutLogging("GET_NETWORK " + netId + " " + name); 468 } 469 470 public boolean removeNetwork(int netId) { 471 return doBooleanCommand("REMOVE_NETWORK " + netId); 472 } 473 474 475 private void logDbg(String debug) { 476 long now = SystemClock.elapsedRealtimeNanos(); 477 String ts = String.format("[%,d us] ", now/1000); 478 Log.e("WifiNative: ", ts+debug+ " stack:" 479 + Thread.currentThread().getStackTrace()[2].getMethodName() +" - " 480 + Thread.currentThread().getStackTrace()[3].getMethodName() +" - " 481 + Thread.currentThread().getStackTrace()[4].getMethodName() +" - " 482 + Thread.currentThread().getStackTrace()[5].getMethodName()+" - " 483 + Thread.currentThread().getStackTrace()[6].getMethodName()); 484 485 } 486 487 /** 488 * Enables a network in wpa_supplicant. 489 * @param netId - Network ID of the network to be enabled. 490 * @return true if command succeeded, false otherwise. 491 */ 492 public boolean enableNetwork(int netId) { 493 if (DBG) logDbg("enableNetwork nid=" + Integer.toString(netId)); 494 return doBooleanCommand("ENABLE_NETWORK " + netId); 495 } 496 497 /** 498 * Enable a network in wpa_supplicant, do not connect. 499 * @param netId - Network ID of the network to be enabled. 500 * @return true if command succeeded, false otherwise. 501 */ 502 public boolean enableNetworkWithoutConnect(int netId) { 503 if (DBG) logDbg("enableNetworkWithoutConnect nid=" + Integer.toString(netId)); 504 return doBooleanCommand("ENABLE_NETWORK " + netId + " " + "no-connect"); 505 } 506 507 /** 508 * Disables a network in wpa_supplicant. 509 * @param netId - Network ID of the network to be disabled. 510 * @return true if command succeeded, false otherwise. 511 */ 512 public boolean disableNetwork(int netId) { 513 if (DBG) logDbg("disableNetwork nid=" + Integer.toString(netId)); 514 return doBooleanCommand("DISABLE_NETWORK " + netId); 515 } 516 517 /** 518 * Select a network in wpa_supplicant (Disables all others). 519 * @param netId - Network ID of the network to be selected. 520 * @return true if command succeeded, false otherwise. 521 */ 522 public boolean selectNetwork(int netId) { 523 if (DBG) logDbg("selectNetwork nid=" + Integer.toString(netId)); 524 return doBooleanCommand("SELECT_NETWORK " + netId); 525 } 526 527 public boolean reconnect() { 528 if (DBG) logDbg("RECONNECT "); 529 return doBooleanCommand("RECONNECT"); 530 } 531 532 public boolean reassociate() { 533 if (DBG) logDbg("REASSOCIATE "); 534 return doBooleanCommand("REASSOCIATE"); 535 } 536 537 public boolean disconnect() { 538 if (DBG) logDbg("DISCONNECT "); 539 return doBooleanCommand("DISCONNECT"); 540 } 541 542 public String status() { 543 return status(false); 544 } 545 546 public String status(boolean noEvents) { 547 if (noEvents) { 548 return doStringCommand("STATUS-NO_EVENTS"); 549 } else { 550 return doStringCommand("STATUS"); 551 } 552 } 553 554 public String getMacAddress() { 555 //Macaddr = XX.XX.XX.XX.XX.XX 556 String ret = doStringCommand("DRIVER MACADDR"); 557 if (!TextUtils.isEmpty(ret)) { 558 String[] tokens = ret.split(" = "); 559 if (tokens.length == 2) return tokens[1]; 560 } 561 return null; 562 } 563 564 565 566 /** 567 * Format of results: 568 * ================= 569 * id=1 570 * bssid=68:7f:76:d7:1a:6e 571 * freq=2412 572 * level=-44 573 * tsf=1344626243700342 574 * flags=[WPA2-PSK-CCMP][WPS][ESS] 575 * ssid=zfdy 576 * ==== 577 * id=2 578 * bssid=68:5f:74:d7:1a:6f 579 * freq=5180 580 * level=-73 581 * tsf=1344626243700373 582 * flags=[WPA2-PSK-CCMP][WPS][ESS] 583 * ssid=zuby 584 * ==== 585 * 586 * RANGE=ALL gets all scan results 587 * RANGE=ID- gets results from ID 588 * MASK=<N> BSS command information mask. 589 * 590 * The mask used in this method, 0x29d87, gets the following fields: 591 * 592 * WPA_BSS_MASK_ID (Bit 0) 593 * WPA_BSS_MASK_BSSID (Bit 1) 594 * WPA_BSS_MASK_FREQ (Bit 2) 595 * WPA_BSS_MASK_LEVEL (Bit 7) 596 * WPA_BSS_MASK_TSF (Bit 8) 597 * WPA_BSS_MASK_IE (Bit 10) 598 * WPA_BSS_MASK_FLAGS (Bit 11) 599 * WPA_BSS_MASK_SSID (Bit 12) 600 * WPA_BSS_MASK_INTERNETW (Bit 15) (adds ANQP info) 601 * WPA_BSS_MASK_DELIM (Bit 17) 602 * 603 * See wpa_supplicant/src/common/wpa_ctrl.h for details. 604 */ 605 private String getRawScanResults(String range) { 606 return doStringCommandWithoutLogging("BSS RANGE=" + range + " MASK=0x29d87"); 607 } 608 609 private static final String BSS_IE_STR = "ie="; 610 private static final String BSS_ID_STR = "id="; 611 private static final String BSS_BSSID_STR = "bssid="; 612 private static final String BSS_FREQ_STR = "freq="; 613 private static final String BSS_LEVEL_STR = "level="; 614 private static final String BSS_TSF_STR = "tsf="; 615 private static final String BSS_FLAGS_STR = "flags="; 616 private static final String BSS_SSID_STR = "ssid="; 617 private static final String BSS_DELIMITER_STR = "===="; 618 private static final String BSS_END_STR = "####"; 619 620 public ArrayList<ScanDetail> getScanResults() { 621 int next_sid = 0; 622 ArrayList<ScanDetail> results = new ArrayList<>(); 623 while(next_sid >= 0) { 624 String rawResult = getRawScanResults(next_sid+"-"); 625 next_sid = -1; 626 627 if (TextUtils.isEmpty(rawResult)) 628 break; 629 630 String[] lines = rawResult.split("\n"); 631 632 633 // note that all these splits and substrings keep references to the original 634 // huge string buffer while the amount we really want is generally pretty small 635 // so make copies instead (one example b/11087956 wasted 400k of heap here). 636 final int bssidStrLen = BSS_BSSID_STR.length(); 637 final int flagLen = BSS_FLAGS_STR.length(); 638 639 String bssid = ""; 640 int level = 0; 641 int freq = 0; 642 long tsf = 0; 643 String flags = ""; 644 WifiSsid wifiSsid = null; 645 String infoElementsStr = null; 646 List<String> anqpLines = null; 647 648 for (String line : lines) { 649 if (line.startsWith(BSS_ID_STR)) { // Will find the last id line 650 try { 651 next_sid = Integer.parseInt(line.substring(BSS_ID_STR.length())) + 1; 652 } catch (NumberFormatException e) { 653 // Nothing to do 654 } 655 } else if (line.startsWith(BSS_BSSID_STR)) { 656 bssid = new String(line.getBytes(), bssidStrLen, line.length() - bssidStrLen); 657 } else if (line.startsWith(BSS_FREQ_STR)) { 658 try { 659 freq = Integer.parseInt(line.substring(BSS_FREQ_STR.length())); 660 } catch (NumberFormatException e) { 661 freq = 0; 662 } 663 } else if (line.startsWith(BSS_LEVEL_STR)) { 664 try { 665 level = Integer.parseInt(line.substring(BSS_LEVEL_STR.length())); 666 /* some implementations avoid negative values by adding 256 667 * so we need to adjust for that here. 668 */ 669 if (level > 0) level -= 256; 670 } catch (NumberFormatException e) { 671 level = 0; 672 } 673 } else if (line.startsWith(BSS_TSF_STR)) { 674 try { 675 tsf = Long.parseLong(line.substring(BSS_TSF_STR.length())); 676 } catch (NumberFormatException e) { 677 tsf = 0; 678 } 679 } else if (line.startsWith(BSS_FLAGS_STR)) { 680 flags = new String(line.getBytes(), flagLen, line.length() - flagLen); 681 } else if (line.startsWith(BSS_SSID_STR)) { 682 wifiSsid = WifiSsid.createFromAsciiEncoded( 683 line.substring(BSS_SSID_STR.length())); 684 } else if (line.startsWith(BSS_IE_STR)) { 685 infoElementsStr = line; 686 } else if (SupplicantBridge.isAnqpAttribute(line)) { 687 if (anqpLines == null) { 688 anqpLines = new ArrayList<>(); 689 } 690 anqpLines.add(line); 691 } else if (line.startsWith(BSS_DELIMITER_STR) || line.startsWith(BSS_END_STR)) { 692 if (bssid != null) { 693 try { 694 if (infoElementsStr == null) { 695 throw new IllegalArgumentException("Null information element data"); 696 } 697 int seperator = infoElementsStr.indexOf('='); 698 if (seperator < 0) { 699 throw new IllegalArgumentException("No element separator"); 700 } 701 702 ScanResult.InformationElement[] infoElements = 703 InformationElementUtil.parseInformationElements( 704 Utils.hexToBytes(infoElementsStr.substring(seperator + 1))); 705 706 NetworkDetail networkDetail = new NetworkDetail(bssid, 707 infoElements, anqpLines, freq); 708 if (DBG) { 709 Log.v(TAG + ":DTIM", "SSID" + networkDetail.getSSID() 710 + ", DTIM=" + networkDetail.getDtimInterval() + ", " 711 + " IEstr:" + infoElementsStr); 712 } 713 String xssid = (wifiSsid != null) ? wifiSsid.toString() : WifiSsid.NONE; 714 if (!xssid.equals(networkDetail.getTrimmedSSID())) { 715 Log.d(TAG, String.format( 716 "Inconsistent SSID on BSSID '%s': '%s' vs '%s': %s", 717 bssid, xssid, networkDetail.getSSID(), infoElementsStr)); 718 } 719 720 if (networkDetail.hasInterworking()) { 721 if (DBG) Log.d(TAG, "HSNwk: '" + networkDetail); 722 } 723 ScanDetail scan = new ScanDetail(networkDetail, wifiSsid, bssid, flags, 724 level, freq, tsf, infoElements, anqpLines); 725 results.add(scan); 726 } catch (IllegalArgumentException iae) { 727 Log.d(TAG, "Failed to parse information elements: " + iae); 728 } 729 } 730 bssid = null; 731 level = 0; 732 freq = 0; 733 tsf = 0; 734 flags = ""; 735 wifiSsid = null; 736 infoElementsStr = null; 737 anqpLines = null; 738 } 739 } 740 } 741 return results; 742 } 743 744 /** 745 * Format of result: 746 * id=1016 747 * bssid=00:03:7f:40:84:10 748 * freq=2462 749 * beacon_int=200 750 * capabilities=0x0431 751 * qual=0 752 * noise=0 753 * level=-46 754 * tsf=0000002669008476 755 * age=5 756 * ie=00105143412d485332302d52322d54455354010882848b960c12182403010b0706555... 757 * flags=[WPA2-EAP-CCMP][ESS][P2P][HS20] 758 * ssid=QCA-HS20-R2-TEST 759 * p2p_device_name= 760 * p2p_config_methods=0x0SET_NE 761 * anqp_venue_name=02083d656e6757692d466920416c6c69616e63650a3239383920436f... 762 * anqp_network_auth_type=010000 763 * anqp_roaming_consortium=03506f9a05001bc504bd 764 * anqp_ip_addr_type_availability=0c 765 * anqp_nai_realm=0200300000246d61696c2e6578616d706c652e636f6d3b636973636f2... 766 * anqp_3gpp=000600040132f465 767 * anqp_domain_name=0b65786d61706c652e636f6d 768 * hs20_operator_friendly_name=11656e6757692d466920416c6c69616e63650e636869... 769 * hs20_wan_metrics=01c40900008001000000000a00 770 * hs20_connection_capability=0100000006140001061600000650000106bb010106bb0... 771 * hs20_osu_providers_list=0b5143412d4f53552d425353010901310015656e6757692d... 772 */ 773 public String scanResult(String bssid) { 774 return doStringCommand("BSS " + bssid); 775 } 776 777 public boolean startDriver() { 778 return doBooleanCommand("DRIVER START"); 779 } 780 781 public boolean stopDriver() { 782 return doBooleanCommand("DRIVER STOP"); 783 } 784 785 786 /** 787 * Start filtering out Multicast V4 packets 788 * @return {@code true} if the operation succeeded, {@code false} otherwise 789 * 790 * Multicast filtering rules work as follows: 791 * 792 * The driver can filter multicast (v4 and/or v6) and broadcast packets when in 793 * a power optimized mode (typically when screen goes off). 794 * 795 * In order to prevent the driver from filtering the multicast/broadcast packets, we have to 796 * add a DRIVER RXFILTER-ADD rule followed by DRIVER RXFILTER-START to make the rule effective 797 * 798 * DRIVER RXFILTER-ADD Num 799 * where Num = 0 - Unicast, 1 - Broadcast, 2 - Mutil4 or 3 - Multi6 800 * 801 * and DRIVER RXFILTER-START 802 * In order to stop the usage of these rules, we do 803 * 804 * DRIVER RXFILTER-STOP 805 * DRIVER RXFILTER-REMOVE Num 806 * where Num is as described for RXFILTER-ADD 807 * 808 * The SETSUSPENDOPT driver command overrides the filtering rules 809 */ 810 public boolean startFilteringMulticastV4Packets() { 811 return doBooleanCommand("DRIVER RXFILTER-STOP") 812 && doBooleanCommand("DRIVER RXFILTER-REMOVE 2") 813 && doBooleanCommand("DRIVER RXFILTER-START"); 814 } 815 816 /** 817 * Stop filtering out Multicast V4 packets. 818 * @return {@code true} if the operation succeeded, {@code false} otherwise 819 */ 820 public boolean stopFilteringMulticastV4Packets() { 821 return doBooleanCommand("DRIVER RXFILTER-STOP") 822 && doBooleanCommand("DRIVER RXFILTER-ADD 2") 823 && doBooleanCommand("DRIVER RXFILTER-START"); 824 } 825 826 /** 827 * Start filtering out Multicast V6 packets 828 * @return {@code true} if the operation succeeded, {@code false} otherwise 829 */ 830 public boolean startFilteringMulticastV6Packets() { 831 return doBooleanCommand("DRIVER RXFILTER-STOP") 832 && doBooleanCommand("DRIVER RXFILTER-REMOVE 3") 833 && doBooleanCommand("DRIVER RXFILTER-START"); 834 } 835 836 /** 837 * Stop filtering out Multicast V6 packets. 838 * @return {@code true} if the operation succeeded, {@code false} otherwise 839 */ 840 public boolean stopFilteringMulticastV6Packets() { 841 return doBooleanCommand("DRIVER RXFILTER-STOP") 842 && doBooleanCommand("DRIVER RXFILTER-ADD 3") 843 && doBooleanCommand("DRIVER RXFILTER-START"); 844 } 845 846 /** 847 * Set the operational frequency band 848 * @param band One of 849 * {@link WifiManager#WIFI_FREQUENCY_BAND_AUTO}, 850 * {@link WifiManager#WIFI_FREQUENCY_BAND_5GHZ}, 851 * {@link WifiManager#WIFI_FREQUENCY_BAND_2GHZ}, 852 * @return {@code true} if the operation succeeded, {@code false} otherwise 853 */ 854 public boolean setBand(int band) { 855 String bandstr; 856 857 if (band == WifiManager.WIFI_FREQUENCY_BAND_5GHZ) 858 bandstr = "5G"; 859 else if (band == WifiManager.WIFI_FREQUENCY_BAND_2GHZ) 860 bandstr = "2G"; 861 else 862 bandstr = "AUTO"; 863 return doBooleanCommand("SET SETBAND " + bandstr); 864 } 865 866 public static final int BLUETOOTH_COEXISTENCE_MODE_ENABLED = 0; 867 public static final int BLUETOOTH_COEXISTENCE_MODE_DISABLED = 1; 868 public static final int BLUETOOTH_COEXISTENCE_MODE_SENSE = 2; 869 /** 870 * Sets the bluetooth coexistence mode. 871 * 872 * @param mode One of {@link #BLUETOOTH_COEXISTENCE_MODE_DISABLED}, 873 * {@link #BLUETOOTH_COEXISTENCE_MODE_ENABLED}, or 874 * {@link #BLUETOOTH_COEXISTENCE_MODE_SENSE}. 875 * @return Whether the mode was successfully set. 876 */ 877 public boolean setBluetoothCoexistenceMode(int mode) { 878 return doBooleanCommand("DRIVER BTCOEXMODE " + mode); 879 } 880 881 /** 882 * Enable or disable Bluetooth coexistence scan mode. When this mode is on, 883 * some of the low-level scan parameters used by the driver are changed to 884 * reduce interference with A2DP streaming. 885 * 886 * @param isSet whether to enable or disable this mode 887 * @return {@code true} if the command succeeded, {@code false} otherwise. 888 */ 889 public boolean setBluetoothCoexistenceScanMode(boolean setCoexScanMode) { 890 if (setCoexScanMode) { 891 return doBooleanCommand("DRIVER BTCOEXSCAN-START"); 892 } else { 893 return doBooleanCommand("DRIVER BTCOEXSCAN-STOP"); 894 } 895 } 896 897 public void enableSaveConfig() { 898 doBooleanCommand("SET update_config 1"); 899 } 900 901 public boolean saveConfig() { 902 return doBooleanCommand("SAVE_CONFIG"); 903 } 904 905 public boolean addToBlacklist(String bssid) { 906 if (TextUtils.isEmpty(bssid)) return false; 907 return doBooleanCommand("BLACKLIST " + bssid); 908 } 909 910 public boolean clearBlacklist() { 911 return doBooleanCommand("BLACKLIST clear"); 912 } 913 914 public boolean setSuspendOptimizations(boolean enabled) { 915 if (enabled) { 916 return doBooleanCommand("DRIVER SETSUSPENDMODE 1"); 917 } else { 918 return doBooleanCommand("DRIVER SETSUSPENDMODE 0"); 919 } 920 } 921 922 public boolean setCountryCode(String countryCode) { 923 if (countryCode != null) 924 return doBooleanCommand("DRIVER COUNTRY " + countryCode.toUpperCase(Locale.ROOT)); 925 else 926 return doBooleanCommand("DRIVER COUNTRY"); 927 } 928 929 /** 930 * Start/Stop PNO scan. 931 * @param enable boolean indicating whether PNO is being enabled or disabled. 932 */ 933 public boolean setPnoScan(boolean enable) { 934 String cmd = enable ? "SET pno 1" : "SET pno 0"; 935 return doBooleanCommand(cmd); 936 } 937 938 public void enableAutoConnect(boolean enable) { 939 if (enable) { 940 doBooleanCommand("STA_AUTOCONNECT 1"); 941 } else { 942 doBooleanCommand("STA_AUTOCONNECT 0"); 943 } 944 } 945 946 public void setScanInterval(int scanInterval) { 947 doBooleanCommand("SCAN_INTERVAL " + scanInterval); 948 } 949 950 public void setHs20(boolean hs20) { 951 if (hs20) { 952 doBooleanCommand("SET HS20 1"); 953 } else { 954 doBooleanCommand("SET HS20 0"); 955 } 956 } 957 958 public void startTdls(String macAddr, boolean enable) { 959 if (enable) { 960 synchronized (sLock) { 961 doBooleanCommand("TDLS_DISCOVER " + macAddr); 962 doBooleanCommand("TDLS_SETUP " + macAddr); 963 } 964 } else { 965 doBooleanCommand("TDLS_TEARDOWN " + macAddr); 966 } 967 } 968 969 /** Example output: 970 * RSSI=-65 971 * LINKSPEED=48 972 * NOISE=9999 973 * FREQUENCY=0 974 */ 975 public String signalPoll() { 976 return doStringCommandWithoutLogging("SIGNAL_POLL"); 977 } 978 979 /** Example outout: 980 * TXGOOD=396 981 * TXBAD=1 982 */ 983 public String pktcntPoll() { 984 return doStringCommand("PKTCNT_POLL"); 985 } 986 987 public void bssFlush() { 988 doBooleanCommand("BSS_FLUSH 0"); 989 } 990 991 public boolean startWpsPbc(String bssid) { 992 if (TextUtils.isEmpty(bssid)) { 993 return doBooleanCommand("WPS_PBC"); 994 } else { 995 return doBooleanCommand("WPS_PBC " + bssid); 996 } 997 } 998 999 public boolean startWpsPbc(String iface, String bssid) { 1000 synchronized (sLock) { 1001 if (TextUtils.isEmpty(bssid)) { 1002 return doBooleanCommandNative("IFNAME=" + iface + " WPS_PBC"); 1003 } else { 1004 return doBooleanCommandNative("IFNAME=" + iface + " WPS_PBC " + bssid); 1005 } 1006 } 1007 } 1008 1009 public boolean startWpsPinKeypad(String pin) { 1010 if (TextUtils.isEmpty(pin)) return false; 1011 return doBooleanCommand("WPS_PIN any " + pin); 1012 } 1013 1014 public boolean startWpsPinKeypad(String iface, String pin) { 1015 if (TextUtils.isEmpty(pin)) return false; 1016 synchronized (sLock) { 1017 return doBooleanCommandNative("IFNAME=" + iface + " WPS_PIN any " + pin); 1018 } 1019 } 1020 1021 1022 public String startWpsPinDisplay(String bssid) { 1023 if (TextUtils.isEmpty(bssid)) { 1024 return doStringCommand("WPS_PIN any"); 1025 } else { 1026 return doStringCommand("WPS_PIN " + bssid); 1027 } 1028 } 1029 1030 public String startWpsPinDisplay(String iface, String bssid) { 1031 synchronized (sLock) { 1032 if (TextUtils.isEmpty(bssid)) { 1033 return doStringCommandNative("IFNAME=" + iface + " WPS_PIN any"); 1034 } else { 1035 return doStringCommandNative("IFNAME=" + iface + " WPS_PIN " + bssid); 1036 } 1037 } 1038 } 1039 1040 public boolean setExternalSim(boolean external) { 1041 String value = external ? "1" : "0"; 1042 Log.d(TAG, "Setting external_sim to " + value); 1043 return doBooleanCommand("SET external_sim " + value); 1044 } 1045 1046 public boolean simAuthResponse(int id, String type, String response) { 1047 // with type = GSM-AUTH, UMTS-AUTH or UMTS-AUTS 1048 return doBooleanCommand("CTRL-RSP-SIM-" + id + ":" + type + response); 1049 } 1050 1051 public boolean simAuthFailedResponse(int id) { 1052 // should be used with type GSM-AUTH 1053 return doBooleanCommand("CTRL-RSP-SIM-" + id + ":GSM-FAIL"); 1054 } 1055 1056 public boolean umtsAuthFailedResponse(int id) { 1057 // should be used with type UMTS-AUTH 1058 return doBooleanCommand("CTRL-RSP-SIM-" + id + ":UMTS-FAIL"); 1059 } 1060 1061 public boolean simIdentityResponse(int id, String response) { 1062 return doBooleanCommand("CTRL-RSP-IDENTITY-" + id + ":" + response); 1063 } 1064 1065 /* Configures an access point connection */ 1066 public boolean startWpsRegistrar(String bssid, String pin) { 1067 if (TextUtils.isEmpty(bssid) || TextUtils.isEmpty(pin)) return false; 1068 return doBooleanCommand("WPS_REG " + bssid + " " + pin); 1069 } 1070 1071 public boolean cancelWps() { 1072 return doBooleanCommand("WPS_CANCEL"); 1073 } 1074 1075 public boolean setPersistentReconnect(boolean enabled) { 1076 int value = (enabled == true) ? 1 : 0; 1077 return doBooleanCommand("SET persistent_reconnect " + value); 1078 } 1079 1080 public boolean setDeviceName(String name) { 1081 return doBooleanCommand("SET device_name " + name); 1082 } 1083 1084 public boolean setDeviceType(String type) { 1085 return doBooleanCommand("SET device_type " + type); 1086 } 1087 1088 public boolean setConfigMethods(String cfg) { 1089 return doBooleanCommand("SET config_methods " + cfg); 1090 } 1091 1092 public boolean setManufacturer(String value) { 1093 return doBooleanCommand("SET manufacturer " + value); 1094 } 1095 1096 public boolean setModelName(String value) { 1097 return doBooleanCommand("SET model_name " + value); 1098 } 1099 1100 public boolean setModelNumber(String value) { 1101 return doBooleanCommand("SET model_number " + value); 1102 } 1103 1104 public boolean setSerialNumber(String value) { 1105 return doBooleanCommand("SET serial_number " + value); 1106 } 1107 1108 public boolean setP2pSsidPostfix(String postfix) { 1109 return doBooleanCommand("SET p2p_ssid_postfix " + postfix); 1110 } 1111 1112 public boolean setP2pGroupIdle(String iface, int time) { 1113 synchronized (sLock) { 1114 return doBooleanCommandNative("IFNAME=" + iface + " SET p2p_group_idle " + time); 1115 } 1116 } 1117 1118 public void setPowerSave(boolean enabled) { 1119 if (enabled) { 1120 doBooleanCommand("SET ps 1"); 1121 } else { 1122 doBooleanCommand("SET ps 0"); 1123 } 1124 } 1125 1126 public boolean setP2pPowerSave(String iface, boolean enabled) { 1127 synchronized (sLock) { 1128 if (enabled) { 1129 return doBooleanCommandNative("IFNAME=" + iface + " P2P_SET ps 1"); 1130 } else { 1131 return doBooleanCommandNative("IFNAME=" + iface + " P2P_SET ps 0"); 1132 } 1133 } 1134 } 1135 1136 public boolean setWfdEnable(boolean enable) { 1137 return doBooleanCommand("SET wifi_display " + (enable ? "1" : "0")); 1138 } 1139 1140 public boolean setWfdDeviceInfo(String hex) { 1141 return doBooleanCommand("WFD_SUBELEM_SET 0 " + hex); 1142 } 1143 1144 /** 1145 * "sta" prioritizes STA connection over P2P and "p2p" prioritizes 1146 * P2P connection over STA 1147 */ 1148 public boolean setConcurrencyPriority(String s) { 1149 return doBooleanCommand("P2P_SET conc_pref " + s); 1150 } 1151 1152 public boolean p2pFind() { 1153 return doBooleanCommand("P2P_FIND"); 1154 } 1155 1156 public boolean p2pFind(int timeout) { 1157 if (timeout <= 0) { 1158 return p2pFind(); 1159 } 1160 return doBooleanCommand("P2P_FIND " + timeout); 1161 } 1162 1163 public boolean p2pStopFind() { 1164 return doBooleanCommand("P2P_STOP_FIND"); 1165 } 1166 1167 public boolean p2pListen() { 1168 return doBooleanCommand("P2P_LISTEN"); 1169 } 1170 1171 public boolean p2pListen(int timeout) { 1172 if (timeout <= 0) { 1173 return p2pListen(); 1174 } 1175 return doBooleanCommand("P2P_LISTEN " + timeout); 1176 } 1177 1178 public boolean p2pExtListen(boolean enable, int period, int interval) { 1179 if (enable && interval < period) { 1180 return false; 1181 } 1182 return doBooleanCommand("P2P_EXT_LISTEN" 1183 + (enable ? (" " + period + " " + interval) : "")); 1184 } 1185 1186 public boolean p2pSetChannel(int lc, int oc) { 1187 if (DBG) Log.d(mTAG, "p2pSetChannel: lc="+lc+", oc="+oc); 1188 1189 synchronized (sLock) { 1190 if (lc >=1 && lc <= 11) { 1191 if (!doBooleanCommand("P2P_SET listen_channel " + lc)) { 1192 return false; 1193 } 1194 } else if (lc != 0) { 1195 return false; 1196 } 1197 1198 if (oc >= 1 && oc <= 165 ) { 1199 int freq = (oc <= 14 ? 2407 : 5000) + oc * 5; 1200 return doBooleanCommand("P2P_SET disallow_freq 1000-" 1201 + (freq - 5) + "," + (freq + 5) + "-6000"); 1202 } else if (oc == 0) { 1203 /* oc==0 disables "P2P_SET disallow_freq" (enables all freqs) */ 1204 return doBooleanCommand("P2P_SET disallow_freq \"\""); 1205 } 1206 } 1207 return false; 1208 } 1209 1210 public boolean p2pFlush() { 1211 return doBooleanCommand("P2P_FLUSH"); 1212 } 1213 1214 private static final int DEFAULT_GROUP_OWNER_INTENT = 6; 1215 /* p2p_connect <peer device address> <pbc|pin|PIN#> [label|display|keypad] 1216 [persistent] [join|auth] [go_intent=<0..15>] [freq=<in MHz>] */ 1217 public String p2pConnect(WifiP2pConfig config, boolean joinExistingGroup) { 1218 if (config == null) return null; 1219 List<String> args = new ArrayList<String>(); 1220 WpsInfo wps = config.wps; 1221 args.add(config.deviceAddress); 1222 1223 switch (wps.setup) { 1224 case WpsInfo.PBC: 1225 args.add("pbc"); 1226 break; 1227 case WpsInfo.DISPLAY: 1228 if (TextUtils.isEmpty(wps.pin)) { 1229 args.add("pin"); 1230 } else { 1231 args.add(wps.pin); 1232 } 1233 args.add("display"); 1234 break; 1235 case WpsInfo.KEYPAD: 1236 args.add(wps.pin); 1237 args.add("keypad"); 1238 break; 1239 case WpsInfo.LABEL: 1240 args.add(wps.pin); 1241 args.add("label"); 1242 default: 1243 break; 1244 } 1245 1246 if (config.netId == WifiP2pGroup.PERSISTENT_NET_ID) { 1247 args.add("persistent"); 1248 } 1249 1250 if (joinExistingGroup) { 1251 args.add("join"); 1252 } else { 1253 //TODO: This can be adapted based on device plugged in state and 1254 //device battery state 1255 int groupOwnerIntent = config.groupOwnerIntent; 1256 if (groupOwnerIntent < 0 || groupOwnerIntent > 15) { 1257 groupOwnerIntent = DEFAULT_GROUP_OWNER_INTENT; 1258 } 1259 args.add("go_intent=" + groupOwnerIntent); 1260 } 1261 1262 String command = "P2P_CONNECT "; 1263 for (String s : args) command += s + " "; 1264 1265 return doStringCommand(command); 1266 } 1267 1268 public boolean p2pCancelConnect() { 1269 return doBooleanCommand("P2P_CANCEL"); 1270 } 1271 1272 public boolean p2pProvisionDiscovery(WifiP2pConfig config) { 1273 if (config == null) return false; 1274 1275 switch (config.wps.setup) { 1276 case WpsInfo.PBC: 1277 return doBooleanCommand("P2P_PROV_DISC " + config.deviceAddress + " pbc"); 1278 case WpsInfo.DISPLAY: 1279 //We are doing display, so provision discovery is keypad 1280 return doBooleanCommand("P2P_PROV_DISC " + config.deviceAddress + " keypad"); 1281 case WpsInfo.KEYPAD: 1282 //We are doing keypad, so provision discovery is display 1283 return doBooleanCommand("P2P_PROV_DISC " + config.deviceAddress + " display"); 1284 default: 1285 break; 1286 } 1287 return false; 1288 } 1289 1290 public boolean p2pGroupAdd(boolean persistent) { 1291 if (persistent) { 1292 return doBooleanCommand("P2P_GROUP_ADD persistent"); 1293 } 1294 return doBooleanCommand("P2P_GROUP_ADD"); 1295 } 1296 1297 public boolean p2pGroupAdd(int netId) { 1298 return doBooleanCommand("P2P_GROUP_ADD persistent=" + netId); 1299 } 1300 1301 public boolean p2pGroupRemove(String iface) { 1302 if (TextUtils.isEmpty(iface)) return false; 1303 synchronized (sLock) { 1304 return doBooleanCommandNative("IFNAME=" + iface + " P2P_GROUP_REMOVE " + iface); 1305 } 1306 } 1307 1308 public boolean p2pReject(String deviceAddress) { 1309 return doBooleanCommand("P2P_REJECT " + deviceAddress); 1310 } 1311 1312 /* Invite a peer to a group */ 1313 public boolean p2pInvite(WifiP2pGroup group, String deviceAddress) { 1314 if (TextUtils.isEmpty(deviceAddress)) return false; 1315 1316 if (group == null) { 1317 return doBooleanCommand("P2P_INVITE peer=" + deviceAddress); 1318 } else { 1319 return doBooleanCommand("P2P_INVITE group=" + group.getInterface() 1320 + " peer=" + deviceAddress + " go_dev_addr=" + group.getOwner().deviceAddress); 1321 } 1322 } 1323 1324 /* Reinvoke a persistent connection */ 1325 public boolean p2pReinvoke(int netId, String deviceAddress) { 1326 if (TextUtils.isEmpty(deviceAddress) || netId < 0) return false; 1327 1328 return doBooleanCommand("P2P_INVITE persistent=" + netId + " peer=" + deviceAddress); 1329 } 1330 1331 public String p2pGetSsid(String deviceAddress) { 1332 return p2pGetParam(deviceAddress, "oper_ssid"); 1333 } 1334 1335 public String p2pGetDeviceAddress() { 1336 Log.d(TAG, "p2pGetDeviceAddress"); 1337 1338 String status = null; 1339 1340 /* Explicitly calling the API without IFNAME= prefix to take care of the devices that 1341 don't have p2p0 interface. Supplicant seems to be returning the correct address anyway. */ 1342 1343 synchronized (sLock) { 1344 status = doStringCommandNative("STATUS"); 1345 } 1346 1347 String result = ""; 1348 if (status != null) { 1349 String[] tokens = status.split("\n"); 1350 for (String token : tokens) { 1351 if (token.startsWith("p2p_device_address=")) { 1352 String[] nameValue = token.split("="); 1353 if (nameValue.length != 2) 1354 break; 1355 result = nameValue[1]; 1356 } 1357 } 1358 } 1359 1360 Log.d(TAG, "p2pGetDeviceAddress returning " + result); 1361 return result; 1362 } 1363 1364 public int getGroupCapability(String deviceAddress) { 1365 int gc = 0; 1366 if (TextUtils.isEmpty(deviceAddress)) return gc; 1367 String peerInfo = p2pPeer(deviceAddress); 1368 if (TextUtils.isEmpty(peerInfo)) return gc; 1369 1370 String[] tokens = peerInfo.split("\n"); 1371 for (String token : tokens) { 1372 if (token.startsWith("group_capab=")) { 1373 String[] nameValue = token.split("="); 1374 if (nameValue.length != 2) break; 1375 try { 1376 return Integer.decode(nameValue[1]); 1377 } catch(NumberFormatException e) { 1378 return gc; 1379 } 1380 } 1381 } 1382 return gc; 1383 } 1384 1385 public String p2pPeer(String deviceAddress) { 1386 return doStringCommand("P2P_PEER " + deviceAddress); 1387 } 1388 1389 private String p2pGetParam(String deviceAddress, String key) { 1390 if (deviceAddress == null) return null; 1391 1392 String peerInfo = p2pPeer(deviceAddress); 1393 if (peerInfo == null) return null; 1394 String[] tokens= peerInfo.split("\n"); 1395 1396 key += "="; 1397 for (String token : tokens) { 1398 if (token.startsWith(key)) { 1399 String[] nameValue = token.split("="); 1400 if (nameValue.length != 2) break; 1401 return nameValue[1]; 1402 } 1403 } 1404 return null; 1405 } 1406 1407 public boolean p2pServiceAdd(WifiP2pServiceInfo servInfo) { 1408 /* 1409 * P2P_SERVICE_ADD bonjour <query hexdump> <RDATA hexdump> 1410 * P2P_SERVICE_ADD upnp <version hex> <service> 1411 * 1412 * e.g) 1413 * [Bonjour] 1414 * # IP Printing over TCP (PTR) (RDATA=MyPrinter._ipp._tcp.local.) 1415 * P2P_SERVICE_ADD bonjour 045f697070c00c000c01 094d795072696e746572c027 1416 * # IP Printing over TCP (TXT) (RDATA=txtvers=1,pdl=application/postscript) 1417 * P2P_SERVICE_ADD bonjour 096d797072696e746572045f697070c00c001001 1418 * 09747874766572733d311a70646c3d6170706c69636174696f6e2f706f7374736372797074 1419 * 1420 * [UPnP] 1421 * P2P_SERVICE_ADD upnp 10 uuid:6859dede-8574-59ab-9332-123456789012 1422 * P2P_SERVICE_ADD upnp 10 uuid:6859dede-8574-59ab-9332-123456789012::upnp:rootdevice 1423 * P2P_SERVICE_ADD upnp 10 uuid:6859dede-8574-59ab-9332-123456789012::urn:schemas-upnp 1424 * -org:device:InternetGatewayDevice:1 1425 * P2P_SERVICE_ADD upnp 10 uuid:6859dede-8574-59ab-9322-123456789012::urn:schemas-upnp 1426 * -org:service:ContentDirectory:2 1427 */ 1428 synchronized (sLock) { 1429 for (String s : servInfo.getSupplicantQueryList()) { 1430 String command = "P2P_SERVICE_ADD"; 1431 command += (" " + s); 1432 if (!doBooleanCommand(command)) { 1433 return false; 1434 } 1435 } 1436 } 1437 return true; 1438 } 1439 1440 public boolean p2pServiceDel(WifiP2pServiceInfo servInfo) { 1441 /* 1442 * P2P_SERVICE_DEL bonjour <query hexdump> 1443 * P2P_SERVICE_DEL upnp <version hex> <service> 1444 */ 1445 synchronized (sLock) { 1446 for (String s : servInfo.getSupplicantQueryList()) { 1447 String command = "P2P_SERVICE_DEL "; 1448 1449 String[] data = s.split(" "); 1450 if (data.length < 2) { 1451 return false; 1452 } 1453 if ("upnp".equals(data[0])) { 1454 command += s; 1455 } else if ("bonjour".equals(data[0])) { 1456 command += data[0]; 1457 command += (" " + data[1]); 1458 } else { 1459 return false; 1460 } 1461 if (!doBooleanCommand(command)) { 1462 return false; 1463 } 1464 } 1465 } 1466 return true; 1467 } 1468 1469 public boolean p2pServiceFlush() { 1470 return doBooleanCommand("P2P_SERVICE_FLUSH"); 1471 } 1472 1473 public String p2pServDiscReq(String addr, String query) { 1474 String command = "P2P_SERV_DISC_REQ"; 1475 command += (" " + addr); 1476 command += (" " + query); 1477 1478 return doStringCommand(command); 1479 } 1480 1481 public boolean p2pServDiscCancelReq(String id) { 1482 return doBooleanCommand("P2P_SERV_DISC_CANCEL_REQ " + id); 1483 } 1484 1485 /* Set the current mode of miracast operation. 1486 * 0 = disabled 1487 * 1 = operating as source 1488 * 2 = operating as sink 1489 */ 1490 public void setMiracastMode(int mode) { 1491 // Note: optional feature on the driver. It is ok for this to fail. 1492 doBooleanCommand("DRIVER MIRACAST " + mode); 1493 } 1494 1495 public boolean fetchAnqp(String bssid, String subtypes) { 1496 return doBooleanCommand("ANQP_GET " + bssid + " " + subtypes); 1497 } 1498 1499 /* 1500 * NFC-related calls 1501 */ 1502 public String getNfcWpsConfigurationToken(int netId) { 1503 return doStringCommand("WPS_NFC_CONFIG_TOKEN WPS " + netId); 1504 } 1505 1506 public String getNfcHandoverRequest() { 1507 return doStringCommand("NFC_GET_HANDOVER_REQ NDEF P2P-CR"); 1508 } 1509 1510 public String getNfcHandoverSelect() { 1511 return doStringCommand("NFC_GET_HANDOVER_SEL NDEF P2P-CR"); 1512 } 1513 1514 public boolean initiatorReportNfcHandover(String selectMessage) { 1515 return doBooleanCommand("NFC_REPORT_HANDOVER INIT P2P 00 " + selectMessage); 1516 } 1517 1518 public boolean responderReportNfcHandover(String requestMessage) { 1519 return doBooleanCommand("NFC_REPORT_HANDOVER RESP P2P " + requestMessage + " 00"); 1520 } 1521 1522 1523 /* kernel logging support */ 1524 private static native byte[] readKernelLogNative(); 1525 1526 synchronized public String readKernelLog() { 1527 byte[] bytes = readKernelLogNative(); 1528 if (bytes != null) { 1529 CharsetDecoder decoder = StandardCharsets.UTF_8.newDecoder(); 1530 try { 1531 CharBuffer decoded = decoder.decode(ByteBuffer.wrap(bytes)); 1532 return decoded.toString(); 1533 } catch (CharacterCodingException cce) { 1534 return new String(bytes, StandardCharsets.ISO_8859_1); 1535 } 1536 } else { 1537 return "*** failed to read kernel log ***"; 1538 } 1539 } 1540 1541 /* WIFI HAL support */ 1542 1543 // HAL command ids 1544 private static int sCmdId = 1; 1545 private static int getNewCmdIdLocked() { 1546 return sCmdId++; 1547 } 1548 1549 private static final String TAG = "WifiNative-HAL"; 1550 private static long sWifiHalHandle = 0; /* used by JNI to save wifi_handle */ 1551 private static long[] sWifiIfaceHandles = null; /* used by JNI to save interface handles */ 1552 public static int sWlan0Index = -1; 1553 private static MonitorThread sThread; 1554 private static final int STOP_HAL_TIMEOUT_MS = 1000; 1555 1556 private static native boolean startHalNative(); 1557 private static native void stopHalNative(); 1558 private static native void waitForHalEventNative(); 1559 1560 private static class MonitorThread extends Thread { 1561 public void run() { 1562 Log.i(TAG, "Waiting for HAL events mWifiHalHandle=" + Long.toString(sWifiHalHandle)); 1563 waitForHalEventNative(); 1564 } 1565 } 1566 1567 public boolean startHal() { 1568 String debugLog = "startHal stack: "; 1569 java.lang.StackTraceElement[] elements = Thread.currentThread().getStackTrace(); 1570 for (int i = 2; i < elements.length && i <= 7; i++ ) { 1571 debugLog = debugLog + " - " + elements[i].getMethodName(); 1572 } 1573 1574 sLocalLog.log(debugLog); 1575 1576 synchronized (sLock) { 1577 if (startHalNative()) { 1578 int wlan0Index = queryInterfaceIndex(mInterfaceName); 1579 if (wlan0Index == -1) { 1580 if (DBG) sLocalLog.log("Could not find interface with name: " + mInterfaceName); 1581 return false; 1582 } 1583 sWlan0Index = wlan0Index; 1584 sThread = new MonitorThread(); 1585 sThread.start(); 1586 return true; 1587 } else { 1588 if (DBG) sLocalLog.log("Could not start hal"); 1589 Log.e(TAG, "Could not start hal"); 1590 return false; 1591 } 1592 } 1593 } 1594 1595 public void stopHal() { 1596 synchronized (sLock) { 1597 if (isHalStarted()) { 1598 stopHalNative(); 1599 try { 1600 sThread.join(STOP_HAL_TIMEOUT_MS); 1601 Log.d(TAG, "HAL event thread stopped successfully"); 1602 } catch (InterruptedException e) { 1603 Log.e(TAG, "Could not stop HAL cleanly"); 1604 } 1605 sThread = null; 1606 sWifiHalHandle = 0; 1607 sWifiIfaceHandles = null; 1608 sWlan0Index = -1; 1609 } 1610 } 1611 } 1612 1613 public boolean isHalStarted() { 1614 return (sWifiHalHandle != 0); 1615 } 1616 private static native int getInterfacesNative(); 1617 1618 public int queryInterfaceIndex(String interfaceName) { 1619 synchronized (sLock) { 1620 if (isHalStarted()) { 1621 int num = getInterfacesNative(); 1622 for (int i = 0; i < num; i++) { 1623 String name = getInterfaceNameNative(i); 1624 if (name.equals(interfaceName)) { 1625 return i; 1626 } 1627 } 1628 } 1629 } 1630 return -1; 1631 } 1632 1633 private static native String getInterfaceNameNative(int index); 1634 public String getInterfaceName(int index) { 1635 synchronized (sLock) { 1636 return getInterfaceNameNative(index); 1637 } 1638 } 1639 1640 // TODO: Change variable names to camel style. 1641 public static class ScanCapabilities { 1642 public int max_scan_cache_size; 1643 public int max_scan_buckets; 1644 public int max_ap_cache_per_scan; 1645 public int max_rssi_sample_size; 1646 public int max_scan_reporting_threshold; 1647 public int max_hotlist_bssids; 1648 public int max_significant_wifi_change_aps; 1649 public int max_bssid_history_entries; 1650 public int max_number_epno_networks; 1651 public int max_number_epno_networks_by_ssid; 1652 public int max_number_of_white_listed_ssid; 1653 } 1654 1655 public boolean getScanCapabilities(ScanCapabilities capabilities) { 1656 synchronized (sLock) { 1657 return isHalStarted() && getScanCapabilitiesNative(sWlan0Index, capabilities); 1658 } 1659 } 1660 1661 private static native boolean getScanCapabilitiesNative( 1662 int iface, ScanCapabilities capabilities); 1663 1664 private static native boolean startScanNative(int iface, int id, ScanSettings settings); 1665 private static native boolean stopScanNative(int iface, int id); 1666 private static native WifiScanner.ScanData[] getScanResultsNative(int iface, boolean flush); 1667 private static native WifiLinkLayerStats getWifiLinkLayerStatsNative(int iface); 1668 private static native void setWifiLinkLayerStatsNative(int iface, int enable); 1669 1670 public static class ChannelSettings { 1671 public int frequency; 1672 public int dwell_time_ms; 1673 public boolean passive; 1674 } 1675 1676 public static class BucketSettings { 1677 public int bucket; 1678 public int band; 1679 public int period_ms; 1680 public int max_period_ms; 1681 public int step_count; 1682 public int report_events; 1683 public int num_channels; 1684 public ChannelSettings[] channels; 1685 } 1686 1687 public static class ScanSettings { 1688 public int base_period_ms; 1689 public int max_ap_per_scan; 1690 public int report_threshold_percent; 1691 public int report_threshold_num_scans; 1692 public int num_buckets; 1693 /* Not part of gscan HAL API. Used only for wpa_supplicant scanning */ 1694 public int[] hiddenNetworkIds; 1695 public BucketSettings[] buckets; 1696 } 1697 1698 /** 1699 * Network parameters to start PNO scan. 1700 */ 1701 public static class PnoNetwork { 1702 public String ssid; 1703 public int networkId; 1704 public int priority; 1705 public byte flags; 1706 public byte auth_bit_field; 1707 } 1708 1709 /** 1710 * Parameters to start PNO scan. This holds the list of networks which are going to used for 1711 * PNO scan. 1712 */ 1713 public static class PnoSettings { 1714 public int min5GHzRssi; 1715 public int min24GHzRssi; 1716 public int initialScoreMax; 1717 public int currentConnectionBonus; 1718 public int sameNetworkBonus; 1719 public int secureBonus; 1720 public int band5GHzBonus; 1721 public boolean isConnected; 1722 public PnoNetwork[] networkList; 1723 } 1724 1725 /** 1726 * Wi-Fi channel information. 1727 */ 1728 public static class WifiChannelInfo { 1729 int mPrimaryFrequency; 1730 int mCenterFrequency0; 1731 int mCenterFrequency1; 1732 int mChannelWidth; 1733 // TODO: add preamble once available in HAL. 1734 } 1735 1736 public static interface ScanEventHandler { 1737 /** 1738 * Called for each AP as it is found with the entire contents of the beacon/probe response. 1739 * Only called when WifiScanner.REPORT_EVENT_FULL_SCAN_RESULT is specified. 1740 */ 1741 void onFullScanResult(ScanResult fullScanResult, int bucketsScanned); 1742 /** 1743 * Callback on an event during a gscan scan. 1744 * See WifiNative.WIFI_SCAN_* for possible values. 1745 */ 1746 void onScanStatus(int event); 1747 /** 1748 * Called with the current cached scan results when gscan is paused. 1749 */ 1750 void onScanPaused(WifiScanner.ScanData[] data); 1751 /** 1752 * Called with the current cached scan results when gscan is resumed. 1753 */ 1754 void onScanRestarted(); 1755 } 1756 1757 /** 1758 * Handler to notify the occurrence of various events during PNO scan. 1759 */ 1760 public interface PnoEventHandler { 1761 /** 1762 * Callback to notify when one of the shortlisted networks is found during PNO scan. 1763 * @param results List of Scan results received. 1764 */ 1765 void onPnoNetworkFound(ScanResult[] results); 1766 1767 /** 1768 * Callback to notify when the PNO scan schedule fails. 1769 */ 1770 void onPnoScanFailed(); 1771 } 1772 1773 /* scan status, keep these values in sync with gscan.h */ 1774 public static final int WIFI_SCAN_RESULTS_AVAILABLE = 0; 1775 public static final int WIFI_SCAN_THRESHOLD_NUM_SCANS = 1; 1776 public static final int WIFI_SCAN_THRESHOLD_PERCENT = 2; 1777 public static final int WIFI_SCAN_FAILED = 3; 1778 1779 // Callback from native 1780 private static void onScanStatus(int id, int event) { 1781 ScanEventHandler handler = sScanEventHandler; 1782 if (handler != null) { 1783 handler.onScanStatus(event); 1784 } 1785 } 1786 1787 public static WifiSsid createWifiSsid(byte[] rawSsid) { 1788 String ssidHexString = String.valueOf(HexEncoding.encode(rawSsid)); 1789 1790 if (ssidHexString == null) { 1791 return null; 1792 } 1793 1794 WifiSsid wifiSsid = WifiSsid.createFromHex(ssidHexString); 1795 1796 return wifiSsid; 1797 } 1798 1799 public static String ssidConvert(byte[] rawSsid) { 1800 String ssid; 1801 1802 CharsetDecoder decoder = StandardCharsets.UTF_8.newDecoder(); 1803 try { 1804 CharBuffer decoded = decoder.decode(ByteBuffer.wrap(rawSsid)); 1805 ssid = decoded.toString(); 1806 } catch (CharacterCodingException cce) { 1807 ssid = null; 1808 } 1809 1810 if (ssid == null) { 1811 ssid = new String(rawSsid, StandardCharsets.ISO_8859_1); 1812 } 1813 1814 return ssid; 1815 } 1816 1817 // Called from native 1818 public static boolean setSsid(byte[] rawSsid, ScanResult result) { 1819 if (rawSsid == null || rawSsid.length == 0 || result == null) { 1820 return false; 1821 } 1822 1823 result.SSID = ssidConvert(rawSsid); 1824 result.wifiSsid = createWifiSsid(rawSsid); 1825 return true; 1826 } 1827 1828 private static void populateScanResult(ScanResult result, int beaconCap, String dbg) { 1829 if (dbg == null) dbg = ""; 1830 1831 InformationElementUtil.HtOperation htOperation = new InformationElementUtil.HtOperation(); 1832 InformationElementUtil.VhtOperation vhtOperation = 1833 new InformationElementUtil.VhtOperation(); 1834 InformationElementUtil.ExtendedCapabilities extendedCaps = 1835 new InformationElementUtil.ExtendedCapabilities(); 1836 1837 ScanResult.InformationElement elements[] = 1838 InformationElementUtil.parseInformationElements(result.bytes); 1839 for (ScanResult.InformationElement ie : elements) { 1840 if(ie.id == ScanResult.InformationElement.EID_HT_OPERATION) { 1841 htOperation.from(ie); 1842 } else if(ie.id == ScanResult.InformationElement.EID_VHT_OPERATION) { 1843 vhtOperation.from(ie); 1844 } else if (ie.id == ScanResult.InformationElement.EID_EXTENDED_CAPS) { 1845 extendedCaps.from(ie); 1846 } 1847 } 1848 1849 if (extendedCaps.is80211McRTTResponder) { 1850 result.setFlag(ScanResult.FLAG_80211mc_RESPONDER); 1851 } else { 1852 result.clearFlag(ScanResult.FLAG_80211mc_RESPONDER); 1853 } 1854 1855 //handle RTT related information 1856 if (vhtOperation.isValid()) { 1857 result.channelWidth = vhtOperation.getChannelWidth(); 1858 result.centerFreq0 = vhtOperation.getCenterFreq0(); 1859 result.centerFreq1 = vhtOperation.getCenterFreq1(); 1860 } else { 1861 result.channelWidth = htOperation.getChannelWidth(); 1862 result.centerFreq0 = htOperation.getCenterFreq0(result.frequency); 1863 result.centerFreq1 = 0; 1864 } 1865 1866 // build capabilities string 1867 BitSet beaconCapBits = new BitSet(16); 1868 for (int i = 0; i < 16; i++) { 1869 if ((beaconCap & (1 << i)) != 0) { 1870 beaconCapBits.set(i); 1871 } 1872 } 1873 result.capabilities = InformationElementUtil.Capabilities.buildCapabilities(elements, 1874 beaconCapBits); 1875 1876 if(DBG) { 1877 Log.d(TAG, dbg + "SSID: " + result.SSID + " ChannelWidth is: " + result.channelWidth 1878 + " PrimaryFreq: " + result.frequency + " mCenterfreq0: " + result.centerFreq0 1879 + " mCenterfreq1: " + result.centerFreq1 + (extendedCaps.is80211McRTTResponder 1880 ? "Support RTT reponder: " : "Do not support RTT responder") 1881 + " Capabilities: " + result.capabilities); 1882 } 1883 1884 result.informationElements = elements; 1885 } 1886 1887 // Callback from native 1888 private static void onFullScanResult(int id, ScanResult result, 1889 int bucketsScanned, int beaconCap) { 1890 if (DBG) Log.i(TAG, "Got a full scan results event, ssid = " + result.SSID); 1891 1892 ScanEventHandler handler = sScanEventHandler; 1893 if (handler != null) { 1894 populateScanResult(result, beaconCap, " onFullScanResult "); 1895 handler.onFullScanResult(result, bucketsScanned); 1896 } 1897 } 1898 1899 private static int sScanCmdId = 0; 1900 private static ScanEventHandler sScanEventHandler; 1901 private static ScanSettings sScanSettings; 1902 1903 public boolean startScan(ScanSettings settings, ScanEventHandler eventHandler) { 1904 synchronized (sLock) { 1905 if (isHalStarted()) { 1906 if (sScanCmdId != 0) { 1907 stopScan(); 1908 } else if (sScanSettings != null || sScanEventHandler != null) { 1909 /* current scan is paused; no need to stop it */ 1910 } 1911 1912 sScanCmdId = getNewCmdIdLocked(); 1913 1914 sScanSettings = settings; 1915 sScanEventHandler = eventHandler; 1916 1917 if (startScanNative(sWlan0Index, sScanCmdId, settings) == false) { 1918 sScanEventHandler = null; 1919 sScanSettings = null; 1920 sScanCmdId = 0; 1921 return false; 1922 } 1923 1924 return true; 1925 } else { 1926 return false; 1927 } 1928 } 1929 } 1930 1931 public void stopScan() { 1932 synchronized (sLock) { 1933 if (isHalStarted()) { 1934 if (sScanCmdId != 0) { 1935 stopScanNative(sWlan0Index, sScanCmdId); 1936 } 1937 sScanSettings = null; 1938 sScanEventHandler = null; 1939 sScanCmdId = 0; 1940 } 1941 } 1942 } 1943 1944 public void pauseScan() { 1945 synchronized (sLock) { 1946 if (isHalStarted()) { 1947 if (sScanCmdId != 0 && sScanSettings != null && sScanEventHandler != null) { 1948 Log.d(TAG, "Pausing scan"); 1949 WifiScanner.ScanData scanData[] = getScanResultsNative(sWlan0Index, true); 1950 stopScanNative(sWlan0Index, sScanCmdId); 1951 sScanCmdId = 0; 1952 sScanEventHandler.onScanPaused(scanData); 1953 } 1954 } 1955 } 1956 } 1957 1958 public void restartScan() { 1959 synchronized (sLock) { 1960 if (isHalStarted()) { 1961 if (sScanCmdId == 0 && sScanSettings != null && sScanEventHandler != null) { 1962 Log.d(TAG, "Restarting scan"); 1963 ScanEventHandler handler = sScanEventHandler; 1964 ScanSettings settings = sScanSettings; 1965 if (startScan(sScanSettings, sScanEventHandler)) { 1966 sScanEventHandler.onScanRestarted(); 1967 } else { 1968 /* we are still paused; don't change state */ 1969 sScanEventHandler = handler; 1970 sScanSettings = settings; 1971 } 1972 } 1973 } 1974 } 1975 } 1976 1977 public WifiScanner.ScanData[] getScanResults(boolean flush) { 1978 synchronized (sLock) { 1979 WifiScanner.ScanData[] sd = null; 1980 if (isHalStarted()) { 1981 sd = getScanResultsNative(sWlan0Index, flush); 1982 } 1983 1984 if (sd != null) { 1985 return sd; 1986 } else { 1987 return new WifiScanner.ScanData[0]; 1988 } 1989 } 1990 } 1991 1992 public static interface HotlistEventHandler { 1993 void onHotlistApFound (ScanResult[] result); 1994 void onHotlistApLost (ScanResult[] result); 1995 } 1996 1997 private static int sHotlistCmdId = 0; 1998 private static HotlistEventHandler sHotlistEventHandler; 1999 2000 private native static boolean setHotlistNative(int iface, int id, 2001 WifiScanner.HotlistSettings settings); 2002 private native static boolean resetHotlistNative(int iface, int id); 2003 2004 public boolean setHotlist(WifiScanner.HotlistSettings settings, 2005 HotlistEventHandler eventHandler) { 2006 synchronized (sLock) { 2007 if (isHalStarted()) { 2008 if (sHotlistCmdId != 0) { 2009 return false; 2010 } else { 2011 sHotlistCmdId = getNewCmdIdLocked(); 2012 } 2013 2014 sHotlistEventHandler = eventHandler; 2015 if (setHotlistNative(sWlan0Index, sHotlistCmdId, settings) == false) { 2016 sHotlistEventHandler = null; 2017 return false; 2018 } 2019 2020 return true; 2021 } else { 2022 return false; 2023 } 2024 } 2025 } 2026 2027 public void resetHotlist() { 2028 synchronized (sLock) { 2029 if (isHalStarted()) { 2030 if (sHotlistCmdId != 0) { 2031 resetHotlistNative(sWlan0Index, sHotlistCmdId); 2032 sHotlistCmdId = 0; 2033 sHotlistEventHandler = null; 2034 } 2035 } 2036 } 2037 } 2038 2039 // Callback from native 2040 private static void onHotlistApFound(int id, ScanResult[] results) { 2041 HotlistEventHandler handler = sHotlistEventHandler; 2042 if (handler != null) { 2043 handler.onHotlistApFound(results); 2044 } else { 2045 /* this can happen because of race conditions */ 2046 Log.d(TAG, "Ignoring hotlist AP found event"); 2047 } 2048 } 2049 2050 // Callback from native 2051 private static void onHotlistApLost(int id, ScanResult[] results) { 2052 HotlistEventHandler handler = sHotlistEventHandler; 2053 if (handler != null) { 2054 handler.onHotlistApLost(results); 2055 } else { 2056 /* this can happen because of race conditions */ 2057 Log.d(TAG, "Ignoring hotlist AP lost event"); 2058 } 2059 } 2060 2061 public static interface SignificantWifiChangeEventHandler { 2062 void onChangesFound(ScanResult[] result); 2063 } 2064 2065 private static SignificantWifiChangeEventHandler sSignificantWifiChangeHandler; 2066 private static int sSignificantWifiChangeCmdId; 2067 2068 private static native boolean trackSignificantWifiChangeNative( 2069 int iface, int id, WifiScanner.WifiChangeSettings settings); 2070 private static native boolean untrackSignificantWifiChangeNative(int iface, int id); 2071 2072 public boolean trackSignificantWifiChange( 2073 WifiScanner.WifiChangeSettings settings, SignificantWifiChangeEventHandler handler) { 2074 synchronized (sLock) { 2075 if (isHalStarted()) { 2076 if (sSignificantWifiChangeCmdId != 0) { 2077 return false; 2078 } else { 2079 sSignificantWifiChangeCmdId = getNewCmdIdLocked(); 2080 } 2081 2082 sSignificantWifiChangeHandler = handler; 2083 if (trackSignificantWifiChangeNative(sWlan0Index, sSignificantWifiChangeCmdId, 2084 settings) == false) { 2085 sSignificantWifiChangeHandler = null; 2086 return false; 2087 } 2088 2089 return true; 2090 } else { 2091 return false; 2092 } 2093 2094 } 2095 } 2096 2097 public void untrackSignificantWifiChange() { 2098 synchronized (sLock) { 2099 if (isHalStarted()) { 2100 if (sSignificantWifiChangeCmdId != 0) { 2101 untrackSignificantWifiChangeNative(sWlan0Index, sSignificantWifiChangeCmdId); 2102 sSignificantWifiChangeCmdId = 0; 2103 sSignificantWifiChangeHandler = null; 2104 } 2105 } 2106 } 2107 } 2108 2109 // Callback from native 2110 private static void onSignificantWifiChange(int id, ScanResult[] results) { 2111 SignificantWifiChangeEventHandler handler = sSignificantWifiChangeHandler; 2112 if (handler != null) { 2113 handler.onChangesFound(results); 2114 } else { 2115 /* this can happen because of race conditions */ 2116 Log.d(TAG, "Ignoring significant wifi change"); 2117 } 2118 } 2119 2120 public WifiLinkLayerStats getWifiLinkLayerStats(String iface) { 2121 // TODO: use correct iface name to Index translation 2122 if (iface == null) return null; 2123 synchronized (sLock) { 2124 if (isHalStarted()) { 2125 return getWifiLinkLayerStatsNative(sWlan0Index); 2126 } else { 2127 return null; 2128 } 2129 } 2130 } 2131 2132 public void setWifiLinkLayerStats(String iface, int enable) { 2133 if (iface == null) return; 2134 synchronized (sLock) { 2135 if (isHalStarted()) { 2136 setWifiLinkLayerStatsNative(sWlan0Index, enable); 2137 } 2138 } 2139 } 2140 2141 public static native int getSupportedFeatureSetNative(int iface); 2142 public int getSupportedFeatureSet() { 2143 synchronized (sLock) { 2144 if (isHalStarted()) { 2145 return getSupportedFeatureSetNative(sWlan0Index); 2146 } else { 2147 Log.d(TAG, "Failing getSupportedFeatureset because HAL isn't started"); 2148 return 0; 2149 } 2150 } 2151 } 2152 2153 /* Rtt related commands/events */ 2154 public static interface RttEventHandler { 2155 void onRttResults(RttManager.RttResult[] result); 2156 } 2157 2158 private static RttEventHandler sRttEventHandler; 2159 private static int sRttCmdId; 2160 2161 // Callback from native 2162 private static void onRttResults(int id, RttManager.RttResult[] results) { 2163 RttEventHandler handler = sRttEventHandler; 2164 if (handler != null && id == sRttCmdId) { 2165 Log.d(TAG, "Received " + results.length + " rtt results"); 2166 handler.onRttResults(results); 2167 sRttCmdId = 0; 2168 } else { 2169 Log.d(TAG, "RTT Received event for unknown cmd = " + id + 2170 ", current id = " + sRttCmdId); 2171 } 2172 } 2173 2174 private static native boolean requestRangeNative( 2175 int iface, int id, RttManager.RttParams[] params); 2176 private static native boolean cancelRangeRequestNative( 2177 int iface, int id, RttManager.RttParams[] params); 2178 2179 public boolean requestRtt( 2180 RttManager.RttParams[] params, RttEventHandler handler) { 2181 synchronized (sLock) { 2182 if (isHalStarted()) { 2183 if (sRttCmdId != 0) { 2184 Log.v("TAG", "Last one is still under measurement!"); 2185 return false; 2186 } else { 2187 sRttCmdId = getNewCmdIdLocked(); 2188 } 2189 sRttEventHandler = handler; 2190 Log.v(TAG, "native issue RTT request"); 2191 return requestRangeNative(sWlan0Index, sRttCmdId, params); 2192 } else { 2193 return false; 2194 } 2195 } 2196 } 2197 2198 public boolean cancelRtt(RttManager.RttParams[] params) { 2199 synchronized (sLock) { 2200 if (isHalStarted()) { 2201 if (sRttCmdId == 0) { 2202 return false; 2203 } 2204 2205 sRttCmdId = 0; 2206 2207 if (cancelRangeRequestNative(sWlan0Index, sRttCmdId, params)) { 2208 sRttEventHandler = null; 2209 Log.v(TAG, "RTT cancel Request Successfully"); 2210 return true; 2211 } else { 2212 Log.e(TAG, "RTT cancel Request failed"); 2213 return false; 2214 } 2215 } else { 2216 return false; 2217 } 2218 } 2219 } 2220 2221 private static int sRttResponderCmdId = 0; 2222 2223 private static native ResponderConfig enableRttResponderNative(int iface, int commandId, 2224 int timeoutSeconds, WifiChannelInfo channelHint); 2225 /** 2226 * Enable RTT responder role on the device. Returns {@link ResponderConfig} if the responder 2227 * role is successfully enabled, {@code null} otherwise. 2228 */ 2229 @Nullable 2230 public ResponderConfig enableRttResponder(int timeoutSeconds) { 2231 synchronized (sLock) { 2232 if (!isHalStarted()) return null; 2233 if (sRttResponderCmdId != 0) { 2234 if (DBG) Log.e(mTAG, "responder mode already enabled - this shouldn't happen"); 2235 return null; 2236 } 2237 int id = getNewCmdIdLocked(); 2238 ResponderConfig config = enableRttResponderNative( 2239 sWlan0Index, id, timeoutSeconds, null); 2240 if (config != null) sRttResponderCmdId = id; 2241 if (DBG) Log.d(TAG, "enabling rtt " + (config != null)); 2242 return config; 2243 } 2244 } 2245 2246 private static native boolean disableRttResponderNative(int iface, int commandId); 2247 /** 2248 * Disable RTT responder role. Returns {@code true} if responder role is successfully disabled, 2249 * {@code false} otherwise. 2250 */ 2251 public boolean disableRttResponder() { 2252 synchronized (sLock) { 2253 if (!isHalStarted()) return false; 2254 if (sRttResponderCmdId == 0) { 2255 Log.e(mTAG, "responder role not enabled yet"); 2256 return true; 2257 } 2258 sRttResponderCmdId = 0; 2259 return disableRttResponderNative(sWlan0Index, sRttResponderCmdId); 2260 } 2261 } 2262 2263 private static native boolean setScanningMacOuiNative(int iface, byte[] oui); 2264 2265 public boolean setScanningMacOui(byte[] oui) { 2266 synchronized (sLock) { 2267 if (isHalStarted()) { 2268 return setScanningMacOuiNative(sWlan0Index, oui); 2269 } else { 2270 return false; 2271 } 2272 } 2273 } 2274 2275 private static native int[] getChannelsForBandNative( 2276 int iface, int band); 2277 2278 public int [] getChannelsForBand(int band) { 2279 synchronized (sLock) { 2280 if (isHalStarted()) { 2281 return getChannelsForBandNative(sWlan0Index, band); 2282 } else { 2283 return null; 2284 } 2285 } 2286 } 2287 2288 private static native boolean isGetChannelsForBandSupportedNative(); 2289 public boolean isGetChannelsForBandSupported(){ 2290 synchronized (sLock) { 2291 if (isHalStarted()) { 2292 return isGetChannelsForBandSupportedNative(); 2293 } else { 2294 return false; 2295 } 2296 } 2297 } 2298 2299 private static native boolean setDfsFlagNative(int iface, boolean dfsOn); 2300 public boolean setDfsFlag(boolean dfsOn) { 2301 synchronized (sLock) { 2302 if (isHalStarted()) { 2303 return setDfsFlagNative(sWlan0Index, dfsOn); 2304 } else { 2305 return false; 2306 } 2307 } 2308 } 2309 2310 private static native boolean setInterfaceUpNative(boolean up); 2311 public boolean setInterfaceUp(boolean up) { 2312 synchronized (sLock) { 2313 if (isHalStarted()) { 2314 return setInterfaceUpNative(up); 2315 } else { 2316 return false; 2317 } 2318 } 2319 } 2320 2321 private static native RttManager.RttCapabilities getRttCapabilitiesNative(int iface); 2322 public RttManager.RttCapabilities getRttCapabilities() { 2323 synchronized (sLock) { 2324 if (isHalStarted()) { 2325 return getRttCapabilitiesNative(sWlan0Index); 2326 } else { 2327 return null; 2328 } 2329 } 2330 } 2331 2332 private static native ApfCapabilities getApfCapabilitiesNative(int iface); 2333 public ApfCapabilities getApfCapabilities() { 2334 synchronized (sLock) { 2335 if (isHalStarted()) { 2336 return getApfCapabilitiesNative(sWlan0Index); 2337 } else { 2338 return null; 2339 } 2340 } 2341 } 2342 2343 private static native boolean installPacketFilterNative(int iface, byte[] filter); 2344 public boolean installPacketFilter(byte[] filter) { 2345 synchronized (sLock) { 2346 if (isHalStarted()) { 2347 return installPacketFilterNative(sWlan0Index, filter); 2348 } else { 2349 return false; 2350 } 2351 } 2352 } 2353 2354 private static native boolean setCountryCodeHalNative(int iface, String CountryCode); 2355 public boolean setCountryCodeHal(String CountryCode) { 2356 synchronized (sLock) { 2357 if (isHalStarted()) { 2358 return setCountryCodeHalNative(sWlan0Index, CountryCode); 2359 } else { 2360 return false; 2361 } 2362 } 2363 } 2364 2365 /* Rtt related commands/events */ 2366 public abstract class TdlsEventHandler { 2367 abstract public void onTdlsStatus(String macAddr, int status, int reason); 2368 } 2369 2370 private static TdlsEventHandler sTdlsEventHandler; 2371 2372 private static native boolean enableDisableTdlsNative(int iface, boolean enable, 2373 String macAddr); 2374 public boolean enableDisableTdls(boolean enable, String macAdd, TdlsEventHandler tdlsCallBack) { 2375 synchronized (sLock) { 2376 sTdlsEventHandler = tdlsCallBack; 2377 return enableDisableTdlsNative(sWlan0Index, enable, macAdd); 2378 } 2379 } 2380 2381 // Once TDLS per mac and event feature is implemented, this class definition should be 2382 // moved to the right place, like WifiManager etc 2383 public static class TdlsStatus { 2384 int channel; 2385 int global_operating_class; 2386 int state; 2387 int reason; 2388 } 2389 private static native TdlsStatus getTdlsStatusNative(int iface, String macAddr); 2390 public TdlsStatus getTdlsStatus(String macAdd) { 2391 synchronized (sLock) { 2392 if (isHalStarted()) { 2393 return getTdlsStatusNative(sWlan0Index, macAdd); 2394 } else { 2395 return null; 2396 } 2397 } 2398 } 2399 2400 //ToFix: Once TDLS per mac and event feature is implemented, this class definition should be 2401 // moved to the right place, like WifiStateMachine etc 2402 public static class TdlsCapabilities { 2403 /* Maximum TDLS session number can be supported by the Firmware and hardware */ 2404 int maxConcurrentTdlsSessionNumber; 2405 boolean isGlobalTdlsSupported; 2406 boolean isPerMacTdlsSupported; 2407 boolean isOffChannelTdlsSupported; 2408 } 2409 2410 2411 2412 private static native TdlsCapabilities getTdlsCapabilitiesNative(int iface); 2413 public TdlsCapabilities getTdlsCapabilities () { 2414 synchronized (sLock) { 2415 if (isHalStarted()) { 2416 return getTdlsCapabilitiesNative(sWlan0Index); 2417 } else { 2418 return null; 2419 } 2420 } 2421 } 2422 2423 private static boolean onTdlsStatus(String macAddr, int status, int reason) { 2424 TdlsEventHandler handler = sTdlsEventHandler; 2425 if (handler == null) { 2426 return false; 2427 } else { 2428 handler.onTdlsStatus(macAddr, status, reason); 2429 return true; 2430 } 2431 } 2432 2433 //--------------------------------------------------------------------------------- 2434 2435 /* Wifi Logger commands/events */ 2436 2437 public static interface WifiLoggerEventHandler { 2438 void onRingBufferData(RingBufferStatus status, byte[] buffer); 2439 void onWifiAlert(int errorCode, byte[] buffer); 2440 } 2441 2442 private static WifiLoggerEventHandler sWifiLoggerEventHandler = null; 2443 2444 // Callback from native 2445 private static void onRingBufferData(RingBufferStatus status, byte[] buffer) { 2446 WifiLoggerEventHandler handler = sWifiLoggerEventHandler; 2447 if (handler != null) 2448 handler.onRingBufferData(status, buffer); 2449 } 2450 2451 // Callback from native 2452 private static void onWifiAlert(byte[] buffer, int errorCode) { 2453 WifiLoggerEventHandler handler = sWifiLoggerEventHandler; 2454 if (handler != null) 2455 handler.onWifiAlert(errorCode, buffer); 2456 } 2457 2458 private static int sLogCmdId = -1; 2459 private static native boolean setLoggingEventHandlerNative(int iface, int id); 2460 public boolean setLoggingEventHandler(WifiLoggerEventHandler handler) { 2461 synchronized (sLock) { 2462 if (isHalStarted()) { 2463 int oldId = sLogCmdId; 2464 sLogCmdId = getNewCmdIdLocked(); 2465 if (!setLoggingEventHandlerNative(sWlan0Index, sLogCmdId)) { 2466 sLogCmdId = oldId; 2467 return false; 2468 } 2469 sWifiLoggerEventHandler = handler; 2470 return true; 2471 } else { 2472 return false; 2473 } 2474 } 2475 } 2476 2477 private static native boolean startLoggingRingBufferNative(int iface, int verboseLevel, 2478 int flags, int minIntervalSec ,int minDataSize, String ringName); 2479 public boolean startLoggingRingBuffer(int verboseLevel, int flags, int maxInterval, 2480 int minDataSize, String ringName){ 2481 synchronized (sLock) { 2482 if (isHalStarted()) { 2483 return startLoggingRingBufferNative(sWlan0Index, verboseLevel, flags, maxInterval, 2484 minDataSize, ringName); 2485 } else { 2486 return false; 2487 } 2488 } 2489 } 2490 2491 private static native int getSupportedLoggerFeatureSetNative(int iface); 2492 public int getSupportedLoggerFeatureSet() { 2493 synchronized (sLock) { 2494 if (isHalStarted()) { 2495 return getSupportedLoggerFeatureSetNative(sWlan0Index); 2496 } else { 2497 return 0; 2498 } 2499 } 2500 } 2501 2502 private static native boolean resetLogHandlerNative(int iface, int id); 2503 public boolean resetLogHandler() { 2504 synchronized (sLock) { 2505 if (isHalStarted()) { 2506 if (sLogCmdId == -1) { 2507 Log.e(TAG,"Can not reset handler Before set any handler"); 2508 return false; 2509 } 2510 sWifiLoggerEventHandler = null; 2511 if (resetLogHandlerNative(sWlan0Index, sLogCmdId)) { 2512 sLogCmdId = -1; 2513 return true; 2514 } else { 2515 return false; 2516 } 2517 } else { 2518 return false; 2519 } 2520 } 2521 } 2522 2523 private static native String getDriverVersionNative(int iface); 2524 public String getDriverVersion() { 2525 synchronized (sLock) { 2526 if (isHalStarted()) { 2527 return getDriverVersionNative(sWlan0Index); 2528 } else { 2529 return ""; 2530 } 2531 } 2532 } 2533 2534 2535 private static native String getFirmwareVersionNative(int iface); 2536 public String getFirmwareVersion() { 2537 synchronized (sLock) { 2538 if (isHalStarted()) { 2539 return getFirmwareVersionNative(sWlan0Index); 2540 } else { 2541 return ""; 2542 } 2543 } 2544 } 2545 2546 public static class RingBufferStatus{ 2547 String name; 2548 int flag; 2549 int ringBufferId; 2550 int ringBufferByteSize; 2551 int verboseLevel; 2552 int writtenBytes; 2553 int readBytes; 2554 int writtenRecords; 2555 2556 @Override 2557 public String toString() { 2558 return "name: " + name + " flag: " + flag + " ringBufferId: " + ringBufferId + 2559 " ringBufferByteSize: " +ringBufferByteSize + " verboseLevel: " +verboseLevel + 2560 " writtenBytes: " + writtenBytes + " readBytes: " + readBytes + 2561 " writtenRecords: " + writtenRecords; 2562 } 2563 } 2564 2565 private static native RingBufferStatus[] getRingBufferStatusNative(int iface); 2566 public RingBufferStatus[] getRingBufferStatus() { 2567 synchronized (sLock) { 2568 if (isHalStarted()) { 2569 return getRingBufferStatusNative(sWlan0Index); 2570 } else { 2571 return null; 2572 } 2573 } 2574 } 2575 2576 private static native boolean getRingBufferDataNative(int iface, String ringName); 2577 public boolean getRingBufferData(String ringName) { 2578 synchronized (sLock) { 2579 if (isHalStarted()) { 2580 return getRingBufferDataNative(sWlan0Index, ringName); 2581 } else { 2582 return false; 2583 } 2584 } 2585 } 2586 2587 private static byte[] mFwMemoryDump; 2588 // Callback from native 2589 private static void onWifiFwMemoryAvailable(byte[] buffer) { 2590 mFwMemoryDump = buffer; 2591 if (DBG) { 2592 Log.d(TAG, "onWifiFwMemoryAvailable is called and buffer length is: " + 2593 (buffer == null ? 0 : buffer.length)); 2594 } 2595 } 2596 2597 private static native boolean getFwMemoryDumpNative(int iface); 2598 public byte[] getFwMemoryDump() { 2599 synchronized (sLock) { 2600 if (isHalStarted()) { 2601 if(getFwMemoryDumpNative(sWlan0Index)) { 2602 byte[] fwMemoryDump = mFwMemoryDump; 2603 mFwMemoryDump = null; 2604 return fwMemoryDump; 2605 } else { 2606 return null; 2607 } 2608 } 2609 return null; 2610 } 2611 } 2612 2613 private static native byte[] getDriverStateDumpNative(int iface); 2614 /** Fetch the driver state, for driver debugging. */ 2615 public byte[] getDriverStateDump() { 2616 synchronized (sLock) { 2617 if (isHalStarted()) { 2618 return getDriverStateDumpNative(sWlan0Index); 2619 } else { 2620 return null; 2621 } 2622 } 2623 } 2624 2625 //--------------------------------------------------------------------------------- 2626 /* Packet fate API */ 2627 2628 @Immutable 2629 abstract static class FateReport { 2630 final byte mFate; 2631 final long mDriverTimestampUSec; 2632 final byte mFrameType; 2633 final byte[] mFrameBytes; 2634 2635 FateReport(byte fate, long driverTimestampUSec, byte frameType, byte[] frameBytes) { 2636 mFate = fate; 2637 mDriverTimestampUSec = driverTimestampUSec; 2638 mFrameType = frameType; 2639 mFrameBytes = frameBytes; 2640 } 2641 2642 public String toTableRowString() { 2643 StringWriter sw = new StringWriter(); 2644 PrintWriter pw = new PrintWriter(sw); 2645 FrameParser parser = new FrameParser(mFrameType, mFrameBytes); 2646 pw.format("%-15s %-9s %-32s %-12s %s\n", 2647 mDriverTimestampUSec, directionToString(), fateToString(), 2648 parser.mMostSpecificProtocolString, parser.mTypeString); 2649 return sw.toString(); 2650 } 2651 2652 public String toVerboseStringWithPiiAllowed() { 2653 StringWriter sw = new StringWriter(); 2654 PrintWriter pw = new PrintWriter(sw); 2655 FrameParser parser = new FrameParser(mFrameType, mFrameBytes); 2656 pw.format("Frame direction: %s\n", directionToString()); 2657 pw.format("Frame timestamp: %d\n", mDriverTimestampUSec); 2658 pw.format("Frame fate: %s\n", fateToString()); 2659 pw.format("Frame type: %s\n", frameTypeToString(mFrameType)); 2660 pw.format("Frame protocol: %s\n", parser.mMostSpecificProtocolString); 2661 pw.format("Frame protocol type: %s\n", parser.mTypeString); 2662 pw.format("Frame length: %d\n", mFrameBytes.length); 2663 pw.append("Frame bytes"); 2664 pw.append(HexDump.dumpHexString(mFrameBytes)); // potentially contains PII 2665 pw.append("\n"); 2666 return sw.toString(); 2667 } 2668 2669 /* Returns a header to match the output of toTableRowString(). */ 2670 public static String getTableHeader() { 2671 StringWriter sw = new StringWriter(); 2672 PrintWriter pw = new PrintWriter(sw); 2673 pw.format("\n%-15s %-9s %-32s %-12s %s\n", 2674 "Timestamp", "Direction", "Fate", "Protocol", "Type"); 2675 pw.format("%-15s %-9s %-32s %-12s %s\n", 2676 "---------", "---------", "----", "--------", "----"); 2677 return sw.toString(); 2678 } 2679 2680 protected abstract String directionToString(); 2681 2682 protected abstract String fateToString(); 2683 2684 private static String frameTypeToString(byte frameType) { 2685 switch (frameType) { 2686 case WifiLoggerHal.FRAME_TYPE_UNKNOWN: 2687 return "unknown"; 2688 case WifiLoggerHal.FRAME_TYPE_ETHERNET_II: 2689 return "data"; 2690 case WifiLoggerHal.FRAME_TYPE_80211_MGMT: 2691 return "802.11 management"; 2692 default: 2693 return Byte.toString(frameType); 2694 } 2695 } 2696 } 2697 2698 /** 2699 * Represents the fate information for one outbound packet. 2700 */ 2701 @Immutable 2702 public static final class TxFateReport extends FateReport { 2703 TxFateReport(byte fate, long driverTimestampUSec, byte frameType, byte[] frameBytes) { 2704 super(fate, driverTimestampUSec, frameType, frameBytes); 2705 } 2706 2707 @Override 2708 protected String directionToString() { 2709 return "TX"; 2710 } 2711 2712 @Override 2713 protected String fateToString() { 2714 switch (mFate) { 2715 case WifiLoggerHal.TX_PKT_FATE_ACKED: 2716 return "acked"; 2717 case WifiLoggerHal.TX_PKT_FATE_SENT: 2718 return "sent"; 2719 case WifiLoggerHal.TX_PKT_FATE_FW_QUEUED: 2720 return "firmware queued"; 2721 case WifiLoggerHal.TX_PKT_FATE_FW_DROP_INVALID: 2722 return "firmware dropped (invalid frame)"; 2723 case WifiLoggerHal.TX_PKT_FATE_FW_DROP_NOBUFS: 2724 return "firmware dropped (no bufs)"; 2725 case WifiLoggerHal.TX_PKT_FATE_FW_DROP_OTHER: 2726 return "firmware dropped (other)"; 2727 case WifiLoggerHal.TX_PKT_FATE_DRV_QUEUED: 2728 return "driver queued"; 2729 case WifiLoggerHal.TX_PKT_FATE_DRV_DROP_INVALID: 2730 return "driver dropped (invalid frame)"; 2731 case WifiLoggerHal.TX_PKT_FATE_DRV_DROP_NOBUFS: 2732 return "driver dropped (no bufs)"; 2733 case WifiLoggerHal.TX_PKT_FATE_DRV_DROP_OTHER: 2734 return "driver dropped (other)"; 2735 default: 2736 return Byte.toString(mFate); 2737 } 2738 } 2739 } 2740 2741 /** 2742 * Represents the fate information for one inbound packet. 2743 */ 2744 @Immutable 2745 public static final class RxFateReport extends FateReport { 2746 RxFateReport(byte fate, long driverTimestampUSec, byte frameType, byte[] frameBytes) { 2747 super(fate, driverTimestampUSec, frameType, frameBytes); 2748 } 2749 2750 @Override 2751 protected String directionToString() { 2752 return "RX"; 2753 } 2754 2755 @Override 2756 protected String fateToString() { 2757 switch (mFate) { 2758 case WifiLoggerHal.RX_PKT_FATE_SUCCESS: 2759 return "success"; 2760 case WifiLoggerHal.RX_PKT_FATE_FW_QUEUED: 2761 return "firmware queued"; 2762 case WifiLoggerHal.RX_PKT_FATE_FW_DROP_FILTER: 2763 return "firmware dropped (filter)"; 2764 case WifiLoggerHal.RX_PKT_FATE_FW_DROP_INVALID: 2765 return "firmware dropped (invalid frame)"; 2766 case WifiLoggerHal.RX_PKT_FATE_FW_DROP_NOBUFS: 2767 return "firmware dropped (no bufs)"; 2768 case WifiLoggerHal.RX_PKT_FATE_FW_DROP_OTHER: 2769 return "firmware dropped (other)"; 2770 case WifiLoggerHal.RX_PKT_FATE_DRV_QUEUED: 2771 return "driver queued"; 2772 case WifiLoggerHal.RX_PKT_FATE_DRV_DROP_FILTER: 2773 return "driver dropped (filter)"; 2774 case WifiLoggerHal.RX_PKT_FATE_DRV_DROP_INVALID: 2775 return "driver dropped (invalid frame)"; 2776 case WifiLoggerHal.RX_PKT_FATE_DRV_DROP_NOBUFS: 2777 return "driver dropped (no bufs)"; 2778 case WifiLoggerHal.RX_PKT_FATE_DRV_DROP_OTHER: 2779 return "driver dropped (other)"; 2780 default: 2781 return Byte.toString(mFate); 2782 } 2783 } 2784 } 2785 2786 private static native int startPktFateMonitoringNative(int iface); 2787 /** 2788 * Ask the HAL to enable packet fate monitoring. Fails unless HAL is started. 2789 */ 2790 public boolean startPktFateMonitoring() { 2791 synchronized (sLock) { 2792 if (isHalStarted()) { 2793 return startPktFateMonitoringNative(sWlan0Index) == WIFI_SUCCESS; 2794 } else { 2795 return false; 2796 } 2797 } 2798 } 2799 2800 private static native int getTxPktFatesNative(int iface, TxFateReport[] reportBufs); 2801 /** 2802 * Fetch the most recent TX packet fates from the HAL. Fails unless HAL is started. 2803 */ 2804 public boolean getTxPktFates(TxFateReport[] reportBufs) { 2805 synchronized (sLock) { 2806 if (isHalStarted()) { 2807 int res = getTxPktFatesNative(sWlan0Index, reportBufs); 2808 if (res != WIFI_SUCCESS) { 2809 Log.e(TAG, "getTxPktFatesNative returned " + res); 2810 return false; 2811 } else { 2812 return true; 2813 } 2814 } else { 2815 return false; 2816 } 2817 } 2818 } 2819 2820 private static native int getRxPktFatesNative(int iface, RxFateReport[] reportBufs); 2821 /** 2822 * Fetch the most recent RX packet fates from the HAL. Fails unless HAL is started. 2823 */ 2824 public boolean getRxPktFates(RxFateReport[] reportBufs) { 2825 synchronized (sLock) { 2826 if (isHalStarted()) { 2827 int res = getRxPktFatesNative(sWlan0Index, reportBufs); 2828 if (res != WIFI_SUCCESS) { 2829 Log.e(TAG, "getRxPktFatesNative returned " + res); 2830 return false; 2831 } else { 2832 return true; 2833 } 2834 } else { 2835 return false; 2836 } 2837 } 2838 } 2839 2840 //--------------------------------------------------------------------------------- 2841 /* Configure ePNO/PNO */ 2842 private static PnoEventHandler sPnoEventHandler; 2843 private static int sPnoCmdId = 0; 2844 2845 private static native boolean setPnoListNative(int iface, int id, PnoSettings settings); 2846 2847 /** 2848 * Set the PNO settings & the network list in HAL to start PNO. 2849 * @param settings PNO settings and network list. 2850 * @param eventHandler Handler to receive notifications back during PNO scan. 2851 * @return true if success, false otherwise 2852 */ 2853 public boolean setPnoList(PnoSettings settings, PnoEventHandler eventHandler) { 2854 Log.e(TAG, "setPnoList cmd " + sPnoCmdId); 2855 2856 synchronized (sLock) { 2857 if (isHalStarted()) { 2858 sPnoCmdId = getNewCmdIdLocked(); 2859 sPnoEventHandler = eventHandler; 2860 if (setPnoListNative(sWlan0Index, sPnoCmdId, settings)) { 2861 return true; 2862 } 2863 } 2864 sPnoEventHandler = null; 2865 return false; 2866 } 2867 } 2868 2869 /** 2870 * Set the PNO network list in HAL to start PNO. 2871 * @param list PNO network list. 2872 * @param eventHandler Handler to receive notifications back during PNO scan. 2873 * @return true if success, false otherwise 2874 */ 2875 public boolean setPnoList(PnoNetwork[] list, PnoEventHandler eventHandler) { 2876 PnoSettings settings = new PnoSettings(); 2877 settings.networkList = list; 2878 return setPnoList(settings, eventHandler); 2879 } 2880 2881 private static native boolean resetPnoListNative(int iface, int id); 2882 2883 /** 2884 * Reset the PNO settings in HAL to stop PNO. 2885 * @return true if success, false otherwise 2886 */ 2887 public boolean resetPnoList() { 2888 Log.e(TAG, "resetPnoList cmd " + sPnoCmdId); 2889 2890 synchronized (sLock) { 2891 if (isHalStarted()) { 2892 sPnoCmdId = getNewCmdIdLocked(); 2893 sPnoEventHandler = null; 2894 if (resetPnoListNative(sWlan0Index, sPnoCmdId)) { 2895 return true; 2896 } 2897 } 2898 return false; 2899 } 2900 } 2901 2902 // Callback from native 2903 private static void onPnoNetworkFound(int id, ScanResult[] results, int[] beaconCaps) { 2904 if (results == null) { 2905 Log.e(TAG, "onPnoNetworkFound null results"); 2906 return; 2907 2908 } 2909 Log.d(TAG, "WifiNative.onPnoNetworkFound result " + results.length); 2910 2911 PnoEventHandler handler = sPnoEventHandler; 2912 if (sPnoCmdId != 0 && handler != null) { 2913 for (int i=0; i<results.length; i++) { 2914 Log.e(TAG, "onPnoNetworkFound SSID " + results[i].SSID 2915 + " " + results[i].level + " " + results[i].frequency); 2916 2917 populateScanResult(results[i], beaconCaps[i], "onPnoNetworkFound "); 2918 results[i].wifiSsid = WifiSsid.createFromAsciiEncoded(results[i].SSID); 2919 } 2920 2921 handler.onPnoNetworkFound(results); 2922 } else { 2923 /* this can happen because of race conditions */ 2924 Log.d(TAG, "Ignoring Pno Network found event"); 2925 } 2926 } 2927 2928 private native static boolean setBssidBlacklistNative(int iface, int id, 2929 String list[]); 2930 2931 public boolean setBssidBlacklist(String list[]) { 2932 int size = 0; 2933 if (list != null) { 2934 size = list.length; 2935 } 2936 Log.e(TAG, "setBssidBlacklist cmd " + sPnoCmdId + " size " + size); 2937 2938 synchronized (sLock) { 2939 if (isHalStarted()) { 2940 sPnoCmdId = getNewCmdIdLocked(); 2941 return setBssidBlacklistNative(sWlan0Index, sPnoCmdId, list); 2942 } else { 2943 return false; 2944 } 2945 } 2946 } 2947 2948 private native static int startSendingOffloadedPacketNative(int iface, int idx, 2949 byte[] srcMac, byte[] dstMac, byte[] pktData, int period); 2950 2951 public int 2952 startSendingOffloadedPacket(int slot, KeepalivePacketData keepAlivePacket, int period) { 2953 Log.d(TAG, "startSendingOffloadedPacket slot=" + slot + " period=" + period); 2954 2955 String[] macAddrStr = getMacAddress().split(":"); 2956 byte[] srcMac = new byte[6]; 2957 for(int i = 0; i < 6; i++) { 2958 Integer hexVal = Integer.parseInt(macAddrStr[i], 16); 2959 srcMac[i] = hexVal.byteValue(); 2960 } 2961 synchronized (sLock) { 2962 if (isHalStarted()) { 2963 return startSendingOffloadedPacketNative(sWlan0Index, slot, srcMac, 2964 keepAlivePacket.dstMac, keepAlivePacket.data, period); 2965 } else { 2966 return -1; 2967 } 2968 } 2969 } 2970 2971 private native static int stopSendingOffloadedPacketNative(int iface, int idx); 2972 2973 public int 2974 stopSendingOffloadedPacket(int slot) { 2975 Log.d(TAG, "stopSendingOffloadedPacket " + slot); 2976 synchronized (sLock) { 2977 if (isHalStarted()) { 2978 return stopSendingOffloadedPacketNative(sWlan0Index, slot); 2979 } else { 2980 return -1; 2981 } 2982 } 2983 } 2984 2985 public static interface WifiRssiEventHandler { 2986 void onRssiThresholdBreached(byte curRssi); 2987 } 2988 2989 private static WifiRssiEventHandler sWifiRssiEventHandler; 2990 2991 // Callback from native 2992 private static void onRssiThresholdBreached(int id, byte curRssi) { 2993 WifiRssiEventHandler handler = sWifiRssiEventHandler; 2994 if (handler != null) { 2995 handler.onRssiThresholdBreached(curRssi); 2996 } 2997 } 2998 2999 private native static int startRssiMonitoringNative(int iface, int id, 3000 byte maxRssi, byte minRssi); 3001 3002 private static int sRssiMonitorCmdId = 0; 3003 3004 public int startRssiMonitoring(byte maxRssi, byte minRssi, 3005 WifiRssiEventHandler rssiEventHandler) { 3006 Log.d(TAG, "startRssiMonitoring: maxRssi=" + maxRssi + " minRssi=" + minRssi); 3007 synchronized (sLock) { 3008 sWifiRssiEventHandler = rssiEventHandler; 3009 if (isHalStarted()) { 3010 if (sRssiMonitorCmdId != 0) { 3011 stopRssiMonitoring(); 3012 } 3013 3014 sRssiMonitorCmdId = getNewCmdIdLocked(); 3015 Log.d(TAG, "sRssiMonitorCmdId = " + sRssiMonitorCmdId); 3016 int ret = startRssiMonitoringNative(sWlan0Index, sRssiMonitorCmdId, 3017 maxRssi, minRssi); 3018 if (ret != 0) { // if not success 3019 sRssiMonitorCmdId = 0; 3020 } 3021 return ret; 3022 } else { 3023 return -1; 3024 } 3025 } 3026 } 3027 3028 private native static int stopRssiMonitoringNative(int iface, int idx); 3029 3030 public int stopRssiMonitoring() { 3031 Log.d(TAG, "stopRssiMonitoring, cmdId " + sRssiMonitorCmdId); 3032 synchronized (sLock) { 3033 if (isHalStarted()) { 3034 int ret = 0; 3035 if (sRssiMonitorCmdId != 0) { 3036 ret = stopRssiMonitoringNative(sWlan0Index, sRssiMonitorCmdId); 3037 } 3038 sRssiMonitorCmdId = 0; 3039 return ret; 3040 } else { 3041 return -1; 3042 } 3043 } 3044 } 3045 3046 private static native WifiWakeReasonAndCounts getWlanWakeReasonCountNative(int iface); 3047 3048 /** 3049 * Fetch the host wakeup reasons stats from wlan driver. 3050 * @return the |WifiWakeReasonAndCounts| object retrieved from the wlan driver. 3051 */ 3052 public WifiWakeReasonAndCounts getWlanWakeReasonCount() { 3053 Log.d(TAG, "getWlanWakeReasonCount " + sWlan0Index); 3054 synchronized (sLock) { 3055 if (isHalStarted()) { 3056 return getWlanWakeReasonCountNative(sWlan0Index); 3057 } else { 3058 return null; 3059 } 3060 } 3061 } 3062 3063 private static native int configureNeighborDiscoveryOffload(int iface, boolean enabled); 3064 3065 public boolean configureNeighborDiscoveryOffload(boolean enabled) { 3066 final String logMsg = "configureNeighborDiscoveryOffload(" + enabled + ")"; 3067 Log.d(mTAG, logMsg); 3068 synchronized (sLock) { 3069 if (isHalStarted()) { 3070 final int ret = configureNeighborDiscoveryOffload(sWlan0Index, enabled); 3071 if (ret != 0) { 3072 Log.d(mTAG, logMsg + " returned: " + ret); 3073 } 3074 return (ret == 0); 3075 } 3076 } 3077 return false; 3078 } 3079} 3080