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