AccessPoint.java revision 8d106780b6a638552749e54e169fc72537d4bccc
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(mConfig, 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 concise ? context.getString(R.string.wifi_security_short_eap) :
297                context.getString(R.string.wifi_security_eap);
298        }
299        switch(security) {
300            case SECURITY_EAP:
301                return concise ? context.getString(R.string.wifi_security_short_eap) :
302                    context.getString(R.string.wifi_security_eap);
303            case SECURITY_PSK:
304                switch (pskType) {
305                    case PSK_WPA:
306                        return concise ? context.getString(R.string.wifi_security_short_wpa) :
307                            context.getString(R.string.wifi_security_wpa);
308                    case PSK_WPA2:
309                        return concise ? context.getString(R.string.wifi_security_short_wpa2) :
310                            context.getString(R.string.wifi_security_wpa2);
311                    case PSK_WPA_WPA2:
312                        return concise ? context.getString(R.string.wifi_security_short_wpa_wpa2) :
313                            context.getString(R.string.wifi_security_wpa_wpa2);
314                    case PSK_UNKNOWN:
315                    default:
316                        return concise ? context.getString(R.string.wifi_security_short_psk_generic)
317                                : context.getString(R.string.wifi_security_psk_generic);
318                }
319            case SECURITY_WEP:
320                return concise ? context.getString(R.string.wifi_security_short_wep) :
321                    context.getString(R.string.wifi_security_wep);
322            case SECURITY_NONE:
323            default:
324                return concise ? "" : context.getString(R.string.wifi_security_none);
325        }
326    }
327
328    public String getSsidStr() {
329        return ssid;
330    }
331
332    public CharSequence getSsid() {
333        SpannableString str = new SpannableString(ssid);
334        str.setSpan(new TtsSpan.VerbatimBuilder(ssid).build(), 0, ssid.length(),
335                Spannable.SPAN_INCLUSIVE_INCLUSIVE);
336        return str;
337    }
338
339    public String getConfigName() {
340        if (mConfig != null && mConfig.isPasspoint()) {
341            return mConfig.providerFriendlyName;
342        } else {
343            return ssid;
344        }
345    }
346
347    public DetailedState getDetailedState() {
348        return mNetworkInfo != null ? mNetworkInfo.getDetailedState() : null;
349    }
350
351    public String getSavedNetworkSummary() {
352        if (mConfig != null) {
353            PackageManager pm = mContext.getPackageManager();
354            String systemName = pm.getNameForUid(android.os.Process.SYSTEM_UID);
355            int userId = UserHandle.getUserId(mConfig.creatorUid);
356            ApplicationInfo appInfo = null;
357            if (mConfig.creatorName != null && mConfig.creatorName.equals(systemName)) {
358                appInfo = mContext.getApplicationInfo();
359            } else {
360                try {
361                    IPackageManager ipm = AppGlobals.getPackageManager();
362                    appInfo = ipm.getApplicationInfo(mConfig.creatorName, 0 /* flags */, userId);
363                } catch (RemoteException rex) {
364                }
365            }
366            if (appInfo != null &&
367                    !appInfo.packageName.equals(mContext.getString(R.string.settings_package)) &&
368                    !appInfo.packageName.equals(
369                    mContext.getString(R.string.certinstaller_package))) {
370                return mContext.getString(R.string.saved_network, appInfo.loadLabel(pm));
371            }
372        }
373        return "";
374    }
375
376    public String getSummary() {
377        return getSettingsSummary();
378    }
379
380    public String getSettingsSummary() {
381        // Update to new summary
382        StringBuilder summary = new StringBuilder();
383
384        if (isActive() && mConfig != null && mConfig.isPasspoint()) {
385            // This is the active connection on passpoint
386            summary.append(getSummary(mContext, getDetailedState(),
387                    false, mConfig.providerFriendlyName));
388        } else if (isActive()) {
389            // This is the active connection on non-passpoint network
390            summary.append(getSummary(mContext, getDetailedState(),
391                    mInfo != null && mInfo.isEphemeral()));
392        } else if (mConfig != null && mConfig.isPasspoint()) {
393            String format = mContext.getString(R.string.available_via_passpoint);
394            summary.append(String.format(format, mConfig.providerFriendlyName));
395        } else if (mConfig != null && mConfig.hasNoInternetAccess()) {
396            summary.append(mContext.getString(R.string.wifi_no_internet));
397        } else if (mConfig != null && !mConfig.getNetworkSelectionStatus().isNetworkEnabled()) {
398            WifiConfiguration.NetworkSelectionStatus networkStatus =
399                    mConfig.getNetworkSelectionStatus();
400            switch (networkStatus.getNetworkSelectionDisableReason()) {
401                case WifiConfiguration.NetworkSelectionStatus.DISABLED_AUTHENTICATION_FAILURE:
402                    summary.append(mContext.getString(R.string.wifi_disabled_password_failure));
403                    break;
404                case WifiConfiguration.NetworkSelectionStatus.DISABLED_DHCP_FAILURE:
405                case WifiConfiguration.NetworkSelectionStatus.DISABLED_DNS_FAILURE:
406                    summary.append(mContext.getString(R.string.wifi_disabled_network_failure));
407                    break;
408                case WifiConfiguration.NetworkSelectionStatus.DISABLED_ASSOCIATION_REJECTION:
409                    summary.append(mContext.getString(R.string.wifi_disabled_generic));
410                    break;
411            }
412        } else if (mRssi == Integer.MAX_VALUE) { // Wifi out of range
413            summary.append(mContext.getString(R.string.wifi_not_in_range));
414        } else { // In range, not disabled.
415            if (mConfig != null) { // Is saved network
416                summary.append(mContext.getString(R.string.wifi_remembered));
417            }
418        }
419
420        if (WifiTracker.sVerboseLogging > 0) {
421            // Add RSSI/band information for this config, what was seen up to 6 seconds ago
422            // verbose WiFi Logging is only turned on thru developers settings
423            if (mInfo != null && mNetworkInfo != null) { // This is the active connection
424                summary.append(" f=" + Integer.toString(mInfo.getFrequency()));
425            }
426            summary.append(" " + getVisibilityStatus());
427            if (mConfig != null && !mConfig.getNetworkSelectionStatus().isNetworkEnabled()) {
428                summary.append(" (" + mConfig.getNetworkSelectionStatus().getNetworkStatusString());
429                if (mConfig.getNetworkSelectionStatus().getDisableTime() > 0) {
430                    long now = System.currentTimeMillis();
431                    long diff = (now - mConfig.getNetworkSelectionStatus().getDisableTime()) / 1000;
432                    long sec = diff%60; //seconds
433                    long min = (diff/60)%60; //minutes
434                    long hour = (min/60)%60; //hours
435                    summary.append(", ");
436                    if (hour > 0) summary.append(Long.toString(hour) + "h ");
437                    summary.append( Long.toString(min) + "m ");
438                    summary.append( Long.toString(sec) + "s ");
439                }
440                summary.append(")");
441            }
442
443            if (mConfig != null) {
444                WifiConfiguration.NetworkSelectionStatus networkStatus =
445                        mConfig.getNetworkSelectionStatus();
446                for (int index = WifiConfiguration.NetworkSelectionStatus.NETWORK_SELECTION_ENABLE;
447                        index < WifiConfiguration.NetworkSelectionStatus
448                        .NETWORK_SELECTION_DISABLED_MAX; index++) {
449                    if (networkStatus.getDisableReasonCounter(index) != 0) {
450                        summary.append(" " + WifiConfiguration.NetworkSelectionStatus
451                                .getNetworkDisableReasonString(index) + "="
452                                + networkStatus.getDisableReasonCounter(index));
453                    }
454                }
455            }
456        }
457        return summary.toString();
458    }
459
460    /**
461     * Returns the visibility status of the WifiConfiguration.
462     *
463     * @return autojoin debugging information
464     * TODO: use a string formatter
465     * ["rssi 5Ghz", "num results on 5GHz" / "rssi 5Ghz", "num results on 5GHz"]
466     * For instance [-40,5/-30,2]
467     */
468    private String getVisibilityStatus() {
469        StringBuilder visibility = new StringBuilder();
470        StringBuilder scans24GHz = null;
471        StringBuilder scans5GHz = null;
472        String bssid = null;
473
474        long now = System.currentTimeMillis();
475
476        if (mInfo != null) {
477            bssid = mInfo.getBSSID();
478            if (bssid != null) {
479                visibility.append(" ").append(bssid);
480            }
481            visibility.append(" rssi=").append(mInfo.getRssi());
482            visibility.append(" ");
483            visibility.append(" score=").append(mInfo.score);
484            visibility.append(String.format(" tx=%.1f,", mInfo.txSuccessRate));
485            visibility.append(String.format("%.1f,", mInfo.txRetriesRate));
486            visibility.append(String.format("%.1f ", mInfo.txBadRate));
487            visibility.append(String.format("rx=%.1f", mInfo.rxSuccessRate));
488        }
489
490        int rssi5 = WifiConfiguration.INVALID_RSSI;
491        int rssi24 = WifiConfiguration.INVALID_RSSI;
492        int num5 = 0;
493        int num24 = 0;
494        int numBlackListed = 0;
495        int n24 = 0; // Number scan results we included in the string
496        int n5 = 0; // Number scan results we included in the string
497        Map<String, ScanResult> list = mScanResultCache.snapshot();
498        // TODO: sort list by RSSI or age
499        for (ScanResult result : list.values()) {
500
501            if (result.frequency >= LOWER_FREQ_5GHZ
502                    && result.frequency <= HIGHER_FREQ_5GHZ) {
503                // Strictly speaking: [4915, 5825]
504                // number of known BSSID on 5GHz band
505                num5 = num5 + 1;
506            } else if (result.frequency >= LOWER_FREQ_24GHZ
507                    && result.frequency <= HIGHER_FREQ_24GHZ) {
508                // Strictly speaking: [2412, 2482]
509                // number of known BSSID on 2.4Ghz band
510                num24 = num24 + 1;
511            }
512
513
514            if (result.frequency >= LOWER_FREQ_5GHZ
515                    && result.frequency <= HIGHER_FREQ_5GHZ) {
516                if (result.level > rssi5) {
517                    rssi5 = result.level;
518                }
519                if (n5 < 4) {
520                    if (scans5GHz == null) scans5GHz = new StringBuilder();
521                    scans5GHz.append(" \n{").append(result.BSSID);
522                    if (bssid != null && result.BSSID.equals(bssid)) scans5GHz.append("*");
523                    scans5GHz.append("=").append(result.frequency);
524                    scans5GHz.append(",").append(result.level);
525                    scans5GHz.append("}");
526                    n5++;
527                }
528            } else if (result.frequency >= LOWER_FREQ_24GHZ
529                    && result.frequency <= HIGHER_FREQ_24GHZ) {
530                if (result.level > rssi24) {
531                    rssi24 = result.level;
532                }
533                if (n24 < 4) {
534                    if (scans24GHz == null) scans24GHz = new StringBuilder();
535                    scans24GHz.append(" \n{").append(result.BSSID);
536                    if (bssid != null && result.BSSID.equals(bssid)) scans24GHz.append("*");
537                    scans24GHz.append("=").append(result.frequency);
538                    scans24GHz.append(",").append(result.level);
539                    scans24GHz.append("}");
540                    n24++;
541                }
542            }
543        }
544        visibility.append(" [");
545        if (num24 > 0) {
546            visibility.append("(").append(num24).append(")");
547            if (n24 <= 4) {
548                if (scans24GHz != null) {
549                    visibility.append(scans24GHz.toString());
550                }
551            } else {
552                visibility.append("max=").append(rssi24);
553                if (scans24GHz != null) {
554                    visibility.append(",").append(scans24GHz.toString());
555                }
556            }
557        }
558        visibility.append(";");
559        if (num5 > 0) {
560            visibility.append("(").append(num5).append(")");
561            if (n5 <= 4) {
562                if (scans5GHz != null) {
563                    visibility.append(scans5GHz.toString());
564                }
565            } else {
566                visibility.append("max=").append(rssi5);
567                if (scans5GHz != null) {
568                    visibility.append(",").append(scans5GHz.toString());
569                }
570            }
571        }
572        if (numBlackListed > 0)
573            visibility.append("!").append(numBlackListed);
574        visibility.append("]");
575
576        return visibility.toString();
577    }
578
579    /**
580     * Return whether this is the active connection.
581     * For ephemeral connections (networkId is invalid), this returns false if the network is
582     * disconnected.
583     */
584    public boolean isActive() {
585        return mNetworkInfo != null &&
586                (networkId != WifiConfiguration.INVALID_NETWORK_ID ||
587                 mNetworkInfo.getState() != State.DISCONNECTED);
588    }
589
590    public boolean isConnectable() {
591        return getLevel() != -1 && getDetailedState() == null;
592    }
593
594    public boolean isEphemeral() {
595        return mInfo != null && mInfo.isEphemeral() &&
596                mNetworkInfo != null && mNetworkInfo.getState() != State.DISCONNECTED;
597    }
598
599    public boolean isPasspoint() {
600        return mConfig != null && mConfig.isPasspoint();
601    }
602
603    /**
604     * Return whether the given {@link WifiInfo} is for this access point.
605     * If the current AP does not have a network Id then the config is used to
606     * match based on SSID and security.
607     */
608    private boolean isInfoForThisAccessPoint(WifiConfiguration config, WifiInfo info) {
609        if (isPasspoint() == false && networkId != WifiConfiguration.INVALID_NETWORK_ID) {
610            return networkId == info.getNetworkId();
611        } else if (config != null) {
612            return matches(config);
613        }
614        else {
615            // Might be an ephemeral connection with no WifiConfiguration. Try matching on SSID.
616            // (Note that we only do this if the WifiConfiguration explicitly equals INVALID).
617            // TODO: Handle hex string SSIDs.
618            return ssid.equals(removeDoubleQuotes(info.getSSID()));
619        }
620    }
621
622    public boolean isSaved() {
623        return networkId != WifiConfiguration.INVALID_NETWORK_ID;
624    }
625
626    public Object getTag() {
627        return mTag;
628    }
629
630    public void setTag(Object tag) {
631        mTag = tag;
632    }
633
634    /**
635     * Generate and save a default wifiConfiguration with common values.
636     * Can only be called for unsecured networks.
637     */
638    public void generateOpenNetworkConfig() {
639        if (security != SECURITY_NONE)
640            throw new IllegalStateException();
641        if (mConfig != null)
642            return;
643        mConfig = new WifiConfiguration();
644        mConfig.SSID = AccessPoint.convertToQuotedString(ssid);
645        mConfig.allowedKeyManagement.set(KeyMgmt.NONE);
646    }
647
648    void loadConfig(WifiConfiguration config) {
649        if (config.isPasspoint())
650            ssid = config.providerFriendlyName;
651        else
652            ssid = (config.SSID == null ? "" : removeDoubleQuotes(config.SSID));
653
654        security = getSecurity(config);
655        networkId = config.networkId;
656        mConfig = config;
657    }
658
659    private void initWithScanResult(ScanResult result) {
660        ssid = result.SSID;
661        security = getSecurity(result);
662        if (security == SECURITY_PSK)
663            pskType = getPskType(result);
664        mRssi = result.level;
665        mSeen = result.timestamp;
666    }
667
668    public void saveWifiState(Bundle savedState) {
669        if (ssid != null) savedState.putString(KEY_SSID, getSsidStr());
670        savedState.putInt(KEY_SECURITY, security);
671        savedState.putInt(KEY_PSKTYPE, pskType);
672        if (mConfig != null) savedState.putParcelable(KEY_CONFIG, mConfig);
673        savedState.putParcelable(KEY_WIFIINFO, mInfo);
674        savedState.putParcelableArrayList(KEY_SCANRESULTCACHE,
675                new ArrayList<ScanResult>(mScanResultCache.snapshot().values()));
676        if (mNetworkInfo != null) {
677            savedState.putParcelable(KEY_NETWORKINFO, mNetworkInfo);
678        }
679    }
680
681    public void setListener(AccessPointListener listener) {
682        mAccessPointListener = listener;
683    }
684
685    boolean update(ScanResult result) {
686        if (matches(result)) {
687            /* Update the LRU timestamp, if BSSID exists */
688            mScanResultCache.get(result.BSSID);
689
690            /* Add or update the scan result for the BSSID */
691            mScanResultCache.put(result.BSSID, result);
692
693            int oldLevel = getLevel();
694            int oldRssi = getRssi();
695            mSeen = getSeen();
696            mRssi = (getRssi() + oldRssi)/2;
697            int newLevel = getLevel();
698
699            if (newLevel > 0 && newLevel != oldLevel && mAccessPointListener != null) {
700                mAccessPointListener.onLevelChanged(this);
701            }
702            // This flag only comes from scans, is not easily saved in config
703            if (security == SECURITY_PSK) {
704                pskType = getPskType(result);
705            }
706
707            if (mAccessPointListener != null) {
708                mAccessPointListener.onAccessPointChanged(this);
709            }
710
711            return true;
712        }
713        return false;
714    }
715
716    boolean update(WifiConfiguration config, WifiInfo info, NetworkInfo networkInfo) {
717        boolean reorder = false;
718        if (info != null && isInfoForThisAccessPoint(config, info)) {
719            reorder = (mInfo == null);
720            mRssi = info.getRssi();
721            mInfo = info;
722            mNetworkInfo = networkInfo;
723            if (mAccessPointListener != null) {
724                mAccessPointListener.onAccessPointChanged(this);
725            }
726        } else if (mInfo != null) {
727            reorder = true;
728            mInfo = null;
729            mNetworkInfo = null;
730            if (mAccessPointListener != null) {
731                mAccessPointListener.onAccessPointChanged(this);
732            }
733        }
734        return reorder;
735    }
736
737    void update(WifiConfiguration config) {
738        mConfig = config;
739        networkId = config.networkId;
740        if (mAccessPointListener != null) {
741            mAccessPointListener.onAccessPointChanged(this);
742        }
743    }
744
745    public static String getSummary(Context context, String ssid, DetailedState state,
746            boolean isEphemeral, String passpointProvider) {
747        if (state == DetailedState.CONNECTED && ssid == null) {
748            if (TextUtils.isEmpty(passpointProvider) == false) {
749                // Special case for connected + passpoint networks.
750                String format = context.getString(R.string.connected_via_passpoint);
751                return String.format(format, passpointProvider);
752            } else if (isEphemeral) {
753                // Special case for connected + ephemeral networks.
754                return context.getString(R.string.connected_via_wfa);
755            }
756        }
757
758        // Case when there is wifi connected without internet connectivity.
759        final ConnectivityManager cm = (ConnectivityManager)
760                context.getSystemService(Context.CONNECTIVITY_SERVICE);
761        if (state == DetailedState.CONNECTED) {
762            IWifiManager wifiManager = IWifiManager.Stub.asInterface(
763                    ServiceManager.getService(Context.WIFI_SERVICE));
764            Network nw;
765
766            try {
767                nw = wifiManager.getCurrentNetwork();
768            } catch (RemoteException e) {
769                nw = null;
770            }
771            NetworkCapabilities nc = cm.getNetworkCapabilities(nw);
772            if (nc != null && !nc.hasCapability(nc.NET_CAPABILITY_VALIDATED)) {
773                return context.getString(R.string.wifi_connected_no_internet);
774            }
775        }
776
777        String[] formats = context.getResources().getStringArray((ssid == null)
778                ? R.array.wifi_status : R.array.wifi_status_with_ssid);
779        int index = state.ordinal();
780
781        if (index >= formats.length || formats[index].length() == 0) {
782            return "";
783        }
784        return String.format(formats[index], ssid);
785    }
786
787    public static String getSummary(Context context, DetailedState state, boolean isEphemeral) {
788        return getSummary(context, null, state, isEphemeral, null);
789    }
790
791    public static String getSummary(Context context, DetailedState state, boolean isEphemeral,
792            String passpointProvider) {
793        return getSummary(context, null, state, isEphemeral, passpointProvider);
794    }
795
796    public static String convertToQuotedString(String string) {
797        return "\"" + string + "\"";
798    }
799
800    private static int getPskType(ScanResult result) {
801        boolean wpa = result.capabilities.contains("WPA-PSK");
802        boolean wpa2 = result.capabilities.contains("WPA2-PSK");
803        if (wpa2 && wpa) {
804            return PSK_WPA_WPA2;
805        } else if (wpa2) {
806            return PSK_WPA2;
807        } else if (wpa) {
808            return PSK_WPA;
809        } else {
810            Log.w(TAG, "Received abnormal flag string: " + result.capabilities);
811            return PSK_UNKNOWN;
812        }
813    }
814
815    private static int getSecurity(ScanResult result) {
816        if (result.capabilities.contains("WEP")) {
817            return SECURITY_WEP;
818        } else if (result.capabilities.contains("PSK")) {
819            return SECURITY_PSK;
820        } else if (result.capabilities.contains("EAP")) {
821            return SECURITY_EAP;
822        }
823        return SECURITY_NONE;
824    }
825
826    static int getSecurity(WifiConfiguration config) {
827        if (config.allowedKeyManagement.get(KeyMgmt.WPA_PSK)) {
828            return SECURITY_PSK;
829        }
830        if (config.allowedKeyManagement.get(KeyMgmt.WPA_EAP) ||
831                config.allowedKeyManagement.get(KeyMgmt.IEEE8021X)) {
832            return SECURITY_EAP;
833        }
834        return (config.wepKeys[0] != null) ? SECURITY_WEP : SECURITY_NONE;
835    }
836
837    public static String securityToString(int security, int pskType) {
838        if (security == SECURITY_WEP) {
839            return "WEP";
840        } else if (security == SECURITY_PSK) {
841            if (pskType == PSK_WPA) {
842                return "WPA";
843            } else if (pskType == PSK_WPA2) {
844                return "WPA2";
845            } else if (pskType == PSK_WPA_WPA2) {
846                return "WPA_WPA2";
847            }
848            return "PSK";
849        } else if (security == SECURITY_EAP) {
850            return "EAP";
851        }
852        return "NONE";
853    }
854
855    static String removeDoubleQuotes(String string) {
856        if (TextUtils.isEmpty(string)) {
857            return "";
858        }
859        int length = string.length();
860        if ((length > 1) && (string.charAt(0) == '"')
861                && (string.charAt(length - 1) == '"')) {
862            return string.substring(1, length - 1);
863        }
864        return string;
865    }
866
867    public interface AccessPointListener {
868        void onAccessPointChanged(AccessPoint accessPoint);
869        void onLevelChanged(AccessPoint accessPoint);
870    }
871}
872