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