AccessPoint.java revision 733ea26747332f01865929d04c6444f95a4ebbef
1/*
2 * Copyright (C) 2015 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.settingslib.wifi;
18
19import android.annotation.IntDef;
20import android.annotation.Nullable;
21import android.app.AppGlobals;
22import android.content.Context;
23import android.content.pm.ApplicationInfo;
24import android.content.pm.IPackageManager;
25import android.content.pm.PackageManager;
26import android.net.ConnectivityManager;
27import android.net.NetworkCapabilities;
28import android.net.NetworkInfo;
29import android.net.NetworkInfo.DetailedState;
30import android.net.NetworkInfo.State;
31import android.net.NetworkKey;
32import android.net.NetworkScoreManager;
33import android.net.NetworkScorerAppData;
34import android.net.ScoredNetwork;
35import android.net.WifiKey;
36import android.net.wifi.IWifiManager;
37import android.net.wifi.ScanResult;
38import android.net.wifi.WifiConfiguration;
39import android.net.wifi.WifiConfiguration.KeyMgmt;
40import android.net.wifi.WifiEnterpriseConfig;
41import android.net.wifi.WifiInfo;
42import android.net.wifi.WifiManager;
43import android.net.wifi.WifiNetworkScoreCache;
44import android.net.wifi.hotspot2.PasspointConfiguration;
45import android.os.Bundle;
46import android.os.RemoteException;
47import android.os.ServiceManager;
48import android.os.SystemClock;
49import android.os.UserHandle;
50import android.support.annotation.NonNull;
51import android.text.Spannable;
52import android.text.SpannableString;
53import android.text.TextUtils;
54import android.text.style.TtsSpan;
55import android.util.Log;
56
57import com.android.internal.annotations.VisibleForTesting;
58import com.android.settingslib.R;
59
60import java.lang.annotation.Retention;
61import java.lang.annotation.RetentionPolicy;
62import java.util.ArrayList;
63import java.util.HashMap;
64import java.util.Iterator;
65import java.util.Map;
66import java.util.concurrent.ConcurrentHashMap;
67import java.util.concurrent.atomic.AtomicInteger;
68
69
70public class AccessPoint implements Comparable<AccessPoint> {
71    static final String TAG = "SettingsLib.AccessPoint";
72
73    /**
74     * Lower bound on the 2.4 GHz (802.11b/g/n) WLAN channels
75     */
76    public static final int LOWER_FREQ_24GHZ = 2400;
77
78    /**
79     * Upper bound on the 2.4 GHz (802.11b/g/n) WLAN channels
80     */
81    public static final int HIGHER_FREQ_24GHZ = 2500;
82
83    /**
84     * Lower bound on the 5.0 GHz (802.11a/h/j/n/ac) WLAN channels
85     */
86    public static final int LOWER_FREQ_5GHZ = 4900;
87
88    /**
89     * Upper bound on the 5.0 GHz (802.11a/h/j/n/ac) WLAN channels
90     */
91    public static final int HIGHER_FREQ_5GHZ = 5900;
92
93    @IntDef({Speed.NONE, Speed.SLOW, Speed.MODERATE, Speed.FAST, Speed.VERY_FAST})
94    @Retention(RetentionPolicy.SOURCE)
95    public @interface Speed {
96        /**
97         * Constant value representing an unlabeled / unscored network.
98         */
99        int NONE = 0;
100        /**
101         * Constant value representing a slow speed network connection.
102         */
103        int SLOW = 5;
104        /**
105         * Constant value representing a medium speed network connection.
106         */
107        int MODERATE = 10;
108        /**
109         * Constant value representing a fast speed network connection.
110         */
111        int FAST = 20;
112        /**
113         * Constant value representing a very fast speed network connection.
114         */
115        int VERY_FAST = 30;
116    }
117
118    /**
119     * Experimental: we should be able to show the user the list of BSSIDs and bands
120     *  for that SSID.
121     *  For now this data is used only with Verbose Logging so as to show the band and number
122     *  of BSSIDs on which that network is seen.
123     */
124    private final ConcurrentHashMap<String, ScanResult> mScanResultCache =
125            new ConcurrentHashMap<String, ScanResult>(32);
126
127    /** Map of BSSIDs to speed values for individual ScanResults. */
128    private final Map<String, Integer> mScanResultScores = new HashMap<>();
129
130    /** Maximum age of scan results to hold onto while actively scanning. **/
131    private static final long MAX_SCAN_RESULT_AGE_MS = 15000;
132
133    static final String KEY_NETWORKINFO = "key_networkinfo";
134    static final String KEY_WIFIINFO = "key_wifiinfo";
135    static final String KEY_SCANRESULT = "key_scanresult";
136    static final String KEY_SSID = "key_ssid";
137    static final String KEY_SECURITY = "key_security";
138    static final String KEY_SPEED = "key_speed";
139    static final String KEY_PSKTYPE = "key_psktype";
140    static final String KEY_SCANRESULTCACHE = "key_scanresultcache";
141    static final String KEY_CONFIG = "key_config";
142    static final String KEY_FQDN = "key_fqdn";
143    static final String KEY_PROVIDER_FRIENDLY_NAME = "key_provider_friendly_name";
144    static final String KEY_IS_CARRIER_AP = "key_is_carrier_ap";
145    static final String KEY_CARRIER_AP_EAP_TYPE = "key_carrier_ap_eap_type";
146    static final String KEY_CARRIER_NAME = "key_carrier_name";
147    static final AtomicInteger sLastId = new AtomicInteger(0);
148
149    /**
150     * These values are matched in string arrays -- changes must be kept in sync
151     */
152    public static final int SECURITY_NONE = 0;
153    public static final int SECURITY_WEP = 1;
154    public static final int SECURITY_PSK = 2;
155    public static final int SECURITY_EAP = 3;
156
157    private static final int PSK_UNKNOWN = 0;
158    private static final int PSK_WPA = 1;
159    private static final int PSK_WPA2 = 2;
160    private static final int PSK_WPA_WPA2 = 3;
161
162    /**
163     * The number of distinct wifi levels.
164     *
165     * <p>Must keep in sync with {@link R.array.wifi_signal} and {@link WifiManager#RSSI_LEVELS}.
166     */
167    public static final int SIGNAL_LEVELS = 5;
168
169    public static final int UNREACHABLE_RSSI = Integer.MIN_VALUE;
170
171    private final Context mContext;
172
173    private String ssid;
174    private String bssid;
175    private int security;
176    private int networkId = WifiConfiguration.INVALID_NETWORK_ID;
177
178    private int pskType = PSK_UNKNOWN;
179
180    private WifiConfiguration mConfig;
181
182    private int mRssi = UNREACHABLE_RSSI;
183    private long mSeen = 0;
184
185    private WifiInfo mInfo;
186    private NetworkInfo mNetworkInfo;
187    AccessPointListener mAccessPointListener;
188
189    private Object mTag;
190
191    private int mSpeed = Speed.NONE;
192    private boolean mIsScoredNetworkMetered = false;
193
194    // used to co-relate internal vs returned accesspoint.
195    int mId;
196
197    /**
198     * Information associated with the {@link PasspointConfiguration}.  Only maintaining
199     * the relevant info to preserve spaces.
200     */
201    private String mFqdn;
202    private String mProviderFriendlyName;
203
204    private boolean mIsCarrierAp = false;
205    /**
206     * The EAP type {@link WifiEnterpriseConfig.Eap} associated with this AP if it is a carrier AP.
207     */
208    private int mCarrierApEapType = WifiEnterpriseConfig.Eap.NONE;
209    private String mCarrierName = null;
210
211    public AccessPoint(Context context, Bundle savedState) {
212        mContext = context;
213        mConfig = savedState.getParcelable(KEY_CONFIG);
214        if (mConfig != null) {
215            loadConfig(mConfig);
216        }
217        if (savedState.containsKey(KEY_SSID)) {
218            ssid = savedState.getString(KEY_SSID);
219        }
220        if (savedState.containsKey(KEY_SECURITY)) {
221            security = savedState.getInt(KEY_SECURITY);
222        }
223        if (savedState.containsKey(KEY_SPEED)) {
224            mSpeed = savedState.getInt(KEY_SPEED);
225        }
226        if (savedState.containsKey(KEY_PSKTYPE)) {
227            pskType = savedState.getInt(KEY_PSKTYPE);
228        }
229        mInfo = savedState.getParcelable(KEY_WIFIINFO);
230        if (savedState.containsKey(KEY_NETWORKINFO)) {
231            mNetworkInfo = savedState.getParcelable(KEY_NETWORKINFO);
232        }
233        if (savedState.containsKey(KEY_SCANRESULTCACHE)) {
234            ArrayList<ScanResult> scanResultArrayList =
235                    savedState.getParcelableArrayList(KEY_SCANRESULTCACHE);
236            mScanResultCache.clear();
237            for (ScanResult result : scanResultArrayList) {
238                mScanResultCache.put(result.BSSID, result);
239            }
240        }
241        if (savedState.containsKey(KEY_FQDN)) {
242            mFqdn = savedState.getString(KEY_FQDN);
243        }
244        if (savedState.containsKey(KEY_PROVIDER_FRIENDLY_NAME)) {
245            mProviderFriendlyName = savedState.getString(KEY_PROVIDER_FRIENDLY_NAME);
246        }
247        if (savedState.containsKey(KEY_IS_CARRIER_AP)) {
248            mIsCarrierAp = savedState.getBoolean(KEY_IS_CARRIER_AP);
249        }
250        if (savedState.containsKey(KEY_CARRIER_AP_EAP_TYPE)) {
251            mCarrierApEapType = savedState.getInt(KEY_CARRIER_AP_EAP_TYPE);
252        }
253        if (savedState.containsKey(KEY_CARRIER_NAME)) {
254            mCarrierName = savedState.getString(KEY_CARRIER_NAME);
255        }
256        update(mConfig, mInfo, mNetworkInfo);
257        updateRssi();
258        updateSeen();
259        mId = sLastId.incrementAndGet();
260    }
261
262    public AccessPoint(Context context, WifiConfiguration config) {
263        mContext = context;
264        loadConfig(config);
265        mId = sLastId.incrementAndGet();
266    }
267
268    /**
269     * Initialize an AccessPoint object for a {@link PasspointConfiguration}.  This is mainly
270     * used by "Saved Networks" page for managing the saved {@link PasspointConfiguration}.
271     */
272    public AccessPoint(Context context, PasspointConfiguration config) {
273        mContext = context;
274        mFqdn = config.getHomeSp().getFqdn();
275        mProviderFriendlyName = config.getHomeSp().getFriendlyName();
276        mId = sLastId.incrementAndGet();
277    }
278
279    AccessPoint(Context context, AccessPoint other) {
280        mContext = context;
281        copyFrom(other);
282    }
283
284    AccessPoint(Context context, ScanResult result) {
285        mContext = context;
286        initWithScanResult(result);
287        mId = sLastId.incrementAndGet();
288    }
289
290    /**
291     * Copy accesspoint information. NOTE: We do not copy tag information because that is never
292     * set on the internal copy.
293     * @param that
294     */
295    void copyFrom(AccessPoint that) {
296        that.evictOldScanResults();
297        this.ssid = that.ssid;
298        this.bssid = that.bssid;
299        this.security = that.security;
300        this.networkId = that.networkId;
301        this.pskType = that.pskType;
302        this.mConfig = that.mConfig; //TODO: Watch out, this object is mutated.
303        this.mRssi = that.mRssi;
304        this.mSeen = that.mSeen;
305        this.mInfo = that.mInfo;
306        this.mNetworkInfo = that.mNetworkInfo;
307        this.mScanResultCache.clear();
308        this.mScanResultCache.putAll(that.mScanResultCache);
309        this.mScanResultScores.clear();
310        this.mScanResultScores.putAll(that.mScanResultScores);
311        this.mId = that.mId;
312        this.mSpeed = that.mSpeed;
313        this.mIsScoredNetworkMetered = that.mIsScoredNetworkMetered;
314        this.mIsCarrierAp = that.mIsCarrierAp;
315        this.mCarrierApEapType = that.mCarrierApEapType;
316        this.mCarrierName = that.mCarrierName;
317    }
318
319    /**
320    * Returns a negative integer, zero, or a positive integer if this AccessPoint is less than,
321    * equal to, or greater than the other AccessPoint.
322    *
323    * Sort order rules for AccessPoints:
324    *   1. Active before inactive
325    *   2. Reachable before unreachable
326    *   3. Saved before unsaved
327    *   4. Network speed value
328    *   5. Stronger signal before weaker signal
329    *   6. SSID alphabetically
330    *
331    * Note that AccessPoints with a signal are usually also Reachable,
332    * and will thus appear before unreachable saved AccessPoints.
333    */
334    @Override
335    public int compareTo(@NonNull AccessPoint other) {
336        // Active one goes first.
337        if (isActive() && !other.isActive()) return -1;
338        if (!isActive() && other.isActive()) return 1;
339
340        // Reachable one goes before unreachable one.
341        if (isReachable() && !other.isReachable()) return -1;
342        if (!isReachable() && other.isReachable()) return 1;
343
344        // Configured (saved) one goes before unconfigured one.
345        if (isSaved() && !other.isSaved()) return -1;
346        if (!isSaved() && other.isSaved()) return 1;
347
348        // Faster speeds go before slower speeds
349        if (getSpeed() != other.getSpeed()) {
350            return other.getSpeed() - getSpeed();
351        }
352
353        // Sort by signal strength, bucketed by level
354        int difference = WifiManager.calculateSignalLevel(other.mRssi, SIGNAL_LEVELS)
355                - WifiManager.calculateSignalLevel(mRssi, SIGNAL_LEVELS);
356        if (difference != 0) {
357            return difference;
358        }
359
360        // Sort by ssid.
361        difference = getSsidStr().compareToIgnoreCase(other.getSsidStr());
362        if (difference != 0) {
363            return difference;
364        }
365
366        // Do a case sensitive comparison to distinguish SSIDs that differ in case only
367        return getSsidStr().compareTo(other.getSsidStr());
368    }
369
370    @Override
371    public boolean equals(Object other) {
372        if (!(other instanceof AccessPoint)) return false;
373        return (this.compareTo((AccessPoint) other) == 0);
374    }
375
376    @Override
377    public int hashCode() {
378        int result = 0;
379        if (mInfo != null) result += 13 * mInfo.hashCode();
380        result += 19 * mRssi;
381        result += 23 * networkId;
382        result += 29 * ssid.hashCode();
383        return result;
384    }
385
386    @Override
387    public String toString() {
388        StringBuilder builder = new StringBuilder().append("AccessPoint(")
389                .append(ssid);
390        if (bssid != null) {
391            builder.append(":").append(bssid);
392        }
393        if (isSaved()) {
394            builder.append(',').append("saved");
395        }
396        if (isActive()) {
397            builder.append(',').append("active");
398        }
399        if (isEphemeral()) {
400            builder.append(',').append("ephemeral");
401        }
402        if (isConnectable()) {
403            builder.append(',').append("connectable");
404        }
405        if (security != SECURITY_NONE) {
406            builder.append(',').append(securityToString(security, pskType));
407        }
408        builder.append(",level=").append(getLevel());
409        if (mSpeed != Speed.NONE) {
410            builder.append(",speed=").append(mSpeed);
411        }
412        builder.append(",metered=").append(isMetered());
413
414        return builder.append(')').toString();
415    }
416
417    /**
418     * Updates the AccessPoint rankingScore, metering, and speed, returning true if the data has
419     * changed.
420     *
421     * @param scoreCache The score cache to use to retrieve scores.
422     * @param scoringUiEnabled Whether to show scoring and badging UI.
423     */
424    boolean update(WifiNetworkScoreCache scoreCache, boolean scoringUiEnabled) {
425        boolean scoreChanged = false;
426        mScanResultScores.clear();
427        if (scoringUiEnabled) {
428            scoreChanged = updateScores(scoreCache);
429        }
430        return updateMetered(scoreCache) || scoreChanged;
431    }
432
433    /**
434     * Updates the AccessPoint rankingScore and speed, returning true if the data has changed.
435     *
436     * @param scoreCache The score cache to use to retrieve scores.
437     */
438    private boolean updateScores(WifiNetworkScoreCache scoreCache) {
439        int oldSpeed = mSpeed;
440        mSpeed = Speed.NONE;
441
442        for (ScanResult result : mScanResultCache.values()) {
443            ScoredNetwork score = scoreCache.getScoredNetwork(result);
444            if (score == null) {
445                continue;
446            }
447
448            int speed = score.calculateBadge(result.level);
449            mScanResultScores.put(result.BSSID, speed);
450            mSpeed = Math.max(mSpeed, speed);
451        }
452
453        // set mSpeed to the connected ScanResult if the AccessPoint is the active network
454        if (isActive() && mInfo != null) {
455            NetworkKey key = NetworkKey.createFromWifiInfo(mInfo);
456            ScoredNetwork score = scoreCache.getScoredNetwork(key);
457            if (score != null) {
458                mSpeed = score.calculateBadge(mInfo.getRssi());
459            }
460        }
461
462        if(WifiTracker.sVerboseLogging) {
463            Log.i(TAG, String.format("%s: Set speed to %d", ssid, mSpeed));
464        }
465
466        return oldSpeed != mSpeed;
467    }
468
469    /**
470     * Updates the AccessPoint's metering based on {@link ScoredNetwork#meteredHint}, returning
471     * true if the metering changed.
472     */
473    private boolean updateMetered(WifiNetworkScoreCache scoreCache) {
474        boolean oldMetering = mIsScoredNetworkMetered;
475        mIsScoredNetworkMetered = false;
476
477        if (isActive() && mInfo != null) {
478            NetworkKey key = NetworkKey.createFromWifiInfo(mInfo);
479            ScoredNetwork score = scoreCache.getScoredNetwork(key);
480            if (score != null) {
481                mIsScoredNetworkMetered |= score.meteredHint;
482            }
483        } else {
484            for (ScanResult result : mScanResultCache.values()) {
485                ScoredNetwork score = scoreCache.getScoredNetwork(result);
486                if (score == null) {
487                    continue;
488                }
489                mIsScoredNetworkMetered |= score.meteredHint;
490            }
491        }
492        return oldMetering == mIsScoredNetworkMetered;
493    }
494
495    private void evictOldScanResults() {
496        if (WifiTracker.sStaleScanResults) {
497            // Do not evict old scan results unless we are scanning and have fresh results.
498            return;
499        }
500        long nowMs = SystemClock.elapsedRealtime();
501        for (Iterator<ScanResult> iter = mScanResultCache.values().iterator(); iter.hasNext(); ) {
502            ScanResult result = iter.next();
503            // result timestamp is in microseconds
504            if (nowMs - result.timestamp / 1000 > MAX_SCAN_RESULT_AGE_MS) {
505                iter.remove();
506            }
507        }
508    }
509
510    public boolean matches(ScanResult result) {
511        return ssid.equals(result.SSID) && security == getSecurity(result);
512    }
513
514    public boolean matches(WifiConfiguration config) {
515        if (config.isPasspoint() && mConfig != null && mConfig.isPasspoint()) {
516            return ssid.equals(removeDoubleQuotes(config.SSID)) && config.FQDN.equals(mConfig.FQDN);
517        } else {
518            return ssid.equals(removeDoubleQuotes(config.SSID))
519                    && security == getSecurity(config)
520                    && (mConfig == null || mConfig.shared == config.shared);
521        }
522    }
523
524    public WifiConfiguration getConfig() {
525        return mConfig;
526    }
527
528    public String getPasspointFqdn() {
529        return mFqdn;
530    }
531
532    public void clearConfig() {
533        mConfig = null;
534        networkId = WifiConfiguration.INVALID_NETWORK_ID;
535    }
536
537    public WifiInfo getInfo() {
538        return mInfo;
539    }
540
541    /**
542     * Returns the number of levels to show for a Wifi icon, from 0 to {@link #SIGNAL_LEVELS}-1.
543     *
544     * <p>Use {@#isReachable()} to determine if an AccessPoint is in range, as this method will
545     * always return at least 0.
546     */
547    public int getLevel() {
548        return WifiManager.calculateSignalLevel(mRssi, SIGNAL_LEVELS);
549    }
550
551    public int getRssi() {
552        return mRssi;
553    }
554
555    /**
556     * Updates {@link #mRssi}.
557     *
558     * <p>If the given connection is active, the existing value of {@link #mRssi} will be returned.
559     * If the given AccessPoint is not active, a value will be calculated from previous scan
560     * results, returning the best RSSI for all matching AccessPoints averaged with the previous
561     * value. If the access point is not connected and there are no scan results, the rssi will be
562     * set to {@link #UNREACHABLE_RSSI}.
563     *
564     * <p>Old scan results will be evicted from the cache when this method is invoked.
565     */
566    private void updateRssi() {
567        evictOldScanResults();
568
569        if (this.isActive()) {
570            return;
571        }
572
573        int rssi = UNREACHABLE_RSSI;
574        for (ScanResult result : mScanResultCache.values()) {
575            if (result.level > rssi) {
576                rssi = result.level;
577            }
578        }
579
580        if (rssi != UNREACHABLE_RSSI && mRssi != UNREACHABLE_RSSI) {
581            mRssi = (mRssi + rssi) / 2; // half-life previous value
582        } else {
583            mRssi = rssi;
584        }
585    }
586
587    /**
588     * Updates {@link #mSeen} based on the scan result cache.
589     *
590     * <p>Old scan results will be evicted from the cache when this method is invoked.
591     */
592    private void updateSeen() {
593        evictOldScanResults();
594
595        // TODO(sghuman): Set to now if connected
596
597        long seen = 0;
598        for (ScanResult result : mScanResultCache.values()) {
599            if (result.timestamp > seen) {
600                seen = result.timestamp;
601            }
602        }
603
604        // Only replace the previous value if we have a recent scan result to use
605        if (seen != 0) {
606            mSeen = seen;
607        }
608    }
609
610    /**
611     * Returns if the network should be considered metered.
612     */
613    public boolean isMetered() {
614        return mIsScoredNetworkMetered
615                || WifiConfiguration.isMetered(mConfig, mInfo);
616    }
617
618    public NetworkInfo getNetworkInfo() {
619        return mNetworkInfo;
620    }
621
622    public int getSecurity() {
623        return security;
624    }
625
626    public String getSecurityString(boolean concise) {
627        Context context = mContext;
628        if (isPasspoint() || isPasspointConfig()) {
629            return concise ? context.getString(R.string.wifi_security_short_eap) :
630                context.getString(R.string.wifi_security_eap);
631        }
632        switch(security) {
633            case SECURITY_EAP:
634                return concise ? context.getString(R.string.wifi_security_short_eap) :
635                    context.getString(R.string.wifi_security_eap);
636            case SECURITY_PSK:
637                switch (pskType) {
638                    case PSK_WPA:
639                        return concise ? context.getString(R.string.wifi_security_short_wpa) :
640                            context.getString(R.string.wifi_security_wpa);
641                    case PSK_WPA2:
642                        return concise ? context.getString(R.string.wifi_security_short_wpa2) :
643                            context.getString(R.string.wifi_security_wpa2);
644                    case PSK_WPA_WPA2:
645                        return concise ? context.getString(R.string.wifi_security_short_wpa_wpa2) :
646                            context.getString(R.string.wifi_security_wpa_wpa2);
647                    case PSK_UNKNOWN:
648                    default:
649                        return concise ? context.getString(R.string.wifi_security_short_psk_generic)
650                                : context.getString(R.string.wifi_security_psk_generic);
651                }
652            case SECURITY_WEP:
653                return concise ? context.getString(R.string.wifi_security_short_wep) :
654                    context.getString(R.string.wifi_security_wep);
655            case SECURITY_NONE:
656            default:
657                return concise ? "" : context.getString(R.string.wifi_security_none);
658        }
659    }
660
661    public String getSsidStr() {
662        return ssid;
663    }
664
665    public String getBssid() {
666        return bssid;
667    }
668
669    public CharSequence getSsid() {
670        final SpannableString str = new SpannableString(ssid);
671        str.setSpan(new TtsSpan.TelephoneBuilder(ssid).build(), 0, ssid.length(),
672                Spannable.SPAN_INCLUSIVE_INCLUSIVE);
673        return str;
674    }
675
676    public String getConfigName() {
677        if (mConfig != null && mConfig.isPasspoint()) {
678            return mConfig.providerFriendlyName;
679        } else if (mFqdn != null) {
680            return mProviderFriendlyName;
681        } else {
682            return ssid;
683        }
684    }
685
686    public DetailedState getDetailedState() {
687        if (mNetworkInfo != null) {
688            return mNetworkInfo.getDetailedState();
689        }
690        Log.w(TAG, "NetworkInfo is null, cannot return detailed state");
691        return null;
692    }
693
694    public boolean isCarrierAp() {
695        return mIsCarrierAp;
696    }
697
698    public int getCarrierApEapType() {
699        return mCarrierApEapType;
700    }
701
702    public String getCarrierName() {
703        return mCarrierName;
704    }
705
706    public String getSavedNetworkSummary() {
707        WifiConfiguration config = mConfig;
708        if (config != null) {
709            PackageManager pm = mContext.getPackageManager();
710            String systemName = pm.getNameForUid(android.os.Process.SYSTEM_UID);
711            int userId = UserHandle.getUserId(config.creatorUid);
712            ApplicationInfo appInfo = null;
713            if (config.creatorName != null && config.creatorName.equals(systemName)) {
714                appInfo = mContext.getApplicationInfo();
715            } else {
716                try {
717                    IPackageManager ipm = AppGlobals.getPackageManager();
718                    appInfo = ipm.getApplicationInfo(config.creatorName, 0 /* flags */, userId);
719                } catch (RemoteException rex) {
720                }
721            }
722            if (appInfo != null &&
723                    !appInfo.packageName.equals(mContext.getString(R.string.settings_package)) &&
724                    !appInfo.packageName.equals(
725                    mContext.getString(R.string.certinstaller_package))) {
726                return mContext.getString(R.string.saved_network, appInfo.loadLabel(pm));
727            }
728        }
729        return "";
730    }
731
732    public String getSummary() {
733        return getSettingsSummary(mConfig);
734    }
735
736    public String getSettingsSummary() {
737        return getSettingsSummary(mConfig);
738    }
739
740    private String getSettingsSummary(WifiConfiguration config) {
741        // Update to new summary
742        StringBuilder summary = new StringBuilder();
743
744        if (isActive() && config != null && config.isPasspoint()) {
745            // This is the active connection on passpoint
746            summary.append(getSummary(mContext, getDetailedState(),
747                    false, config.providerFriendlyName));
748        } else if (isActive() && config != null && getDetailedState() == DetailedState.CONNECTED
749                && mIsCarrierAp) {
750            summary.append(String.format(mContext.getString(R.string.connected_via_carrier), mCarrierName));
751        } else if (isActive()) {
752            // This is the active connection on non-passpoint network
753            summary.append(getSummary(mContext, getDetailedState(),
754                    mInfo != null && mInfo.isEphemeral()));
755        } else if (config != null && config.isPasspoint()
756                && config.getNetworkSelectionStatus().isNetworkEnabled()) {
757            String format = mContext.getString(R.string.available_via_passpoint);
758            summary.append(String.format(format, config.providerFriendlyName));
759        } else if (config != null && config.hasNoInternetAccess()) {
760            int messageID = config.getNetworkSelectionStatus().isNetworkPermanentlyDisabled()
761                    ? R.string.wifi_no_internet_no_reconnect
762                    : R.string.wifi_no_internet;
763            summary.append(mContext.getString(messageID));
764        } else if (config != null && !config.getNetworkSelectionStatus().isNetworkEnabled()) {
765            WifiConfiguration.NetworkSelectionStatus networkStatus =
766                    config.getNetworkSelectionStatus();
767            switch (networkStatus.getNetworkSelectionDisableReason()) {
768                case WifiConfiguration.NetworkSelectionStatus.DISABLED_AUTHENTICATION_FAILURE:
769                    summary.append(mContext.getString(R.string.wifi_disabled_password_failure));
770                    break;
771                case WifiConfiguration.NetworkSelectionStatus.DISABLED_BY_WRONG_PASSWORD:
772                    summary.append(mContext.getString(R.string.wifi_check_password_try_again));
773                    break;
774                case WifiConfiguration.NetworkSelectionStatus.DISABLED_DHCP_FAILURE:
775                case WifiConfiguration.NetworkSelectionStatus.DISABLED_DNS_FAILURE:
776                    summary.append(mContext.getString(R.string.wifi_disabled_network_failure));
777                    break;
778                case WifiConfiguration.NetworkSelectionStatus.DISABLED_ASSOCIATION_REJECTION:
779                    summary.append(mContext.getString(R.string.wifi_disabled_generic));
780                    break;
781            }
782        } else if (config != null && config.getNetworkSelectionStatus().isNotRecommended()) {
783            summary.append(mContext.getString(R.string.wifi_disabled_by_recommendation_provider));
784        } else if (mIsCarrierAp) {
785            summary.append(String.format(mContext.getString(R.string.available_via_carrier), mCarrierName));
786        } else if (!isReachable()) { // Wifi out of range
787            summary.append(mContext.getString(R.string.wifi_not_in_range));
788        } else { // In range, not disabled.
789            if (config != null) { // Is saved network
790                // Last attempt to connect to this failed. Show reason why
791                switch (config.recentFailure.getAssociationStatus()) {
792                    case WifiConfiguration.RecentFailure.STATUS_AP_UNABLE_TO_HANDLE_NEW_STA:
793                        summary.append(mContext.getString(
794                                R.string.wifi_ap_unable_to_handle_new_sta));
795                        break;
796                    default:
797                        // "Saved"
798                        summary.append(mContext.getString(R.string.wifi_remembered));
799                        break;
800                }
801            }
802        }
803
804        if (WifiTracker.sVerboseLogging) {
805            // Add RSSI/band information for this config, what was seen up to 6 seconds ago
806            // verbose WiFi Logging is only turned on thru developers settings
807            if (isActive() && mInfo != null) {
808                summary.append(" f=" + Integer.toString(mInfo.getFrequency()));
809            }
810            summary.append(" " + getVisibilityStatus());
811            if (config != null && !config.getNetworkSelectionStatus().isNetworkEnabled()) {
812                summary.append(" (" + config.getNetworkSelectionStatus().getNetworkStatusString());
813                if (config.getNetworkSelectionStatus().getDisableTime() > 0) {
814                    long now = System.currentTimeMillis();
815                    long diff = (now - config.getNetworkSelectionStatus().getDisableTime()) / 1000;
816                    long sec = diff%60; //seconds
817                    long min = (diff/60)%60; //minutes
818                    long hour = (min/60)%60; //hours
819                    summary.append(", ");
820                    if (hour > 0) summary.append(Long.toString(hour) + "h ");
821                    summary.append( Long.toString(min) + "m ");
822                    summary.append( Long.toString(sec) + "s ");
823                }
824                summary.append(")");
825            }
826
827            if (config != null) {
828                WifiConfiguration.NetworkSelectionStatus networkStatus =
829                        config.getNetworkSelectionStatus();
830                for (int index = WifiConfiguration.NetworkSelectionStatus.NETWORK_SELECTION_ENABLE;
831                        index < WifiConfiguration.NetworkSelectionStatus
832                        .NETWORK_SELECTION_DISABLED_MAX; index++) {
833                    if (networkStatus.getDisableReasonCounter(index) != 0) {
834                        summary.append(" " + WifiConfiguration.NetworkSelectionStatus
835                                .getNetworkDisableReasonString(index) + "="
836                                + networkStatus.getDisableReasonCounter(index));
837                    }
838                }
839            }
840        }
841
842        // If Speed label and summary are both present, use the preference combination to combine
843        // the two, else return the non-null one.
844        if (getSpeedLabel() != null && summary.length() != 0) {
845            return mContext.getResources().getString(
846                    R.string.preference_summary_default_combination,
847                    getSpeedLabel(),
848                    summary.toString());
849        } else if (getSpeedLabel() != null) {
850            return getSpeedLabel();
851        } else {
852            return summary.toString();
853        }
854    }
855
856    /**
857     * Returns the visibility status of the WifiConfiguration.
858     *
859     * @return autojoin debugging information
860     * TODO: use a string formatter
861     * ["rssi 5Ghz", "num results on 5GHz" / "rssi 5Ghz", "num results on 5GHz"]
862     * For instance [-40,5/-30,2]
863     */
864    private String getVisibilityStatus() {
865        StringBuilder visibility = new StringBuilder();
866        StringBuilder scans24GHz = new StringBuilder();
867        StringBuilder scans5GHz = new StringBuilder();
868        String bssid = null;
869
870        long now = System.currentTimeMillis();
871
872        if (isActive() && mInfo != null) {
873            bssid = mInfo.getBSSID();
874            if (bssid != null) {
875                visibility.append(" ").append(bssid);
876            }
877            visibility.append(" rssi=").append(mInfo.getRssi());
878            visibility.append(" ");
879            visibility.append(" score=").append(mInfo.score);
880            if (mSpeed != Speed.NONE) {
881                visibility.append(" speed=").append(getSpeedLabel());
882            }
883            visibility.append(String.format(" tx=%.1f,", mInfo.txSuccessRate));
884            visibility.append(String.format("%.1f,", mInfo.txRetriesRate));
885            visibility.append(String.format("%.1f ", mInfo.txBadRate));
886            visibility.append(String.format("rx=%.1f", mInfo.rxSuccessRate));
887        }
888
889        int maxRssi5 = WifiConfiguration.INVALID_RSSI;
890        int maxRssi24 = WifiConfiguration.INVALID_RSSI;
891        final int maxDisplayedScans = 4;
892        int num5 = 0; // number of scanned BSSID on 5GHz band
893        int num24 = 0; // number of scanned BSSID on 2.4Ghz band
894        int numBlackListed = 0;
895        evictOldScanResults();
896
897        // TODO: sort list by RSSI or age
898        for (ScanResult result : mScanResultCache.values()) {
899            if (result.frequency >= LOWER_FREQ_5GHZ
900                    && result.frequency <= HIGHER_FREQ_5GHZ) {
901                // Strictly speaking: [4915, 5825]
902                num5++;
903
904                if (result.level > maxRssi5) {
905                    maxRssi5 = result.level;
906                }
907                if (num5 <= maxDisplayedScans) {
908                    scans5GHz.append(verboseScanResultSummary(result, bssid));
909                }
910            } else if (result.frequency >= LOWER_FREQ_24GHZ
911                    && result.frequency <= HIGHER_FREQ_24GHZ) {
912                // Strictly speaking: [2412, 2482]
913                num24++;
914
915                if (result.level > maxRssi24) {
916                    maxRssi24 = result.level;
917                }
918                if (num24 <= maxDisplayedScans) {
919                    scans24GHz.append(verboseScanResultSummary(result, bssid));
920                }
921            }
922        }
923        visibility.append(" [");
924        if (num24 > 0) {
925            visibility.append("(").append(num24).append(")");
926            if (num24 > maxDisplayedScans) {
927                visibility.append("max=").append(maxRssi24).append(",");
928            }
929            visibility.append(scans24GHz.toString());
930        }
931        visibility.append(";");
932        if (num5 > 0) {
933            visibility.append("(").append(num5).append(")");
934            if (num5 > maxDisplayedScans) {
935                visibility.append("max=").append(maxRssi5).append(",");
936            }
937            visibility.append(scans5GHz.toString());
938        }
939        if (numBlackListed > 0)
940            visibility.append("!").append(numBlackListed);
941        visibility.append("]");
942
943        return visibility.toString();
944    }
945
946    @VisibleForTesting
947    /* package */ String verboseScanResultSummary(ScanResult result, String bssid) {
948        StringBuilder stringBuilder = new StringBuilder();
949        stringBuilder.append(" \n{").append(result.BSSID);
950        if (result.BSSID.equals(bssid)) {
951            stringBuilder.append("*");
952        }
953        stringBuilder.append("=").append(result.frequency);
954        stringBuilder.append(",").append(result.level);
955        if (hasSpeed(result)) {
956            stringBuilder.append(",")
957                    .append(getSpeedLabel(mScanResultScores.get(result.BSSID)));
958        }
959        stringBuilder.append("}");
960        return stringBuilder.toString();
961    }
962
963    private boolean hasSpeed(ScanResult result) {
964        return mScanResultScores.containsKey(result.BSSID)
965                && mScanResultScores.get(result.BSSID) != Speed.NONE;
966    }
967
968    /**
969     * Return whether this is the active connection.
970     * For ephemeral connections (networkId is invalid), this returns false if the network is
971     * disconnected.
972     */
973    public boolean isActive() {
974        return mNetworkInfo != null &&
975                (networkId != WifiConfiguration.INVALID_NETWORK_ID ||
976                 mNetworkInfo.getState() != State.DISCONNECTED);
977    }
978
979    public boolean isConnectable() {
980        return getLevel() != -1 && getDetailedState() == null;
981    }
982
983    public boolean isEphemeral() {
984        return mInfo != null && mInfo.isEphemeral() &&
985                mNetworkInfo != null && mNetworkInfo.getState() != State.DISCONNECTED;
986    }
987
988    /**
989     * Return true if this AccessPoint represents a Passpoint AP.
990     */
991    public boolean isPasspoint() {
992        return mConfig != null && mConfig.isPasspoint();
993    }
994
995    /**
996     * Return true if this AccessPoint represents a Passpoint provider configuration.
997     */
998    public boolean isPasspointConfig() {
999        return mFqdn != null;
1000    }
1001
1002    /**
1003     * Return whether the given {@link WifiInfo} is for this access point.
1004     * If the current AP does not have a network Id then the config is used to
1005     * match based on SSID and security.
1006     */
1007    private boolean isInfoForThisAccessPoint(WifiConfiguration config, WifiInfo info) {
1008        if (isPasspoint() == false && networkId != WifiConfiguration.INVALID_NETWORK_ID) {
1009            return networkId == info.getNetworkId();
1010        } else if (config != null) {
1011            return matches(config);
1012        }
1013        else {
1014            // Might be an ephemeral connection with no WifiConfiguration. Try matching on SSID.
1015            // (Note that we only do this if the WifiConfiguration explicitly equals INVALID).
1016            // TODO: Handle hex string SSIDs.
1017            return ssid.equals(removeDoubleQuotes(info.getSSID()));
1018        }
1019    }
1020
1021    public boolean isSaved() {
1022        return networkId != WifiConfiguration.INVALID_NETWORK_ID;
1023    }
1024
1025    public Object getTag() {
1026        return mTag;
1027    }
1028
1029    public void setTag(Object tag) {
1030        mTag = tag;
1031    }
1032
1033    /**
1034     * Generate and save a default wifiConfiguration with common values.
1035     * Can only be called for unsecured networks.
1036     */
1037    public void generateOpenNetworkConfig() {
1038        if (security != SECURITY_NONE)
1039            throw new IllegalStateException();
1040        if (mConfig != null)
1041            return;
1042        mConfig = new WifiConfiguration();
1043        mConfig.SSID = AccessPoint.convertToQuotedString(ssid);
1044        mConfig.allowedKeyManagement.set(KeyMgmt.NONE);
1045    }
1046
1047    void loadConfig(WifiConfiguration config) {
1048        ssid = (config.SSID == null ? "" : removeDoubleQuotes(config.SSID));
1049        bssid = config.BSSID;
1050        security = getSecurity(config);
1051        networkId = config.networkId;
1052        mConfig = config;
1053    }
1054
1055    private void initWithScanResult(ScanResult result) {
1056        ssid = result.SSID;
1057        bssid = result.BSSID;
1058        security = getSecurity(result);
1059        if (security == SECURITY_PSK)
1060            pskType = getPskType(result);
1061
1062        mScanResultCache.put(result.BSSID, result);
1063        updateRssi();
1064        mSeen = result.timestamp; // even if the timestamp is old it is still valid
1065        mIsCarrierAp = result.isCarrierAp;
1066        mCarrierApEapType = result.carrierApEapType;
1067        mCarrierName = result.carrierName;
1068    }
1069
1070    public void saveWifiState(Bundle savedState) {
1071        if (ssid != null) savedState.putString(KEY_SSID, getSsidStr());
1072        savedState.putInt(KEY_SECURITY, security);
1073        savedState.putInt(KEY_SPEED, mSpeed);
1074        savedState.putInt(KEY_PSKTYPE, pskType);
1075        if (mConfig != null) savedState.putParcelable(KEY_CONFIG, mConfig);
1076        savedState.putParcelable(KEY_WIFIINFO, mInfo);
1077        evictOldScanResults();
1078        savedState.putParcelableArrayList(KEY_SCANRESULTCACHE,
1079                new ArrayList<ScanResult>(mScanResultCache.values()));
1080        if (mNetworkInfo != null) {
1081            savedState.putParcelable(KEY_NETWORKINFO, mNetworkInfo);
1082        }
1083        if (mFqdn != null) {
1084            savedState.putString(KEY_FQDN, mFqdn);
1085        }
1086        if (mProviderFriendlyName != null) {
1087            savedState.putString(KEY_PROVIDER_FRIENDLY_NAME, mProviderFriendlyName);
1088        }
1089        savedState.putBoolean(KEY_IS_CARRIER_AP, mIsCarrierAp);
1090        savedState.putInt(KEY_CARRIER_AP_EAP_TYPE, mCarrierApEapType);
1091        savedState.putString(KEY_CARRIER_NAME, mCarrierName);
1092    }
1093
1094    public void setListener(AccessPointListener listener) {
1095        mAccessPointListener = listener;
1096    }
1097
1098    boolean update(ScanResult result) {
1099        if (matches(result)) {
1100            int oldLevel = getLevel();
1101
1102            /* Add or update the scan result for the BSSID */
1103            mScanResultCache.put(result.BSSID, result);
1104            updateSeen();
1105            updateRssi();
1106            int newLevel = getLevel();
1107
1108            if (newLevel > 0 && newLevel != oldLevel && mAccessPointListener != null) {
1109                mAccessPointListener.onLevelChanged(this);
1110            }
1111            // This flag only comes from scans, is not easily saved in config
1112            if (security == SECURITY_PSK) {
1113                pskType = getPskType(result);
1114            }
1115
1116            if (mAccessPointListener != null) {
1117                mAccessPointListener.onAccessPointChanged(this);
1118            }
1119
1120            // The carrier info in the ScanResult is set by the platform based on the SSID and will
1121            // always be the same for all matching scan results.
1122            mIsCarrierAp = result.isCarrierAp;
1123            mCarrierApEapType = result.carrierApEapType;
1124            mCarrierName = result.carrierName;
1125
1126            return true;
1127        }
1128        return false;
1129    }
1130
1131    /** Attempt to update the AccessPoint and return true if an update occurred. */
1132    public boolean update(
1133            @Nullable WifiConfiguration config, WifiInfo info, NetworkInfo networkInfo) {
1134        boolean updated = false;
1135        final int oldLevel = getLevel();
1136        if (info != null && isInfoForThisAccessPoint(config, info)) {
1137            updated = (mInfo == null);
1138            if (mConfig != config) {
1139                // We do not set updated = true as we do not want to increase the amount of sorting
1140                // and copying performed in WifiTracker at this time. If issues involving refresh
1141                // are still seen, we will investigate further.
1142                update(config); // Notifies the AccessPointListener of the change
1143            }
1144            if (mRssi != info.getRssi() && info.getRssi() != WifiInfo.INVALID_RSSI) {
1145                mRssi = info.getRssi();
1146                updated = true;
1147            } else if (mNetworkInfo != null && networkInfo != null
1148                    && mNetworkInfo.getDetailedState() != networkInfo.getDetailedState()) {
1149                updated = true;
1150            }
1151            mInfo = info;
1152            mNetworkInfo = networkInfo;
1153        } else if (mInfo != null) {
1154            updated = true;
1155            mInfo = null;
1156            mNetworkInfo = null;
1157        }
1158        if (updated && mAccessPointListener != null) {
1159            mAccessPointListener.onAccessPointChanged(this);
1160
1161            if (oldLevel != getLevel() /* current level */) {
1162                mAccessPointListener.onLevelChanged(this);
1163            }
1164        }
1165        return updated;
1166    }
1167
1168    void update(@Nullable WifiConfiguration config) {
1169        mConfig = config;
1170        networkId = config != null ? config.networkId : WifiConfiguration.INVALID_NETWORK_ID;
1171        if (mAccessPointListener != null) {
1172            mAccessPointListener.onAccessPointChanged(this);
1173        }
1174    }
1175
1176    @VisibleForTesting
1177    void setRssi(int rssi) {
1178        mRssi = rssi;
1179    }
1180
1181    /** Sets the rssi to {@link #UNREACHABLE_RSSI}. */
1182    void setUnreachable() {
1183        setRssi(AccessPoint.UNREACHABLE_RSSI);
1184    }
1185
1186    int getSpeed() { return mSpeed;}
1187
1188    @Nullable
1189    String getSpeedLabel() {
1190        return getSpeedLabel(mSpeed);
1191    }
1192
1193    @Nullable
1194    private String getSpeedLabel(int speed) {
1195        switch (speed) {
1196            case Speed.VERY_FAST:
1197                return mContext.getString(R.string.speed_label_very_fast);
1198            case Speed.FAST:
1199                return mContext.getString(R.string.speed_label_fast);
1200            case Speed.MODERATE:
1201                return mContext.getString(R.string.speed_label_okay);
1202            case Speed.SLOW:
1203                return mContext.getString(R.string.speed_label_slow);
1204            case Speed.NONE:
1205            default:
1206                return null;
1207        }
1208    }
1209
1210    /** Return true if the current RSSI is reachable, and false otherwise. */
1211    public boolean isReachable() {
1212        return mRssi != UNREACHABLE_RSSI;
1213    }
1214
1215    public static String getSummary(Context context, String ssid, DetailedState state,
1216            boolean isEphemeral, String passpointProvider) {
1217        if (state == DetailedState.CONNECTED && ssid == null) {
1218            if (TextUtils.isEmpty(passpointProvider) == false) {
1219                // Special case for connected + passpoint networks.
1220                String format = context.getString(R.string.connected_via_passpoint);
1221                return String.format(format, passpointProvider);
1222            } else if (isEphemeral) {
1223                // Special case for connected + ephemeral networks.
1224                final NetworkScoreManager networkScoreManager = context.getSystemService(
1225                        NetworkScoreManager.class);
1226                NetworkScorerAppData scorer = networkScoreManager.getActiveScorer();
1227                if (scorer != null && scorer.getRecommendationServiceLabel() != null) {
1228                    String format = context.getString(R.string.connected_via_network_scorer);
1229                    return String.format(format, scorer.getRecommendationServiceLabel());
1230                } else {
1231                    return context.getString(R.string.connected_via_network_scorer_default);
1232                }
1233            }
1234        }
1235
1236        // Case when there is wifi connected without internet connectivity.
1237        final ConnectivityManager cm = (ConnectivityManager)
1238                context.getSystemService(Context.CONNECTIVITY_SERVICE);
1239        if (state == DetailedState.CONNECTED) {
1240            IWifiManager wifiManager = IWifiManager.Stub.asInterface(
1241                    ServiceManager.getService(Context.WIFI_SERVICE));
1242            NetworkCapabilities nc = null;
1243
1244            try {
1245                nc = cm.getNetworkCapabilities(wifiManager.getCurrentNetwork());
1246            } catch (RemoteException e) {}
1247
1248            if (nc != null) {
1249                if (nc.hasCapability(nc.NET_CAPABILITY_CAPTIVE_PORTAL)) {
1250                    int id = context.getResources()
1251                            .getIdentifier("network_available_sign_in", "string", "android");
1252                    return context.getString(id);
1253                } else if (!nc.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)) {
1254                    return context.getString(R.string.wifi_connected_no_internet);
1255                }
1256            }
1257        }
1258        if (state == null) {
1259            Log.w(TAG, "state is null, returning empty summary");
1260            return "";
1261        }
1262        String[] formats = context.getResources().getStringArray((ssid == null)
1263                ? R.array.wifi_status : R.array.wifi_status_with_ssid);
1264        int index = state.ordinal();
1265
1266        if (index >= formats.length || formats[index].length() == 0) {
1267            return "";
1268        }
1269        return String.format(formats[index], ssid);
1270    }
1271
1272    public static String getSummary(Context context, DetailedState state, boolean isEphemeral) {
1273        return getSummary(context, null, state, isEphemeral, null);
1274    }
1275
1276    public static String getSummary(Context context, DetailedState state, boolean isEphemeral,
1277            String passpointProvider) {
1278        return getSummary(context, null, state, isEphemeral, passpointProvider);
1279    }
1280
1281    public static String convertToQuotedString(String string) {
1282        return "\"" + string + "\"";
1283    }
1284
1285    private static int getPskType(ScanResult result) {
1286        boolean wpa = result.capabilities.contains("WPA-PSK");
1287        boolean wpa2 = result.capabilities.contains("WPA2-PSK");
1288        if (wpa2 && wpa) {
1289            return PSK_WPA_WPA2;
1290        } else if (wpa2) {
1291            return PSK_WPA2;
1292        } else if (wpa) {
1293            return PSK_WPA;
1294        } else {
1295            Log.w(TAG, "Received abnormal flag string: " + result.capabilities);
1296            return PSK_UNKNOWN;
1297        }
1298    }
1299
1300    private static int getSecurity(ScanResult result) {
1301        if (result.capabilities.contains("WEP")) {
1302            return SECURITY_WEP;
1303        } else if (result.capabilities.contains("PSK")) {
1304            return SECURITY_PSK;
1305        } else if (result.capabilities.contains("EAP")) {
1306            return SECURITY_EAP;
1307        }
1308        return SECURITY_NONE;
1309    }
1310
1311    static int getSecurity(WifiConfiguration config) {
1312        if (config.allowedKeyManagement.get(KeyMgmt.WPA_PSK)) {
1313            return SECURITY_PSK;
1314        }
1315        if (config.allowedKeyManagement.get(KeyMgmt.WPA_EAP) ||
1316                config.allowedKeyManagement.get(KeyMgmt.IEEE8021X)) {
1317            return SECURITY_EAP;
1318        }
1319        return (config.wepKeys[0] != null) ? SECURITY_WEP : SECURITY_NONE;
1320    }
1321
1322    public static String securityToString(int security, int pskType) {
1323        if (security == SECURITY_WEP) {
1324            return "WEP";
1325        } else if (security == SECURITY_PSK) {
1326            if (pskType == PSK_WPA) {
1327                return "WPA";
1328            } else if (pskType == PSK_WPA2) {
1329                return "WPA2";
1330            } else if (pskType == PSK_WPA_WPA2) {
1331                return "WPA_WPA2";
1332            }
1333            return "PSK";
1334        } else if (security == SECURITY_EAP) {
1335            return "EAP";
1336        }
1337        return "NONE";
1338    }
1339
1340    static String removeDoubleQuotes(String string) {
1341        if (TextUtils.isEmpty(string)) {
1342            return "";
1343        }
1344        int length = string.length();
1345        if ((length > 1) && (string.charAt(0) == '"')
1346                && (string.charAt(length - 1) == '"')) {
1347            return string.substring(1, length - 1);
1348        }
1349        return string;
1350    }
1351
1352    public interface AccessPointListener {
1353        void onAccessPointChanged(AccessPoint accessPoint);
1354        void onLevelChanged(AccessPoint accessPoint);
1355    }
1356}
1357