WifiConfiguration.java revision 72e1d3f53826c2f19727e30e4b576a0e2d0e3728
1/*
2 * Copyright (C) 2008 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 android.net.wifi;
18
19import android.annotation.SystemApi;
20import android.net.IpConfiguration;
21import android.net.IpConfiguration.ProxySettings;
22import android.net.IpConfiguration.IpAssignment;
23import android.net.ProxyInfo;
24import android.net.StaticIpConfiguration;
25import android.os.Parcel;
26import android.os.Parcelable;
27import android.text.TextUtils;
28import android.annotation.SystemApi;
29
30import java.util.HashMap;
31import java.util.BitSet;
32import java.util.ArrayList;
33import java.util.Collections;
34import java.util.Comparator;
35
36/**
37 * A class representing a configured Wi-Fi network, including the
38 * security configuration.
39 */
40public class WifiConfiguration implements Parcelable {
41    private static final String TAG = "WifiConfiguration";
42    /** {@hide} */
43    public static final String ssidVarName = "ssid";
44    /** {@hide} */
45    public static final String bssidVarName = "bssid";
46    /** {@hide} */
47    public static final String pskVarName = "psk";
48    /** {@hide} */
49    public static final String[] wepKeyVarNames = { "wep_key0", "wep_key1", "wep_key2", "wep_key3" };
50    /** {@hide} */
51    public static final String wepTxKeyIdxVarName = "wep_tx_keyidx";
52    /** {@hide} */
53    public static final String priorityVarName = "priority";
54    /** {@hide} */
55    public static final String hiddenSSIDVarName = "scan_ssid";
56    /** {@hide} */
57    public static final String pmfVarName = "ieee80211w";
58    /** {@hide} */
59    public static final String updateIdentiferVarName = "update_identifier";
60    /** {@hide} */
61    public static final int INVALID_NETWORK_ID = -1;
62    /**
63     * Recognized key management schemes.
64     */
65    public static class KeyMgmt {
66        private KeyMgmt() { }
67
68        /** WPA is not used; plaintext or static WEP could be used. */
69        public static final int NONE = 0;
70        /** WPA pre-shared key (requires {@code preSharedKey} to be specified). */
71        public static final int WPA_PSK = 1;
72        /** WPA using EAP authentication. Generally used with an external authentication server. */
73        public static final int WPA_EAP = 2;
74        /** IEEE 802.1X using EAP authentication and (optionally) dynamically
75         * generated WEP keys. */
76        public static final int IEEE8021X = 3;
77
78        /** WPA2 pre-shared key for use with soft access point
79          * (requires {@code preSharedKey} to be specified).
80          * @hide
81          */
82        public static final int WPA2_PSK = 4;
83
84        public static final String varName = "key_mgmt";
85
86        public static final String[] strings = { "NONE", "WPA_PSK", "WPA_EAP", "IEEE8021X",
87                "WPA2_PSK" };
88    }
89
90    /**
91     * Recognized security protocols.
92     */
93    public static class Protocol {
94        private Protocol() { }
95
96        /** WPA/IEEE 802.11i/D3.0 */
97        public static final int WPA = 0;
98        /** WPA2/IEEE 802.11i */
99        public static final int RSN = 1;
100
101        public static final String varName = "proto";
102
103        public static final String[] strings = { "WPA", "RSN" };
104    }
105
106    /**
107     * Recognized IEEE 802.11 authentication algorithms.
108     */
109    public static class AuthAlgorithm {
110        private AuthAlgorithm() { }
111
112        /** Open System authentication (required for WPA/WPA2) */
113        public static final int OPEN = 0;
114        /** Shared Key authentication (requires static WEP keys) */
115        public static final int SHARED = 1;
116        /** LEAP/Network EAP (only used with LEAP) */
117        public static final int LEAP = 2;
118
119        public static final String varName = "auth_alg";
120
121        public static final String[] strings = { "OPEN", "SHARED", "LEAP" };
122    }
123
124    /**
125     * Recognized pairwise ciphers for WPA.
126     */
127    public static class PairwiseCipher {
128        private PairwiseCipher() { }
129
130        /** Use only Group keys (deprecated) */
131        public static final int NONE = 0;
132        /** Temporal Key Integrity Protocol [IEEE 802.11i/D7.0] */
133        public static final int TKIP = 1;
134        /** AES in Counter mode with CBC-MAC [RFC 3610, IEEE 802.11i/D7.0] */
135        public static final int CCMP = 2;
136
137        public static final String varName = "pairwise";
138
139        public static final String[] strings = { "NONE", "TKIP", "CCMP" };
140    }
141
142    /**
143     * Recognized group ciphers.
144     * <pre>
145     * CCMP = AES in Counter mode with CBC-MAC [RFC 3610, IEEE 802.11i/D7.0]
146     * TKIP = Temporal Key Integrity Protocol [IEEE 802.11i/D7.0]
147     * WEP104 = WEP (Wired Equivalent Privacy) with 104-bit key
148     * WEP40 = WEP (Wired Equivalent Privacy) with 40-bit key (original 802.11)
149     * </pre>
150     */
151    public static class GroupCipher {
152        private GroupCipher() { }
153
154        /** WEP40 = WEP (Wired Equivalent Privacy) with 40-bit key (original 802.11) */
155        public static final int WEP40 = 0;
156        /** WEP104 = WEP (Wired Equivalent Privacy) with 104-bit key */
157        public static final int WEP104 = 1;
158        /** Temporal Key Integrity Protocol [IEEE 802.11i/D7.0] */
159        public static final int TKIP = 2;
160        /** AES in Counter mode with CBC-MAC [RFC 3610, IEEE 802.11i/D7.0] */
161        public static final int CCMP = 3;
162
163        public static final String varName = "group";
164
165        public static final String[] strings = { "WEP40", "WEP104", "TKIP", "CCMP" };
166    }
167
168    /** Possible status of a network configuration. */
169    public static class Status {
170        private Status() { }
171
172        /** this is the network we are currently connected to */
173        public static final int CURRENT = 0;
174        /** supplicant will not attempt to use this network */
175        public static final int DISABLED = 1;
176        /** supplicant will consider this network available for association */
177        public static final int ENABLED = 2;
178
179        public static final String[] strings = { "current", "disabled", "enabled" };
180    }
181
182    /** @hide */
183    public static final int DISABLED_UNKNOWN_REASON                         = 0;
184    /** @hide */
185    public static final int DISABLED_DNS_FAILURE                            = 1;
186    /** @hide */
187    public static final int DISABLED_DHCP_FAILURE                           = 2;
188    /** @hide */
189    public static final int DISABLED_AUTH_FAILURE                           = 3;
190    /** @hide */
191    public static final int DISABLED_ASSOCIATION_REJECT                     = 4;
192    /** @hide */
193    public static final int DISABLED_BY_WIFI_MANAGER                        = 5;
194
195    /**
196     * The ID number that the supplicant uses to identify this
197     * network configuration entry. This must be passed as an argument
198     * to most calls into the supplicant.
199     */
200    public int networkId;
201
202    /**
203     * The current status of this network configuration entry.
204     * @see Status
205     */
206    public int status;
207
208    /**
209     * The configuration needs to be written to networkHistory.txt
210     * @hide
211     */
212    public boolean dirty;
213
214    /**
215     * The code referring to a reason for disabling the network
216     * Valid when {@link #status} == Status.DISABLED
217     * @hide
218     */
219    public int disableReason;
220
221    /**
222     * The network's SSID. Can either be an ASCII string,
223     * which must be enclosed in double quotation marks
224     * (e.g., {@code "MyNetwork"}, or a string of
225     * hex digits,which are not enclosed in quotes
226     * (e.g., {@code 01a243f405}).
227     */
228    public String SSID;
229    /**
230     * When set, this network configuration entry should only be used when
231     * associating with the AP having the specified BSSID. The value is
232     * a string in the format of an Ethernet MAC address, e.g.,
233     * <code>XX:XX:XX:XX:XX:XX</code> where each <code>X</code> is a hex digit.
234     */
235    public String BSSID;
236    /**
237     * Fully qualified domain name (FQDN) of AAA server or RADIUS server
238     * e.g. {@code "mail.example.com"}.
239     */
240    public String FQDN;
241    /**
242     * Network access identifier (NAI) realm, for Passpoint credential.
243     * e.g. {@code "myhost.example.com"}.
244     * @hide
245     */
246    public String naiRealm;
247
248    /**
249     * Pre-shared key for use with WPA-PSK.
250     * <p/>
251     * When the value of this key is read, the actual key is
252     * not returned, just a "*" if the key has a value, or the null
253     * string otherwise.
254     */
255    public String preSharedKey;
256    /**
257     * Up to four WEP keys. Either an ASCII string enclosed in double
258     * quotation marks (e.g., {@code "abcdef"} or a string
259     * of hex digits (e.g., {@code 0102030405}).
260     * <p/>
261     * When the value of one of these keys is read, the actual key is
262     * not returned, just a "*" if the key has a value, or the null
263     * string otherwise.
264     */
265    public String[] wepKeys;
266
267    /** Default WEP key index, ranging from 0 to 3. */
268    public int wepTxKeyIndex;
269
270    /**
271     * Priority determines the preference given to a network by {@code wpa_supplicant}
272     * when choosing an access point with which to associate.
273     */
274    public int priority;
275
276    /**
277     * This is a network that does not broadcast its SSID, so an
278     * SSID-specific probe request must be used for scans.
279     */
280    public boolean hiddenSSID;
281
282    /**
283     * This is a network that requries Protected Management Frames (PMF).
284     * @hide
285     */
286    public boolean requirePMF;
287
288    /**
289     * Update identifier, for Passpoint network.
290     * @hide
291     */
292    public String updateIdentifier;
293
294    /**
295     * The set of key management protocols supported by this configuration.
296     * See {@link KeyMgmt} for descriptions of the values.
297     * Defaults to WPA-PSK WPA-EAP.
298     */
299    public BitSet allowedKeyManagement;
300    /**
301     * The set of security protocols supported by this configuration.
302     * See {@link Protocol} for descriptions of the values.
303     * Defaults to WPA RSN.
304     */
305    public BitSet allowedProtocols;
306    /**
307     * The set of authentication protocols supported by this configuration.
308     * See {@link AuthAlgorithm} for descriptions of the values.
309     * Defaults to automatic selection.
310     */
311    public BitSet allowedAuthAlgorithms;
312    /**
313     * The set of pairwise ciphers for WPA supported by this configuration.
314     * See {@link PairwiseCipher} for descriptions of the values.
315     * Defaults to CCMP TKIP.
316     */
317    public BitSet allowedPairwiseCiphers;
318    /**
319     * The set of group ciphers supported by this configuration.
320     * See {@link GroupCipher} for descriptions of the values.
321     * Defaults to CCMP TKIP WEP104 WEP40.
322     */
323    public BitSet allowedGroupCiphers;
324    /**
325     * The enterprise configuration details specifying the EAP method,
326     * certificates and other settings associated with the EAP.
327     */
328    public WifiEnterpriseConfig enterpriseConfig;
329
330    /**
331     * @hide
332     */
333    private IpConfiguration mIpConfiguration;
334
335    /**
336     * @hide
337     * dhcp server MAC address if known
338     */
339    public String dhcpServer;
340
341    /**
342     * @hide
343     * default Gateway MAC address if known
344     */
345    public String defaultGwMacAddress;
346
347    /**
348     * @hide
349     * last failure
350     */
351    public String lastFailure;
352
353    /**
354     * @hide
355     * last time we connected, this configuration had validated internet access
356     */
357    public boolean validatedInternetAccess;
358
359    /**
360     * @hide
361     * Uid of app creating the configuration
362     */
363    @SystemApi
364    public int creatorUid;
365
366    /**
367     * @hide
368     * Uid of last app issuing a connection related command
369     */
370    public int lastConnectUid;
371
372    /**
373     * @hide
374     * Uid of last app modifying the configuration
375     */
376    @SystemApi
377    public int lastUpdateUid;
378
379    /**
380     * @hide
381     * Uid used by autoJoin
382     */
383    public String autoJoinBSSID;
384
385    /**
386     * @hide
387     * BSSID list on which this configuration was seen.
388     * TODO: prevent this list to grow infinitely, age-out the results
389     */
390    public HashMap<String, ScanResult> scanResultCache;
391
392    /** The Below RSSI thresholds are used to configure AutoJoin
393     *  - GOOD/LOW/BAD thresholds are used so as to calculate link score
394     *  - UNWANTED_SOFT are used by the blacklisting logic so as to handle
395     *  the unwanted network message coming from CS
396     *  - UNBLACKLIST thresholds are used so as to tweak the speed at which
397     *  the network is unblacklisted (i.e. if
398     *          it is seen with good RSSI, it is blacklisted faster)
399     *  - INITIAL_AUTOJOIN_ATTEMPT, used to determine how close from
400     *  the network we need to be before autojoin kicks in
401     */
402    /** @hide **/
403    public static int INVALID_RSSI = -127;
404
405    /** @hide **/
406    public static int UNWANTED_BLACKLIST_SOFT_RSSI_24 = -80;
407
408    /** @hide **/
409    public static int UNWANTED_BLACKLIST_SOFT_RSSI_5 = -70;
410
411    /** @hide **/
412    public static int GOOD_RSSI_24 = -65;
413
414    /** @hide **/
415    public static int LOW_RSSI_24 = -77;
416
417    /** @hide **/
418    public static int BAD_RSSI_24 = -87;
419
420    /** @hide **/
421    public static int GOOD_RSSI_5 = -60;
422
423    /** @hide **/
424    public static int LOW_RSSI_5 = -72;
425
426    /** @hide **/
427    public static int BAD_RSSI_5 = -82;
428
429    /** @hide **/
430    public static int UNWANTED_BLACKLIST_SOFT_BUMP = 4;
431
432    /** @hide **/
433    public static int UNWANTED_BLACKLIST_HARD_BUMP = 8;
434
435    /** @hide **/
436    public static int UNBLACKLIST_THRESHOLD_24_SOFT = -77;
437
438    /** @hide **/
439    public static int UNBLACKLIST_THRESHOLD_24_HARD = -68;
440
441    /** @hide **/
442    public static int UNBLACKLIST_THRESHOLD_5_SOFT = -63;
443
444    /** @hide **/
445    public static int UNBLACKLIST_THRESHOLD_5_HARD = -56;
446
447    /** @hide **/
448    public static int INITIAL_AUTO_JOIN_ATTEMPT_MIN_24 = -80;
449
450    /** @hide **/
451    public static int INITIAL_AUTO_JOIN_ATTEMPT_MIN_5 = -70;
452
453    /** @hide
454     * 5GHz band is prefered low over 2.4 if the 5GHz RSSI is higher than this threshold */
455    public static int A_BAND_PREFERENCE_RSSI_THRESHOLD = -65;
456
457    /** @hide
458     * 5GHz band is penalized if the 5GHz RSSI is lower than this threshold **/
459    public static int G_BAND_PREFERENCE_RSSI_THRESHOLD = -75;
460
461    /** @hide
462     * Boost given to RSSI on a home network for the purpose of calculating the score
463     * This adds stickiness to home networks, as defined by:
464     * - less than 4 known BSSIDs
465     * - PSK only
466     * - TODO: add a test to verify that all BSSIDs are behind same gateway
467     ***/
468    public static int HOME_NETWORK_RSSI_BOOST = 5;
469
470    /** @hide
471     * RSSI boost for configuration which use autoJoinUseAggressiveJoinAttemptThreshold
472     * To be more aggressive when initially attempting to auto join
473     */
474    public static int MAX_INITIAL_AUTO_JOIN_RSSI_BOOST = 8;
475
476    /**
477     * @hide
478     * A summary of the RSSI and Band status for that configuration
479     * This is used as a temporary value by the auto-join controller
480     */
481    public final class Visibility {
482        public int rssi5;   // strongest 5GHz RSSI
483        public int rssi24;  // strongest 2.4GHz RSSI
484        public int num5;    // number of BSSIDs on 5GHz
485        public int num24;   // number of BSSIDs on 2.4GHz
486        public long age5;   // timestamp of the strongest 5GHz BSSID (last time it was seen)
487        public long age24;  // timestamp of the strongest 2.4GHz BSSID (last time it was seen)
488        public String BSSID24;
489        public String BSSID5;
490        public int score; // Debug only, indicate last score used for autojoin/cell-handover
491        public int currentNetworkBoost; // Debug only, indicate boost applied to RSSI if current
492        public int bandPreferenceBoost; // Debug only, indicate boost applied to RSSI if current
493        public int lastChoiceBoost; // Debug only, indicate last choice applied to this configuration
494        public String lastChoiceConfig; // Debug only, indicate last choice applied to this configuration
495
496        public Visibility() {
497            rssi5 = INVALID_RSSI;
498            rssi24 = INVALID_RSSI;
499        }
500
501        public Visibility(Visibility source) {
502            rssi5 = source.rssi5;
503            rssi24 = source.rssi24;
504            age24 = source.age24;
505            age5 = source.age5;
506            num24 = source.num24;
507            num5 = source.num5;
508            BSSID5 = source.BSSID5;
509            BSSID24 = source.BSSID24;
510        }
511
512        @Override
513        public String toString() {
514            StringBuilder sbuf = new StringBuilder();
515            sbuf.append("[");
516            if (rssi24 > INVALID_RSSI) {
517                sbuf.append(Integer.toString(rssi24));
518                sbuf.append(",");
519                sbuf.append(Integer.toString(num24));
520                if (BSSID24 != null) sbuf.append(",").append(BSSID24);
521            }
522            sbuf.append("; ");
523            if (rssi5 > INVALID_RSSI) {
524                sbuf.append(Integer.toString(rssi5));
525                sbuf.append(",");
526                sbuf.append(Integer.toString(num5));
527                if (BSSID5 != null) sbuf.append(",").append(BSSID5);
528            }
529            if (score != 0) {
530                sbuf.append("; ").append(score);
531                sbuf.append(", ").append(currentNetworkBoost);
532                sbuf.append(", ").append(bandPreferenceBoost);
533                if (lastChoiceConfig != null) {
534                    sbuf.append(", ").append(lastChoiceBoost);
535                    sbuf.append(", ").append(lastChoiceConfig);
536                }
537            }
538            sbuf.append("]");
539            return sbuf.toString();
540        }
541    }
542
543    /** @hide
544     * Cache the visibility status of this configuration.
545     * Visibility can change at any time depending on scan results availability.
546     * Owner of the WifiConfiguration is responsible to set this field based on
547     * recent scan results.
548     ***/
549    public Visibility visibility;
550
551    /** @hide
552     * calculate and set Visibility for that configuration.
553     *
554     * age in milliseconds: we will consider only ScanResults that are more recent,
555     * i.e. younger.
556     ***/
557    public Visibility setVisibility(long age) {
558        if (scanResultCache == null) {
559            visibility = null;
560            return null;
561        }
562
563        Visibility status = new Visibility();
564
565        long now_ms = System.currentTimeMillis();
566        for(ScanResult result : scanResultCache.values()) {
567            if (result.seen == 0)
568                continue;
569
570            if (result.is5GHz()) {
571                //strictly speaking: [4915, 5825]
572                //number of known BSSID on 5GHz band
573                status.num5 = status.num5 + 1;
574            } else if (result.is24GHz()) {
575                //strictly speaking: [2412, 2482]
576                //number of known BSSID on 2.4Ghz band
577                status.num24 = status.num24 + 1;
578            }
579
580            if ((now_ms - result.seen) > age) continue;
581
582            if (result.is5GHz()) {
583                if (result.level > status.rssi5) {
584                    status.rssi5 = result.level;
585                    status.age5 = result.seen;
586                    status.BSSID5 = result.BSSID;
587                }
588            } else if (result.is24GHz()) {
589                if (result.level > status.rssi24) {
590                    status.rssi24 = result.level;
591                    status.age24 = result.seen;
592                    status.BSSID24 = result.BSSID;
593                }
594            }
595        }
596        visibility = status;
597        return status;
598    }
599
600    /** @hide */
601    public static final int AUTO_JOIN_ENABLED                   = 0;
602    /**
603     * if this is set, the WifiConfiguration cannot use linkages so as to bump
604     * it's relative priority.
605     * - status between and 128 indicate various level of blacklisting depending
606     * on the severity or frequency of the connection error
607     * - deleted status indicates that the user is deleting the configuration, and so
608     * although it may have been self added we will not re-self-add it, ignore it,
609     * not return it to applications, and not connect to it
610     * */
611
612    /** @hide
613     * network was temporary disabled due to bad connection, most likely due
614     * to weak RSSI */
615    public static final int AUTO_JOIN_TEMPORARY_DISABLED  = 1;
616    /** @hide
617     * network was temporary disabled due to bad connection, which cant be attributed
618     * to weak RSSI */
619    public static final int AUTO_JOIN_TEMPORARY_DISABLED_LINK_ERRORS  = 32;
620    /** @hide */
621    public static final int AUTO_JOIN_TEMPORARY_DISABLED_AT_SUPPLICANT  = 64;
622    /** @hide */
623    public static final int AUTO_JOIN_DISABLED_ON_AUTH_FAILURE  = 128;
624    /** @hide */
625    public static final int AUTO_JOIN_DISABLED_NO_CREDENTIALS = 160;
626    /** @hide */
627    public static final int AUTO_JOIN_DISABLED_USER_ACTION = 161;
628
629    /** @hide */
630    public static final int AUTO_JOIN_DELETED  = 200;
631
632    /**
633     * @hide
634     */
635    public int autoJoinStatus;
636
637    /**
638     * @hide
639     * Number of connection failures
640     */
641    public int numConnectionFailures;
642
643    /**
644     * @hide
645     * Number of IP config failures
646     */
647    public int numIpConfigFailures;
648
649    /**
650     * @hide
651     * Number of Auth failures
652     */
653    public int numAuthFailures;
654
655    /**
656     * @hide
657     * Number of reports indicating no Internet Access
658     */
659    public int numNoInternetAccessReports;
660
661    /**
662     * @hide
663     * The WiFi configuration is considered to have no internet access for purpose of autojoining
664     * if there has been a report of it having no internet access, and, it never have had
665     * internet access in the past.
666     */
667    public boolean hasNoInternetAccess() {
668        return numNoInternetAccessReports > 0 && !validatedInternetAccess;
669    }
670
671    /**
672     * @hide
673     * Last time we blacklisted the configuration
674     */
675    public long blackListTimestamp;
676
677    /**
678     * @hide
679     * Last time the system was connected to this configuration.
680     */
681    public long lastConnected;
682
683    /**
684     * @hide
685     * Last time the system tried to connect and failed.
686     */
687    public long lastConnectionFailure;
688
689    /**
690     * @hide
691     * Last time the system was disconnected to this configuration.
692     */
693    public long lastDisconnected;
694
695    /**
696     * Set if the configuration was self added by the framework
697     * This boolean is cleared if we get a connect/save/ update or
698     * any wifiManager command that indicate the user interacted with the configuration
699     * since we will now consider that the configuration belong to him.
700     * @hide
701     */
702    public boolean selfAdded;
703
704    /**
705     * Set if the configuration was self added by the framework
706     * This boolean is set once and never cleared. It is used
707     * so as we never loose track of who created the
708     * configuration in the first place.
709     * @hide
710     */
711    public boolean didSelfAdd;
712
713    /**
714     * Peer WifiConfiguration this WifiConfiguration was added for
715     * @hide
716     */
717    public String peerWifiConfiguration;
718
719    /**
720     * @hide
721     * Indicate that a WifiConfiguration is temporary and should not be saved
722     * nor considered by AutoJoin.
723     */
724    public boolean ephemeral;
725
726    /**
727     * @hide
728     * Indicate that we didn't auto-join because rssi was too low
729     */
730    public boolean autoJoinBailedDueToLowRssi;
731
732    /**
733     * @hide
734     * AutoJoin even though RSSI is 10dB below threshold
735     */
736    public int autoJoinUseAggressiveJoinAttemptThreshold;
737
738    /**
739     * @hide
740     * Number of time the scorer overrode a the priority based choice, when comparing two
741     * WifiConfigurations, note that since comparing WifiConfiguration happens very often
742     * potentially at every scan, this number might become very large, even on an idle
743     * system.
744     */
745    @SystemApi
746    public int numScorerOverride;
747
748    /**
749     * @hide
750     * Number of time the scorer overrode a the priority based choice, and the comparison
751     * triggered a network switch
752     */
753    @SystemApi
754    public int numScorerOverrideAndSwitchedNetwork;
755
756    /**
757     * @hide
758     * Number of time we associated to this configuration.
759     */
760    @SystemApi
761    public int numAssociation;
762
763    /**
764     * @hide
765     * Number of time user disabled WiFi while associated to this configuration with Low RSSI.
766     */
767    public int numUserTriggeredWifiDisableLowRSSI;
768
769    /**
770     * @hide
771     * Number of time user disabled WiFi while associated to this configuration with Bad RSSI.
772     */
773    public int numUserTriggeredWifiDisableBadRSSI;
774
775    /**
776     * @hide
777     * Number of time user disabled WiFi while associated to this configuration
778     * and RSSI was not HIGH.
779     */
780    public int numUserTriggeredWifiDisableNotHighRSSI;
781
782    /**
783     * @hide
784     * Number of ticks associated to this configuration with Low RSSI.
785     */
786    public int numTicksAtLowRSSI;
787
788    /**
789     * @hide
790     * Number of ticks associated to this configuration with Bad RSSI.
791     */
792    public int numTicksAtBadRSSI;
793
794    /**
795     * @hide
796     * Number of ticks associated to this configuration
797     * and RSSI was not HIGH.
798     */
799    public int numTicksAtNotHighRSSI;
800    /**
801     * @hide
802     * Number of time user (WifiManager) triggered association to this configuration.
803     * TODO: count this only for Wifi Settings uuid, so as to not count 3rd party apps
804     */
805    public int numUserTriggeredJoinAttempts;
806
807    /**
808     * @hide
809     * Connect choices
810     *
811     * remember the keys identifying the known WifiConfiguration over which this configuration
812     * was preferred by user or a "WiFi Network Management app", that is,
813     * a WifiManager.CONNECT_NETWORK or SELECT_NETWORK was received while this configuration
814     * was visible to the user:
815     * configKey is : "SSID"-WEP-WPA_PSK-WPA_EAP
816     *
817     * The integer represents the configuration's RSSI at that time (useful?)
818     *
819     * The overall auto-join algorithm make use of past connect choice so as to sort configuration,
820     * the exact algorithm still fluctuating as of 5/7/2014
821     *
822     */
823    public HashMap<String, Integer> connectChoices;
824
825    /**
826     * @hide
827     * Linked Configurations: represent the set of Wificonfigurations that are equivalent
828     * regarding roaming and auto-joining.
829     * The linked configuration may or may not have same SSID, and may or may not have same
830     * credentials.
831     * For instance, linked configurations will have same defaultGwMacAddress or same dhcp server.
832     */
833    public HashMap<String, Integer>  linkedConfigurations;
834
835    public WifiConfiguration() {
836        networkId = INVALID_NETWORK_ID;
837        SSID = null;
838        BSSID = null;
839        FQDN = null;
840        naiRealm = null;
841        priority = 0;
842        hiddenSSID = false;
843        disableReason = DISABLED_UNKNOWN_REASON;
844        allowedKeyManagement = new BitSet();
845        allowedProtocols = new BitSet();
846        allowedAuthAlgorithms = new BitSet();
847        allowedPairwiseCiphers = new BitSet();
848        allowedGroupCiphers = new BitSet();
849        wepKeys = new String[4];
850        for (int i = 0; i < wepKeys.length; i++) {
851            wepKeys[i] = null;
852        }
853        enterpriseConfig = new WifiEnterpriseConfig();
854        autoJoinStatus = AUTO_JOIN_ENABLED;
855        selfAdded = false;
856        didSelfAdd = false;
857        ephemeral = false;
858        validatedInternetAccess = false;
859        mIpConfiguration = new IpConfiguration();
860    }
861
862    /**
863     * indicates whether the configuration is valid
864     * @return true if valid, false otherwise
865     * @hide
866     */
867    public boolean isValid() {
868
869        if (allowedKeyManagement == null)
870            return false;
871
872        if (allowedKeyManagement.cardinality() > 1) {
873            if (allowedKeyManagement.cardinality() != 2) {
874                return false;
875            }
876            if (allowedKeyManagement.get(KeyMgmt.WPA_EAP) == false) {
877                return false;
878            }
879            if ((allowedKeyManagement.get(KeyMgmt.IEEE8021X) == false)
880                    && (allowedKeyManagement.get(KeyMgmt.WPA_PSK) == false)) {
881                return false;
882            }
883        }
884
885        // TODO: Add more checks
886        return true;
887    }
888
889    /**
890     * Helper function, identify if a configuration is linked
891     * @hide
892     */
893    public boolean isLinked(WifiConfiguration config) {
894        if (config.linkedConfigurations != null && linkedConfigurations != null) {
895            if (config.linkedConfigurations.get(configKey()) != null
896                    && linkedConfigurations.get(config.configKey()) != null) {
897                return true;
898            }
899        }
900        return  false;
901    }
902
903    /**
904     * most recent time we have seen this configuration
905     * @return most recent scanResult
906     * @hide
907     */
908    public ScanResult lastSeen() {
909        ScanResult mostRecent = null;
910
911        if (scanResultCache == null) {
912            return null;
913        }
914
915        for (ScanResult result : scanResultCache.values()) {
916            if (mostRecent == null) {
917                if (result.seen != 0)
918                   mostRecent = result;
919            } else {
920                if (result.seen > mostRecent.seen) {
921                   mostRecent = result;
922                }
923            }
924        }
925        return mostRecent;
926    }
927
928    /** @hide **/
929    public void setAutoJoinStatus(int status) {
930        if (status < 0) status = 0;
931        if (status == 0) {
932            blackListTimestamp = 0;
933        }  else if (status > autoJoinStatus) {
934            blackListTimestamp = System.currentTimeMillis();
935        }
936        if (status != autoJoinStatus) {
937            autoJoinStatus = status;
938            dirty = true;
939        }
940    }
941
942    /** @hide
943     *  trim the scan Result Cache
944     * @param: number of entries to keep in the cache
945     */
946    public void trimScanResultsCache(int num) {
947        if (this.scanResultCache == null) {
948            return;
949        }
950        int currenSize = this.scanResultCache.size();
951        if (currenSize <= num) {
952            return; // Nothing to trim
953        }
954        ArrayList<ScanResult> list = new ArrayList<ScanResult>(this.scanResultCache.values());
955        if (list.size() != 0) {
956            // Sort by descending timestamp
957            Collections.sort(list, new Comparator() {
958                public int compare(Object o1, Object o2) {
959                    ScanResult a = (ScanResult)o1;
960                    ScanResult b = (ScanResult)o2;
961                    if (a.seen > b.seen) {
962                        return 1;
963                    }
964                    if (a.seen < b.seen) {
965                        return -1;
966                    }
967                    return a.BSSID.compareTo(b.BSSID);
968                }
969            });
970        }
971        for (int i = 0; i < currenSize - num ; i++) {
972            // Remove oldest results from scan cache
973            ScanResult result = list.get(i);
974            this.scanResultCache.remove(result.BSSID);
975        }
976    }
977
978    /* @hide */
979    private ArrayList<ScanResult> sortScanResults() {
980        ArrayList<ScanResult> list = new ArrayList<ScanResult>(this.scanResultCache.values());
981        if (list.size() != 0) {
982            Collections.sort(list, new Comparator() {
983                public int compare(Object o1, Object o2) {
984                    ScanResult a = (ScanResult)o1;
985                    ScanResult b = (ScanResult)o2;
986                    if (a.numIpConfigFailures > b.numIpConfigFailures) {
987                        return 1;
988                    }
989                    if (a.numIpConfigFailures < b.numIpConfigFailures) {
990                        return -1;
991                    }
992                    if (a.seen > b.seen) {
993                        return -1;
994                    }
995                    if (a.seen < b.seen) {
996                        return 1;
997                    }
998                    if (a.level > b.level) {
999                        return -1;
1000                    }
1001                    if (a.level < b.level) {
1002                        return 1;
1003                    }
1004                    return a.BSSID.compareTo(b.BSSID);
1005                }
1006            });
1007        }
1008        return list;
1009    }
1010
1011    @Override
1012    public String toString() {
1013        StringBuilder sbuf = new StringBuilder();
1014        if (this.status == WifiConfiguration.Status.CURRENT) {
1015            sbuf.append("* ");
1016        } else if (this.status == WifiConfiguration.Status.DISABLED) {
1017            sbuf.append("- DSBLE ");
1018        }
1019        sbuf.append("ID: ").append(this.networkId).append(" SSID: ").append(this.SSID).
1020                append(" BSSID: ").append(this.BSSID).append(" FQDN: ").append(this.FQDN).
1021                append(" REALM: ").append(this.naiRealm).append(" PRIO: ").append(this.priority).
1022                append('\n');
1023        if (this.numConnectionFailures > 0) {
1024            sbuf.append(" numConnectFailures ").append(this.numConnectionFailures).append("\n");
1025        }
1026        if (this.numIpConfigFailures > 0) {
1027            sbuf.append(" numIpConfigFailures ").append(this.numIpConfigFailures).append("\n");
1028        }
1029        if (this.numAuthFailures > 0) {
1030            sbuf.append(" numAuthFailures ").append(this.numAuthFailures).append("\n");
1031        }
1032        if (this.autoJoinStatus > 0) {
1033            sbuf.append(" autoJoinStatus ").append(this.autoJoinStatus).append("\n");
1034        }
1035        if (this.disableReason > 0) {
1036            sbuf.append(" disableReason ").append(this.disableReason).append("\n");
1037        }
1038        if (this.numAssociation > 0) {
1039            sbuf.append(" numAssociation ").append(this.numAssociation).append("\n");
1040        }
1041        if (this.numNoInternetAccessReports > 0) {
1042            sbuf.append(" numNoInternetAccessReports ");
1043            sbuf.append(this.numNoInternetAccessReports).append("\n");
1044        }
1045        if (this.didSelfAdd) sbuf.append(" didSelfAdd");
1046        if (this.selfAdded) sbuf.append(" selfAdded");
1047        if (this.validatedInternetAccess) sbuf.append(" validatedInternetAccess");
1048        if (this.ephemeral) sbuf.append(" ephemeral");
1049        if (this.didSelfAdd || this.selfAdded || this.validatedInternetAccess || this.ephemeral) {
1050            sbuf.append("\n");
1051        }
1052        sbuf.append(" KeyMgmt:");
1053        for (int k = 0; k < this.allowedKeyManagement.size(); k++) {
1054            if (this.allowedKeyManagement.get(k)) {
1055                sbuf.append(" ");
1056                if (k < KeyMgmt.strings.length) {
1057                    sbuf.append(KeyMgmt.strings[k]);
1058                } else {
1059                    sbuf.append("??");
1060                }
1061            }
1062        }
1063        sbuf.append(" Protocols:");
1064        for (int p = 0; p < this.allowedProtocols.size(); p++) {
1065            if (this.allowedProtocols.get(p)) {
1066                sbuf.append(" ");
1067                if (p < Protocol.strings.length) {
1068                    sbuf.append(Protocol.strings[p]);
1069                } else {
1070                    sbuf.append("??");
1071                }
1072            }
1073        }
1074        sbuf.append('\n');
1075        sbuf.append(" AuthAlgorithms:");
1076        for (int a = 0; a < this.allowedAuthAlgorithms.size(); a++) {
1077            if (this.allowedAuthAlgorithms.get(a)) {
1078                sbuf.append(" ");
1079                if (a < AuthAlgorithm.strings.length) {
1080                    sbuf.append(AuthAlgorithm.strings[a]);
1081                } else {
1082                    sbuf.append("??");
1083                }
1084            }
1085        }
1086        sbuf.append('\n');
1087        sbuf.append(" PairwiseCiphers:");
1088        for (int pc = 0; pc < this.allowedPairwiseCiphers.size(); pc++) {
1089            if (this.allowedPairwiseCiphers.get(pc)) {
1090                sbuf.append(" ");
1091                if (pc < PairwiseCipher.strings.length) {
1092                    sbuf.append(PairwiseCipher.strings[pc]);
1093                } else {
1094                    sbuf.append("??");
1095                }
1096            }
1097        }
1098        sbuf.append('\n');
1099        sbuf.append(" GroupCiphers:");
1100        for (int gc = 0; gc < this.allowedGroupCiphers.size(); gc++) {
1101            if (this.allowedGroupCiphers.get(gc)) {
1102                sbuf.append(" ");
1103                if (gc < GroupCipher.strings.length) {
1104                    sbuf.append(GroupCipher.strings[gc]);
1105                } else {
1106                    sbuf.append("??");
1107                }
1108            }
1109        }
1110        sbuf.append('\n').append(" PSK: ");
1111        if (this.preSharedKey != null) {
1112            sbuf.append('*');
1113        }
1114        sbuf.append("\nEnterprise config:\n");
1115        sbuf.append(enterpriseConfig);
1116
1117        sbuf.append("IP config:\n");
1118        sbuf.append(mIpConfiguration.toString());
1119
1120        if (this.creatorUid != 0)  sbuf.append(" uid=" + Integer.toString(creatorUid));
1121        if (this.autoJoinBSSID != null) sbuf.append(" autoJoinBSSID=" + autoJoinBSSID);
1122        long now_ms = System.currentTimeMillis();
1123        if (this.blackListTimestamp != 0) {
1124            sbuf.append('\n');
1125            long diff = now_ms - this.blackListTimestamp;
1126            if (diff <= 0) {
1127                sbuf.append(" blackListed since <incorrect>");
1128            } else {
1129                sbuf.append(" blackListed: ").append(Long.toString(diff/1000)).append( "sec");
1130            }
1131        }
1132        if (this.lastConnected != 0) {
1133            sbuf.append('\n');
1134            long diff = now_ms - this.lastConnected;
1135            if (diff <= 0) {
1136                sbuf.append("lastConnected since <incorrect>");
1137            } else {
1138                sbuf.append("lastConnected: ").append(Long.toString(diff/1000)).append( "sec");
1139            }
1140        }
1141        if (this.lastConnectionFailure != 0) {
1142            sbuf.append('\n');
1143            long diff = now_ms - this.lastConnectionFailure;
1144            if (diff <= 0) {
1145                sbuf.append("lastConnectionFailure since <incorrect>");
1146            } else {
1147                sbuf.append("lastConnectionFailure: ").append(Long.toString(diff/1000));
1148                sbuf.append( "sec");
1149            }
1150        }
1151        sbuf.append('\n');
1152        if (this.linkedConfigurations != null) {
1153            for(String key : this.linkedConfigurations.keySet()) {
1154                sbuf.append(" linked: ").append(key);
1155                sbuf.append('\n');
1156            }
1157        }
1158        if (this.connectChoices != null) {
1159            for(String key : this.connectChoices.keySet()) {
1160                Integer choice = this.connectChoices.get(key);
1161                if (choice != null) {
1162                    sbuf.append(" choice: ").append(key);
1163                    sbuf.append(" = ").append(choice);
1164                    sbuf.append('\n');
1165                }
1166            }
1167        }
1168        if (this.scanResultCache != null) {
1169            sbuf.append("Scan Cache:  ").append('\n');
1170            ArrayList<ScanResult> list = sortScanResults();
1171            if (list.size() > 0) {
1172                for (ScanResult result : list) {
1173                    long milli = now_ms - result.seen;
1174                    long ageSec = 0;
1175                    long ageMin = 0;
1176                    long ageHour = 0;
1177                    long ageMilli = 0;
1178                    long ageDay = 0;
1179                    if (now_ms > result.seen && result.seen > 0) {
1180                        ageMilli = milli % 1000;
1181                        ageSec   = (milli / 1000) % 60;
1182                        ageMin   = (milli / (60*1000)) % 60;
1183                        ageHour  = (milli / (60*60*1000)) % 24;
1184                        ageDay   = (milli / (24*60*60*1000));
1185                    }
1186                    sbuf.append("{").append(result.BSSID).append(",").append(result.frequency);
1187                    sbuf.append(",").append(String.format("%3d", result.level));
1188                    if (result.autoJoinStatus > 0) {
1189                        sbuf.append(",st=").append(result.autoJoinStatus);
1190                    }
1191                    if (ageSec > 0 || ageMilli > 0) {
1192                        sbuf.append(String.format(",%4d.%02d.%02d.%02d.%03dms", ageDay,
1193                                ageHour, ageMin, ageSec, ageMilli));
1194                    }
1195                    if (result.numIpConfigFailures > 0) {
1196                        sbuf.append(",ipfail=");
1197                        sbuf.append(result.numIpConfigFailures);
1198                    }
1199                    sbuf.append("} ");
1200                }
1201                sbuf.append('\n');
1202            }
1203        }
1204        sbuf.append("triggeredLow: ").append(this.numUserTriggeredWifiDisableLowRSSI);
1205        sbuf.append(" triggeredBad: ").append(this.numUserTriggeredWifiDisableBadRSSI);
1206        sbuf.append(" triggeredNotHigh: ").append(this.numUserTriggeredWifiDisableNotHighRSSI);
1207        sbuf.append('\n');
1208        sbuf.append("ticksLow: ").append(this.numTicksAtLowRSSI);
1209        sbuf.append(" ticksBad: ").append(this.numTicksAtBadRSSI);
1210        sbuf.append(" ticksNotHigh: ").append(this.numTicksAtNotHighRSSI);
1211        sbuf.append('\n');
1212        sbuf.append("triggeredJoin: ").append(this.numUserTriggeredJoinAttempts);
1213        sbuf.append('\n');
1214        sbuf.append("autoJoinBailedDueToLowRssi: ").append(this.autoJoinBailedDueToLowRssi);
1215        sbuf.append('\n');
1216        sbuf.append("autoJoinUseAggressiveJoinAttemptThreshold: ");
1217        sbuf.append(this.autoJoinUseAggressiveJoinAttemptThreshold);
1218        sbuf.append('\n');
1219
1220        return sbuf.toString();
1221    }
1222
1223    /**
1224     * Construct a WifiConfiguration from a scanned network
1225     * @param scannedAP the scan result used to construct the config entry
1226     * TODO: figure out whether this is a useful way to construct a new entry.
1227     *
1228    public WifiConfiguration(ScanResult scannedAP) {
1229        networkId = -1;
1230        SSID = scannedAP.SSID;
1231        BSSID = scannedAP.BSSID;
1232    }
1233    */
1234
1235    /** {@hide} */
1236    public String getPrintableSsid() {
1237        if (SSID == null) return "";
1238        final int length = SSID.length();
1239        if (length > 2 && (SSID.charAt(0) == '"') && SSID.charAt(length - 1) == '"') {
1240            return SSID.substring(1, length - 1);
1241        }
1242
1243        /** The ascii-encoded string format is P"<ascii-encoded-string>"
1244         * The decoding is implemented in the supplicant for a newly configured
1245         * network.
1246         */
1247        if (length > 3 && (SSID.charAt(0) == 'P') && (SSID.charAt(1) == '"') &&
1248                (SSID.charAt(length-1) == '"')) {
1249            WifiSsid wifiSsid = WifiSsid.createFromAsciiEncoded(
1250                    SSID.substring(2, length - 1));
1251            return wifiSsid.toString();
1252        }
1253        return SSID;
1254    }
1255
1256    /**
1257     * Get an identifier for associating credentials with this config
1258     * @param current configuration contains values for additional fields
1259     *                that are not part of this configuration. Used
1260     *                when a config with some fields is passed by an application.
1261     * @throws IllegalStateException if config is invalid for key id generation
1262     * @hide
1263     */
1264    public String getKeyIdForCredentials(WifiConfiguration current) {
1265        String keyMgmt = null;
1266
1267        try {
1268            // Get current config details for fields that are not initialized
1269            if (TextUtils.isEmpty(SSID)) SSID = current.SSID;
1270            if (allowedKeyManagement.cardinality() == 0) {
1271                allowedKeyManagement = current.allowedKeyManagement;
1272            }
1273            if (allowedKeyManagement.get(KeyMgmt.WPA_EAP)) {
1274                keyMgmt = KeyMgmt.strings[KeyMgmt.WPA_EAP];
1275            }
1276            if (allowedKeyManagement.get(KeyMgmt.IEEE8021X)) {
1277                keyMgmt += KeyMgmt.strings[KeyMgmt.IEEE8021X];
1278            }
1279
1280            if (TextUtils.isEmpty(keyMgmt)) {
1281                throw new IllegalStateException("Not an EAP network");
1282            }
1283
1284            return trimStringForKeyId(SSID) + "_" + keyMgmt + "_" +
1285                    trimStringForKeyId(enterpriseConfig.getKeyId(current != null ?
1286                            current.enterpriseConfig : null));
1287        } catch (NullPointerException e) {
1288            throw new IllegalStateException("Invalid config details");
1289        }
1290    }
1291
1292    private String trimStringForKeyId(String string) {
1293        // Remove quotes and spaces
1294        return string.replace("\"", "").replace(" ", "");
1295    }
1296
1297    private static BitSet readBitSet(Parcel src) {
1298        int cardinality = src.readInt();
1299
1300        BitSet set = new BitSet();
1301        for (int i = 0; i < cardinality; i++) {
1302            set.set(src.readInt());
1303        }
1304
1305        return set;
1306    }
1307
1308    private static void writeBitSet(Parcel dest, BitSet set) {
1309        int nextSetBit = -1;
1310
1311        dest.writeInt(set.cardinality());
1312
1313        while ((nextSetBit = set.nextSetBit(nextSetBit + 1)) != -1) {
1314            dest.writeInt(nextSetBit);
1315        }
1316    }
1317
1318    /** @hide */
1319    public int getAuthType() {
1320        if (isValid() == false) {
1321            throw new IllegalStateException("Invalid configuration");
1322        }
1323        if (allowedKeyManagement.get(KeyMgmt.WPA_PSK)) {
1324            return KeyMgmt.WPA_PSK;
1325        } else if (allowedKeyManagement.get(KeyMgmt.WPA2_PSK)) {
1326            return KeyMgmt.WPA2_PSK;
1327        } else if (allowedKeyManagement.get(KeyMgmt.WPA_EAP)) {
1328            return KeyMgmt.WPA_EAP;
1329        } else if (allowedKeyManagement.get(KeyMgmt.IEEE8021X)) {
1330            return KeyMgmt.IEEE8021X;
1331        }
1332        return KeyMgmt.NONE;
1333    }
1334
1335    /* @hide
1336     * Cache the config key, this seems useful as a speed up since a lot of
1337     * lookups in the config store are done and based on this key.
1338     */
1339    String mCachedConfigKey;
1340
1341    /** @hide
1342     *  return the string used to calculate the hash in WifiConfigStore
1343     *  and uniquely identify this WifiConfiguration
1344     */
1345    public String configKey(boolean allowCached) {
1346        String key;
1347        if (allowCached && mCachedConfigKey != null) {
1348            key = mCachedConfigKey;
1349        } else {
1350            if (allowedKeyManagement.get(KeyMgmt.WPA_PSK)) {
1351                key = SSID + KeyMgmt.strings[KeyMgmt.WPA_PSK];
1352            } else if (allowedKeyManagement.get(KeyMgmt.WPA_EAP) ||
1353                    allowedKeyManagement.get(KeyMgmt.IEEE8021X)) {
1354                key = SSID + KeyMgmt.strings[KeyMgmt.WPA_EAP];
1355            } else if (wepKeys[0] != null) {
1356                key = SSID + "WEP";
1357            } else {
1358                key = SSID + KeyMgmt.strings[KeyMgmt.NONE];
1359            }
1360            mCachedConfigKey = key;
1361        }
1362        return key;
1363    }
1364
1365    /** @hide
1366     * get configKey, force calculating the config string
1367     */
1368    public String configKey() {
1369        return configKey(false);
1370    }
1371
1372    /** @hide
1373     * return the config key string based on a scan result
1374     */
1375    static public String configKey(ScanResult result) {
1376        String key = "\"" + result.SSID + "\"";
1377
1378        if (result.capabilities.contains("WEP")) {
1379            key = key + "-WEP";
1380        }
1381
1382        if (result.capabilities.contains("PSK")) {
1383            key = key + "-" + KeyMgmt.strings[KeyMgmt.WPA_PSK];
1384        }
1385
1386        if (result.capabilities.contains("EAP")) {
1387            key = key + "-" + KeyMgmt.strings[KeyMgmt.WPA_EAP];
1388        }
1389
1390        return key;
1391    }
1392
1393    /** @hide */
1394    public IpConfiguration getIpConfiguration() {
1395        return mIpConfiguration;
1396    }
1397
1398    /** @hide */
1399    public void setIpConfiguration(IpConfiguration ipConfiguration) {
1400        mIpConfiguration = ipConfiguration;
1401    }
1402
1403    /** @hide */
1404    public StaticIpConfiguration getStaticIpConfiguration() {
1405        return mIpConfiguration.getStaticIpConfiguration();
1406    }
1407
1408    /** @hide */
1409    public void setStaticIpConfiguration(StaticIpConfiguration staticIpConfiguration) {
1410        mIpConfiguration.setStaticIpConfiguration(staticIpConfiguration);
1411    }
1412
1413    /** @hide */
1414    public IpConfiguration.IpAssignment getIpAssignment() {
1415        return mIpConfiguration.ipAssignment;
1416    }
1417
1418    /** @hide */
1419    public void setIpAssignment(IpConfiguration.IpAssignment ipAssignment) {
1420        mIpConfiguration.ipAssignment = ipAssignment;
1421    }
1422
1423    /** @hide */
1424    public IpConfiguration.ProxySettings getProxySettings() {
1425        return mIpConfiguration.proxySettings;
1426    }
1427
1428    /** @hide */
1429    public void setProxySettings(IpConfiguration.ProxySettings proxySettings) {
1430        mIpConfiguration.proxySettings = proxySettings;
1431    }
1432
1433    /** @hide */
1434    public ProxyInfo getHttpProxy() {
1435        return mIpConfiguration.httpProxy;
1436    }
1437
1438    /** @hide */
1439    public void setHttpProxy(ProxyInfo httpProxy) {
1440        mIpConfiguration.httpProxy = httpProxy;
1441    }
1442
1443    /** @hide */
1444    public void setProxy(ProxySettings settings, ProxyInfo proxy) {
1445        mIpConfiguration.proxySettings = settings;
1446        mIpConfiguration.httpProxy = proxy;
1447    }
1448
1449    /** Implement the Parcelable interface {@hide} */
1450    public int describeContents() {
1451        return 0;
1452    }
1453
1454    /** copy constructor {@hide} */
1455    public WifiConfiguration(WifiConfiguration source) {
1456        if (source != null) {
1457            networkId = source.networkId;
1458            status = source.status;
1459            disableReason = source.disableReason;
1460            disableReason = source.disableReason;
1461            SSID = source.SSID;
1462            BSSID = source.BSSID;
1463            FQDN = source.FQDN;
1464            naiRealm = source.naiRealm;
1465            preSharedKey = source.preSharedKey;
1466
1467            wepKeys = new String[4];
1468            for (int i = 0; i < wepKeys.length; i++) {
1469                wepKeys[i] = source.wepKeys[i];
1470            }
1471
1472            wepTxKeyIndex = source.wepTxKeyIndex;
1473            priority = source.priority;
1474            hiddenSSID = source.hiddenSSID;
1475            allowedKeyManagement   = (BitSet) source.allowedKeyManagement.clone();
1476            allowedProtocols       = (BitSet) source.allowedProtocols.clone();
1477            allowedAuthAlgorithms  = (BitSet) source.allowedAuthAlgorithms.clone();
1478            allowedPairwiseCiphers = (BitSet) source.allowedPairwiseCiphers.clone();
1479            allowedGroupCiphers    = (BitSet) source.allowedGroupCiphers.clone();
1480
1481            enterpriseConfig = new WifiEnterpriseConfig(source.enterpriseConfig);
1482
1483            defaultGwMacAddress = source.defaultGwMacAddress;
1484
1485            mIpConfiguration = new IpConfiguration(source.mIpConfiguration);
1486
1487            if ((source.scanResultCache != null) && (source.scanResultCache.size() > 0)) {
1488                scanResultCache = new HashMap<String, ScanResult>();
1489                scanResultCache.putAll(source.scanResultCache);
1490            }
1491
1492            if ((source.connectChoices != null) && (source.connectChoices.size() > 0)) {
1493                connectChoices = new HashMap<String, Integer>();
1494                connectChoices.putAll(source.connectChoices);
1495            }
1496
1497            if ((source.linkedConfigurations != null)
1498                    && (source.linkedConfigurations.size() > 0)) {
1499                linkedConfigurations = new HashMap<String, Integer>();
1500                linkedConfigurations.putAll(source.linkedConfigurations);
1501            }
1502            mCachedConfigKey = null; //force null configKey
1503            autoJoinStatus = source.autoJoinStatus;
1504            selfAdded = source.selfAdded;
1505            validatedInternetAccess = source.validatedInternetAccess;
1506            ephemeral = source.ephemeral;
1507            if (source.visibility != null) {
1508                visibility = new Visibility(source.visibility);
1509            }
1510
1511            lastFailure = source.lastFailure;
1512            didSelfAdd = source.didSelfAdd;
1513            lastConnectUid = source.lastConnectUid;
1514            lastUpdateUid = source.lastUpdateUid;
1515            creatorUid = source.creatorUid;
1516            peerWifiConfiguration = source.peerWifiConfiguration;
1517            blackListTimestamp = source.blackListTimestamp;
1518            lastConnected = source.lastConnected;
1519            lastDisconnected = source.lastDisconnected;
1520            lastConnectionFailure = source.lastConnectionFailure;
1521            numConnectionFailures = source.numConnectionFailures;
1522            numIpConfigFailures = source.numIpConfigFailures;
1523            numAuthFailures = source.numAuthFailures;
1524            numScorerOverride = source.numScorerOverride;
1525            numScorerOverrideAndSwitchedNetwork = source.numScorerOverrideAndSwitchedNetwork;
1526            numAssociation = source.numAssociation;
1527            numUserTriggeredWifiDisableLowRSSI = source.numUserTriggeredWifiDisableLowRSSI;
1528            numUserTriggeredWifiDisableBadRSSI = source.numUserTriggeredWifiDisableBadRSSI;
1529            numUserTriggeredWifiDisableNotHighRSSI = source.numUserTriggeredWifiDisableNotHighRSSI;
1530            numTicksAtLowRSSI = source.numTicksAtLowRSSI;
1531            numTicksAtBadRSSI = source.numTicksAtBadRSSI;
1532            numTicksAtNotHighRSSI = source.numTicksAtNotHighRSSI;
1533            numUserTriggeredJoinAttempts = source.numUserTriggeredJoinAttempts;
1534            autoJoinBSSID = source.autoJoinBSSID;
1535            autoJoinUseAggressiveJoinAttemptThreshold
1536                    = source.autoJoinUseAggressiveJoinAttemptThreshold;
1537            autoJoinBailedDueToLowRssi = source.autoJoinBailedDueToLowRssi;
1538            dirty = source.dirty;
1539            numNoInternetAccessReports = source.numNoInternetAccessReports;
1540        }
1541    }
1542
1543    /** {@hide} */
1544    //public static final int NOTHING_TAG = 0;
1545    /** {@hide} */
1546    //public static final int SCAN_CACHE_TAG = 1;
1547
1548    /** Implement the Parcelable interface {@hide} */
1549    @Override
1550    public void writeToParcel(Parcel dest, int flags) {
1551        dest.writeInt(networkId);
1552        dest.writeInt(status);
1553        dest.writeInt(disableReason);
1554        dest.writeString(SSID);
1555        dest.writeString(BSSID);
1556        dest.writeString(autoJoinBSSID);
1557        dest.writeString(FQDN);
1558        dest.writeString(naiRealm);
1559        dest.writeString(preSharedKey);
1560        for (String wepKey : wepKeys) {
1561            dest.writeString(wepKey);
1562        }
1563        dest.writeInt(wepTxKeyIndex);
1564        dest.writeInt(priority);
1565        dest.writeInt(hiddenSSID ? 1 : 0);
1566        dest.writeInt(requirePMF ? 1 : 0);
1567        dest.writeString(updateIdentifier);
1568
1569        writeBitSet(dest, allowedKeyManagement);
1570        writeBitSet(dest, allowedProtocols);
1571        writeBitSet(dest, allowedAuthAlgorithms);
1572        writeBitSet(dest, allowedPairwiseCiphers);
1573        writeBitSet(dest, allowedGroupCiphers);
1574
1575        dest.writeParcelable(enterpriseConfig, flags);
1576
1577        dest.writeParcelable(mIpConfiguration, flags);
1578        dest.writeString(dhcpServer);
1579        dest.writeString(defaultGwMacAddress);
1580        dest.writeInt(autoJoinStatus);
1581        dest.writeInt(selfAdded ? 1 : 0);
1582        dest.writeInt(didSelfAdd ? 1 : 0);
1583        dest.writeInt(validatedInternetAccess ? 1 : 0);
1584        dest.writeInt(ephemeral ? 1 : 0);
1585        dest.writeInt(creatorUid);
1586        dest.writeInt(lastConnectUid);
1587        dest.writeInt(lastUpdateUid);
1588        dest.writeLong(blackListTimestamp);
1589        dest.writeLong(lastConnectionFailure);
1590        dest.writeInt(numConnectionFailures);
1591        dest.writeInt(numIpConfigFailures);
1592        dest.writeInt(numAuthFailures);
1593        dest.writeInt(numScorerOverride);
1594        dest.writeInt(numScorerOverrideAndSwitchedNetwork);
1595        dest.writeInt(numAssociation);
1596        dest.writeInt(numUserTriggeredWifiDisableLowRSSI);
1597        dest.writeInt(numUserTriggeredWifiDisableBadRSSI);
1598        dest.writeInt(numUserTriggeredWifiDisableNotHighRSSI);
1599        dest.writeInt(numTicksAtLowRSSI);
1600        dest.writeInt(numTicksAtBadRSSI);
1601        dest.writeInt(numTicksAtNotHighRSSI);
1602        dest.writeInt(numUserTriggeredJoinAttempts);
1603        dest.writeInt(autoJoinUseAggressiveJoinAttemptThreshold);
1604        dest.writeInt(autoJoinBailedDueToLowRssi ? 1 : 0);
1605        dest.writeInt(numNoInternetAccessReports);
1606    }
1607
1608    /** Implement the Parcelable interface {@hide} */
1609    public static final Creator<WifiConfiguration> CREATOR =
1610        new Creator<WifiConfiguration>() {
1611            public WifiConfiguration createFromParcel(Parcel in) {
1612                WifiConfiguration config = new WifiConfiguration();
1613                config.networkId = in.readInt();
1614                config.status = in.readInt();
1615                config.disableReason = in.readInt();
1616                config.SSID = in.readString();
1617                config.BSSID = in.readString();
1618                config.autoJoinBSSID = in.readString();
1619                config.FQDN = in.readString();
1620                config.naiRealm = in.readString();
1621                config.preSharedKey = in.readString();
1622                for (int i = 0; i < config.wepKeys.length; i++) {
1623                    config.wepKeys[i] = in.readString();
1624                }
1625                config.wepTxKeyIndex = in.readInt();
1626                config.priority = in.readInt();
1627                config.hiddenSSID = in.readInt() != 0;
1628                config.requirePMF = in.readInt() != 0;
1629                config.updateIdentifier = in.readString();
1630
1631                config.allowedKeyManagement   = readBitSet(in);
1632                config.allowedProtocols       = readBitSet(in);
1633                config.allowedAuthAlgorithms  = readBitSet(in);
1634                config.allowedPairwiseCiphers = readBitSet(in);
1635                config.allowedGroupCiphers    = readBitSet(in);
1636
1637                config.enterpriseConfig = in.readParcelable(null);
1638
1639                config.mIpConfiguration = in.readParcelable(null);
1640                config.dhcpServer = in.readString();
1641                config.defaultGwMacAddress = in.readString();
1642                config.autoJoinStatus = in.readInt();
1643                config.selfAdded = in.readInt() != 0;
1644                config.didSelfAdd = in.readInt() != 0;
1645                config.validatedInternetAccess = in.readInt() != 0;
1646                config.ephemeral = in.readInt() != 0;
1647                config.creatorUid = in.readInt();
1648                config.lastConnectUid = in.readInt();
1649                config.lastUpdateUid = in.readInt();
1650                config.blackListTimestamp = in.readLong();
1651                config.lastConnectionFailure = in.readLong();
1652                config.numConnectionFailures = in.readInt();
1653                config.numIpConfigFailures = in.readInt();
1654                config.numAuthFailures = in.readInt();
1655                config.numScorerOverride = in.readInt();
1656                config.numScorerOverrideAndSwitchedNetwork = in.readInt();
1657                config.numAssociation = in.readInt();
1658                config.numUserTriggeredWifiDisableLowRSSI = in.readInt();
1659                config.numUserTriggeredWifiDisableBadRSSI = in.readInt();
1660                config.numUserTriggeredWifiDisableNotHighRSSI = in.readInt();
1661                config.numTicksAtLowRSSI = in.readInt();
1662                config.numTicksAtBadRSSI = in.readInt();
1663                config.numTicksAtNotHighRSSI = in.readInt();
1664                config.numUserTriggeredJoinAttempts = in.readInt();
1665                config.autoJoinUseAggressiveJoinAttemptThreshold = in.readInt();
1666                config.autoJoinBailedDueToLowRssi = in.readInt() != 0;
1667                config.numNoInternetAccessReports = in.readInt();
1668                return config;
1669            }
1670
1671            public WifiConfiguration[] newArray(int size) {
1672                return new WifiConfiguration[size];
1673            }
1674        };
1675}
1676