AccessPoint.java revision 53200edba1bee7fe6dc3f567fb92876780881ac2
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        // Sort by ssid.
324        return getSsidStr().compareToIgnoreCase(other.getSsidStr());
325    }
326
327    @Override
328    public boolean equals(Object other) {
329        if (!(other instanceof AccessPoint)) return false;
330        return (this.compareTo((AccessPoint) other) == 0);
331    }
332
333    @Override
334    public int hashCode() {
335        int result = 0;
336        if (mInfo != null) result += 13 * mInfo.hashCode();
337        result += 19 * mRssi;
338        result += 23 * networkId;
339        result += 29 * ssid.hashCode();
340        return result;
341    }
342
343    @Override
344    public String toString() {
345        StringBuilder builder = new StringBuilder().append("AccessPoint(")
346                .append(ssid);
347        if (bssid != null) {
348            builder.append(":").append(bssid);
349        }
350        if (isSaved()) {
351            builder.append(',').append("saved");
352        }
353        if (isActive()) {
354            builder.append(',').append("active");
355        }
356        if (isEphemeral()) {
357            builder.append(',').append("ephemeral");
358        }
359        if (isConnectable()) {
360            builder.append(',').append("connectable");
361        }
362        if (security != SECURITY_NONE) {
363            builder.append(',').append(securityToString(security, pskType));
364        }
365        builder.append(",level=").append(getLevel());
366        if (mRankingScore != Integer.MIN_VALUE) {
367            builder.append(",rankingScore=").append(mRankingScore);
368        }
369        if (mSpeed != Speed.NONE) {
370            builder.append(",speed=").append(mSpeed);
371        }
372        builder.append(",metered=").append(isMetered());
373
374        return builder.append(')').toString();
375    }
376
377    /**
378     * Updates the AccessPoint rankingScore, metering, and speed, returning true if the data has
379     * changed.
380     *
381     * @param scoreCache The score cache to use to retrieve scores.
382     * @param scoringUiEnabled Whether to show scoring and badging UI.
383     */
384    boolean update(WifiNetworkScoreCache scoreCache, boolean scoringUiEnabled) {
385        boolean scoreChanged = false;
386        if (scoringUiEnabled) {
387            scoreChanged = updateScores(scoreCache);
388        }
389        return updateMetered(scoreCache) || scoreChanged;
390    }
391
392    /**
393     * Updates the AccessPoint rankingScore and speed, returning true if the data has changed.
394     *
395     * @param scoreCache The score cache to use to retrieve scores.
396     */
397    private boolean updateScores(WifiNetworkScoreCache scoreCache) {
398        int oldSpeed = mSpeed;
399        int oldRankingScore = mRankingScore;
400        mSpeed = Speed.NONE;
401        mRankingScore = Integer.MIN_VALUE;
402
403        for (ScanResult result : mScanResultCache.values()) {
404            ScoredNetwork score = scoreCache.getScoredNetwork(result);
405            if (score == null) {
406                continue;
407            }
408
409            if (score.hasRankingScore()) {
410                mRankingScore = Math.max(mRankingScore, score.calculateRankingScore(result.level));
411            }
412            // TODO(sghuman): Rename calculateBadge API
413            mSpeed = Math.max(mSpeed, score.calculateBadge(result.level));
414        }
415
416        return (oldSpeed != mSpeed || oldRankingScore != mRankingScore);
417    }
418
419    /**
420     * Updates the AccessPoint's metering based on {@link ScoredNetwork#meteredHint}, returning
421     * true if the metering changed.
422     */
423    private boolean updateMetered(WifiNetworkScoreCache scoreCache) {
424        boolean oldMetering = mIsScoredNetworkMetered;
425        mIsScoredNetworkMetered = false;
426        for (ScanResult result : mScanResultCache.values()) {
427            ScoredNetwork score = scoreCache.getScoredNetwork(result);
428            if (score == null) {
429                continue;
430            }
431            mIsScoredNetworkMetered |= score.meteredHint;
432        }
433        return oldMetering == mIsScoredNetworkMetered;
434    }
435
436    private void evictOldScanResults() {
437        long nowMs = SystemClock.elapsedRealtime();
438        for (Iterator<ScanResult> iter = mScanResultCache.values().iterator(); iter.hasNext(); ) {
439            ScanResult result = iter.next();
440            // result timestamp is in microseconds
441            if (nowMs - result.timestamp / 1000 > MAX_SCAN_RESULT_AGE_MS) {
442                iter.remove();
443            }
444        }
445    }
446
447    public boolean matches(ScanResult result) {
448        return ssid.equals(result.SSID) && security == getSecurity(result);
449    }
450
451    public boolean matches(WifiConfiguration config) {
452        if (config.isPasspoint() && mConfig != null && mConfig.isPasspoint()) {
453            return ssid.equals(removeDoubleQuotes(config.SSID)) && config.FQDN.equals(mConfig.FQDN);
454        } else {
455            return ssid.equals(removeDoubleQuotes(config.SSID))
456                    && security == getSecurity(config)
457                    && (mConfig == null || mConfig.shared == config.shared);
458        }
459    }
460
461    public WifiConfiguration getConfig() {
462        return mConfig;
463    }
464
465    public String getPasspointFqdn() {
466        return mFqdn;
467    }
468
469    public void clearConfig() {
470        mConfig = null;
471        networkId = WifiConfiguration.INVALID_NETWORK_ID;
472    }
473
474    public WifiInfo getInfo() {
475        return mInfo;
476    }
477
478    /**
479     * Returns the number of levels to show for a Wifi icon, from 0 to {@link #SIGNAL_LEVELS}-1.
480     *
481     * <p>Use {@#isReachable()} to determine if an AccessPoint is in range, as this method will
482     * always return at least 0.
483     */
484    public int getLevel() {
485        return WifiManager.calculateSignalLevel(mRssi, SIGNAL_LEVELS);
486    }
487
488    public int getRssi() {
489        return mRssi;
490    }
491
492    /**
493     * Updates {@link #mRssi}.
494     *
495     * <p>If the given connection is active, the existing value of {@link #mRssi} will be returned.
496     * If the given AccessPoint is not active, a value will be calculated from previous scan
497     * results, returning the best RSSI for all matching AccessPoints averaged with the previous
498     * value. If the access point is not connected and there are no scan results, the rssi will be
499     * set to {@link #UNREACHABLE_RSSI}.
500     *
501     * <p>Old scan results will be evicted from the cache when this method is invoked.
502     */
503    private void updateRssi() {
504        evictOldScanResults();
505
506        if (this.isActive()) {
507            return;
508        }
509
510        int rssi = UNREACHABLE_RSSI;
511        for (ScanResult result : mScanResultCache.values()) {
512            if (result.level > rssi) {
513                rssi = result.level;
514            }
515        }
516
517        if (rssi != UNREACHABLE_RSSI && mRssi != UNREACHABLE_RSSI) {
518            mRssi = (mRssi + rssi) / 2; // half-life previous value
519        } else {
520            mRssi = rssi;
521        }
522    }
523
524    /**
525     * Updates {@link #mSeen} based on the scan result cache.
526     *
527     * <p>Old scan results will be evicted from the cache when this method is invoked.
528     */
529    private void updateSeen() {
530        evictOldScanResults();
531
532        // TODO(sghuman): Set to now if connected
533
534        long seen = 0;
535        for (ScanResult result : mScanResultCache.values()) {
536            if (result.timestamp > seen) {
537                seen = result.timestamp;
538            }
539        }
540
541        // Only replace the previous value if we have a recent scan result to use
542        if (seen != 0) {
543            mSeen = seen;
544        }
545    }
546
547    /**
548     * Returns if the network is marked metered. Metering can be marked through its config in
549     * {@link WifiConfiguration}, after connection in {@link WifiInfo}, or from a score config in
550     * {@link ScoredNetwork}.
551     */
552    public boolean isMetered() {
553        return mIsScoredNetworkMetered
554                || (mConfig != null && mConfig.meteredHint)
555                || (mInfo != null && mInfo.getMeteredHint()
556                || (mNetworkInfo != null && mNetworkInfo.isMetered()));
557    }
558
559    public NetworkInfo getNetworkInfo() {
560        return mNetworkInfo;
561    }
562
563    public int getSecurity() {
564        return security;
565    }
566
567    public String getSecurityString(boolean concise) {
568        Context context = mContext;
569        if (mConfig != null && mConfig.isPasspoint()) {
570            return concise ? context.getString(R.string.wifi_security_short_eap) :
571                context.getString(R.string.wifi_security_eap);
572        }
573        switch(security) {
574            case SECURITY_EAP:
575                return concise ? context.getString(R.string.wifi_security_short_eap) :
576                    context.getString(R.string.wifi_security_eap);
577            case SECURITY_PSK:
578                switch (pskType) {
579                    case PSK_WPA:
580                        return concise ? context.getString(R.string.wifi_security_short_wpa) :
581                            context.getString(R.string.wifi_security_wpa);
582                    case PSK_WPA2:
583                        return concise ? context.getString(R.string.wifi_security_short_wpa2) :
584                            context.getString(R.string.wifi_security_wpa2);
585                    case PSK_WPA_WPA2:
586                        return concise ? context.getString(R.string.wifi_security_short_wpa_wpa2) :
587                            context.getString(R.string.wifi_security_wpa_wpa2);
588                    case PSK_UNKNOWN:
589                    default:
590                        return concise ? context.getString(R.string.wifi_security_short_psk_generic)
591                                : context.getString(R.string.wifi_security_psk_generic);
592                }
593            case SECURITY_WEP:
594                return concise ? context.getString(R.string.wifi_security_short_wep) :
595                    context.getString(R.string.wifi_security_wep);
596            case SECURITY_NONE:
597            default:
598                return concise ? "" : context.getString(R.string.wifi_security_none);
599        }
600    }
601
602    public String getSsidStr() {
603        return ssid;
604    }
605
606    public String getBssid() {
607        return bssid;
608    }
609
610    public CharSequence getSsid() {
611        final SpannableString str = new SpannableString(ssid);
612        str.setSpan(new TtsSpan.TelephoneBuilder(ssid).build(), 0, ssid.length(),
613                Spannable.SPAN_INCLUSIVE_INCLUSIVE);
614        return str;
615    }
616
617    public String getConfigName() {
618        if (mConfig != null && mConfig.isPasspoint()) {
619            return mConfig.providerFriendlyName;
620        } else if (mFqdn != null) {
621            return mProviderFriendlyName;
622        } else {
623            return ssid;
624        }
625    }
626
627    public DetailedState getDetailedState() {
628        if (mNetworkInfo != null) {
629            return mNetworkInfo.getDetailedState();
630        }
631        Log.w(TAG, "NetworkInfo is null, cannot return detailed state");
632        return null;
633    }
634
635    public String getSavedNetworkSummary() {
636        WifiConfiguration config = mConfig;
637        if (config != null) {
638            PackageManager pm = mContext.getPackageManager();
639            String systemName = pm.getNameForUid(android.os.Process.SYSTEM_UID);
640            int userId = UserHandle.getUserId(config.creatorUid);
641            ApplicationInfo appInfo = null;
642            if (config.creatorName != null && config.creatorName.equals(systemName)) {
643                appInfo = mContext.getApplicationInfo();
644            } else {
645                try {
646                    IPackageManager ipm = AppGlobals.getPackageManager();
647                    appInfo = ipm.getApplicationInfo(config.creatorName, 0 /* flags */, userId);
648                } catch (RemoteException rex) {
649                }
650            }
651            if (appInfo != null &&
652                    !appInfo.packageName.equals(mContext.getString(R.string.settings_package)) &&
653                    !appInfo.packageName.equals(
654                    mContext.getString(R.string.certinstaller_package))) {
655                return mContext.getString(R.string.saved_network, appInfo.loadLabel(pm));
656            }
657        }
658        return "";
659    }
660
661    public String getSummary() {
662        return getSettingsSummary(mConfig);
663    }
664
665    public String getSettingsSummary() {
666        return getSettingsSummary(mConfig);
667    }
668
669    private String getSettingsSummary(WifiConfiguration config) {
670        // Update to new summary
671        StringBuilder summary = new StringBuilder();
672
673        // TODO(b/62354743): Standardize and international delimiter usage
674        final String concatenator = " / ";
675
676        if (mSpeed != Speed.NONE) {
677            summary.append(getSpeedLabel() + concatenator);
678        }
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        // Strip trailing delimiter if applicable
764        int concatLength = concatenator.length();
765        if (summary.length() >= concatLength && summary.substring(
766                summary.length() - concatLength, summary.length()).equals(concatenator)) {
767            summary.delete(summary.length() - concatLength, summary.length());
768        }
769
770        return summary.toString();
771    }
772
773    /**
774     * Returns the visibility status of the WifiConfiguration.
775     *
776     * @return autojoin debugging information
777     * TODO: use a string formatter
778     * ["rssi 5Ghz", "num results on 5GHz" / "rssi 5Ghz", "num results on 5GHz"]
779     * For instance [-40,5/-30,2]
780     */
781    private String getVisibilityStatus() {
782        StringBuilder visibility = new StringBuilder();
783        StringBuilder scans24GHz = null;
784        StringBuilder scans5GHz = null;
785        String bssid = null;
786
787        long now = System.currentTimeMillis();
788
789        if (mInfo != null) {
790            bssid = mInfo.getBSSID();
791            if (bssid != null) {
792                visibility.append(" ").append(bssid);
793            }
794            visibility.append(" rssi=").append(mInfo.getRssi());
795            visibility.append(" ");
796            visibility.append(" score=").append(mInfo.score);
797            if (mRankingScore != Integer.MIN_VALUE) {
798                visibility.append(" rankingScore=").append(getRankingScore());
799            }
800            if (mSpeed != Speed.NONE) {
801                visibility.append(" speed=").append(getSpeedLabel());
802            }
803            visibility.append(String.format(" tx=%.1f,", mInfo.txSuccessRate));
804            visibility.append(String.format("%.1f,", mInfo.txRetriesRate));
805            visibility.append(String.format("%.1f ", mInfo.txBadRate));
806            visibility.append(String.format("rx=%.1f", mInfo.rxSuccessRate));
807        }
808
809        int rssi5 = WifiConfiguration.INVALID_RSSI;
810        int rssi24 = WifiConfiguration.INVALID_RSSI;
811        int num5 = 0;
812        int num24 = 0;
813        int numBlackListed = 0;
814        int n24 = 0; // Number scan results we included in the string
815        int n5 = 0; // Number scan results we included in the string
816        evictOldScanResults();
817        // TODO: sort list by RSSI or age
818        for (ScanResult result : mScanResultCache.values()) {
819
820            if (result.frequency >= LOWER_FREQ_5GHZ
821                    && result.frequency <= HIGHER_FREQ_5GHZ) {
822                // Strictly speaking: [4915, 5825]
823                // number of known BSSID on 5GHz band
824                num5 = num5 + 1;
825            } else if (result.frequency >= LOWER_FREQ_24GHZ
826                    && result.frequency <= HIGHER_FREQ_24GHZ) {
827                // Strictly speaking: [2412, 2482]
828                // number of known BSSID on 2.4Ghz band
829                num24 = num24 + 1;
830            }
831
832
833            if (result.frequency >= LOWER_FREQ_5GHZ
834                    && result.frequency <= HIGHER_FREQ_5GHZ) {
835                if (result.level > rssi5) {
836                    rssi5 = result.level;
837                }
838                if (n5 < 4) {
839                    if (scans5GHz == null) scans5GHz = new StringBuilder();
840                    scans5GHz.append(" \n{").append(result.BSSID);
841                    if (bssid != null && result.BSSID.equals(bssid)) scans5GHz.append("*");
842                    scans5GHz.append("=").append(result.frequency);
843                    scans5GHz.append(",").append(result.level);
844                    scans5GHz.append("}");
845                    n5++;
846                }
847            } else if (result.frequency >= LOWER_FREQ_24GHZ
848                    && result.frequency <= HIGHER_FREQ_24GHZ) {
849                if (result.level > rssi24) {
850                    rssi24 = result.level;
851                }
852                if (n24 < 4) {
853                    if (scans24GHz == null) scans24GHz = new StringBuilder();
854                    scans24GHz.append(" \n{").append(result.BSSID);
855                    if (bssid != null && result.BSSID.equals(bssid)) scans24GHz.append("*");
856                    scans24GHz.append("=").append(result.frequency);
857                    scans24GHz.append(",").append(result.level);
858                    scans24GHz.append("}");
859                    n24++;
860                }
861            }
862        }
863        visibility.append(" [");
864        if (num24 > 0) {
865            visibility.append("(").append(num24).append(")");
866            if (n24 <= 4) {
867                if (scans24GHz != null) {
868                    visibility.append(scans24GHz.toString());
869                }
870            } else {
871                visibility.append("max=").append(rssi24);
872                if (scans24GHz != null) {
873                    visibility.append(",").append(scans24GHz.toString());
874                }
875            }
876        }
877        visibility.append(";");
878        if (num5 > 0) {
879            visibility.append("(").append(num5).append(")");
880            if (n5 <= 4) {
881                if (scans5GHz != null) {
882                    visibility.append(scans5GHz.toString());
883                }
884            } else {
885                visibility.append("max=").append(rssi5);
886                if (scans5GHz != null) {
887                    visibility.append(",").append(scans5GHz.toString());
888                }
889            }
890        }
891        if (numBlackListed > 0)
892            visibility.append("!").append(numBlackListed);
893        visibility.append("]");
894
895        return visibility.toString();
896    }
897
898    /**
899     * Return whether this is the active connection.
900     * For ephemeral connections (networkId is invalid), this returns false if the network is
901     * disconnected.
902     */
903    public boolean isActive() {
904        return mNetworkInfo != null &&
905                (networkId != WifiConfiguration.INVALID_NETWORK_ID ||
906                 mNetworkInfo.getState() != State.DISCONNECTED);
907    }
908
909    public boolean isConnectable() {
910        return getLevel() != -1 && getDetailedState() == null;
911    }
912
913    public boolean isEphemeral() {
914        return mInfo != null && mInfo.isEphemeral() &&
915                mNetworkInfo != null && mNetworkInfo.getState() != State.DISCONNECTED;
916    }
917
918    /**
919     * Return true if this AccessPoint represents a Passpoint AP.
920     */
921    public boolean isPasspoint() {
922        return mConfig != null && mConfig.isPasspoint();
923    }
924
925    /**
926     * Return true if this AccessPoint represents a Passpoint provider configuration.
927     */
928    public boolean isPasspointConfig() {
929        return mFqdn != null;
930    }
931
932    /**
933     * Return whether the given {@link WifiInfo} is for this access point.
934     * If the current AP does not have a network Id then the config is used to
935     * match based on SSID and security.
936     */
937    private boolean isInfoForThisAccessPoint(WifiConfiguration config, WifiInfo info) {
938        if (isPasspoint() == false && networkId != WifiConfiguration.INVALID_NETWORK_ID) {
939            return networkId == info.getNetworkId();
940        } else if (config != null) {
941            return matches(config);
942        }
943        else {
944            // Might be an ephemeral connection with no WifiConfiguration. Try matching on SSID.
945            // (Note that we only do this if the WifiConfiguration explicitly equals INVALID).
946            // TODO: Handle hex string SSIDs.
947            return ssid.equals(removeDoubleQuotes(info.getSSID()));
948        }
949    }
950
951    public boolean isSaved() {
952        return networkId != WifiConfiguration.INVALID_NETWORK_ID;
953    }
954
955    public Object getTag() {
956        return mTag;
957    }
958
959    public void setTag(Object tag) {
960        mTag = tag;
961    }
962
963    /**
964     * Generate and save a default wifiConfiguration with common values.
965     * Can only be called for unsecured networks.
966     */
967    public void generateOpenNetworkConfig() {
968        if (security != SECURITY_NONE)
969            throw new IllegalStateException();
970        if (mConfig != null)
971            return;
972        mConfig = new WifiConfiguration();
973        mConfig.SSID = AccessPoint.convertToQuotedString(ssid);
974        mConfig.allowedKeyManagement.set(KeyMgmt.NONE);
975    }
976
977    void loadConfig(WifiConfiguration config) {
978        ssid = (config.SSID == null ? "" : removeDoubleQuotes(config.SSID));
979        bssid = config.BSSID;
980        security = getSecurity(config);
981        networkId = config.networkId;
982        mConfig = config;
983    }
984
985    private void initWithScanResult(ScanResult result) {
986        ssid = result.SSID;
987        bssid = result.BSSID;
988        security = getSecurity(result);
989        if (security == SECURITY_PSK)
990            pskType = getPskType(result);
991
992        mScanResultCache.put(result.BSSID, result);
993        updateRssi();
994        mSeen = result.timestamp; // even if the timestamp is old it is still valid
995    }
996
997    public void saveWifiState(Bundle savedState) {
998        if (ssid != null) savedState.putString(KEY_SSID, getSsidStr());
999        savedState.putInt(KEY_SECURITY, security);
1000        savedState.putInt(KEY_PSKTYPE, pskType);
1001        if (mConfig != null) savedState.putParcelable(KEY_CONFIG, mConfig);
1002        savedState.putParcelable(KEY_WIFIINFO, mInfo);
1003        evictOldScanResults();
1004        savedState.putParcelableArrayList(KEY_SCANRESULTCACHE,
1005                new ArrayList<ScanResult>(mScanResultCache.values()));
1006        if (mNetworkInfo != null) {
1007            savedState.putParcelable(KEY_NETWORKINFO, mNetworkInfo);
1008        }
1009        if (mFqdn != null) {
1010            savedState.putString(KEY_FQDN, mFqdn);
1011        }
1012        if (mProviderFriendlyName != null) {
1013            savedState.putString(KEY_PROVIDER_FRIENDLY_NAME, mProviderFriendlyName);
1014        }
1015    }
1016
1017    public void setListener(AccessPointListener listener) {
1018        mAccessPointListener = listener;
1019    }
1020
1021    boolean update(ScanResult result) {
1022        if (matches(result)) {
1023            int oldLevel = getLevel();
1024
1025            /* Add or update the scan result for the BSSID */
1026            mScanResultCache.put(result.BSSID, result);
1027            updateSeen();
1028            updateRssi();
1029            int newLevel = getLevel();
1030
1031            if (newLevel > 0 && newLevel != oldLevel && mAccessPointListener != null) {
1032                mAccessPointListener.onLevelChanged(this);
1033            }
1034            // This flag only comes from scans, is not easily saved in config
1035            if (security == SECURITY_PSK) {
1036                pskType = getPskType(result);
1037            }
1038
1039            if (mAccessPointListener != null) {
1040                mAccessPointListener.onAccessPointChanged(this);
1041            }
1042
1043            return true;
1044        }
1045        return false;
1046    }
1047
1048    /** Attempt to update the AccessPoint and return true if an update occurred. */
1049    public boolean update(WifiConfiguration config, WifiInfo info, NetworkInfo networkInfo) {
1050        boolean updated = false;
1051        final int oldLevel = getLevel();
1052        if (info != null && isInfoForThisAccessPoint(config, info)) {
1053            updated = (mInfo == null);
1054            if (mRssi != info.getRssi()) {
1055                mRssi = info.getRssi();
1056                updated = true;
1057            } else if (mNetworkInfo != null && networkInfo != null
1058                    && mNetworkInfo.getDetailedState() != networkInfo.getDetailedState()) {
1059                updated = true;
1060            }
1061            mInfo = info;
1062            mNetworkInfo = networkInfo;
1063        } else if (mInfo != null) {
1064            updated = true;
1065            mInfo = null;
1066            mNetworkInfo = null;
1067        }
1068        if (updated && mAccessPointListener != null) {
1069            mAccessPointListener.onAccessPointChanged(this);
1070
1071            if (oldLevel != getLevel() /* current level */) {
1072                mAccessPointListener.onLevelChanged(this);
1073            }
1074        }
1075        return updated;
1076    }
1077
1078    void update(WifiConfiguration config) {
1079        mConfig = config;
1080        networkId = config.networkId;
1081        if (mAccessPointListener != null) {
1082            mAccessPointListener.onAccessPointChanged(this);
1083        }
1084    }
1085
1086    @VisibleForTesting
1087    void setRssi(int rssi) {
1088        mRssi = rssi;
1089    }
1090
1091    /** Sets the rssi to {@link #UNREACHABLE_RSSI}. */
1092    void setUnreachable() {
1093        setRssi(AccessPoint.UNREACHABLE_RSSI);
1094    }
1095
1096    int getRankingScore() {
1097        return mRankingScore;
1098    }
1099
1100    int getSpeed() { return mSpeed;}
1101
1102    @Nullable
1103    String getSpeedLabel() {
1104        switch (mSpeed) {
1105            case Speed.VERY_FAST:
1106                return mContext.getString(R.string.speed_label_very_fast);
1107            case Speed.FAST:
1108                return mContext.getString(R.string.speed_label_fast);
1109            case Speed.MODERATE:
1110                return mContext.getString(R.string.speed_label_okay);
1111            case Speed.SLOW:
1112                return mContext.getString(R.string.speed_label_slow);
1113            case Speed.NONE:
1114            default:
1115                return null;
1116        }
1117    }
1118
1119    /** Return true if the current RSSI is reachable, and false otherwise. */
1120    public boolean isReachable() {
1121        return mRssi != UNREACHABLE_RSSI;
1122    }
1123
1124    public static String getSummary(Context context, String ssid, DetailedState state,
1125            boolean isEphemeral, String passpointProvider) {
1126        if (state == DetailedState.CONNECTED && ssid == null) {
1127            if (TextUtils.isEmpty(passpointProvider) == false) {
1128                // Special case for connected + passpoint networks.
1129                String format = context.getString(R.string.connected_via_passpoint);
1130                return String.format(format, passpointProvider);
1131            } else if (isEphemeral) {
1132                // Special case for connected + ephemeral networks.
1133                final NetworkScoreManager networkScoreManager = context.getSystemService(
1134                        NetworkScoreManager.class);
1135                NetworkScorerAppData scorer = networkScoreManager.getActiveScorer();
1136                if (scorer != null && scorer.getRecommendationServiceLabel() != null) {
1137                    String format = context.getString(R.string.connected_via_network_scorer);
1138                    return String.format(format, scorer.getRecommendationServiceLabel());
1139                } else {
1140                    return context.getString(R.string.connected_via_network_scorer_default);
1141                }
1142            }
1143        }
1144
1145        // Case when there is wifi connected without internet connectivity.
1146        final ConnectivityManager cm = (ConnectivityManager)
1147                context.getSystemService(Context.CONNECTIVITY_SERVICE);
1148        if (state == DetailedState.CONNECTED) {
1149            IWifiManager wifiManager = IWifiManager.Stub.asInterface(
1150                    ServiceManager.getService(Context.WIFI_SERVICE));
1151            NetworkCapabilities nc = null;
1152
1153            try {
1154                nc = cm.getNetworkCapabilities(wifiManager.getCurrentNetwork());
1155            } catch (RemoteException e) {}
1156
1157            if (nc != null) {
1158                if (nc.hasCapability(nc.NET_CAPABILITY_CAPTIVE_PORTAL)) {
1159                    return context.getString(
1160                        com.android.internal.R.string.network_available_sign_in);
1161                } else if (!nc.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)) {
1162                    return context.getString(R.string.wifi_connected_no_internet);
1163                }
1164            }
1165        }
1166        if (state == null) {
1167            Log.w(TAG, "state is null, returning empty summary");
1168            return "";
1169        }
1170        String[] formats = context.getResources().getStringArray((ssid == null)
1171                ? R.array.wifi_status : R.array.wifi_status_with_ssid);
1172        int index = state.ordinal();
1173
1174        if (index >= formats.length || formats[index].length() == 0) {
1175            return "";
1176        }
1177        return String.format(formats[index], ssid);
1178    }
1179
1180    public static String getSummary(Context context, DetailedState state, boolean isEphemeral) {
1181        return getSummary(context, null, state, isEphemeral, null);
1182    }
1183
1184    public static String getSummary(Context context, DetailedState state, boolean isEphemeral,
1185            String passpointProvider) {
1186        return getSummary(context, null, state, isEphemeral, passpointProvider);
1187    }
1188
1189    public static String convertToQuotedString(String string) {
1190        return "\"" + string + "\"";
1191    }
1192
1193    private static int getPskType(ScanResult result) {
1194        boolean wpa = result.capabilities.contains("WPA-PSK");
1195        boolean wpa2 = result.capabilities.contains("WPA2-PSK");
1196        if (wpa2 && wpa) {
1197            return PSK_WPA_WPA2;
1198        } else if (wpa2) {
1199            return PSK_WPA2;
1200        } else if (wpa) {
1201            return PSK_WPA;
1202        } else {
1203            Log.w(TAG, "Received abnormal flag string: " + result.capabilities);
1204            return PSK_UNKNOWN;
1205        }
1206    }
1207
1208    private static int getSecurity(ScanResult result) {
1209        if (result.capabilities.contains("WEP")) {
1210            return SECURITY_WEP;
1211        } else if (result.capabilities.contains("PSK")) {
1212            return SECURITY_PSK;
1213        } else if (result.capabilities.contains("EAP")) {
1214            return SECURITY_EAP;
1215        }
1216        return SECURITY_NONE;
1217    }
1218
1219    static int getSecurity(WifiConfiguration config) {
1220        if (config.allowedKeyManagement.get(KeyMgmt.WPA_PSK)) {
1221            return SECURITY_PSK;
1222        }
1223        if (config.allowedKeyManagement.get(KeyMgmt.WPA_EAP) ||
1224                config.allowedKeyManagement.get(KeyMgmt.IEEE8021X)) {
1225            return SECURITY_EAP;
1226        }
1227        return (config.wepKeys[0] != null) ? SECURITY_WEP : SECURITY_NONE;
1228    }
1229
1230    public static String securityToString(int security, int pskType) {
1231        if (security == SECURITY_WEP) {
1232            return "WEP";
1233        } else if (security == SECURITY_PSK) {
1234            if (pskType == PSK_WPA) {
1235                return "WPA";
1236            } else if (pskType == PSK_WPA2) {
1237                return "WPA2";
1238            } else if (pskType == PSK_WPA_WPA2) {
1239                return "WPA_WPA2";
1240            }
1241            return "PSK";
1242        } else if (security == SECURITY_EAP) {
1243            return "EAP";
1244        }
1245        return "NONE";
1246    }
1247
1248    static String removeDoubleQuotes(String string) {
1249        if (TextUtils.isEmpty(string)) {
1250            return "";
1251        }
1252        int length = string.length();
1253        if ((length > 1) && (string.charAt(0) == '"')
1254                && (string.charAt(length - 1) == '"')) {
1255            return string.substring(1, length - 1);
1256        }
1257        return string;
1258    }
1259
1260    public interface AccessPointListener {
1261        void onAccessPointChanged(AccessPoint accessPoint);
1262        void onLevelChanged(AccessPoint accessPoint);
1263    }
1264}
1265