summaryrefslogtreecommitdiffstats
path: root/service/java/com/android/server/wifi/WifiQualifiedNetworkSelector.java
blob: e429d835a0146bf78a4eb60c57740088030f227e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
/*
 * Copyright (C) 2015 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.android.server.wifi;

import android.annotation.Nullable;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.NetworkKey;
import android.net.NetworkScoreManager;
import android.net.WifiKey;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiEnterpriseConfig;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.PersistableBundle;
import android.telephony.CarrierConfigManager;
import android.text.TextUtils;
import android.util.Base64;
import android.util.LocalLog;
import android.util.Log;
import android.util.Pair;

import com.android.internal.R;
import com.android.internal.annotations.VisibleForTesting;
import com.android.server.wifi.util.ScanDetailUtil;

import java.io.FileDescriptor;
import java.io.PrintWriter;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.nio.charset.StandardCharsets;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * This class looks at all the connectivity scan results then
 * select an network for the phone to connect/roam to.
 */
public class WifiQualifiedNetworkSelector {
    private WifiConfigManager mWifiConfigManager;
    private WifiInfo mWifiInfo;
    private NetworkScoreManager mScoreManager;
    private WifiNetworkScoreCache mNetworkScoreCache;
    private Clock mClock;
    private static final String TAG = "WifiQualifiedNetworkSelector:";
    private boolean skipQualifiedNetworkSelectionForAutoConnect = false;
    // Always enable debugging logs for now since QNS is still a new feature.
    private static final boolean FORCE_DEBUG = false;
    private boolean mDbg = FORCE_DEBUG;
    private WifiConfiguration mCurrentConnectedNetwork = null;
    private String mCurrentBssid = null;
    //buffer most recent scan results
    private List<ScanDetail> mScanDetails = null;
    //buffer of filtered scan results (Scan results considered by network selection) & associated
    //WifiConfiguration (if any)
    private volatile List<Pair<ScanDetail, WifiConfiguration>> mFilteredScanDetails = null;

    //Minimum time gap between last successful Qualified Network Selection and new selection attempt
    //usable only when current state is connected state   default 10 s
    private static final int MINIMUM_QUALIFIED_NETWORK_SELECTION_INTERVAL = 10 * 1000;

    private static final int CARRIER_SSID = 0;
    private static final int CARRIER_KEY = 1;
    private static final int CARRIER_EAP_METHOD = 2;

    //if current network is on 2.4GHz band and has a RSSI over this, need not new network selection
    public static final int QUALIFIED_RSSI_24G_BAND = -73;
    //if current network is on 5GHz band and has a RSSI over this, need not new network selection
    public static final int QUALIFIED_RSSI_5G_BAND = -70;
    //any RSSI larger than this will benefit the traffic very limited
    public static final int RSSI_SATURATION_2G_BAND = -60;
    public static final int RSSI_SATURATION_5G_BAND = -57;
    //Any value below this will be considered not usable
    public static final int MINIMUM_2G_ACCEPT_RSSI = -85;
    public static final int MINIMUM_5G_ACCEPT_RSSI = -82;

    public static final int RSSI_SCORE_SLOPE = 4;
    public static final int RSSI_SCORE_OFFSET = 85;

    public static final int BAND_AWARD_5GHz = 40;
    public static final int SAME_NETWORK_AWARD = 16;

    public static final int SAME_BSSID_AWARD = 24;
    public static final int LAST_SELECTION_AWARD = 480;
    public static final int PASSPOINT_SECURITY_AWARD = 40;
    public static final int SECURITY_AWARD = 80;
    public static final int BSSID_BLACKLIST_THRESHOLD = 3;
    public static final int BSSID_BLACKLIST_EXPIRE_TIME = 5 * 60 * 1000;
    private final int mNoIntnetPenalty;
    //TODO: check whether we still need this one when we update the scan manager
    public static final int SCAN_RESULT_MAXIMUNM_AGE = 40000;
    private static final int INVALID_TIME_STAMP = -1;
    private long mLastQualifiedNetworkSelectionTimeStamp = INVALID_TIME_STAMP;

    private final LocalLog mLocalLog = new LocalLog(512);
    private int mRssiScoreSlope = RSSI_SCORE_SLOPE;
    private int mRssiScoreOffset = RSSI_SCORE_OFFSET;
    private int mSameBssidAward = SAME_BSSID_AWARD;
    private int mLastSelectionAward = LAST_SELECTION_AWARD;
    private int mPasspointSecurityAward = PASSPOINT_SECURITY_AWARD;
    private int mSecurityAward = SECURITY_AWARD;
    private int mUserPreferedBand = WifiManager.WIFI_FREQUENCY_BAND_AUTO;
    private Map<String, BssidBlacklistStatus> mBssidBlacklist =
            new HashMap<String, BssidBlacklistStatus>();
    private List<WifiConfiguration> mCarrierConfiguredNetworks = new ArrayList<WifiConfiguration>();
    private Context mContext;

    /**
     * class save the blacklist status of a given BSSID
     */
    private static class BssidBlacklistStatus {
        //how many times it is requested to be blacklisted (association rejection trigger this)
        int mCounter;
        boolean mIsBlacklisted;
        long mBlacklistedTimeStamp = INVALID_TIME_STAMP;
    }

    private void localLog(String log) {
        if (mDbg) {
            Log.d(TAG, log);
            mLocalLog.log(log);
        }
    }

    @VisibleForTesting
    public void setCarrierConfiguredNetworks(List<WifiConfiguration> carrierConfiguredNetworks) {
        mCarrierConfiguredNetworks = carrierConfiguredNetworks;
    }

    private void localLoge(String log) {
        mLocalLog.log(log);
    }

    @VisibleForTesting
    void setWifiNetworkScoreCache(WifiNetworkScoreCache cache) {
        mNetworkScoreCache = cache;
    }

    /**
     * @return current target connected network
     */
    public WifiConfiguration getConnetionTargetNetwork() {
        return mCurrentConnectedNetwork;
    }

    /**
     * @return the list of ScanDetails scored as potential candidates by the last run of
     * selectQualifiedNetwork, this will be empty if QNS determined no selection was needed on last
     * run. This includes scan details of sufficient signal strength, and had an associated
     * WifiConfiguration.
     */
    public List<Pair<ScanDetail, WifiConfiguration>> getFilteredScanDetails() {
        return mFilteredScanDetails;
    }

    /**
     * set the user selected preferred band
     *
     * @param band preferred band user selected
     */
    public void setUserPreferredBand(int band) {
        mUserPreferedBand = band;
    }

