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