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