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