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