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