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