AccessPoint.java revision d3171ca2a15a6be6412d626fffbb7a536a7cb5c0
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        if (isActive() && config != null && config.isPasspoint()) {
681            // This is the active connection on passpoint
682            summary.append(getSummary(mContext, getDetailedState(),
683                    false, config.providerFriendlyName));
684        } else if (isActive()) {
685            // This is the active connection on non-passpoint network
686            summary.append(getSummary(mContext, getDetailedState(),
687                    mInfo != null && mInfo.isEphemeral()));
688        } else if (config != null && config.isPasspoint()
689                && config.getNetworkSelectionStatus().isNetworkEnabled()) {
690            String format = mContext.getString(R.string.available_via_passpoint);
691            summary.append(String.format(format, config.providerFriendlyName));
692        } else if (config != null && config.hasNoInternetAccess()) {
693            int messageID = config.getNetworkSelectionStatus().isNetworkPermanentlyDisabled()
694                    ? R.string.wifi_no_internet_no_reconnect
695                    : R.string.wifi_no_internet;
696            summary.append(mContext.getString(messageID));
697        } else if (config != null && !config.getNetworkSelectionStatus().isNetworkEnabled()) {
698            WifiConfiguration.NetworkSelectionStatus networkStatus =
699                    config.getNetworkSelectionStatus();
700            switch (networkStatus.getNetworkSelectionDisableReason()) {
701                case WifiConfiguration.NetworkSelectionStatus.DISABLED_AUTHENTICATION_FAILURE:
702                    summary.append(mContext.getString(R.string.wifi_disabled_password_failure));
703                    break;
704                case WifiConfiguration.NetworkSelectionStatus.DISABLED_BY_WRONG_PASSWORD:
705                    summary.append(mContext.getString(R.string.wifi_check_password_try_again));
706                    break;
707                case WifiConfiguration.NetworkSelectionStatus.DISABLED_DHCP_FAILURE:
708                case WifiConfiguration.NetworkSelectionStatus.DISABLED_DNS_FAILURE:
709                    summary.append(mContext.getString(R.string.wifi_disabled_network_failure));
710                    break;
711                case WifiConfiguration.NetworkSelectionStatus.DISABLED_ASSOCIATION_REJECTION:
712                    summary.append(mContext.getString(R.string.wifi_disabled_generic));
713                    break;
714            }
715        } else if (config != null && config.getNetworkSelectionStatus().isNotRecommended()) {
716            summary.append(mContext.getString(R.string.wifi_disabled_by_recommendation_provider));
717        } else if (!isReachable()) { // Wifi out of range
718            summary.append(mContext.getString(R.string.wifi_not_in_range));
719        } else { // In range, not disabled.
720            if (config != null) { // Is saved network
721                summary.append(mContext.getString(R.string.wifi_remembered));
722            }
723        }
724
725        if (WifiTracker.sVerboseLogging > 0) {
726            // Add RSSI/band information for this config, what was seen up to 6 seconds ago
727            // verbose WiFi Logging is only turned on thru developers settings
728            if (mInfo != null && mNetworkInfo != null) { // This is the active connection
729                summary.append(" f=" + Integer.toString(mInfo.getFrequency()));
730            }
731            summary.append(" " + getVisibilityStatus());
732            if (config != null && !config.getNetworkSelectionStatus().isNetworkEnabled()) {
733                summary.append(" (" + config.getNetworkSelectionStatus().getNetworkStatusString());
734                if (config.getNetworkSelectionStatus().getDisableTime() > 0) {
735                    long now = System.currentTimeMillis();
736                    long diff = (now - config.getNetworkSelectionStatus().getDisableTime()) / 1000;
737                    long sec = diff%60; //seconds
738                    long min = (diff/60)%60; //minutes
739                    long hour = (min/60)%60; //hours
740                    summary.append(", ");
741                    if (hour > 0) summary.append(Long.toString(hour) + "h ");
742                    summary.append( Long.toString(min) + "m ");
743                    summary.append( Long.toString(sec) + "s ");
744                }
745                summary.append(")");
746            }
747
748            if (config != null) {
749                WifiConfiguration.NetworkSelectionStatus networkStatus =
750                        config.getNetworkSelectionStatus();
751                for (int index = WifiConfiguration.NetworkSelectionStatus.NETWORK_SELECTION_ENABLE;
752                        index < WifiConfiguration.NetworkSelectionStatus
753                        .NETWORK_SELECTION_DISABLED_MAX; index++) {
754                    if (networkStatus.getDisableReasonCounter(index) != 0) {
755                        summary.append(" " + WifiConfiguration.NetworkSelectionStatus
756                                .getNetworkDisableReasonString(index) + "="
757                                + networkStatus.getDisableReasonCounter(index));
758                    }
759                }
760            }
761        }
762
763        // If Speed label is present, use the preference combination to prepend it to the summary.
764        if (mSpeed != Speed.NONE) {
765            return mContext.getResources().getString(
766                    R.string.preference_summary_default_combination,
767                    getSpeedLabel(),
768                    summary.toString());
769        } else {
770            return summary.toString();
771        }
772    }
773
774    /**
775     * Returns the visibility status of the WifiConfiguration.
776     *
777     * @return autojoin debugging information
778     * TODO: use a string formatter
779     * ["rssi 5Ghz", "num results on 5GHz" / "rssi 5Ghz", "num results on 5GHz"]
780     * For instance [-40,5/-30,2]
781     */
782    private String getVisibilityStatus() {
783        StringBuilder visibility = new StringBuilder();
784        StringBuilder scans24GHz = null;
785        StringBuilder scans5GHz = null;
786        String bssid = null;
787
788        long now = System.currentTimeMillis();
789
790        if (mInfo != null) {
791            bssid = mInfo.getBSSID();
792            if (bssid != null) {
793                visibility.append(" ").append(bssid);
794            }
795            visibility.append(" rssi=").append(mInfo.getRssi());
796            visibility.append(" ");
797            visibility.append(" score=").append(mInfo.score);
798            if (mRankingScore != Integer.MIN_VALUE) {
799                visibility.append(" rankingScore=").append(getRankingScore());
800            }
801            if (mSpeed != Speed.NONE) {
802                visibility.append(" speed=").append(getSpeedLabel());
803            }
804            visibility.append(String.format(" tx=%.1f,", mInfo.txSuccessRate));
805            visibility.append(String.format("%.1f,", mInfo.txRetriesRate));
806            visibility.append(String.format("%.1f ", mInfo.txBadRate));
807            visibility.append(String.format("rx=%.1f", mInfo.rxSuccessRate));
808        }
809
810        int rssi5 = WifiConfiguration.INVALID_RSSI;
811        int rssi24 = WifiConfiguration.INVALID_RSSI;
812        int num5 = 0;
813        int num24 = 0;
814        int numBlackListed = 0;
815        int n24 = 0; // Number scan results we included in the string
816        int n5 = 0; // Number scan results we included in the string
817        evictOldScanResults();
818        // TODO: sort list by RSSI or age
819        for (ScanResult result : mScanResultCache.values()) {
820
821            if (result.frequency >= LOWER_FREQ_5GHZ
822                    && result.frequency <= HIGHER_FREQ_5GHZ) {
823                // Strictly speaking: [4915, 5825]
824                // number of known BSSID on 5GHz band
825                num5 = num5 + 1;
826            } else if (result.frequency >= LOWER_FREQ_24GHZ
827                    && result.frequency <= HIGHER_FREQ_24GHZ) {
828                // Strictly speaking: [2412, 2482]
829                // number of known BSSID on 2.4Ghz band
830                num24 = num24 + 1;
831            }
832
833
834            if (result.frequency >= LOWER_FREQ_5GHZ
835                    && result.frequency <= HIGHER_FREQ_5GHZ) {
836                if (result.level > rssi5) {
837                    rssi5 = result.level;
838                }
839                if (n5 < 4) {
840                    if (scans5GHz == null) scans5GHz = new StringBuilder();
841                    scans5GHz.append(" \n{").append(result.BSSID);
842                    if (bssid != null && result.BSSID.equals(bssid)) scans5GHz.append("*");
843                    scans5GHz.append("=").append(result.frequency);
844                    scans5GHz.append(",").append(result.level);
845                    scans5GHz.append("}");
846                    n5++;
847                }
848            } else if (result.frequency >= LOWER_FREQ_24GHZ
849                    && result.frequency <= HIGHER_FREQ_24GHZ) {
850                if (result.level > rssi24) {
851                    rssi24 = result.level;
852                }
853                if (n24 < 4) {
854                    if (scans24GHz == null) scans24GHz = new StringBuilder();
855                    scans24GHz.append(" \n{").append(result.BSSID);
856                    if (bssid != null && result.BSSID.equals(bssid)) scans24GHz.append("*");
857                    scans24GHz.append("=").append(result.frequency);
858                    scans24GHz.append(",").append(result.level);
859                    scans24GHz.append("}");
860                    n24++;
861                }
862            }
863        }
864        visibility.append(" [");
865        if (num24 > 0) {
866            visibility.append("(").append(num24).append(")");
867            if (n24 <= 4) {
868                if (scans24GHz != null) {
869                    visibility.append(scans24GHz.toString());
870                }
871            } else {
872                visibility.append("max=").append(rssi24);
873                if (scans24GHz != null) {
874                    visibility.append(",").append(scans24GHz.toString());
875                }
876            }
877        }
878        visibility.append(";");
879        if (num5 > 0) {
880            visibility.append("(").append(num5).append(")");
881            if (n5 <= 4) {
882                if (scans5GHz != null) {
883                    visibility.append(scans5GHz.toString());
884                }
885            } else {
886                visibility.append("max=").append(rssi5);
887                if (scans5GHz != null) {
888                    visibility.append(",").append(scans5GHz.toString());
889                }
890            }
891        }
892        if (numBlackListed > 0)
893            visibility.append("!").append(numBlackListed);
894        visibility.append("]");
895
896        return visibility.toString();
897    }
898
899    /**
900     * Return whether this is the active connection.
901     * For ephemeral connections (networkId is invalid), this returns false if the network is
902     * disconnected.
903     */
904    public boolean isActive() {
905        return mNetworkInfo != null &&
906                (networkId != WifiConfiguration.INVALID_NETWORK_ID ||
907                 mNetworkInfo.getState() != State.DISCONNECTED);
908    }
909
910    public boolean isConnectable() {
911        return getLevel() != -1 && getDetailedState() == null;
912    }
913
914    public boolean isEphemeral() {
915        return mInfo != null && mInfo.isEphemeral() &&
916                mNetworkInfo != null && mNetworkInfo.getState() != State.DISCONNECTED;
917    }
918
919    /**
920     * Return true if this AccessPoint represents a Passpoint AP.
921     */
922    public boolean isPasspoint() {
923        return mConfig != null && mConfig.isPasspoint();
924    }
925
926    /**
927     * Return true if this AccessPoint represents a Passpoint provider configuration.
928     */
929    public boolean isPasspointConfig() {
930        return mFqdn != null;
931    }
932
933    /**
934     * Return whether the given {@link WifiInfo} is for this access point.
935     * If the current AP does not have a network Id then the config is used to
936     * match based on SSID and security.
937     */
938    private boolean isInfoForThisAccessPoint(WifiConfiguration config, WifiInfo info) {
939        if (isPasspoint() == false && networkId != WifiConfiguration.INVALID_NETWORK_ID) {
940            return networkId == info.getNetworkId();
941        } else if (config != null) {
942            return matches(config);
943        }
944        else {
945            // Might be an ephemeral connection with no WifiConfiguration. Try matching on SSID.
946            // (Note that we only do this if the WifiConfiguration explicitly equals INVALID).
947            // TODO: Handle hex string SSIDs.
948            return ssid.equals(removeDoubleQuotes(info.getSSID()));
949        }
950    }
951
952    public boolean isSaved() {
953        return networkId != WifiConfiguration.INVALID_NETWORK_ID;
954    }
955
956    public Object getTag() {
957        return mTag;
958    }
959
960    public void setTag(Object tag) {
961        mTag = tag;
962    }
963
964    /**
965     * Generate and save a default wifiConfiguration with common values.
966     * Can only be called for unsecured networks.
967     */
968    public void generateOpenNetworkConfig() {
969        if (security != SECURITY_NONE)
970            throw new IllegalStateException();
971        if (mConfig != null)
972            return;
973        mConfig = new WifiConfiguration();
974        mConfig.SSID = AccessPoint.convertToQuotedString(ssid);
975        mConfig.allowedKeyManagement.set(KeyMgmt.NONE);
976    }
977
978    void loadConfig(WifiConfiguration config) {
979        ssid = (config.SSID == null ? "" : removeDoubleQuotes(config.SSID));
980        bssid = config.BSSID;
981        security = getSecurity(config);
982        networkId = config.networkId;
983        mConfig = config;
984    }
985
986    private void initWithScanResult(ScanResult result) {
987        ssid = result.SSID;
988        bssid = result.BSSID;
989        security = getSecurity(result);
990        if (security == SECURITY_PSK)
991            pskType = getPskType(result);
992
993        mScanResultCache.put(result.BSSID, result);
994        updateRssi();
995        mSeen = result.timestamp; // even if the timestamp is old it is still valid
996    }
997
998    public void saveWifiState(Bundle savedState) {
999        if (ssid != null) savedState.putString(KEY_SSID, getSsidStr());
1000        savedState.putInt(KEY_SECURITY, security);
1001        savedState.putInt(KEY_PSKTYPE, pskType);
1002        if (mConfig != null) savedState.putParcelable(KEY_CONFIG, mConfig);
1003        savedState.putParcelable(KEY_WIFIINFO, mInfo);
1004        evictOldScanResults();
1005        savedState.putParcelableArrayList(KEY_SCANRESULTCACHE,
1006                new ArrayList<ScanResult>(mScanResultCache.values()));
1007        if (mNetworkInfo != null) {
1008            savedState.putParcelable(KEY_NETWORKINFO, mNetworkInfo);
1009        }
1010        if (mFqdn != null) {
1011            savedState.putString(KEY_FQDN, mFqdn);
1012        }
1013        if (mProviderFriendlyName != null) {
1014            savedState.putString(KEY_PROVIDER_FRIENDLY_NAME, mProviderFriendlyName);
1015        }
1016    }
1017
1018    public void setListener(AccessPointListener listener) {
1019        mAccessPointListener = listener;
1020    }
1021
1022    boolean update(ScanResult result) {
1023        if (matches(result)) {
1024            int oldLevel = getLevel();
1025
1026            /* Add or update the scan result for the BSSID */
1027            mScanResultCache.put(result.BSSID, result);
1028            updateSeen();
1029            updateRssi();
1030            int newLevel = getLevel();
1031
1032            if (newLevel > 0 && newLevel != oldLevel && mAccessPointListener != null) {
1033                mAccessPointListener.onLevelChanged(this);
1034            }
1035            // This flag only comes from scans, is not easily saved in config
1036            if (security == SECURITY_PSK) {
1037                pskType = getPskType(result);
1038            }
1039
1040            if (mAccessPointListener != null) {
1041                mAccessPointListener.onAccessPointChanged(this);
1042            }
1043
1044            return true;
1045        }
1046        return false;
1047    }
1048
1049    /** Attempt to update the AccessPoint and return true if an update occurred. */
1050    public boolean update(
1051            @Nullable WifiConfiguration config, WifiInfo info, NetworkInfo networkInfo) {
1052        boolean updated = false;
1053        final int oldLevel = getLevel();
1054        if (info != null && isInfoForThisAccessPoint(config, info)) {
1055            updated = (mInfo == null);
1056            if (mConfig != config) {
1057                // We do not set updated = true as we do not want to increase the amount of sorting
1058                // and copying performed in WifiTracker at this time. If issues involving refresh
1059                // are still seen, we will investigate further.
1060                update(config); // Notifies the AccessPointListener of the change
1061            }
1062            if (mRssi != info.getRssi()) {
1063                mRssi = info.getRssi();
1064                updated = true;
1065            } else if (mNetworkInfo != null && networkInfo != null
1066                    && mNetworkInfo.getDetailedState() != networkInfo.getDetailedState()) {
1067                updated = true;
1068            }
1069            mInfo = info;
1070            mNetworkInfo = networkInfo;
1071        } else if (mInfo != null) {
1072            updated = true;
1073            mInfo = null;
1074            mNetworkInfo = null;
1075        }
1076        if (updated && mAccessPointListener != null) {
1077            mAccessPointListener.onAccessPointChanged(this);
1078
1079            if (oldLevel != getLevel() /* current level */) {
1080                mAccessPointListener.onLevelChanged(this);
1081            }
1082        }
1083        return updated;
1084    }
1085
1086    void update(@Nullable WifiConfiguration config) {
1087        mConfig = config;
1088        networkId = config != null ? config.networkId : WifiConfiguration.INVALID_NETWORK_ID;
1089        if (mAccessPointListener != null) {
1090            mAccessPointListener.onAccessPointChanged(this);
1091        }
1092    }
1093
1094    @VisibleForTesting
1095    void setRssi(int rssi) {
1096        mRssi = rssi;
1097    }
1098
1099    /** Sets the rssi to {@link #UNREACHABLE_RSSI}. */
1100    void setUnreachable() {
1101        setRssi(AccessPoint.UNREACHABLE_RSSI);
1102    }
1103
1104    int getRankingScore() {
1105        return mRankingScore;
1106    }
1107
1108    int getSpeed() { return mSpeed;}
1109
1110    @Nullable
1111    String getSpeedLabel() {
1112        switch (mSpeed) {
1113            case Speed.VERY_FAST:
1114                return mContext.getString(R.string.speed_label_very_fast);
1115            case Speed.FAST:
1116                return mContext.getString(R.string.speed_label_fast);
1117            case Speed.MODERATE:
1118                return mContext.getString(R.string.speed_label_okay);
1119            case Speed.SLOW:
1120                return mContext.getString(R.string.speed_label_slow);
1121            case Speed.NONE:
1122            default:
1123                return null;
1124        }
1125    }
1126
1127    /** Return true if the current RSSI is reachable, and false otherwise. */
1128    public boolean isReachable() {
1129        return mRssi != UNREACHABLE_RSSI;
1130    }
1131
1132    public static String getSummary(Context context, String ssid, DetailedState state,
1133            boolean isEphemeral, String passpointProvider) {
1134        if (state == DetailedState.CONNECTED && ssid == null) {
1135            if (TextUtils.isEmpty(passpointProvider) == false) {
1136                // Special case for connected + passpoint networks.
1137                String format = context.getString(R.string.connected_via_passpoint);
1138                return String.format(format, passpointProvider);
1139            } else if (isEphemeral) {
1140                // Special case for connected + ephemeral networks.
1141                final NetworkScoreManager networkScoreManager = context.getSystemService(
1142                        NetworkScoreManager.class);
1143                NetworkScorerAppData scorer = networkScoreManager.getActiveScorer();
1144                if (scorer != null && scorer.getRecommendationServiceLabel() != null) {
1145                    String format = context.getString(R.string.connected_via_network_scorer);
1146                    return String.format(format, scorer.getRecommendationServiceLabel());
1147                } else {
1148                    return context.getString(R.string.connected_via_network_scorer_default);
1149                }
1150            }
1151        }
1152
1153        // Case when there is wifi connected without internet connectivity.
1154        final ConnectivityManager cm = (ConnectivityManager)
1155                context.getSystemService(Context.CONNECTIVITY_SERVICE);
1156        if (state == DetailedState.CONNECTED) {
1157            IWifiManager wifiManager = IWifiManager.Stub.asInterface(
1158                    ServiceManager.getService(Context.WIFI_SERVICE));
1159            NetworkCapabilities nc = null;
1160
1161            try {
1162                nc = cm.getNetworkCapabilities(wifiManager.getCurrentNetwork());
1163            } catch (RemoteException e) {}
1164
1165            if (nc != null) {
1166                if (nc.hasCapability(nc.NET_CAPABILITY_CAPTIVE_PORTAL)) {
1167                    return context.getString(
1168                        com.android.internal.R.string.network_available_sign_in);
1169                } else if (!nc.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)) {
1170                    return context.getString(R.string.wifi_connected_no_internet);
1171                }
1172            }
1173        }
1174        if (state == null) {
1175            Log.w(TAG, "state is null, returning empty summary");
1176            return "";
1177        }
1178        String[] formats = context.getResources().getStringArray((ssid == null)
1179                ? R.array.wifi_status : R.array.wifi_status_with_ssid);
1180        int index = state.ordinal();
1181
1182        if (index >= formats.length || formats[index].length() == 0) {
1183            return "";
1184        }
1185        return String.format(formats[index], ssid);
1186    }
1187
1188    public static String getSummary(Context context, DetailedState state, boolean isEphemeral) {
1189        return getSummary(context, null, state, isEphemeral, null);
1190    }
1191
1192    public static String getSummary(Context context, DetailedState state, boolean isEphemeral,
1193            String passpointProvider) {
1194        return getSummary(context, null, state, isEphemeral, passpointProvider);
1195    }
1196
1197    public static String convertToQuotedString(String string) {
1198        return "\"" + string + "\"";
1199    }
1200
1201    private static int getPskType(ScanResult result) {
1202        boolean wpa = result.capabilities.contains("WPA-PSK");
1203        boolean wpa2 = result.capabilities.contains("WPA2-PSK");
1204        if (wpa2 && wpa) {
1205            return PSK_WPA_WPA2;
1206        } else if (wpa2) {
1207            return PSK_WPA2;
1208        } else if (wpa) {
1209            return PSK_WPA;
1210        } else {
1211            Log.w(TAG, "Received abnormal flag string: " + result.capabilities);
1212            return PSK_UNKNOWN;
1213        }
1214    }
1215
1216    private static int getSecurity(ScanResult result) {
1217        if (result.capabilities.contains("WEP")) {
1218            return SECURITY_WEP;
1219        } else if (result.capabilities.contains("PSK")) {
1220            return SECURITY_PSK;
1221        } else if (result.capabilities.contains("EAP")) {
1222            return SECURITY_EAP;
1223        }
1224        return SECURITY_NONE;
1225    }
1226
1227    static int getSecurity(WifiConfiguration config) {
1228        if (config.allowedKeyManagement.get(KeyMgmt.WPA_PSK)) {
1229            return SECURITY_PSK;
1230        }
1231        if (config.allowedKeyManagement.get(KeyMgmt.WPA_EAP) ||
1232                config.allowedKeyManagement.get(KeyMgmt.IEEE8021X)) {
1233            return SECURITY_EAP;
1234        }
1235        return (config.wepKeys[0] != null) ? SECURITY_WEP : SECURITY_NONE;
1236    }
1237
1238    public static String securityToString(int security, int pskType) {
1239        if (security == SECURITY_WEP) {
1240            return "WEP";
1241        } else if (security == SECURITY_PSK) {
1242            if (pskType == PSK_WPA) {
1243                return "WPA";
1244            } else if (pskType == PSK_WPA2) {
1245                return "WPA2";
1246            } else if (pskType == PSK_WPA_WPA2) {
1247                return "WPA_WPA2";
1248            }
1249            return "PSK";
1250        } else if (security == SECURITY_EAP) {
1251            return "EAP";
1252        }
1253        return "NONE";
1254    }
1255
1256    static String removeDoubleQuotes(String string) {
1257        if (TextUtils.isEmpty(string)) {
1258            return "";
1259        }
1260        int length = string.length();
1261        if ((length > 1) && (string.charAt(0) == '"')
1262                && (string.charAt(length - 1) == '"')) {
1263            return string.substring(1, length - 1);
1264        }
1265        return string;
1266    }
1267
1268    public interface AccessPointListener {
1269        void onAccessPointChanged(AccessPoint accessPoint);
1270        void onLevelChanged(AccessPoint accessPoint);
1271    }
1272}
1273