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