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