    WifiQualifiedNetworkSelector(WifiConfigManager configureStore, Context context,
            WifiInfo wifiInfo, Clock clock) {
        mWifiConfigManager = configureStore;
        mWifiInfo = wifiInfo;
        mClock = clock;
        mContext = context;
        mScoreManager =
                (NetworkScoreManager) context.getSystemService(Context.NETWORK_SCORE_SERVICE);
        if (mScoreManager != null) {
            mNetworkScoreCache = new WifiNetworkScoreCache(context);
            mScoreManager.registerNetworkScoreCache(NetworkKey.TYPE_WIFI, mNetworkScoreCache);
        } else {
            localLoge("No network score service: Couldn't register as a WiFi score Manager, type="
                    + NetworkKey.TYPE_WIFI + " service= " + Context.NETWORK_SCORE_SERVICE);
            mNetworkScoreCache = null;
        }

        mRssiScoreSlope = context.getResources().getInteger(
                R.integer.config_wifi_framework_RSSI_SCORE_SLOPE);
        mRssiScoreOffset = context.getResources().getInteger(
                R.integer.config_wifi_framework_RSSI_SCORE_OFFSET);
        mSameBssidAward = context.getResources().getInteger(
                R.integer.config_wifi_framework_SAME_BSSID_AWARD);
        mLastSelectionAward = context.getResources().getInteger(
                R.integer.config_wifi_framework_LAST_SELECTION_AWARD);
        mPasspointSecurityAward = context.getResources().getInteger(
                R.integer.config_wifi_framework_PASSPOINT_SECURITY_AWARD);
        mSecurityAward = context.getResources().getInteger(
                R.integer.config_wifi_framework_SECURITY_AWARD);
        mNoIntnetPenalty = (mWifiConfigManager.mThresholdSaturatedRssi24.get() + mRssiScoreOffset)
                * mRssiScoreSlope + mWifiConfigManager.mBandAward5Ghz.get()
                + mWifiConfigManager.mCurrentNetworkBoost.get() + mSameBssidAward + mSecurityAward;

        context.registerReceiver(mBroadcastReceiver, new IntentFilter(
                CarrierConfigManager.ACTION_CARRIER_CONFIG_CHANGED));
    }

    @VisibleForTesting
    public List<WifiConfiguration> parseCarrierSuppliedWifiInfo(String[] wifiArray) {
        List<WifiConfiguration> carrierConfiguredNetworks = new ArrayList<WifiConfiguration>();
        for (String config : wifiArray) {
            String[] wc = config.split("\\|");
            if (wc.length != 3) {
                continue;
            }
            WifiConfiguration wifiConfig = new WifiConfiguration();
            try {
                byte[] decodedBytes = Base64.decode(wc[CARRIER_SSID], Base64.DEFAULT);
                String ssid = new String(decodedBytes);
                wifiConfig.SSID = "\"" + ssid + "\"";
            } catch (IllegalArgumentException ex) {
                localLog("mBroadcaseReceiver: Could not decode base64 string");
                continue;
            }
            try {
                int key = Integer.parseInt(wc[CARRIER_KEY]);
                wifiConfig.allowedKeyManagement.set(key);
                int eapType = Integer.parseInt(wc[CARRIER_EAP_METHOD]);
                wifiConfig.enterpriseConfig = new WifiEnterpriseConfig();
                wifiConfig.enterpriseConfig.setEapMethod(eapType);
            } catch (NumberFormatException e) {
                localLog("mBroadcastReceiver: not an integer:" + wc[CARRIER_KEY] + "," +
                        wc[CARRIER_EAP_METHOD]);
                continue;
            } catch (IllegalArgumentException e) {
                localLog("mBroadcastReceiver: invalid config" + wc[CARRIER_KEY] + "," +
                        wc[CARRIER_EAP_METHOD]);
            }
            carrierConfiguredNetworks.add(wifiConfig);
            localLog("mBroadcastReceiver: carrier config:" + wifiConfig.SSID);
        }
        return carrierConfiguredNetworks;
    }

    final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            localLog("mBroadcastReceiver: onReceive " + intent.getAction());
            String[] wifiArray = null;
            CarrierConfigManager carrierConfigManager = (CarrierConfigManager)
                    mContext.getSystemService(Context.CARRIER_CONFIG_SERVICE);
            if (carrierConfigManager != null) {
                PersistableBundle b = carrierConfigManager.getConfig();
                if (b != null) {
                    wifiArray = b.getStringArray(
                            CarrierConfigManager.KEY_CARRIER_WIFI_STRING_ARRAY);
                }
            }

