WifiNative.java revision ebfe1fbec6d52e10b9dbe532b969782edb7e21f2
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.text.SimpleDateFormat;
72import java.util.ArrayList;
73import java.util.BitSet;
74import java.util.Date;
75import java.util.HashMap;
76import java.util.Iterator;
77import java.util.List;
78import java.util.Locale;
79import java.util.Map;
80import java.util.Set;
81import java.util.TimeZone;
82
83
84/**
85 * Native calls for bring up/shut down of the supplicant daemon and for
86 * sending requests to the supplicant daemon
87 *
88 * waitForEvent() is called on the monitor thread for events. All other methods
89 * must be serialized from the framework.
90 *
91 * {@hide}
92 */
93public class WifiNative {
94    private static boolean DBG = false;
95
96    // Must match wifi_hal.h
97    public static final int WIFI_SUCCESS = 0;
98
99    /**
100     * Hold this lock before calling supplicant or HAL methods
101     * it is required to mutually exclude access to the driver
102     */
103    public static final Object sLock = new Object();
104
105    private static final LocalLog sLocalLog = new LocalLog(8192);
106
107    public static LocalLog getLocalLog() {
108        return sLocalLog;
109    }
110
111    /* Register native functions */
112    static {
113        /* Native functions are defined in libwifi-service.so */
114        System.loadLibrary("wifi-service");
115        registerNatives();
116    }
117
118    private static native int registerNatives();
119
120    /*
121     * Singleton WifiNative instances
122     */
123    private static WifiNative wlanNativeInterface =
124            new WifiNative(SystemProperties.get("wifi.interface", "wlan0"), true);
125    public static WifiNative getWlanNativeInterface() {
126        return wlanNativeInterface;
127    }
128
129    private static WifiNative p2pNativeInterface =
130            // commands for p2p0 interface don't need prefix
131            new WifiNative(SystemProperties.get("wifi.direct.interface", "p2p0"), false);
132    public static WifiNative getP2pNativeInterface() {
133        return p2pNativeInterface;
134    }
135
136
137    private final String mTAG;
138    private final String mInterfaceName;
139    private final String mInterfacePrefix;
140
141    private Context mContext = null;
142    public void initContext(Context context) {
143        if (mContext == null && context != null) {
144            mContext = context;
145        }
146    }
147
148    private WifiNative(String interfaceName,
149                       boolean requiresPrefix) {
150        mInterfaceName = interfaceName;
151        mTAG = "WifiNative-" + interfaceName;
152
153        if (requiresPrefix) {
154            mInterfacePrefix = "IFNAME=" + interfaceName + " ";
155        } else {
156            mInterfacePrefix = "";
157        }
158    }
159
160    public String getInterfaceName() {
161        return mInterfaceName;
162    }
163
164    // Note this affects logging on for all interfaces
165    void enableVerboseLogging(int verbose) {
166        if (verbose > 0) {
167            DBG = true;
168        } else {
169            DBG = false;
170        }
171    }
172
173    private void localLog(String s) {
174        if (sLocalLog != null) sLocalLog.log(mInterfaceName + ": " + s);
175    }
176
177
178
179    /*
180     * Driver and Supplicant management
181     */
182    private native static boolean loadDriverNative();
183    public boolean loadDriver() {
184        synchronized (sLock) {
185            return loadDriverNative();
186        }
187    }
188
189    private native static boolean isDriverLoadedNative();
190    public boolean isDriverLoaded() {
191        synchronized (sLock) {
192            return isDriverLoadedNative();
193        }
194    }
195
196    private native static boolean unloadDriverNative();
197    public boolean unloadDriver() {
198        synchronized (sLock) {
199            return unloadDriverNative();
200        }
201    }
202
203    private native static boolean startSupplicantNative(boolean p2pSupported);
204    public boolean startSupplicant(boolean p2pSupported) {
205        synchronized (sLock) {
206            return startSupplicantNative(p2pSupported);
207        }
208    }
209
210    /* Sends a kill signal to supplicant. To be used when we have lost connection
211       or when the supplicant is hung */
212    private native static boolean killSupplicantNative(boolean p2pSupported);
213    public boolean killSupplicant(boolean p2pSupported) {
214        synchronized (sLock) {
215            return killSupplicantNative(p2pSupported);
216        }
217    }
218
219    private native static boolean connectToSupplicantNative();
220    public boolean connectToSupplicant() {
221        synchronized (sLock) {
222            localLog(mInterfacePrefix + "connectToSupplicant");
223            return connectToSupplicantNative();
224        }
225    }
226
227    private native static void closeSupplicantConnectionNative();
228    public void closeSupplicantConnection() {
229        synchronized (sLock) {
230            localLog(mInterfacePrefix + "closeSupplicantConnection");
231            closeSupplicantConnectionNative();
232        }
233    }
234
235    /**
236     * Wait for the supplicant to send an event, returning the event string.
237     * @return the event string sent by the supplicant.
238     */
239    private native static String waitForEventNative();
240    public String waitForEvent() {
241        // No synchronization necessary .. it is implemented in WifiMonitor
242        return waitForEventNative();
243    }
244
245
246    /*
247     * Supplicant Command Primitives
248     */
249    private native boolean doBooleanCommandNative(String command);
250
251    private native int doIntCommandNative(String command);
252
253    private native String doStringCommandNative(String command);
254
255    private boolean doBooleanCommand(String command) {
256        if (DBG) Log.d(mTAG, "doBoolean: " + command);
257        synchronized (sLock) {
258            String toLog = mInterfacePrefix + command;
259            boolean result = doBooleanCommandNative(mInterfacePrefix + command);
260            localLog(toLog + " -> " + result);
261            if (DBG) Log.d(mTAG, command + ": returned " + result);
262            return result;
263        }
264    }
265
266    private boolean doBooleanCommandWithoutLogging(String command) {
267        if (DBG) Log.d(mTAG, "doBooleanCommandWithoutLogging: " + command);
268        synchronized (sLock) {
269            boolean result = doBooleanCommandNative(mInterfacePrefix + command);
270            if (DBG) Log.d(mTAG, command + ": returned " + result);
271            return result;
272        }
273    }
274
275    private int doIntCommand(String command) {
276        if (DBG) Log.d(mTAG, "doInt: " + command);
277        synchronized (sLock) {
278            String toLog = mInterfacePrefix + command;
279            int result = doIntCommandNative(mInterfacePrefix + command);
280            localLog(toLog + " -> " + result);
281            if (DBG) Log.d(mTAG, "   returned " + result);
282            return result;
283        }
284    }
285
286    private String doStringCommand(String command) {
287        if (DBG) {
288            //GET_NETWORK commands flood the logs
289            if (!command.startsWith("GET_NETWORK")) {
290                Log.d(mTAG, "doString: [" + command + "]");
291            }
292        }
293        synchronized (sLock) {
294            String toLog = mInterfacePrefix + command;
295            String result = doStringCommandNative(mInterfacePrefix + command);
296            if (result == null) {
297                if (DBG) Log.d(mTAG, "doStringCommandNative no result");
298            } else {
299                if (!command.startsWith("STATUS-")) {
300                    localLog(toLog + " -> " + result);
301                }
302                if (DBG) Log.d(mTAG, "   returned " + result.replace("\n", " "));
303            }
304            return result;
305        }
306    }
307
308    private String doStringCommandWithoutLogging(String command) {
309        if (DBG) {
310            //GET_NETWORK commands flood the logs
311            if (!command.startsWith("GET_NETWORK")) {
312                Log.d(mTAG, "doString: [" + command + "]");
313            }
314        }
315        synchronized (sLock) {
316            return doStringCommandNative(mInterfacePrefix + command);
317        }
318    }
319
320    public String doCustomSupplicantCommand(String command) {
321        return doStringCommand(command);
322    }
323
324    /*
325     * Wrappers for supplicant commands
326     */
327    public boolean ping() {
328        String pong = doStringCommand("PING");
329        return (pong != null && pong.equals("PONG"));
330    }
331
332    public void setSupplicantLogLevel(String level) {
333        doStringCommand("LOG_LEVEL " + level);
334    }
335
336    public String getFreqCapability() {
337        return doStringCommand("GET_CAPABILITY freq");
338    }
339
340    /**
341     * Create a comma separate string from integer set.
342     * @param values List of integers.
343     * @return comma separated string.
344     */
345    private static String createCSVStringFromIntegerSet(Set<Integer> values) {
346        StringBuilder list = new StringBuilder();
347        boolean first = true;
348        for (Integer value : values) {
349            if (!first) {
350                list.append(",");
351            }
352            list.append(value);
353            first = false;
354        }
355        return list.toString();
356    }
357
358    /**
359     * Start a scan using wpa_supplicant for the given frequencies.
360     * @param freqs list of frequencies to scan for, if null scan all supported channels.
361     * @param hiddenNetworkIds List of hidden networks to be scanned for.
362     */
363    public boolean scan(Set<Integer> freqs, Set<Integer> hiddenNetworkIds) {
364        String freqList = null;
365        String hiddenNetworkIdList = null;
366        if (freqs != null && freqs.size() != 0) {
367            freqList = createCSVStringFromIntegerSet(freqs);
368        }
369        if (hiddenNetworkIds != null && hiddenNetworkIds.size() != 0) {
370            hiddenNetworkIdList = createCSVStringFromIntegerSet(hiddenNetworkIds);
371        }
372        return scanWithParams(freqList, hiddenNetworkIdList);
373    }
374
375    private boolean scanWithParams(String freqList, String hiddenNetworkIdList) {
376        StringBuilder scanCommand = new StringBuilder();
377        scanCommand.append("SCAN TYPE=ONLY");
378        if (freqList != null) {
379            scanCommand.append(" freq=" + freqList);
380        }
381        if (hiddenNetworkIdList != null) {
382            scanCommand.append(" scan_id=" + hiddenNetworkIdList);
383        }
384        return doBooleanCommand(scanCommand.toString());
385    }
386
387    /* Does a graceful shutdown of supplicant. Is a common stop function for both p2p and sta.
388     *
389     * Note that underneath we use a harsh-sounding "terminate" supplicant command
390     * for a graceful stop and a mild-sounding "stop" interface
391     * to kill the process
392     */
393    public boolean stopSupplicant() {
394        return doBooleanCommand("TERMINATE");
395    }
396
397    public String listNetworks() {
398        return doStringCommand("LIST_NETWORKS");
399    }
400
401    public String listNetworks(int last_id) {
402        return doStringCommand("LIST_NETWORKS LAST_ID=" + last_id);
403    }
404
405    public int addNetwork() {
406        return doIntCommand("ADD_NETWORK");
407    }
408
409    public boolean setNetworkExtra(int netId, String name, Map<String, String> values) {
410        final String encoded;
411        try {
412            encoded = URLEncoder.encode(new JSONObject(values).toString(), "UTF-8");
413        } catch (NullPointerException e) {
414            Log.e(TAG, "Unable to serialize networkExtra: " + e.toString());
415            return false;
416        } catch (UnsupportedEncodingException e) {
417            Log.e(TAG, "Unable to serialize networkExtra: " + e.toString());
418            return false;
419        }
420        return setNetworkVariable(netId, name, "\"" + encoded + "\"");
421    }
422
423    public boolean setNetworkVariable(int netId, String name, String value) {
424        if (TextUtils.isEmpty(name) || TextUtils.isEmpty(value)) return false;
425        if (name.equals(WifiConfiguration.pskVarName)
426                || name.equals(WifiEnterpriseConfig.PASSWORD_KEY)
427                || name.equals(WifiEnterpriseConfig.IDENTITY_KEY)
428                || name.equals(WifiEnterpriseConfig.ANON_IDENTITY_KEY)) {
429            return doBooleanCommandWithoutLogging("SET_NETWORK " + netId + " " + name + " " + value);
430        } else {
431            return doBooleanCommand("SET_NETWORK " + netId + " " + name + " " + value);
432        }
433    }
434
435    public Map<String, String> getNetworkExtra(int netId, String name) {
436        final String wrapped = getNetworkVariable(netId, name);
437        if (wrapped == null || !wrapped.startsWith("\"") || !wrapped.endsWith("\"")) {
438            return null;
439        }
440        try {
441            final String encoded = wrapped.substring(1, wrapped.length() - 1);
442            // This method reads a JSON dictionary that was written by setNetworkExtra(). However,
443            // on devices that upgraded from Marshmallow, it may encounter a legacy value instead -
444            // an FQDN stored as a plain string. If such a value is encountered, the JSONObject
445            // constructor will thrown a JSONException and the method will return null.
446            final JSONObject json = new JSONObject(URLDecoder.decode(encoded, "UTF-8"));
447            final Map<String, String> values = new HashMap<String, String>();
448            final Iterator<?> it = json.keys();
449            while (it.hasNext()) {
450                final String key = (String) it.next();
451                final Object value = json.get(key);
452                if (value instanceof String) {
453                    values.put(key, (String) value);
454                }
455            }
456            return values;
457        } catch (UnsupportedEncodingException e) {
458            Log.e(TAG, "Unable to deserialize networkExtra: " + e.toString());
459            return null;
460        } catch (JSONException e) {
461            // This is not necessarily an error. This exception will also occur if we encounter a
462            // legacy FQDN stored as a plain string. We want to return null in this case as no JSON
463            // dictionary of extras was found.
464            return null;
465        }
466    }
467
468    public String getNetworkVariable(int netId, String name) {
469        if (TextUtils.isEmpty(name)) return null;
470
471        // GET_NETWORK will likely flood the logs ...
472        return doStringCommandWithoutLogging("GET_NETWORK " + netId + " " + name);
473    }
474
475    public boolean removeNetwork(int netId) {
476        return doBooleanCommand("REMOVE_NETWORK " + netId);
477    }
478
479
480    private void logDbg(String debug) {
481        long now = SystemClock.elapsedRealtimeNanos();
482        String ts = String.format("[%,d us] ", now/1000);
483        Log.e("WifiNative: ", ts+debug+ " stack:"
484                + Thread.currentThread().getStackTrace()[2].getMethodName() +" - "
485                + Thread.currentThread().getStackTrace()[3].getMethodName() +" - "
486                + Thread.currentThread().getStackTrace()[4].getMethodName() +" - "
487                + Thread.currentThread().getStackTrace()[5].getMethodName()+" - "
488                + Thread.currentThread().getStackTrace()[6].getMethodName());
489
490    }
491
492    /**
493     * Enables a network in wpa_supplicant.
494     * @param netId - Network ID of the network to be enabled.
495     * @return true if command succeeded, false otherwise.
496     */
497    public boolean enableNetwork(int netId) {
498        if (DBG) logDbg("enableNetwork nid=" + Integer.toString(netId));
499        return doBooleanCommand("ENABLE_NETWORK " + netId);
500    }
501
502    /**
503     * Enable a network in wpa_supplicant, do not connect.
504     * @param netId - Network ID of the network to be enabled.
505     * @return true if command succeeded, false otherwise.
506     */
507    public boolean enableNetworkWithoutConnect(int netId) {
508        if (DBG) logDbg("enableNetworkWithoutConnect nid=" + Integer.toString(netId));
509        return doBooleanCommand("ENABLE_NETWORK " + netId + " " + "no-connect");
510    }
511
512    /**
513     * Disables a network in wpa_supplicant.
514     * @param netId - Network ID of the network to be disabled.
515     * @return true if command succeeded, false otherwise.
516     */
517    public boolean disableNetwork(int netId) {
518        if (DBG) logDbg("disableNetwork nid=" + Integer.toString(netId));
519        return doBooleanCommand("DISABLE_NETWORK " + netId);
520    }
521
522    /**
523     * Select a network in wpa_supplicant (Disables all others).
524     * @param netId - Network ID of the network to be selected.
525     * @return true if command succeeded, false otherwise.
526     */
527    public boolean selectNetwork(int netId) {
528        if (DBG) logDbg("selectNetwork nid=" + Integer.toString(netId));
529        return doBooleanCommand("SELECT_NETWORK " + netId);
530    }
531
532    public boolean reconnect() {
533        if (DBG) logDbg("RECONNECT ");
534        return doBooleanCommand("RECONNECT");
535    }
536
537    public boolean reassociate() {
538        if (DBG) logDbg("REASSOCIATE ");
539        return doBooleanCommand("REASSOCIATE");
540    }
541
542    public boolean disconnect() {
543        if (DBG) logDbg("DISCONNECT ");
544        return doBooleanCommand("DISCONNECT");
545    }
546
547    public String status() {
548        return status(false);
549    }
550
551    public String status(boolean noEvents) {
552        if (noEvents) {
553            return doStringCommand("STATUS-NO_EVENTS");
554        } else {
555            return doStringCommand("STATUS");
556        }
557    }
558
559    public String getMacAddress() {
560        //Macaddr = XX.XX.XX.XX.XX.XX
561        String ret = doStringCommand("DRIVER MACADDR");
562        if (!TextUtils.isEmpty(ret)) {
563            String[] tokens = ret.split(" = ");
564            if (tokens.length == 2) return tokens[1];
565        }
566        return null;
567    }
568
569
570
571    /**
572     * Format of results:
573     * =================
574     * id=1
575     * bssid=68:7f:76:d7:1a:6e
576     * freq=2412
577     * level=-44
578     * tsf=1344626243700342
579     * flags=[WPA2-PSK-CCMP][WPS][ESS]
580     * ssid=zfdy
581     * ====
582     * id=2
583     * bssid=68:5f:74:d7:1a:6f
584     * freq=5180
585     * level=-73
586     * tsf=1344626243700373
587     * flags=[WPA2-PSK-CCMP][WPS][ESS]
588     * ssid=zuby
589     * ====
590     *
591     * RANGE=ALL gets all scan results
592     * RANGE=ID- gets results from ID
593     * MASK=<N> BSS command information mask.
594     *
595     * The mask used in this method, 0x29d87, gets the following fields:
596     *
597     *     WPA_BSS_MASK_ID         (Bit 0)
598     *     WPA_BSS_MASK_BSSID      (Bit 1)
599     *     WPA_BSS_MASK_FREQ       (Bit 2)
600     *     WPA_BSS_MASK_LEVEL      (Bit 7)
601     *     WPA_BSS_MASK_TSF        (Bit 8)
602     *     WPA_BSS_MASK_IE         (Bit 10)
603     *     WPA_BSS_MASK_FLAGS      (Bit 11)
604     *     WPA_BSS_MASK_SSID       (Bit 12)
605     *     WPA_BSS_MASK_INTERNETW  (Bit 15) (adds ANQP info)
606     *     WPA_BSS_MASK_DELIM      (Bit 17)
607     *
608     * See wpa_supplicant/src/common/wpa_ctrl.h for details.
609     */
610    private String getRawScanResults(String range) {
611        return doStringCommandWithoutLogging("BSS RANGE=" + range + " MASK=0x29d87");
612    }
613
614    private static final String BSS_IE_STR = "ie=";
615    private static final String BSS_ID_STR = "id=";
616    private static final String BSS_BSSID_STR = "bssid=";
617    private static final String BSS_FREQ_STR = "freq=";
618    private static final String BSS_LEVEL_STR = "level=";
619    private static final String BSS_TSF_STR = "tsf=";
620    private static final String BSS_FLAGS_STR = "flags=";
621    private static final String BSS_SSID_STR = "ssid=";
622    private static final String BSS_DELIMITER_STR = "====";
623    private static final String BSS_END_STR = "####";
624
625    public ArrayList<ScanDetail> getScanResults() {
626        int next_sid = 0;
627        ArrayList<ScanDetail> results = new ArrayList<>();
628        while(next_sid >= 0) {
629            String rawResult = getRawScanResults(next_sid+"-");
630            next_sid = -1;
631
632            if (TextUtils.isEmpty(rawResult))
633                break;
634
635            String[] lines = rawResult.split("\n");
636
637
638            // note that all these splits and substrings keep references to the original
639            // huge string buffer while the amount we really want is generally pretty small
640            // so make copies instead (one example b/11087956 wasted 400k of heap here).
641            final int bssidStrLen = BSS_BSSID_STR.length();
642            final int flagLen = BSS_FLAGS_STR.length();
643
644            String bssid = "";
645            int level = 0;
646            int freq = 0;
647            long tsf = 0;
648            String flags = "";
649            WifiSsid wifiSsid = null;
650            String infoElementsStr = null;
651            List<String> anqpLines = null;
652
653            for (String line : lines) {
654                if (line.startsWith(BSS_ID_STR)) { // Will find the last id line
655                    try {
656                        next_sid = Integer.parseInt(line.substring(BSS_ID_STR.length())) + 1;
657                    } catch (NumberFormatException e) {
658                        // Nothing to do
659                    }
660                } else if (line.startsWith(BSS_BSSID_STR)) {
661                    bssid = new String(line.getBytes(), bssidStrLen, line.length() - bssidStrLen);
662                } else if (line.startsWith(BSS_FREQ_STR)) {
663                    try {
664                        freq = Integer.parseInt(line.substring(BSS_FREQ_STR.length()));
665                    } catch (NumberFormatException e) {
666                        freq = 0;
667                    }
668                } else if (line.startsWith(BSS_LEVEL_STR)) {
669                    try {
670                        level = Integer.parseInt(line.substring(BSS_LEVEL_STR.length()));
671                        /* some implementations avoid negative values by adding 256
672                         * so we need to adjust for that here.
673                         */
674                        if (level > 0) level -= 256;
675                    } catch (NumberFormatException e) {
676                        level = 0;
677                    }
678                } else if (line.startsWith(BSS_TSF_STR)) {
679                    try {
680                        tsf = Long.parseLong(line.substring(BSS_TSF_STR.length()));
681                    } catch (NumberFormatException e) {
682                        tsf = 0;
683                    }
684                } else if (line.startsWith(BSS_FLAGS_STR)) {
685                    flags = new String(line.getBytes(), flagLen, line.length() - flagLen);
686                } else if (line.startsWith(BSS_SSID_STR)) {
687                    wifiSsid = WifiSsid.createFromAsciiEncoded(
688                            line.substring(BSS_SSID_STR.length()));
689                } else if (line.startsWith(BSS_IE_STR)) {
690                    infoElementsStr = line;
691                } else if (SupplicantBridge.isAnqpAttribute(line)) {
692                    if (anqpLines == null) {
693                        anqpLines = new ArrayList<>();
694                    }
695                    anqpLines.add(line);
696                } else if (line.startsWith(BSS_DELIMITER_STR) || line.startsWith(BSS_END_STR)) {
697                    if (bssid != null) {
698                        try {
699                            if (infoElementsStr == null) {
700                                throw new IllegalArgumentException("Null information element data");
701                            }
702                            int seperator = infoElementsStr.indexOf('=');
703                            if (seperator < 0) {
704                                throw new IllegalArgumentException("No element separator");
705                            }
706
707                            ScanResult.InformationElement[] infoElements =
708                                        InformationElementUtil.parseInformationElements(
709                                        Utils.hexToBytes(infoElementsStr.substring(seperator + 1)));
710
711                            NetworkDetail networkDetail = new NetworkDetail(bssid,
712                                    infoElements, anqpLines, freq);
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 static int USEC_PER_MSEC = 1000;
2631        // The driver timestamp is a 32-bit counter, in microseconds. This field holds the
2632        // maximal value of a driver timestamp in milliseconds.
2633        final static int MAX_DRIVER_TIMESTAMP_MSEC = (int) (0xffffffffL / 1000);
2634        final static SimpleDateFormat dateFormatter = new SimpleDateFormat("HH:mm:ss.SSS");
2635
2636        final byte mFate;
2637        final long mDriverTimestampUSec;
2638        final byte mFrameType;
2639        final byte[] mFrameBytes;
2640        final long mEstimatedWallclockMSec;
2641
2642        FateReport(byte fate, long driverTimestampUSec, byte frameType, byte[] frameBytes) {
2643            mFate = fate;
2644            mDriverTimestampUSec = driverTimestampUSec;
2645            mEstimatedWallclockMSec =
2646                    convertDriverTimestampUSecToWallclockMSec(mDriverTimestampUSec);
2647            mFrameType = frameType;
2648            mFrameBytes = frameBytes;
2649        }
2650
2651        public String toTableRowString() {
2652            StringWriter sw = new StringWriter();
2653            PrintWriter pw = new PrintWriter(sw);
2654            FrameParser parser = new FrameParser(mFrameType, mFrameBytes);
2655            dateFormatter.setTimeZone(TimeZone.getDefault());
2656            pw.format("%-15s  %12s  %-9s  %-32s  %-12s  %-23s  %s\n",
2657                    mDriverTimestampUSec,
2658                    dateFormatter.format(new Date(mEstimatedWallclockMSec)),
2659                    directionToString(), fateToString(), parser.mMostSpecificProtocolString,
2660                    parser.mTypeString, parser.mResultString);
2661            return sw.toString();
2662        }
2663
2664        public String toVerboseStringWithPiiAllowed() {
2665            StringWriter sw = new StringWriter();
2666            PrintWriter pw = new PrintWriter(sw);
2667            FrameParser parser = new FrameParser(mFrameType, mFrameBytes);
2668            pw.format("Frame direction: %s\n", directionToString());
2669            pw.format("Frame timestamp: %d\n", mDriverTimestampUSec);
2670            pw.format("Frame fate: %s\n", fateToString());
2671            pw.format("Frame type: %s\n", frameTypeToString(mFrameType));
2672            pw.format("Frame protocol: %s\n", parser.mMostSpecificProtocolString);
2673            pw.format("Frame protocol type: %s\n", parser.mTypeString);
2674            pw.format("Frame length: %d\n", mFrameBytes.length);
2675            pw.append("Frame bytes");
2676            pw.append(HexDump.dumpHexString(mFrameBytes));  // potentially contains PII
2677            pw.append("\n");
2678            return sw.toString();
2679        }
2680
2681        /* Returns a header to match the output of toTableRowString(). */
2682        public static String getTableHeader() {
2683            StringWriter sw = new StringWriter();
2684            PrintWriter pw = new PrintWriter(sw);
2685            pw.format("\n%-15s  %-12s  %-9s  %-32s  %-12s  %-23s  %s\n",
2686                    "Time usec", "Walltime", "Direction", "Fate", "Protocol", "Type", "Result");
2687            pw.format("%-15s  %-12s  %-9s  %-32s  %-12s  %-23s  %s\n",
2688                    "---------", "--------", "---------", "----", "--------", "----", "------");
2689            return sw.toString();
2690        }
2691
2692        protected abstract String directionToString();
2693
2694        protected abstract String fateToString();
2695
2696        private static String frameTypeToString(byte frameType) {
2697            switch (frameType) {
2698                case WifiLoggerHal.FRAME_TYPE_UNKNOWN:
2699                    return "unknown";
2700                case WifiLoggerHal.FRAME_TYPE_ETHERNET_II:
2701                    return "data";
2702                case WifiLoggerHal.FRAME_TYPE_80211_MGMT:
2703                    return "802.11 management";
2704                default:
2705                    return Byte.toString(frameType);
2706            }
2707        }
2708
2709        /**
2710         * Converts a driver timestamp to a wallclock time, based on the current
2711         * BOOTTIME to wallclock mapping. The driver timestamp is a 32-bit counter of
2712         * microseconds, with the same base as BOOTTIME.
2713         */
2714        private static long convertDriverTimestampUSecToWallclockMSec(long driverTimestampUSec) {
2715            final long wallclockMillisNow = System.currentTimeMillis();
2716            final long boottimeMillisNow = SystemClock.elapsedRealtime();
2717            final long driverTimestampMillis = driverTimestampUSec / USEC_PER_MSEC;
2718
2719            long boottimeTimestampMillis = boottimeMillisNow % MAX_DRIVER_TIMESTAMP_MSEC;
2720            if (boottimeTimestampMillis < driverTimestampMillis) {
2721                // The 32-bit microsecond count has wrapped between the time that the driver
2722                // recorded the packet, and the call to this function. Adjust the BOOTTIME
2723                // timestamp, to compensate.
2724                //
2725                // Note that overflow is not a concern here, since the result is less than
2726                // 2 * MAX_DRIVER_TIMESTAMP_MSEC. (Given the modulus operation above,
2727                // boottimeTimestampMillis must be less than MAX_DRIVER_TIMESTAMP_MSEC.) And, since
2728                // MAX_DRIVER_TIMESTAMP_MSEC is an int, 2 * MAX_DRIVER_TIMESTAMP_MSEC must fit
2729                // within a long.
2730                boottimeTimestampMillis += MAX_DRIVER_TIMESTAMP_MSEC;
2731            }
2732
2733            final long millisSincePacketTimestamp = boottimeTimestampMillis - driverTimestampMillis;
2734            return wallclockMillisNow - millisSincePacketTimestamp;
2735        }
2736    }
2737
2738    /**
2739     * Represents the fate information for one outbound packet.
2740     */
2741    @Immutable
2742    public static final class TxFateReport extends FateReport {
2743        TxFateReport(byte fate, long driverTimestampUSec, byte frameType, byte[] frameBytes) {
2744            super(fate, driverTimestampUSec, frameType, frameBytes);
2745        }
2746
2747        @Override
2748        protected String directionToString() {
2749            return "TX";
2750        }
2751
2752        @Override
2753        protected String fateToString() {
2754            switch (mFate) {
2755                case WifiLoggerHal.TX_PKT_FATE_ACKED:
2756                    return "acked";
2757                case WifiLoggerHal.TX_PKT_FATE_SENT:
2758                    return "sent";
2759                case WifiLoggerHal.TX_PKT_FATE_FW_QUEUED:
2760                    return "firmware queued";
2761                case WifiLoggerHal.TX_PKT_FATE_FW_DROP_INVALID:
2762                    return "firmware dropped (invalid frame)";
2763                case WifiLoggerHal.TX_PKT_FATE_FW_DROP_NOBUFS:
2764                    return "firmware dropped (no bufs)";
2765                case WifiLoggerHal.TX_PKT_FATE_FW_DROP_OTHER:
2766                    return "firmware dropped (other)";
2767                case WifiLoggerHal.TX_PKT_FATE_DRV_QUEUED:
2768                    return "driver queued";
2769                case WifiLoggerHal.TX_PKT_FATE_DRV_DROP_INVALID:
2770                    return "driver dropped (invalid frame)";
2771                case WifiLoggerHal.TX_PKT_FATE_DRV_DROP_NOBUFS:
2772                    return "driver dropped (no bufs)";
2773                case WifiLoggerHal.TX_PKT_FATE_DRV_DROP_OTHER:
2774                    return "driver dropped (other)";
2775                default:
2776                    return Byte.toString(mFate);
2777            }
2778        }
2779    }
2780
2781    /**
2782     * Represents the fate information for one inbound packet.
2783     */
2784    @Immutable
2785    public static final class RxFateReport extends FateReport {
2786        RxFateReport(byte fate, long driverTimestampUSec, byte frameType, byte[] frameBytes) {
2787            super(fate, driverTimestampUSec, frameType, frameBytes);
2788        }
2789
2790        @Override
2791        protected String directionToString() {
2792            return "RX";
2793        }
2794
2795        @Override
2796        protected String fateToString() {
2797            switch (mFate) {
2798                case WifiLoggerHal.RX_PKT_FATE_SUCCESS:
2799                    return "success";
2800                case WifiLoggerHal.RX_PKT_FATE_FW_QUEUED:
2801                    return "firmware queued";
2802                case WifiLoggerHal.RX_PKT_FATE_FW_DROP_FILTER:
2803                    return "firmware dropped (filter)";
2804                case WifiLoggerHal.RX_PKT_FATE_FW_DROP_INVALID:
2805                    return "firmware dropped (invalid frame)";
2806                case WifiLoggerHal.RX_PKT_FATE_FW_DROP_NOBUFS:
2807                    return "firmware dropped (no bufs)";
2808                case WifiLoggerHal.RX_PKT_FATE_FW_DROP_OTHER:
2809                    return "firmware dropped (other)";
2810                case WifiLoggerHal.RX_PKT_FATE_DRV_QUEUED:
2811                    return "driver queued";
2812                case WifiLoggerHal.RX_PKT_FATE_DRV_DROP_FILTER:
2813                    return "driver dropped (filter)";
2814                case WifiLoggerHal.RX_PKT_FATE_DRV_DROP_INVALID:
2815                    return "driver dropped (invalid frame)";
2816                case WifiLoggerHal.RX_PKT_FATE_DRV_DROP_NOBUFS:
2817                    return "driver dropped (no bufs)";
2818                case WifiLoggerHal.RX_PKT_FATE_DRV_DROP_OTHER:
2819                    return "driver dropped (other)";
2820                default:
2821                    return Byte.toString(mFate);
2822            }
2823        }
2824    }
2825
2826    private static native int startPktFateMonitoringNative(int iface);
2827    /**
2828     * Ask the HAL to enable packet fate monitoring. Fails unless HAL is started.
2829     */
2830    public boolean startPktFateMonitoring() {
2831        synchronized (sLock) {
2832            if (isHalStarted()) {
2833                return startPktFateMonitoringNative(sWlan0Index) == WIFI_SUCCESS;
2834            } else {
2835                return false;
2836            }
2837        }
2838    }
2839
2840    private static native int getTxPktFatesNative(int iface, TxFateReport[] reportBufs);
2841    /**
2842     * Fetch the most recent TX packet fates from the HAL. Fails unless HAL is started.
2843     */
2844    public boolean getTxPktFates(TxFateReport[] reportBufs) {
2845        synchronized (sLock) {
2846            if (isHalStarted()) {
2847                int res = getTxPktFatesNative(sWlan0Index, reportBufs);
2848                if (res != WIFI_SUCCESS) {
2849                    Log.e(TAG, "getTxPktFatesNative returned " + res);
2850                    return false;
2851                } else {
2852                    return true;
2853                }
2854            } else {
2855                return false;
2856            }
2857        }
2858    }
2859
2860    private static native int getRxPktFatesNative(int iface, RxFateReport[] reportBufs);
2861    /**
2862     * Fetch the most recent RX packet fates from the HAL. Fails unless HAL is started.
2863     */
2864    public boolean getRxPktFates(RxFateReport[] reportBufs) {
2865        synchronized (sLock) {
2866            if (isHalStarted()) {
2867                int res = getRxPktFatesNative(sWlan0Index, reportBufs);
2868                if (res != WIFI_SUCCESS) {
2869                    Log.e(TAG, "getRxPktFatesNative returned " + res);
2870                    return false;
2871                } else {
2872                    return true;
2873                }
2874            } else {
2875                return false;
2876            }
2877        }
2878    }
2879
2880    //---------------------------------------------------------------------------------
2881    /* Configure ePNO/PNO */
2882    private static PnoEventHandler sPnoEventHandler;
2883    private static int sPnoCmdId = 0;
2884
2885    private static native boolean setPnoListNative(int iface, int id, PnoSettings settings);
2886
2887    /**
2888     * Set the PNO settings & the network list in HAL to start PNO.
2889     * @param settings PNO settings and network list.
2890     * @param eventHandler Handler to receive notifications back during PNO scan.
2891     * @return true if success, false otherwise
2892     */
2893    public boolean setPnoList(PnoSettings settings, PnoEventHandler eventHandler) {
2894        Log.e(TAG, "setPnoList cmd " + sPnoCmdId);
2895
2896        synchronized (sLock) {
2897            if (isHalStarted()) {
2898                sPnoCmdId = getNewCmdIdLocked();
2899                sPnoEventHandler = eventHandler;
2900                if (setPnoListNative(sWlan0Index, sPnoCmdId, settings)) {
2901                    return true;
2902                }
2903            }
2904            sPnoEventHandler = null;
2905            return false;
2906        }
2907    }
2908
2909    /**
2910     * Set the PNO network list in HAL to start PNO.
2911     * @param list PNO network list.
2912     * @param eventHandler Handler to receive notifications back during PNO scan.
2913     * @return true if success, false otherwise
2914     */
2915    public boolean setPnoList(PnoNetwork[] list, PnoEventHandler eventHandler) {
2916        PnoSettings settings = new PnoSettings();
2917        settings.networkList = list;
2918        return setPnoList(settings, eventHandler);
2919    }
2920
2921    private static native boolean resetPnoListNative(int iface, int id);
2922
2923    /**
2924     * Reset the PNO settings in HAL to stop PNO.
2925     * @return true if success, false otherwise
2926     */
2927    public boolean resetPnoList() {
2928        Log.e(TAG, "resetPnoList cmd " + sPnoCmdId);
2929
2930        synchronized (sLock) {
2931            if (isHalStarted()) {
2932                sPnoCmdId = getNewCmdIdLocked();
2933                sPnoEventHandler = null;
2934                if (resetPnoListNative(sWlan0Index, sPnoCmdId)) {
2935                    return true;
2936                }
2937            }
2938            return false;
2939        }
2940    }
2941
2942    // Callback from native
2943    private static void onPnoNetworkFound(int id, ScanResult[] results, int[] beaconCaps) {
2944        if (results == null) {
2945            Log.e(TAG, "onPnoNetworkFound null results");
2946            return;
2947
2948        }
2949        Log.d(TAG, "WifiNative.onPnoNetworkFound result " + results.length);
2950
2951        PnoEventHandler handler = sPnoEventHandler;
2952        if (sPnoCmdId != 0 && handler != null) {
2953            for (int i=0; i<results.length; i++) {
2954                Log.e(TAG, "onPnoNetworkFound SSID " + results[i].SSID
2955                        + " " + results[i].level + " " + results[i].frequency);
2956
2957                populateScanResult(results[i], beaconCaps[i], "onPnoNetworkFound ");
2958                results[i].wifiSsid = WifiSsid.createFromAsciiEncoded(results[i].SSID);
2959            }
2960
2961            handler.onPnoNetworkFound(results);
2962        } else {
2963            /* this can happen because of race conditions */
2964            Log.d(TAG, "Ignoring Pno Network found event");
2965        }
2966    }
2967
2968    private native static boolean setBssidBlacklistNative(int iface, int id,
2969                                              String list[]);
2970
2971    public boolean setBssidBlacklist(String list[]) {
2972        int size = 0;
2973        if (list != null) {
2974            size = list.length;
2975        }
2976        Log.e(TAG, "setBssidBlacklist cmd " + sPnoCmdId + " size " + size);
2977
2978        synchronized (sLock) {
2979            if (isHalStarted()) {
2980                sPnoCmdId = getNewCmdIdLocked();
2981                return setBssidBlacklistNative(sWlan0Index, sPnoCmdId, list);
2982            } else {
2983                return false;
2984            }
2985        }
2986    }
2987
2988    private native static int startSendingOffloadedPacketNative(int iface, int idx,
2989                                    byte[] srcMac, byte[] dstMac, byte[] pktData, int period);
2990
2991    public int
2992    startSendingOffloadedPacket(int slot, KeepalivePacketData keepAlivePacket, int period) {
2993        Log.d(TAG, "startSendingOffloadedPacket slot=" + slot + " period=" + period);
2994
2995        String[] macAddrStr = getMacAddress().split(":");
2996        byte[] srcMac = new byte[6];
2997        for(int i = 0; i < 6; i++) {
2998            Integer hexVal = Integer.parseInt(macAddrStr[i], 16);
2999            srcMac[i] = hexVal.byteValue();
3000        }
3001        synchronized (sLock) {
3002            if (isHalStarted()) {
3003                return startSendingOffloadedPacketNative(sWlan0Index, slot, srcMac,
3004                        keepAlivePacket.dstMac, keepAlivePacket.data, period);
3005            } else {
3006                return -1;
3007            }
3008        }
3009    }
3010
3011    private native static int stopSendingOffloadedPacketNative(int iface, int idx);
3012
3013    public int
3014    stopSendingOffloadedPacket(int slot) {
3015        Log.d(TAG, "stopSendingOffloadedPacket " + slot);
3016        synchronized (sLock) {
3017            if (isHalStarted()) {
3018                return stopSendingOffloadedPacketNative(sWlan0Index, slot);
3019            } else {
3020                return -1;
3021            }
3022        }
3023    }
3024
3025    public static interface WifiRssiEventHandler {
3026        void onRssiThresholdBreached(byte curRssi);
3027    }
3028
3029    private static WifiRssiEventHandler sWifiRssiEventHandler;
3030
3031    // Callback from native
3032    private static void onRssiThresholdBreached(int id, byte curRssi) {
3033        WifiRssiEventHandler handler = sWifiRssiEventHandler;
3034        if (handler != null) {
3035            handler.onRssiThresholdBreached(curRssi);
3036        }
3037    }
3038
3039    private native static int startRssiMonitoringNative(int iface, int id,
3040                                        byte maxRssi, byte minRssi);
3041
3042    private static int sRssiMonitorCmdId = 0;
3043
3044    public int startRssiMonitoring(byte maxRssi, byte minRssi,
3045                                                WifiRssiEventHandler rssiEventHandler) {
3046        Log.d(TAG, "startRssiMonitoring: maxRssi=" + maxRssi + " minRssi=" + minRssi);
3047        synchronized (sLock) {
3048            sWifiRssiEventHandler = rssiEventHandler;
3049            if (isHalStarted()) {
3050                if (sRssiMonitorCmdId != 0) {
3051                    stopRssiMonitoring();
3052                }
3053
3054                sRssiMonitorCmdId = getNewCmdIdLocked();
3055                Log.d(TAG, "sRssiMonitorCmdId = " + sRssiMonitorCmdId);
3056                int ret = startRssiMonitoringNative(sWlan0Index, sRssiMonitorCmdId,
3057                        maxRssi, minRssi);
3058                if (ret != 0) { // if not success
3059                    sRssiMonitorCmdId = 0;
3060                }
3061                return ret;
3062            } else {
3063                return -1;
3064            }
3065        }
3066    }
3067
3068    private native static int stopRssiMonitoringNative(int iface, int idx);
3069
3070    public int stopRssiMonitoring() {
3071        Log.d(TAG, "stopRssiMonitoring, cmdId " + sRssiMonitorCmdId);
3072        synchronized (sLock) {
3073            if (isHalStarted()) {
3074                int ret = 0;
3075                if (sRssiMonitorCmdId != 0) {
3076                    ret = stopRssiMonitoringNative(sWlan0Index, sRssiMonitorCmdId);
3077                }
3078                sRssiMonitorCmdId = 0;
3079                return ret;
3080            } else {
3081                return -1;
3082            }
3083        }
3084    }
3085
3086    private static native WifiWakeReasonAndCounts getWlanWakeReasonCountNative(int iface);
3087
3088    /**
3089     * Fetch the host wakeup reasons stats from wlan driver.
3090     * @return the |WifiWakeReasonAndCounts| object retrieved from the wlan driver.
3091     */
3092    public WifiWakeReasonAndCounts getWlanWakeReasonCount() {
3093        Log.d(TAG, "getWlanWakeReasonCount " + sWlan0Index);
3094        synchronized (sLock) {
3095            if (isHalStarted()) {
3096                return getWlanWakeReasonCountNative(sWlan0Index);
3097            } else {
3098                return null;
3099            }
3100        }
3101    }
3102
3103    private static native int configureNeighborDiscoveryOffload(int iface, boolean enabled);
3104
3105    public boolean configureNeighborDiscoveryOffload(boolean enabled) {
3106        final String logMsg =  "configureNeighborDiscoveryOffload(" + enabled + ")";
3107        Log.d(mTAG, logMsg);
3108        synchronized (sLock) {
3109            if (isHalStarted()) {
3110                final int ret = configureNeighborDiscoveryOffload(sWlan0Index, enabled);
3111                if (ret != 0) {
3112                    Log.d(mTAG, logMsg + " returned: " + ret);
3113                }
3114                return (ret == 0);
3115            }
3116        }
3117        return false;
3118    }
3119}
3120