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