            if (wifiArray == null) {
                return;
            }
            mCarrierConfiguredNetworks = parseCarrierSuppliedWifiInfo(wifiArray);
            boolean hasCarrierNetworks = (mCarrierConfiguredNetworks == null ||
                    mCarrierConfiguredNetworks.size() == 0) ? false : true;
            mWifiConfigManager.setHasCarrierNetworks(hasCarrierNetworks);
        }
    };

    void enableVerboseLogging(int verbose) {
        mDbg = verbose > 0 || FORCE_DEBUG;
    }

    private String getNetworkString(WifiConfiguration network) {
        if (network == null) {
            return null;
        }

        return (network.SSID + ":" + network.networkId);

    }

    /**
     * check whether current network is good enough we need not consider any potential switch
     *
     * @param currentNetwork -- current connected network
     * @return true -- qualified and do not consider potential network switch
     *         false -- not good enough and should try potential network switch
     */
    private boolean isNetworkQualified(WifiConfiguration currentNetwork) {

        if (currentNetwork == null) {
            localLog("Disconnected");
            return false;
        } else {
            localLog("Current network is: " + currentNetwork.SSID + " ,ID is: "
                    + currentNetwork.networkId);
        }

        //if current connected network is an ephemeral network,we will consider
        // there is no current network
        if (currentNetwork.ephemeral) {
            localLog("Current is ephemeral. Start reselect");
            return false;
        }

        //if current network is open network, not qualified
        if (mWifiConfigManager.isOpenNetwork(currentNetwork)) {
            localLog("Current network is open network");
            return false;
        }

        // Current network band must match with user preference selection
        if (mWifiInfo.is24GHz() && (mUserPreferedBand != WifiManager.WIFI_FREQUENCY_BAND_2GHZ)) {
            localLog("Current band does not match user preference. Start Qualified Network"
                    + " Selection Current band = " + (mWifiInfo.is24GHz() ? "2.4GHz band"
                    : "5GHz band") + "UserPreference band = " + mUserPreferedBand);
            return false;
        }

        int currentRssi = mWifiInfo.getRssi();
        if ((mWifiInfo.is24GHz()
                        && currentRssi < mWifiConfigManager.mThresholdQualifiedRssi24.get())
                || (mWifiInfo.is5GHz()
                        && currentRssi < mWifiConfigManager.mThresholdQualifiedRssi5.get())) {
            localLog("Current band = " + (mWifiInfo.is24GHz() ? "2.4GHz band" : "5GHz band")
                    + "current RSSI is: " + currentRssi);
            return false;
        }

        return true;
    }

    public void skipQualifiedNetworkSelectionForAutoConnect(boolean enable) {
          skipQualifiedNetworkSelectionForAutoConnect = enable;
    }
    /**
     * check whether QualifiedNetworkSelection is needed or not
     *
     * @param isLinkDebouncing true -- Link layer is under debouncing
     *                         false -- Link layer is not under debouncing
     * @param isConnected true -- device is connected to an AP currently
     *                    false -- device is not connected to an AP currently
     * @param isDisconnected true -- WifiStateMachine is at disconnected state
     *                       false -- WifiStateMachine is not at disconnected state
     * @param isSupplicantTransientState true -- supplicant is in a transient state now
     *                                   false -- supplicant is not in a transient state now
     * @return true -- need a Qualified Network Selection procedure
     *         false -- do not need a QualifiedNetworkSelection procedure
     */
    private boolean needQualifiedNetworkSelection(boolean isLinkDebouncing, boolean isConnected,
            boolean isDisconnected, boolean isSupplicantTransientState) {
        if (mScanDetails.size() == 0) {
            localLog("empty scan result");
            return false;
        }

        // Do not trigger Qualified Network Selection during L2 link debouncing procedure
        if (isLinkDebouncing) {
            localLog("Need not Qualified Network Selection during L2 debouncing");
            return false;
        }
        if (skipQualifiedNetworkSelectionForAutoConnect) {
            localLog("Skip network selction, since auto connection disabled");
            return false;
        }

        if (isConnected) {
            //already connected. Just try to find better candidate
            //if switch network is not allowed in connected mode, do not trigger Qualified Network
            //Selection
            if (!mWifiConfigManager.getEnableAutoJoinWhenAssociated()) {
                localLog("Switch network under connection is not allowed");
                return false;
            }

            //Do not select again if last selection is within
            //MINIMUM_QUALIFIED_NETWORK_SELECTION_INTERVAL
            if (mLastQualifiedNetworkSelectionTimeStamp != INVALID_TIME_STAMP) {
                long gap = mClock.elapsedRealtime() - mLastQualifiedNetworkSelectionTimeStamp;
                if (gap < MINIMUM_QUALIFIED_NETWORK_SELECTION_INTERVAL) {
                    localLog("Too short to last successful Qualified Network Selection Gap is:"
                            + gap + " ms!");
                    return false;
                }
            }

            WifiConfiguration currentNetwork =
                    mWifiConfigManager.getWifiConfiguration(mWifiInfo.getNetworkId());
            if (currentNetwork == null) {
                // WifiStateMachine in connected state but WifiInfo is not. It means there is a race
                // condition happened. Do not make QNS until WifiStateMachine goes into
                // disconnected state
                return false;
            }

            if (!isNetworkQualified(mCurrentConnectedNetwork)) {
                //need not trigger Qualified Network Selection if current network is qualified
                localLog("Current network is not qualified");
                return true;
            } else {
                return false;
            }
        } else if (isDisconnected) {
            mCurrentConnectedNetwork = null;
            mCurrentBssid = null;
            //Do not start Qualified Network Selection if current state is a transient state
            if (isSupplicantTransientState) {
                return false;
            }
        } else {
            //Do not allow new network selection in other state
            localLog("WifiStateMachine is not on connected or disconnected state");
            return false;
        }

        return true;
    }

    int calculateBssidScore(ScanResult scanResult, WifiConfiguration network,
            WifiConfiguration currentNetwork, boolean sameBssid, boolean sameSelect,
            StringBuffer sbuf) {

        int score = 0;
        //calculate the RSSI score
        int rssi = scanResult.level <= mWifiConfigManager.mThresholdSaturatedRssi24.get()
                ? scanResult.level : mWifiConfigManager.mThresholdSaturatedRssi24.get();
        score += (rssi + mRssiScoreOffset) * mRssiScoreSlope;
        sbuf.append(" RSSI score: " +  score);
        if (scanResult.is5GHz()) {
            //5GHz band
            score += mWifiConfigManager.mBandAward5Ghz.get();
            sbuf.append(" 5GHz bonus: " + mWifiConfigManager.mBandAward5Ghz.get());
        }

        //last user selection award
        if (sameSelect) {
            long timeDifference = mClock.elapsedRealtime()
                    - mWifiConfigManager.getLastSelectedTimeStamp();

            if (timeDifference > 0) {
                int bonus = mLastSelectionAward - (int) (timeDifference / 1000 / 60);
                score += bonus > 0 ? bonus : 0;
                sbuf.append(" User selected it last time " + (timeDifference / 1000 / 60)
                        + " minutes ago, bonus:" + bonus);
            }
        }

        //same network award
        if (network == currentNetwork || network.isLinked(currentNetwork)) {
            score += mWifiConfigManager.mCurrentNetworkBoost.get();
            sbuf.append(" Same network with current associated. Bonus: "
                    + mWifiConfigManager.mCurrentNetworkBoost.get());
        }

        //same BSSID award
        if (sameBssid) {
            score += mSameBssidAward;
            sbuf.append(" Same BSSID with current association. Bonus: " + mSameBssidAward);
        }

        //security award
        if (network.isPasspoint()) {
            score += mPasspointSecurityAward;
            sbuf.append(" Passpoint Bonus:" + mPasspointSecurityAward);
        } else if (!mWifiConfigManager.isOpenNetwork(network)) {
            score += mSecurityAward;
            sbuf.append(" Secure network Bonus:" + mSecurityAward);
        }

        //Penalty for no internet network. Make sure if there is any network with Internet,
        //however, if there is no any other network with internet, this network can be chosen
        if (network.numNoInternetAccessReports > 0 && !network.validatedInternetAccess) {
            score -= mNoIntnetPenalty;
            sbuf.append(" No internet Penalty:-" + mNoIntnetPenalty);
        }


        sbuf.append(" Score for scanResult: " + scanResult +  " and Network ID: "
                + network.networkId + " final score:" + score + "\n\n");

        return score;
    }

    /**
     * This API try to update all the saved networks' network selection status
     */
    private void updateSavedNetworkSelectionStatus() {
        List<WifiConfiguration> savedNetworks = mWifiConfigManager.getSavedNetworks();
        if (savedNetworks.size() == 0) {
            localLog("no saved network");
            return;
        }

        StringBuffer sbuf = new StringBuffer("Saved Network List\n");
        for (WifiConfiguration network : savedNetworks) {
            WifiConfiguration config = mWifiConfigManager.getWifiConfiguration(network.networkId);
            WifiConfiguration.NetworkSelectionStatus status =
                    config.getNetworkSelectionStatus();

            //If the configuration is temporarily disabled, try to re-enable it
            if (status.isNetworkTemporaryDisabled()) {
                mWifiConfigManager.tryEnableQualifiedNetwork(network.networkId);
            }

            //clean the cached candidate, score and seen
            status.setCandidate(null);
            status.setCandidateScore(Integer.MIN_VALUE);
            status.setSeenInLastQualifiedNetworkSelection(false);

            //print the debug messages
            sbuf.append("    " + getNetworkString(network) + " " + " User Preferred BSSID:"
                    + network.BSSID + " FQDN:" + network.FQDN + " "
                    + status.getNetworkStatusString() + " Disable account: ");
            for (int index = status.NETWORK_SELECTION_ENABLE;
                    index < status.NETWORK_SELECTION_DISABLED_MAX; index++) {
                sbuf.append(status.getDisableReasonCounter(index) + " ");
            }
            sbuf.append("Connect Choice:" + status.getConnectChoice() + " set time:"
                    + status.getConnectChoiceTimestamp());
            sbuf.append("\n");
        }
        localLog(sbuf.toString());
    }

    /**
     * This API is called when user explicitly select a network. Currently, it is used in following
     * cases:
     * (1) User explicitly choose to connect to a saved network
     * (2) User save a network after add a new network
     * (3) User save a network after modify a saved network
     * Following actions will be triggered:
     * 1. if this network is disabled, we need re-enable it again
     * 2. we considered user prefer this network over all the networks visible in latest network
     *    selection procedure
     *
     * @param netId new network ID for either the network the user choose or add
     * @param persist whether user has the authority to overwrite current connect choice
     * @return true -- There is change made to connection choice of any saved network
     *         false -- There is no change made to connection choice of any saved network
     */
    public boolean userSelectNetwork(int netId, boolean persist) {
        WifiConfiguration selected = mWifiConfigManager.getWifiConfiguration(netId);
        localLog("userSelectNetwork:" + netId + " persist:" + persist);
        if (selected == null || selected.SSID == null) {
            localLoge("userSelectNetwork: Bad configuration with nid=" + netId);
            return false;
        }


        if (!selected.getNetworkSelectionStatus().isNetworkEnabled()) {
            mWifiConfigManager.updateNetworkSelectionStatus(netId,
                    WifiConfiguration.NetworkSelectionStatus.NETWORK_SELECTION_ENABLE);
        }

        if (!persist) {
            localLog("User has no privilege to overwrite the current priority");
            return false;
        }

        boolean change = false;
        String key = selected.configKey();
        // This is only used for setting the connect choice timestamp for debugging purposes.
        long currentTime = mClock.currentTimeMillis();
        List<WifiConfiguration> savedNetworks = mWifiConfigManager.getSavedNetworks();

        for (WifiConfiguration network : savedNetworks) {
            WifiConfiguration config = mWifiConfigManager.getWifiConfiguration(network.networkId);
            WifiConfiguration.NetworkSelectionStatus status = config.getNetworkSelectionStatus();
            if (config.networkId == selected.networkId) {
                if (status.getConnectChoice() != null) {
                    localLog("Remove user selection preference of " + status.getConnectChoice()
                            + " Set Time: " + status.getConnectChoiceTimestamp() + " from "
                            + config.SSID + " : " + config.networkId);
                    status.setConnectChoice(null);
                    status.setConnectChoiceTimestamp(WifiConfiguration.NetworkSelectionStatus
                            .INVALID_NETWORK_SELECTION_DISABLE_TIMESTAMP);
                    change = true;
                }
                continue;
            }

            if (status.getSeenInLastQualifiedNetworkSelection()
                    && (status.getConnectChoice() == null
                    || !status.getConnectChoice().equals(key))) {
                localLog("Add key:" + key + " Set Time: " + currentTime + " to "
                        + getNetworkString(config));
                status.setConnectChoice(key);
                status.setConnectChoiceTimestamp(currentTime);
                change = true;
            }
        }
        //Write this change to file
        if (change) {
            mWifiConfigManager.writeKnownNetworkHistory();
            return true;
        }

        return false;
    }

    /**
     * enable/disable a BSSID for Quality Network Selection
     * When an association rejection event is obtained, Quality Network Selector will disable this
     * BSSID but supplicant still can try to connect to this bssid. If supplicant connect to it
     * successfully later, this bssid can be re-enabled.
     *
     * @param bssid the bssid to be enabled / disabled
     * @param enable -- true enable a bssid if it has been disabled
     *               -- false disable a bssid
     */
    public boolean enableBssidForQualityNetworkSelection(String bssid, boolean enable) {
        if (enable) {
            return (mBssidBlacklist.remove(bssid) != null);
        } else {
            if (bssid != null) {
                BssidBlacklistStatus status = mBssidBlacklist.get(bssid);
                if (status == null) {
                    //first time
                    BssidBlacklistStatus newStatus = new BssidBlacklistStatus();
                    newStatus.mCounter++;
                    mBssidBlacklist.put(bssid, newStatus);
                } else if (!status.mIsBlacklisted) {
                    status.mCounter++;
                    if (status.mCounter >= BSSID_BLACKLIST_THRESHOLD) {
                        status.mIsBlacklisted = true;
                        status.mBlacklistedTimeStamp = mClock.elapsedRealtime();
                        return true;
                    }
                }
            }
        }
        return false;
    }

    /**
     * update the buffered BSSID blacklist
     *
     * Go through the whole buffered BSSIDs blacklist and check when the BSSIDs is blocked. If they
     * were blacked before BSSID_BLACKLIST_EXPIRE_TIME, re-enable it again.
     */
    private void updateBssidBlacklist() {
        Iterator<BssidBlacklistStatus> iter = mBssidBlacklist.values().iterator();
        while (iter.hasNext()) {
            BssidBlacklistStatus status = iter.next();
            if (status != null && status.mIsBlacklisted) {
                if (mClock.elapsedRealtime() - status.mBlacklistedTimeStamp
                            >= BSSID_BLACKLIST_EXPIRE_TIME) {
                    iter.remove();
                }
            }
        }
    }

    /**
     * Check whether a bssid is disabled
     * @param bssid -- the bssid to check
     * @return true -- bssid is disabled
     *         false -- bssid is not disabled
     */
    public boolean isBssidDisabled(String bssid) {
        BssidBlacklistStatus status = mBssidBlacklist.get(bssid);
        return status == null ? false : status.mIsBlacklisted;
    }

    private boolean isCarrierNetwork(ScanResult scanResult) {
        return (getMatchingConfigForEAPNetworks(scanResult,
                mCarrierConfiguredNetworks) != null ? true : false);
    }

    /**
     * ToDo: This should be called in Connectivity Manager when it gets new scan result
     * check whether a network slection is needed. If need, check all the new scan results and
     * select a new qualified network/BSSID to connect to
     *
     * @param forceSelectNetwork true -- start a qualified network selection anyway,no matter
     *                           current network is already qualified or not.
     *                           false -- if current network is already qualified, do not do new
     *                           selection
     * @param isUntrustedConnectionsAllowed true -- user allow to connect to untrusted network
     *                                      false -- user do not allow to connect to untrusted
     *                                      network
     * @param scanDetails latest scan result obtained (should be connectivity scan only)
     * @param isLinkDebouncing true -- Link layer is under debouncing
     *                         false -- Link layer is not under debouncing
     * @param isConnected true -- device is connected to an AP currently
     *                    false -- device is not connected to an AP currently
     * @param isDisconnected true -- WifiStateMachine is at disconnected state
     *                       false -- WifiStateMachine is not at disconnected state
     * @param isSupplicantTransient true -- supplicant is in a transient state
     *                              false -- supplicant is not in a transient state
     * @return the qualified network candidate found. If no available candidate, return null
     */
    public WifiConfiguration selectQualifiedNetwork(boolean forceSelectNetwork,
            boolean isUntrustedConnectionsAllowed, List<ScanDetail>  scanDetails,
            boolean isLinkDebouncing, boolean isConnected, boolean isDisconnected,
            boolean isSupplicantTransient) {
        localLog("==========start qualified Network Selection==========");
        mScanDetails = scanDetails;
        List<Pair<ScanDetail, WifiConfiguration>>  filteredScanDetails = new ArrayList<>();
        if (mCurrentConnectedNetwork == null) {
            mCurrentConnectedNetwork =
                    mWifiConfigManager.getWifiConfiguration(mWifiInfo.getNetworkId());
        }

        // Always get the current BSSID from WifiInfo in case that firmware initiated roaming
        // happened.
        mCurrentBssid = mWifiInfo.getBSSID();

        if (!forceSelectNetwork && !needQualifiedNetworkSelection(isLinkDebouncing, isConnected,
                isDisconnected, isSupplicantTransient)) {
            localLog("Quit qualified Network Selection since it is not forced and current network"
                    + " is qualified already");
            mFilteredScanDetails = filteredScanDetails;
            return null;
        }

        int currentHighestScore = Integer.MIN_VALUE;
        ScanResult scanResultCandidate = null;
        WifiConfiguration networkCandidate = null;
        WifiConfiguration carrierCandidate = null;
        final ExternalScoreEvaluator externalScoreEvaluator =
                new ExternalScoreEvaluator(mLocalLog, mDbg);
        final CarrierScoreEvaluator carrierScoreEvaluator =
                new CarrierScoreEvaluator(mLocalLog, mDbg);
        String lastUserSelectedNetWorkKey = mWifiConfigManager.getLastSelectedConfiguration();
        WifiConfiguration lastUserSelectedNetwork =
                mWifiConfigManager.getWifiConfiguration(lastUserSelectedNetWorkKey);
        if (lastUserSelectedNetwork != null) {
            localLog("Last selection is " + lastUserSelectedNetwork.SSID + " Time to now: "
                    + ((mClock.elapsedRealtime() - mWifiConfigManager.getLastSelectedTimeStamp())
                            / 1000 / 60 + " minutes"));
        }

        updateSavedNetworkSelectionStatus();
        updateBssidBlacklist();

        StringBuffer lowSignalScan = new StringBuffer();
        StringBuffer notSavedScan = new StringBuffer();
        StringBuffer noValidSsid = new StringBuffer();
        StringBuffer scoreHistory =  new StringBuffer();
        ArrayList<NetworkKey> unscoredNetworks = new ArrayList<NetworkKey>();
        boolean scanResultsHaveCurrentBssid = false;

        localLog("isCarrierNetworkEnabledByUser: " +
                mWifiConfigManager.getIsCarrierNetworkEnabledByUser());

        //iterate all scan results and find the best candidate with the highest score
        for (ScanDetail scanDetail : mScanDetails) {
            ScanResult scanResult = scanDetail.getScanResult();
            //skip bad scan result
            if (scanResult.SSID == null || TextUtils.isEmpty(scanResult.SSID)) {
                if (mDbg) {
                    //We should not see this in ePNO
                    noValidSsid.append(scanResult.BSSID + " / ");
                }
                continue;
            }

            //check if the scan results contain the current connected
            //BSSID.
            if (scanResult.BSSID.equals(mCurrentBssid)) {
                scanResultsHaveCurrentBssid = true;
            }

            final String scanId = toScanId(scanResult);
            //check whether this BSSID is blocked or not
            if (mWifiConfigManager.isBssidBlacklisted(scanResult.BSSID)
                    || isBssidDisabled(scanResult.BSSID)) {
                //We should not see this in ePNO
                Log.e(TAG, scanId + " is in blacklist.");
                continue;
            }

            //skip scan result with too weak signals
            if ((scanResult.is24GHz() && scanResult.level
                    < mWifiConfigManager.mThresholdMinimumRssi24.get())
                    || (scanResult.is5GHz() && scanResult.level
                    < mWifiConfigManager.mThresholdMinimumRssi5.get())) {
                if (mDbg) {
                    lowSignalScan.append(scanId + "(" + (scanResult.is24GHz() ? "2.4GHz" : "5GHz")
                            + ")" + scanResult.level + " / ");
                }
                continue;
            }

            //check if there is already a score for this network
            if (mNetworkScoreCache != null && !mNetworkScoreCache.isScoredNetwork(scanResult)) {
                //no score for this network yet.
                WifiKey wifiKey;

                try {
                    wifiKey = new WifiKey("\"" + scanResult.SSID + "\"", scanResult.BSSID);
                    NetworkKey ntwkKey = new NetworkKey(wifiKey);
                    //add to the unscoredNetworks list so we can request score later
                    unscoredNetworks.add(ntwkKey);
                } catch (IllegalArgumentException e) {
                    Log.w(TAG, "Invalid SSID=" + scanResult.SSID + " BSSID=" + scanResult.BSSID
                            + " for network score. Skip.");
                }
            }

            //check whether this scan result belong to a saved network
            boolean potentiallyEphemeral = false;
            // Stores WifiConfiguration of potential connection candidates for scan result filtering
            WifiConfiguration potentialEphemeralCandidate = null;
            List<WifiConfiguration> associatedWifiConfigurations =
                    mWifiConfigManager.updateSavedNetworkWithNewScanDetail(scanDetail,
                            isSupplicantTransient || isConnected || isLinkDebouncing);
            if (associatedWifiConfigurations == null) {
                potentiallyEphemeral =  true;
                if (mDbg) {
                    notSavedScan.append(scanId + " / ");
                }
            } else if (associatedWifiConfigurations.size() == 1) {
                //if there are more than 1 associated network, it must be a passpoint network
                WifiConfiguration network = associatedWifiConfigurations.get(0);
                if (network.ephemeral) {
                    potentialEphemeralCandidate = network;
                    potentiallyEphemeral =  true;
                }
            }

            // Evaluate the potentially ephemeral network as a possible candidate if untrusted
            // connections are allowed and we have an external score for the scan result.
            if (potentiallyEphemeral) {
                if (!mWifiConfigManager.wasEphemeralNetworkDeleted(
                        ScanDetailUtil.createQuotedSSID(scanResult.SSID))) {
                    if (isUntrustedConnectionsAllowed) {
                        Integer netScore = getNetworkScore(scanResult, false);
                        if (netScore != null) {
                            externalScoreEvaluator.evalUntrustedCandidate(netScore, scanResult);
                            // scanDetail is for available ephemeral network
                            filteredScanDetails.add(Pair.create(scanDetail,
                                    potentialEphemeralCandidate));
                        }
                        // Evaluate the carrier network as a possible candidate.
                        // todo need to add flag isCarrierConnectionsAllowed, config in settings.
                    } else if (!mCarrierConfiguredNetworks.isEmpty() &&
                            isCarrierNetwork(scanResult) &&
                            mWifiConfigManager.getIsCarrierNetworkEnabledByUser()) {
                        localLog("Checking the carrierScoreEvaluator for candidates...");
                        carrierScoreEvaluator.evalCarrierCandidate(scanResult,
                                getCarrierScore(scanResult, mCurrentConnectedNetwork,
                                        (mCurrentBssid == null ? false :
                                                mCurrentBssid.equals(scanResult.BSSID))));
                        filteredScanDetails.add(Pair.create(scanDetail,
                                potentialEphemeralCandidate));
                    }
                }
                continue;
            }

            // calculate the score of each scanresult whose associated network is not ephemeral. Due
            // to one scan result can associated with more than 1 network, we need calculate all
            // the scores and use the highest one as the scanresults score.
            int highestScore = Integer.MIN_VALUE;
            int score;
            WifiConfiguration configurationCandidateForThisScan = null;
            WifiConfiguration potentialCandidate = null;
            for (WifiConfiguration network : associatedWifiConfigurations) {
                WifiConfiguration.NetworkSelectionStatus status =
                        network.getNetworkSelectionStatus();
                status.setSeenInLastQualifiedNetworkSelection(true);
                if (potentialCandidate == null) {
                    potentialCandidate = network;
                }
                if (!status.isNetworkEnabled()) {
                    continue;
                } else if (network.BSSID != null && !network.BSSID.equals("any")
                        && !network.BSSID.equals(scanResult.BSSID)) {
                    //in such scenario, user (APP) has specified the only BSSID to connect for this
                    // configuration. So only the matched scan result can be candidate
                    localLog("Network: " + getNetworkString(network) + " has specified" + "BSSID:"
                            + network.BSSID + ". Skip " + scanResult.BSSID);
                    continue;
                }

                // If the network is marked to use external scores then attempt to fetch the score.
                // These networks will not be considered alongside the other saved networks.
                if (network.useExternalScores) {
                    Integer netScore = getNetworkScore(scanResult, false);
                    externalScoreEvaluator.evalSavedCandidate(netScore, network, scanResult);
                    continue;
                }

                score = calculateBssidScore(scanResult, network, mCurrentConnectedNetwork,
                        (mCurrentBssid == null ? false : mCurrentBssid.equals(scanResult.BSSID)),
                        (lastUserSelectedNetwork == null ? false : lastUserSelectedNetwork.networkId
                         == network.networkId), scoreHistory);
                if (score > highestScore) {
                    highestScore = score;
                    configurationCandidateForThisScan = network;
                    potentialCandidate = network;
                }
                //update the cached candidate
                if (score > status.getCandidateScore() || (score == status.getCandidateScore()
                      && status.getCandidate() != null
                      && scanResult.level > status.getCandidate().level)) {
                    status.setCandidate(scanResult);
                    status.setCandidateScore(score);
                }
            }
            // Create potential filteredScanDetail entry
            filteredScanDetails.add(Pair.create(scanDetail, potentialCandidate));

            if (highestScore > currentHighestScore || (highestScore == currentHighestScore
                    && scanResultCandidate != null
                    && scanResult.level > scanResultCandidate.level)) {
                currentHighestScore = highestScore;
                scanResultCandidate = scanResult;
                networkCandidate = configurationCandidateForThisScan;
                networkCandidate.getNetworkSelectionStatus().setCandidate(scanResultCandidate);
            }
        }

        mFilteredScanDetails = filteredScanDetails;

        //kick the score manager if there is any unscored network
        if (mScoreManager != null && unscoredNetworks.size() != 0) {
            NetworkKey[] unscoredNetworkKeys =
                    unscoredNetworks.toArray(new NetworkKey[unscoredNetworks.size()]);
            mScoreManager.requestScores(unscoredNetworkKeys);
        }

        if (mDbg) {
            localLog(lowSignalScan + " skipped due to low signal\n");
            localLog(notSavedScan + " skipped due to not saved\n ");
            localLog(noValidSsid + " skipped due to not valid SSID\n");
            localLog(scoreHistory.toString());
        }

        //QNS listens to all single scan results. Some scan requests may not include
        //the channel of the currently connected network, so the currently connected network
        //won't show up in the scan results. We don't act on these scan results to avoid
        //aggressive network switching which might trigger disconnection.
        if (isConnected && !scanResultsHaveCurrentBssid) {
            localLog("Current connected BSSID " + mCurrentBssid + " is not in the scan results."
                    + " Skip network selection.");
            return null;
        }

        //we need traverse the whole user preference to choose the one user like most now
        if (scanResultCandidate != null) {
            WifiConfiguration tempConfig = networkCandidate;

            while (tempConfig.getNetworkSelectionStatus().getConnectChoice() != null) {
                String key = tempConfig.getNetworkSelectionStatus().getConnectChoice();
                tempConfig = mWifiConfigManager.getWifiConfiguration(key);

                if (tempConfig != null) {
                    WifiConfiguration.NetworkSelectionStatus tempStatus =
                            tempConfig.getNetworkSelectionStatus();
                    if (tempStatus.getCandidate() != null && tempStatus.isNetworkEnabled()) {
                        scanResultCandidate = tempStatus.getCandidate();
                        networkCandidate = tempConfig;
                    }
                } else {
                    //we should not come here in theory
                    localLoge("Connect choice: " + key + " has no corresponding saved config");
                    break;
                }
            }
            localLog("After user choice adjust, the final candidate is:"
                    + getNetworkString(networkCandidate) + " : " + scanResultCandidate.BSSID);
        }

        // At this point none of the saved networks were good candidates so we fall back to
        // externally scored networks if any are available.
        if (scanResultCandidate == null) {
            localLog("Checking the externalScoreEvaluator for candidates...");
            networkCandidate = getExternalScoreCandidate(externalScoreEvaluator);
            if (networkCandidate != null) {
                scanResultCandidate = networkCandidate.getNetworkSelectionStatus().getCandidate();
            }
        }

        if (scanResultCandidate == null) {
            networkCandidate = getCarrierScoreCandidate(carrierScoreEvaluator);
            localLog("Carrier candidate::" + networkCandidate);
            if (networkCandidate != null) {
                scanResultCandidate =
                        mWifiConfigManager.getScanResultCandidate(networkCandidate);
            }
        }

        if (scanResultCandidate == null) {
            localLog("Can not find any suitable candidates");
            return null;
        }

        String currentAssociationId = mCurrentConnectedNetwork == null ? "Disconnected" :
                getNetworkString(mCurrentConnectedNetwork);
        String targetAssociationId = getNetworkString(networkCandidate);
        //In passpoint, saved configuration has garbage SSID. We need update it with the SSID of
        //the scan result.
        if (networkCandidate.isPasspoint()) {
            // This will update the passpoint configuration in WifiConfigManager
            networkCandidate.SSID = "\"" + scanResultCandidate.SSID + "\"";
        }

        //For debug purpose only
        if (scanResultCandidate.BSSID.equals(mCurrentBssid)) {
            localLog(currentAssociationId + " is already the best choice!");
        } else if (mCurrentConnectedNetwork != null
                && (mCurrentConnectedNetwork.networkId == networkCandidate.networkId
                || mCurrentConnectedNetwork.isLinked(networkCandidate))) {
            localLog("Roaming from " + currentAssociationId + " to " + targetAssociationId);
        } else {
            localLog("reconnect from " + currentAssociationId + " to " + targetAssociationId);
        }

        mCurrentBssid = scanResultCandidate.BSSID;
        mCurrentConnectedNetwork = networkCandidate;
        mLastQualifiedNetworkSelectionTimeStamp = mClock.elapsedRealtime();
        return networkCandidate;
    }

    /**
     * Returns the best candidate network according to the given ExternalScoreEvaluator.
     */
    @Nullable
    WifiConfiguration getExternalScoreCandidate(ExternalScoreEvaluator scoreEvaluator) {
        WifiConfiguration networkCandidate = null;
        switch (scoreEvaluator.getBestCandidateType()) {
            case ExternalScoreEvaluator.BestCandidateType.UNTRUSTED_NETWORK:
                ScanResult untrustedScanResultCandidate =
                        scoreEvaluator.getScanResultCandidate();
                WifiConfiguration unTrustedNetworkCandidate =
                        mWifiConfigManager.wifiConfigurationFromScanResult(
                                untrustedScanResultCandidate);

                // Mark this config as ephemeral so it isn't persisted.
                unTrustedNetworkCandidate.ephemeral = true;
                if (mNetworkScoreCache != null) {
                    unTrustedNetworkCandidate.meteredHint =
                            mNetworkScoreCache.getMeteredHint(untrustedScanResultCandidate);
                }
                mWifiConfigManager.saveNetwork(unTrustedNetworkCandidate,
                        WifiConfiguration.UNKNOWN_UID);

                localLog(String.format("new ephemeral candidate %s network ID:%d, "
                                + "meteredHint=%b",
                        toScanId(untrustedScanResultCandidate), unTrustedNetworkCandidate.networkId,
                        unTrustedNetworkCandidate.meteredHint));

                unTrustedNetworkCandidate.getNetworkSelectionStatus()
                        .setCandidate(untrustedScanResultCandidate);
                networkCandidate = unTrustedNetworkCandidate;
                break;

            case ExternalScoreEvaluator.BestCandidateType.SAVED_NETWORK:
                ScanResult scanResultCandidate = scoreEvaluator.getScanResultCandidate();
                networkCandidate = scoreEvaluator.getSavedConfig();
                networkCandidate.getNetworkSelectionStatus().setCandidate(scanResultCandidate);
                localLog(String.format("new scored candidate %s network ID:%d",
                        toScanId(scanResultCandidate), networkCandidate.networkId));
                break;

            case ExternalScoreEvaluator.BestCandidateType.NONE:
                localLog("ExternalScoreEvaluator did not see any good candidates.");
                break;

            default:
                localLoge("Unhandled ExternalScoreEvaluator case. No candidate selected.");
                break;
        }
        return networkCandidate;
    }

    /**
     * Returns the best candidate network according to the given CarrierScoreEvaluator.
     */
    @Nullable
    WifiConfiguration getCarrierScoreCandidate(CarrierScoreEvaluator scoreEvaluator) {

        ScanResult untrustedCarrierScanResult = scoreEvaluator.getScanResultCandidate();
        if (untrustedCarrierScanResult == null) {
            return null;
        }

        WifiConfiguration untrustedCandidateConfig = getMatchingConfigForEAPNetworks(
                untrustedCarrierScanResult, mCarrierConfiguredNetworks);

        if (untrustedCandidateConfig == null) {
            return null;
        }

        WifiConfiguration newUntrustedCandidateConfig =
                new WifiConfiguration(untrustedCandidateConfig);

        // Mark this config as ephemeral so it isn't persisted.
        newUntrustedCandidateConfig.ephemeral = true;
        // Mark this config as a Carrier Network.
        newUntrustedCandidateConfig.isCarrierNetwork = true;

        mWifiConfigManager.saveNetworkAndSetCandidate(
                newUntrustedCandidateConfig, untrustedCarrierScanResult);
        return newUntrustedCandidateConfig;
    }

    /**
     * Returns the available external network score or NULL if no score is available.
     *
     * @param scanResult The scan result of the network to score.
     * @param isActiveNetwork Whether or not the network is currently connected.
     * @return A valid external score if one is available or NULL.
     */
    @Nullable
    Integer getNetworkScore(ScanResult scanResult, boolean isActiveNetwork) {
        if (mNetworkScoreCache != null && mNetworkScoreCache.isScoredNetwork(scanResult)) {
            int networkScore = mNetworkScoreCache.getNetworkScore(scanResult, isActiveNetwork);
            localLog(toScanId(scanResult) + " has score: " + networkScore);
            return networkScore;
        }
        return null;
    }

    /**
     * Returns the available external network score or NULL if no score is available.
     *
     * @param scanResult The scan result of the network to score.
     * @return A valid external score if one is available or NULL.
     */
    int getCarrierScore(ScanResult scanResult, WifiConfiguration currentNetwork,
                        boolean sameBssid) {
        localLog("Calc Carrier score: w/" + sameBssid);
        if (currentNetwork != null) {
            localLog("scoring: compare::" + scanResult.SSID + ", with:" + currentNetwork.SSID);
        }
        int score = 0;
        // Calculate the RSSI score.
        int rssi = scanResult.level <= mWifiConfigManager.mThresholdSaturatedRssi24.get()
                ? scanResult.level : mWifiConfigManager.mThresholdSaturatedRssi24.get();
        score += (rssi + mRssiScoreOffset) * mRssiScoreSlope;

        // 5GHz band bonus.
        if (scanResult.is5GHz()) {
            score += BAND_AWARD_5GHz;
        }

        //same network award
        if ((currentNetwork != null) && currentNetwork.SSID.equals(scanResult.SSID)) {
            score += mWifiConfigManager.mCurrentNetworkBoost.get();
        }

        //same BSSID award
        if (sameBssid) {
            score += mSameBssidAward;
        }

        localLog("Calc Carrier score:" + score);
        return score;
    }

    /**
     * Formats the given ScanResult as a scan ID for logging.
     */
    private static String toScanId(@Nullable ScanResult scanResult) {
        return scanResult == null ? "NULL"
                                  : String.format("%s:%s", scanResult.SSID, scanResult.BSSID);
    }

    //Dump the logs
    void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
        pw.println("Dump of WifiQualifiedNetworkSelector");
        pw.println("WifiQualifiedNetworkSelector - Log Begin ----");
        mLocalLog.dump(fd, pw, args);
        pw.println("WifiQualifiedNetworkSelector - Log End ----");
    }

    /**
     * Used to track and evaluate networks that are assigned external scores.
     */
    static class ExternalScoreEvaluator {
        @Retention(RetentionPolicy.SOURCE)
        @interface BestCandidateType {
            int NONE = 0;
            int SAVED_NETWORK = 1;
            int UNTRUSTED_NETWORK = 2;
        }
        // Always set to the best known candidate.
        private @BestCandidateType int mBestCandidateType = BestCandidateType.NONE;
        private int mHighScore = WifiNetworkScoreCache.INVALID_NETWORK_SCORE;
        private WifiConfiguration mSavedConfig;
        private ScanResult mScanResultCandidate;
        private final LocalLog mLocalLog;
        private final boolean mDbg;

        ExternalScoreEvaluator(LocalLog localLog, boolean dbg) {
            mLocalLog = localLog;
            mDbg = dbg;
        }

        // Determines whether or not the given scan result is the best one its seen so far.
        void evalUntrustedCandidate(@Nullable Integer score, ScanResult scanResult) {
            if (score != null && score > mHighScore) {
                mHighScore = score;
                mScanResultCandidate = scanResult;
                mBestCandidateType = BestCandidateType.UNTRUSTED_NETWORK;
                localLog(toScanId(scanResult) + " become the new untrusted candidate");
            }
        }

        // Determines whether or not the given saved network is the best one its seen so far.
        void evalSavedCandidate(@Nullable Integer score, WifiConfiguration config,
                ScanResult scanResult) {
            // Always take the highest score. If there's a tie and an untrusted network is currently
            // the best then pick the saved network.
            if (score != null
                    && (score > mHighScore
                        || (mBestCandidateType == BestCandidateType.UNTRUSTED_NETWORK
                            && score == mHighScore))) {
                mHighScore = score;
                mSavedConfig = config;
                mScanResultCandidate = scanResult;
                mBestCandidateType = BestCandidateType.SAVED_NETWORK;
                localLog(toScanId(scanResult) + " become the new externally scored saved network "
                        + "candidate");
            }
        }

        int getBestCandidateType() {
            return mBestCandidateType;
        }

        int getHighScore() {
            return mHighScore;
        }

        public ScanResult getScanResultCandidate() {
            return mScanResultCandidate;
        }

        WifiConfiguration getSavedConfig() {
            return mSavedConfig;
        }

        private void localLog(String log) {
            if (mDbg) {
                mLocalLog.log(log);
            }
        }
    }

    /**
     * Used to track and evaluate networks that are assigned by the Carriers.
     */
    static class CarrierScoreEvaluator {
        // Always set to the best known candidate
        private int mHighScore = WifiNetworkScoreCache.INVALID_NETWORK_SCORE;
        private ScanResult mScanResultCandidate;
        private final LocalLog mLocalLog;
        private final boolean mDbg;

        CarrierScoreEvaluator(LocalLog localLog, boolean dbg) {
            mLocalLog = localLog;
            mDbg = dbg;
        }

        // Determines whether or not the given scan result is the best one its seen so far.
        void evalCarrierCandidate(ScanResult scanResult, int score) {
            if (score > mHighScore) {
                mHighScore = score;
                mScanResultCandidate = scanResult;
                localLog(toScanId(scanResult) +
                        " become the new untrusted carrier network candidate");
            }
        }

        int getHighScore() {
            return mHighScore;
        }

        public ScanResult getScanResultCandidate() {
            return mScanResultCandidate;
        }

        private void localLog(String log) {
            if (mDbg) {
                mLocalLog.log(log);
            }
        }
    }

    private WifiConfiguration getMatchingConfigForEAPNetworks(
            ScanResult scanResult, List<WifiConfiguration> candidateConfigs) {
        if (scanResult == null || candidateConfigs == null) {
            return null;
        }
        // TODO currently we only support EAP. We'll add to this in OC.
        if (!scanResult.capabilities.contains("EAP")) {
            return null;
        }
        String ssid = "\"" + scanResult.SSID + "\"";
        for (WifiConfiguration config : candidateConfigs) {
            if (config.SSID.equals(ssid)) {
                // TODO currently we only support EAP. We'll add to this in OC.
                if (config.allowedKeyManagement.get(WifiConfiguration.KeyMgmt.WPA_EAP) ||
                        config.allowedKeyManagement.get(WifiConfiguration.KeyMgmt.IEEE8021X)) {
                    return config;
                }
            }
        }
        return null;
    }
}