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