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