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