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