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