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