AccessPoint.java revision 699deaf6103d182dbd291ca2b420f30b439753d4
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            String format = mContext.getString(R.string.available_via_passpoint);
506            summary.append(String.format(format, config.providerFriendlyName));
507        } else if (config != null && config.hasNoInternetAccess()) {
508            int messageID = config.getNetworkSelectionStatus().isNetworkPermanentlyDisabled()
509                    ? R.string.wifi_no_internet_no_reconnect
510                    : R.string.wifi_no_internet;
511            summary.append(mContext.getString(messageID));
512        } else if (config != null && !config.getNetworkSelectionStatus().isNetworkEnabled()) {
513            WifiConfiguration.NetworkSelectionStatus networkStatus =
514                    config.getNetworkSelectionStatus();
515            switch (networkStatus.getNetworkSelectionDisableReason()) {
516                case WifiConfiguration.NetworkSelectionStatus.DISABLED_AUTHENTICATION_FAILURE:
517                    summary.append(mContext.getString(R.string.wifi_disabled_password_failure));
518                    break;
519                case WifiConfiguration.NetworkSelectionStatus.DISABLED_DHCP_FAILURE:
520                case WifiConfiguration.NetworkSelectionStatus.DISABLED_DNS_FAILURE:
521                    summary.append(mContext.getString(R.string.wifi_disabled_network_failure));
522                    break;
523                case WifiConfiguration.NetworkSelectionStatus.DISABLED_ASSOCIATION_REJECTION:
524                    summary.append(mContext.getString(R.string.wifi_disabled_generic));
525                    break;
526            }
527        } else if (mRssi == Integer.MAX_VALUE) { // Wifi out of range
528            summary.append(mContext.getString(R.string.wifi_not_in_range));
529        } else { // In range, not disabled.
530            if (config != null) { // Is saved network
531                summary.append(mContext.getString(R.string.wifi_remembered));
532            }
533        }
534
535        if (WifiTracker.sVerboseLogging > 0) {
536            // Add RSSI/band information for this config, what was seen up to 6 seconds ago
537            // verbose WiFi Logging is only turned on thru developers settings
538            if (mInfo != null && mNetworkInfo != null) { // This is the active connection
539                summary.append(" f=" + Integer.toString(mInfo.getFrequency()));
540            }
541            summary.append(" " + getVisibilityStatus());
542            if (config != null && !config.getNetworkSelectionStatus().isNetworkEnabled()) {
543                summary.append(" (" + config.getNetworkSelectionStatus().getNetworkStatusString());
544                if (config.getNetworkSelectionStatus().getDisableTime() > 0) {
545                    long now = System.currentTimeMillis();
546                    long diff = (now - config.getNetworkSelectionStatus().getDisableTime()) / 1000;
547                    long sec = diff%60; //seconds
548                    long min = (diff/60)%60; //minutes
549                    long hour = (min/60)%60; //hours
550                    summary.append(", ");
551                    if (hour > 0) summary.append(Long.toString(hour) + "h ");
552                    summary.append( Long.toString(min) + "m ");
553                    summary.append( Long.toString(sec) + "s ");
554                }
555                summary.append(")");
556            }
557
558            if (config != null) {
559                WifiConfiguration.NetworkSelectionStatus networkStatus =
560                        config.getNetworkSelectionStatus();
561                for (int index = WifiConfiguration.NetworkSelectionStatus.NETWORK_SELECTION_ENABLE;
562                        index < WifiConfiguration.NetworkSelectionStatus
563                        .NETWORK_SELECTION_DISABLED_MAX; index++) {
564                    if (networkStatus.getDisableReasonCounter(index) != 0) {
565                        summary.append(" " + WifiConfiguration.NetworkSelectionStatus
566                                .getNetworkDisableReasonString(index) + "="
567                                + networkStatus.getDisableReasonCounter(index));
568                    }
569                }
570            }
571        }
572        return summary.toString();
573    }
574
575    /**
576     * Returns the visibility status of the WifiConfiguration.
577     *
578     * @return autojoin debugging information
579     * TODO: use a string formatter
580     * ["rssi 5Ghz", "num results on 5GHz" / "rssi 5Ghz", "num results on 5GHz"]
581     * For instance [-40,5/-30,2]
582     */
583    private String getVisibilityStatus() {
584        StringBuilder visibility = new StringBuilder();
585        StringBuilder scans24GHz = null;
586        StringBuilder scans5GHz = null;
587        String bssid = null;
588
589        long now = System.currentTimeMillis();
590
591        if (mInfo != null) {
592            bssid = mInfo.getBSSID();
593            if (bssid != null) {
594                visibility.append(" ").append(bssid);
595            }
596            visibility.append(" rssi=").append(mInfo.getRssi());
597            visibility.append(" ");
598            visibility.append(" score=").append(mInfo.score);
599            visibility.append(" rankingScore=").append(getRankingScore());
600            visibility.append(" badge=").append(getBadge());
601            visibility.append(String.format(" tx=%.1f,", mInfo.txSuccessRate));
602            visibility.append(String.format("%.1f,", mInfo.txRetriesRate));
603            visibility.append(String.format("%.1f ", mInfo.txBadRate));
604            visibility.append(String.format("rx=%.1f", mInfo.rxSuccessRate));
605        }
606
607        int rssi5 = WifiConfiguration.INVALID_RSSI;
608        int rssi24 = WifiConfiguration.INVALID_RSSI;
609        int num5 = 0;
610        int num24 = 0;
611        int numBlackListed = 0;
612        int n24 = 0; // Number scan results we included in the string
613        int n5 = 0; // Number scan results we included in the string
614        evictOldScanResults();
615        // TODO: sort list by RSSI or age
616        for (ScanResult result : mScanResultCache.values()) {
617
618            if (result.frequency >= LOWER_FREQ_5GHZ
619                    && result.frequency <= HIGHER_FREQ_5GHZ) {
620                // Strictly speaking: [4915, 5825]
621                // number of known BSSID on 5GHz band
622                num5 = num5 + 1;
623            } else if (result.frequency >= LOWER_FREQ_24GHZ
624                    && result.frequency <= HIGHER_FREQ_24GHZ) {
625                // Strictly speaking: [2412, 2482]
626                // number of known BSSID on 2.4Ghz band
627                num24 = num24 + 1;
628            }
629
630
631            if (result.frequency >= LOWER_FREQ_5GHZ
632                    && result.frequency <= HIGHER_FREQ_5GHZ) {
633                if (result.level > rssi5) {
634                    rssi5 = result.level;
635                }
636                if (n5 < 4) {
637                    if (scans5GHz == null) scans5GHz = new StringBuilder();
638                    scans5GHz.append(" \n{").append(result.BSSID);
639                    if (bssid != null && result.BSSID.equals(bssid)) scans5GHz.append("*");
640                    scans5GHz.append("=").append(result.frequency);
641                    scans5GHz.append(",").append(result.level);
642                    scans5GHz.append("}");
643                    n5++;
644                }
645            } else if (result.frequency >= LOWER_FREQ_24GHZ
646                    && result.frequency <= HIGHER_FREQ_24GHZ) {
647                if (result.level > rssi24) {
648                    rssi24 = result.level;
649                }
650                if (n24 < 4) {
651                    if (scans24GHz == null) scans24GHz = new StringBuilder();
652                    scans24GHz.append(" \n{").append(result.BSSID);
653                    if (bssid != null && result.BSSID.equals(bssid)) scans24GHz.append("*");
654                    scans24GHz.append("=").append(result.frequency);
655                    scans24GHz.append(",").append(result.level);
656                    scans24GHz.append("}");
657                    n24++;
658                }
659            }
660        }
661        visibility.append(" [");
662        if (num24 > 0) {
663            visibility.append("(").append(num24).append(")");
664            if (n24 <= 4) {
665                if (scans24GHz != null) {
666                    visibility.append(scans24GHz.toString());
667                }
668            } else {
669                visibility.append("max=").append(rssi24);
670                if (scans24GHz != null) {
671                    visibility.append(",").append(scans24GHz.toString());
672                }
673            }
674        }
675        visibility.append(";");
676        if (num5 > 0) {
677            visibility.append("(").append(num5).append(")");
678            if (n5 <= 4) {
679                if (scans5GHz != null) {
680                    visibility.append(scans5GHz.toString());
681                }
682            } else {
683                visibility.append("max=").append(rssi5);
684                if (scans5GHz != null) {
685                    visibility.append(",").append(scans5GHz.toString());
686                }
687            }
688        }
689        if (numBlackListed > 0)
690            visibility.append("!").append(numBlackListed);
691        visibility.append("]");
692
693        return visibility.toString();
694    }
695
696    /**
697     * Return whether this is the active connection.
698     * For ephemeral connections (networkId is invalid), this returns false if the network is
699     * disconnected.
700     */
701    public boolean isActive() {
702        return mNetworkInfo != null &&
703                (networkId != WifiConfiguration.INVALID_NETWORK_ID ||
704                 mNetworkInfo.getState() != State.DISCONNECTED);
705    }
706
707    public boolean isConnectable() {
708        return getLevel() != -1 && getDetailedState() == null;
709    }
710
711    public boolean isEphemeral() {
712        return mInfo != null && mInfo.isEphemeral() &&
713                mNetworkInfo != null && mNetworkInfo.getState() != State.DISCONNECTED;
714    }
715
716    public boolean isPasspoint() {
717        return mConfig != null && mConfig.isPasspoint();
718    }
719
720    /**
721     * Return whether the given {@link WifiInfo} is for this access point.
722     * If the current AP does not have a network Id then the config is used to
723     * match based on SSID and security.
724     */
725    private boolean isInfoForThisAccessPoint(WifiConfiguration config, WifiInfo info) {
726        if (isPasspoint() == false && networkId != WifiConfiguration.INVALID_NETWORK_ID) {
727            return networkId == info.getNetworkId();
728        } else if (config != null) {
729            return matches(config);
730        }
731        else {
732            // Might be an ephemeral connection with no WifiConfiguration. Try matching on SSID.
733            // (Note that we only do this if the WifiConfiguration explicitly equals INVALID).
734            // TODO: Handle hex string SSIDs.
735            return ssid.equals(removeDoubleQuotes(info.getSSID()));
736        }
737    }
738
739    public boolean isSaved() {
740        return networkId != WifiConfiguration.INVALID_NETWORK_ID;
741    }
742
743    public Object getTag() {
744        return mTag;
745    }
746
747    public void setTag(Object tag) {
748        mTag = tag;
749    }
750
751    /**
752     * Generate and save a default wifiConfiguration with common values.
753     * Can only be called for unsecured networks.
754     */
755    public void generateOpenNetworkConfig() {
756        if (security != SECURITY_NONE)
757            throw new IllegalStateException();
758        if (mConfig != null)
759            return;
760        mConfig = new WifiConfiguration();
761        mConfig.SSID = AccessPoint.convertToQuotedString(ssid);
762        mConfig.allowedKeyManagement.set(KeyMgmt.NONE);
763    }
764
765    void loadConfig(WifiConfiguration config) {
766        if (config.isPasspoint())
767            ssid = config.providerFriendlyName;
768        else
769            ssid = (config.SSID == null ? "" : removeDoubleQuotes(config.SSID));
770
771        bssid = config.BSSID;
772        security = getSecurity(config);
773        networkId = config.networkId;
774        mConfig = config;
775    }
776
777    private void initWithScanResult(ScanResult result) {
778        ssid = result.SSID;
779        bssid = result.BSSID;
780        security = getSecurity(result);
781        if (security == SECURITY_PSK)
782            pskType = getPskType(result);
783        mRssi = result.level;
784        mSeen = result.timestamp;
785    }
786
787    public void saveWifiState(Bundle savedState) {
788        if (ssid != null) savedState.putString(KEY_SSID, getSsidStr());
789        savedState.putInt(KEY_SECURITY, security);
790        savedState.putInt(KEY_PSKTYPE, pskType);
791        if (mConfig != null) savedState.putParcelable(KEY_CONFIG, mConfig);
792        savedState.putParcelable(KEY_WIFIINFO, mInfo);
793        evictOldScanResults();
794        savedState.putParcelableArrayList(KEY_SCANRESULTCACHE,
795                new ArrayList<ScanResult>(mScanResultCache.values()));
796        if (mNetworkInfo != null) {
797            savedState.putParcelable(KEY_NETWORKINFO, mNetworkInfo);
798        }
799    }
800
801    public void setListener(AccessPointListener listener) {
802        mAccessPointListener = listener;
803    }
804
805    boolean update(ScanResult result) {
806        if (matches(result)) {
807            /* Add or update the scan result for the BSSID */
808            mScanResultCache.put(result.BSSID, result);
809
810            int oldLevel = getLevel();
811            int oldRssi = getRssi();
812            mSeen = getSeen();
813            mRssi = (getRssi() + oldRssi)/2;
814            int newLevel = getLevel();
815
816            if (newLevel > 0 && newLevel != oldLevel && mAccessPointListener != null) {
817                mAccessPointListener.onLevelChanged(this);
818            }
819            // This flag only comes from scans, is not easily saved in config
820            if (security == SECURITY_PSK) {
821                pskType = getPskType(result);
822            }
823
824            if (mAccessPointListener != null) {
825                mAccessPointListener.onAccessPointChanged(this);
826            }
827
828            return true;
829        }
830        return false;
831    }
832
833    boolean update(WifiConfiguration config, WifiInfo info, NetworkInfo networkInfo) {
834        boolean reorder = false;
835        if (info != null && isInfoForThisAccessPoint(config, info)) {
836            reorder = (mInfo == null);
837            mRssi = info.getRssi();
838            mInfo = info;
839            mNetworkInfo = networkInfo;
840            if (mAccessPointListener != null) {
841                mAccessPointListener.onAccessPointChanged(this);
842            }
843        } else if (mInfo != null) {
844            reorder = true;
845            mInfo = null;
846            mNetworkInfo = null;
847            if (mAccessPointListener != null) {
848                mAccessPointListener.onAccessPointChanged(this);
849            }
850        }
851        return reorder;
852    }
853
854    void update(WifiConfiguration config) {
855        mConfig = config;
856        networkId = config.networkId;
857        if (mAccessPointListener != null) {
858            mAccessPointListener.onAccessPointChanged(this);
859        }
860    }
861
862    void setRssi(int rssi) {
863        mRssi = rssi;
864    }
865
866    int getRankingScore() {
867        return mRankingScore;
868    }
869
870    int getBadge() {
871        return mBadge;
872    }
873
874    public static String getSummary(Context context, String ssid, DetailedState state,
875            boolean isEphemeral, String passpointProvider) {
876        if (state == DetailedState.CONNECTED && ssid == null) {
877            if (TextUtils.isEmpty(passpointProvider) == false) {
878                // Special case for connected + passpoint networks.
879                String format = context.getString(R.string.connected_via_passpoint);
880                return String.format(format, passpointProvider);
881            } else if (isEphemeral) {
882                // Special case for connected + ephemeral networks.
883                return context.getString(R.string.connected_via_wfa);
884            }
885        }
886
887        // Case when there is wifi connected without internet connectivity.
888        final ConnectivityManager cm = (ConnectivityManager)
889                context.getSystemService(Context.CONNECTIVITY_SERVICE);
890        if (state == DetailedState.CONNECTED) {
891            IWifiManager wifiManager = IWifiManager.Stub.asInterface(
892                    ServiceManager.getService(Context.WIFI_SERVICE));
893            NetworkCapabilities nc = null;
894
895            try {
896                nc = cm.getNetworkCapabilities(wifiManager.getCurrentNetwork());
897            } catch (RemoteException e) {}
898
899            if (nc != null) {
900                if (nc.hasCapability(nc.NET_CAPABILITY_CAPTIVE_PORTAL)) {
901                    return context.getString(
902                        com.android.internal.R.string.network_available_sign_in);
903                } else if (!nc.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)) {
904                    return context.getString(R.string.wifi_connected_no_internet);
905                }
906            }
907        }
908        if (state == null) {
909            Log.w(TAG, "state is null, returning empty summary");
910            return "";
911        }
912        String[] formats = context.getResources().getStringArray((ssid == null)
913                ? R.array.wifi_status : R.array.wifi_status_with_ssid);
914        int index = state.ordinal();
915
916        if (index >= formats.length || formats[index].length() == 0) {
917            return "";
918        }
919        return String.format(formats[index], ssid);
920    }
921
922    public static String getSummary(Context context, DetailedState state, boolean isEphemeral) {
923        return getSummary(context, null, state, isEphemeral, null);
924    }
925
926    public static String getSummary(Context context, DetailedState state, boolean isEphemeral,
927            String passpointProvider) {
928        return getSummary(context, null, state, isEphemeral, passpointProvider);
929    }
930
931    public static String convertToQuotedString(String string) {
932        return "\"" + string + "\"";
933    }
934
935    private static int getPskType(ScanResult result) {
936        boolean wpa = result.capabilities.contains("WPA-PSK");
937        boolean wpa2 = result.capabilities.contains("WPA2-PSK");
938        if (wpa2 && wpa) {
939            return PSK_WPA_WPA2;
940        } else if (wpa2) {
941            return PSK_WPA2;
942        } else if (wpa) {
943            return PSK_WPA;
944        } else {
945            Log.w(TAG, "Received abnormal flag string: " + result.capabilities);
946            return PSK_UNKNOWN;
947        }
948    }
949
950    private static int getSecurity(ScanResult result) {
951        if (result.capabilities.contains("WEP")) {
952            return SECURITY_WEP;
953        } else if (result.capabilities.contains("PSK")) {
954            return SECURITY_PSK;
955        } else if (result.capabilities.contains("EAP")) {
956            return SECURITY_EAP;
957        }
958        return SECURITY_NONE;
959    }
960
961    static int getSecurity(WifiConfiguration config) {
962        if (config.allowedKeyManagement.get(KeyMgmt.WPA_PSK)) {
963            return SECURITY_PSK;
964        }
965        if (config.allowedKeyManagement.get(KeyMgmt.WPA_EAP) ||
966                config.allowedKeyManagement.get(KeyMgmt.IEEE8021X)) {
967            return SECURITY_EAP;
968        }
969        return (config.wepKeys[0] != null) ? SECURITY_WEP : SECURITY_NONE;
970    }
971
972    public static String securityToString(int security, int pskType) {
973        if (security == SECURITY_WEP) {
974            return "WEP";
975        } else if (security == SECURITY_PSK) {
976            if (pskType == PSK_WPA) {
977                return "WPA";
978            } else if (pskType == PSK_WPA2) {
979                return "WPA2";
980            } else if (pskType == PSK_WPA_WPA2) {
981                return "WPA_WPA2";
982            }
983            return "PSK";
984        } else if (security == SECURITY_EAP) {
985            return "EAP";
986        }
987        return "NONE";
988    }
989
990    static String removeDoubleQuotes(String string) {
991        if (TextUtils.isEmpty(string)) {
992            return "";
993        }
994        int length = string.length();
995        if ((length > 1) && (string.charAt(0) == '"')
996                && (string.charAt(length - 1) == '"')) {
997            return string.substring(1, length - 1);
998        }
999        return string;
1000    }
1001
1002    public interface AccessPointListener {
1003        void onAccessPointChanged(AccessPoint accessPoint);
1004        void onLevelChanged(AccessPoint accessPoint);
1005    }
1006}
1007