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