summaryrefslogtreecommitdiffstats
path: root/service/java/com/android/server/wifi/WifiAutoJoinController.java
blob: e525949932a8f791c3987e3eb371fe6660eb4041 (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
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
/*
 * Copyright (C) 2014 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.content.Context;
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.WifiConfiguration.KeyMgmt;
import android.net.wifi.WifiConnectionStatistics;
import android.net.wifi.WifiManager;
import android.os.Process;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import android.os.SystemClock;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

/**
 * AutoJoin controller is responsible for WiFi Connect decision
 *
 * It runs in the thread context of WifiStateMachine
 *
 */
public class WifiAutoJoinController {

    private Context mContext;
    private WifiStateMachine mWifiStateMachine;
    private WifiConfigStore mWifiConfigStore;
    private WifiNative mWifiNative;

    private NetworkScoreManager scoreManager;
    private WifiNetworkScoreCache mNetworkScoreCache;

    private static final String TAG = "WifiAutoJoinController ";
    private static boolean DBG = false;
    private static boolean VDBG = false;
    private static final boolean mStaStaSupported = false;

    public static int mScanResultMaximumAge = 40000; /* milliseconds unit */
    public static int mScanResultAutoJoinAge = 5000; /* milliseconds unit */

    private String mCurrentConfigurationKey = null; //used by autojoin

    private final HashMap<String, ScanDetail> scanResultCache = new HashMap<>();

    private ArrayList<String> mBlacklistedBssids;

    private WifiConnectionStatistics mWifiConnectionStatistics;

    /**
     * Whether to allow connections to untrusted networks.
     */
    private boolean mAllowUntrustedConnections = false;

    /* For debug purpose only: if the scored override a score */
    boolean didOverride = false;

    // Lose the non-auth failure blacklisting after 8 hours
    private final static long loseBlackListHardMilli = 1000 * 60 * 60 * 8;
    // Lose some temporary blacklisting after 30 minutes
    private final static long loseBlackListSoftMilli = 1000 * 60 * 30;

    /**
     * @see android.provider.Settings.Global#WIFI_EPHEMERAL_OUT_OF_RANGE_TIMEOUT_MS
     */
    private static final long DEFAULT_EPHEMERAL_OUT_OF_RANGE_TIMEOUT_MS = 1000 * 60; // 1 minute

    public static final int AUTO_JOIN_IDLE = 0;
    public static final int AUTO_JOIN_ROAMING = 1;
    public static final int AUTO_JOIN_EXTENDED_ROAMING = 2;
    public static final int AUTO_JOIN_OUT_OF_NETWORK_ROAMING = 3;

    public static final int HIGH_THRESHOLD_MODIFIER = 5;

    public static final int MAX_RSSI_DELTA = 50;

    // Below are AutoJoin wide parameters indicating if we should be aggressive before joining
    // weak network. Note that we cannot join weak network that are going to be marked as unanted by
    // ConnectivityService because this will trigger link flapping.
    /**
     * There was a non-blacklisted configuration that we bailed from because of a weak signal
     */
    boolean didBailDueToWeakRssi = false;
    /**
     * number of time we consecutively bailed out of an eligible network because its signal
     * was too weak
     */
    int weakRssiBailCount = 0;

    WifiAutoJoinController(Context c, WifiStateMachine w, WifiConfigStore s,
                           WifiConnectionStatistics st, WifiNative n) {
        mContext = c;
        mWifiStateMachine = w;
        mWifiConfigStore = s;
        mWifiNative = n;
        mNetworkScoreCache = null;
        mWifiConnectionStatistics = st;
        scoreManager =
                (NetworkScoreManager) mContext.getSystemService(Context.NETWORK_SCORE_SERVICE);
        if (scoreManager == null)
            logDbg("Registered scoreManager NULL " + " service " + Context.NETWORK_SCORE_SERVICE);

        if (scoreManager != null) {
            mNetworkScoreCache = new WifiNetworkScoreCache(mContext);
            scoreManager.registerNetworkScoreCache(NetworkKey.TYPE_WIFI, mNetworkScoreCache);
        } else {
            logDbg("No network score service: Couldnt register as a WiFi score Manager, type="
                    + Integer.toString(NetworkKey.TYPE_WIFI)
                    + " service " + Context.NETWORK_SCORE_SERVICE);
            mNetworkScoreCache = null;
        }
        mBlacklistedBssids = new ArrayList<String>();
    }

    void enableVerboseLogging(int verbose) {
        if (verbose > 0) {
            DBG = true;
            VDBG = true;
        } else {
            DBG = false;
            VDBG = false;
        }
    }

    /**
     * Flush out scan results older than mScanResultMaximumAge
     */
    private void ageScanResultsOut(int delay) {
        if (delay <= 0) {
            delay = mScanResultMaximumAge; // Something sane
        }
        long milli = System.currentTimeMillis();
        if (VDBG) {
            logDbg("ageScanResultsOut delay " + Integer.valueOf(delay) + " size "
                    + Integer.valueOf(scanResultCache.size()) + " now " + Long.valueOf(milli));
        }

        Iterator<HashMap.Entry<String, ScanDetail>> iter = scanResultCache.entrySet().iterator();
        while (iter.hasNext()) {
            HashMap.Entry<String, ScanDetail> entry = iter.next();
            ScanDetail scanDetail = entry.getValue();
            if ((scanDetail.getSeen() + delay) < milli) {
                iter.remove();
            }
        }
    }


    void averageRssiAndRemoveFromCache(ScanResult result) {
        // Fetch the previous instance for this result
        ScanDetail sd = scanResultCache.get(result.BSSID);
        if (sd != null) {
            ScanResult sr = sd.getScanResult();
            if (mWifiConfigStore.scanResultRssiLevelPatchUp != 0
                    && result.level == 0
                    && sr.level < -20) {
                // A 'zero' RSSI reading is most likely a chip problem which returns
                // an unknown RSSI, hence ignore it
                result.level = sr.level;
            }

            // If there was a previous cache result for this BSSID, average the RSSI values
            result.averageRssi(sr.level, sr.seen, mScanResultMaximumAge);

            // Remove the previous Scan Result - this is not necessary
            scanResultCache.remove(result.BSSID);
        } else if (mWifiConfigStore.scanResultRssiLevelPatchUp != 0 && result.level == 0) {
            // A 'zero' RSSI reading is most likely a chip problem which returns
            // an unknown RSSI, hence initialize it to a sane value
            result.level = mWifiConfigStore.scanResultRssiLevelPatchUp;
        }
    }

    void addToUnscoredNetworks(ScanResult result, List<NetworkKey> unknownScanResults) {
        WifiKey wkey;
        // Quoted SSIDs are the only one valid at this stage
        try {
            wkey = new WifiKey("\"" + result.SSID + "\"", result.BSSID);
        } catch (IllegalArgumentException e) {
            logDbg("AutoJoinController: received badly encoded SSID=[" + result.SSID +
                    "] ->skipping this network");
            wkey = null;
        }
        if (wkey != null) {
            NetworkKey nkey = new NetworkKey(wkey);
            //if we don't know this scan result then request a score from the scorer
            unknownScanResults.add(nkey);
        }
        if (VDBG) {
            String cap = "";
            if (result.capabilities != null)
                cap = result.capabilities;
            logDbg(result.SSID + " " + result.BSSID + " rssi="
                    + result.level + " cap " + cap + " tsf " + result.timestamp + " is not scored");
        }
    }

    int addToScanCache(List<ScanDetail> scanList) {
        int numScanResultsKnown = 0; // Record number of scan results we knew about
        WifiConfiguration associatedConfig = null;
        boolean didAssociate = false;
        long now = System.currentTimeMillis();

        ArrayList<NetworkKey> unknownScanResults = new ArrayList<NetworkKey>();

        for (ScanDetail scanDetail : scanList) {
            ScanResult result = scanDetail.getScanResult();
            if (result.SSID == null) continue;

            if (VDBG) {
                logDbg(" addToScanCache " + result.SSID + " " + result.BSSID
                        + " tsf=" + result.timestamp
                        + " now= " + now + " uptime=" + SystemClock.uptimeMillis()
                        + " elapsed=" + SystemClock.elapsedRealtime());
            }

            // Make sure we record the last time we saw this result
            scanDetail.setSeen();

            averageRssiAndRemoveFromCache(result);

            if (!mNetworkScoreCache.isScoredNetwork(result)) {
                addToUnscoredNetworks(result, unknownScanResults);
            } else {
                if (VDBG) {
                    String cap = "";
                    if (result.capabilities != null)
                        cap = result.capabilities;
                    int score = mNetworkScoreCache.getNetworkScore(result);
                    logDbg(result.SSID + " " + result.BSSID + " rssi="
                            + result.level + " cap " + cap + " is scored : " + score);
                }
            }

            // scanResultCache.put(result.BSSID, new ScanResult(result));
            scanResultCache.put(result.BSSID, scanDetail);
            // Add this BSSID to the scanResultCache of a Saved WifiConfiguration
            didAssociate = mWifiConfigStore.updateSavedNetworkHistory(scanDetail);

            // If not successful, try to associate this BSSID to an existing Saved WifiConfiguration
            if (!didAssociate) {
                // We couldn't associate the scan result to a Saved WifiConfiguration
                // Hence it is untrusted
                result.untrusted = true;
            } else {
                // If the scan result has been blacklisted fir 18 hours -> unblacklist
                if ((now - result.blackListTimestamp) > loseBlackListHardMilli) {
                    result.setAutoJoinStatus(ScanResult.ENABLED);
                }
            }
            if (didAssociate) {
                numScanResultsKnown++;
                result.isAutoJoinCandidate++;
            } else {
                result.isAutoJoinCandidate = 0;
            }
        }

        if (unknownScanResults.size() != 0) {
            NetworkKey[] newKeys =
                    unknownScanResults.toArray(new NetworkKey[unknownScanResults.size()]);
            // Kick the score manager, we will get updated scores asynchronously
            scoreManager.requestScores(newKeys);
        }
        return numScanResultsKnown;
    }

    void logDbg(String message) {
        logDbg(message, false);
    }

    void logDbg(String message, boolean stackTrace) {
        if (stackTrace) {
            Log.d(TAG, message + " stack:"
                    + Thread.currentThread().getStackTrace()[2].getMethodName() + " - "
                    + Thread.currentThread().getStackTrace()[3].getMethodName() + " - "
                    + Thread.currentThread().getStackTrace()[4].getMethodName() + " - "
                    + Thread.currentThread().getStackTrace()[5].getMethodName());
        } else {
            Log.d(TAG, message);
        }
    }

    // Called directly from WifiStateMachine
    int newSupplicantResults(boolean doAutoJoin) {
        int numScanResultsKnown;
        List<ScanDetail> scanList = mWifiStateMachine.getScanResultsListNoCopyUnsync();
        numScanResultsKnown = addToScanCache(scanList);
        ageScanResultsOut(mScanResultMaximumAge);
        if (DBG) {
            logDbg("newSupplicantResults size=" + Integer.valueOf(scanResultCache.size())
                    + " known=" + numScanResultsKnown + " "
                    + doAutoJoin);
        }
        if (doAutoJoin) {
            attemptAutoJoin();
        }
        mWifiConfigStore.writeKnownNetworkHistory(false);
        return numScanResultsKnown;
    }


    /**
     * Not used at the moment
     * should be a call back from WifiScanner HAL ??
     * this function is not hooked and working yet, it will receive scan results from WifiScanners
     * with the list of IEs,then populate the capabilities by parsing the IEs and inject the scan
     * results as normal.
     */
    void newHalScanResults() {
        List<ScanDetail> scanList = null;//mWifiScanner.syncGetScanResultsList();
        String akm = WifiParser.parse_akm(null, null);
        logDbg(akm);
        addToScanCache(scanList);
        ageScanResultsOut(0);
        attemptAutoJoin();
        mWifiConfigStore.writeKnownNetworkHistory(false);
    }

    /**
     * network link quality changed, called directly from WifiTrafficPoller,
     * or by listening to Link Quality intent
     */
    void linkQualitySignificantChange() {
        attemptAutoJoin();
    }

    /**
     * compare a WifiConfiguration against the current network, return a delta score
     * If not associated, and the candidate will always be better
     * For instance if the candidate is a home network versus an unknown public wifi,
     * the delta will be infinite, else compare Kepler scores etc…
     * Negatve return values from this functions are meaningless per se, just trying to
     * keep them distinct for debug purpose (i.e. -1, -2 etc...)
     */
    private int compareNetwork(WifiConfiguration candidate,
                               String lastSelectedConfiguration) {
        if (candidate == null)
            return -3;

        WifiConfiguration currentNetwork = mWifiStateMachine.getCurrentWifiConfiguration();
        if (currentNetwork == null) {
            // Return any absurdly high score, if we are not connected there is no current
            // network to...
            return 1000;
        }

        if (candidate.configKey(true).equals(currentNetwork.configKey(true))) {
            return -2;
        }

        if (DBG) {
            logDbg("compareNetwork will compare " + candidate.configKey()
                    + " with current " + currentNetwork.configKey());
        }
        int order = compareWifiConfigurations(currentNetwork, candidate);

        // The lastSelectedConfiguration is the configuration the user has manually selected
        // thru WifiPicker, or that a 3rd party app asked us to connect to via the
        // enableNetwork with disableOthers=true WifiManager API
        // As this is a direct user choice, we strongly prefer this configuration,
        // hence give +/-100
        if ((lastSelectedConfiguration != null)
                && currentNetwork.configKey().equals(lastSelectedConfiguration)) {
            // currentNetwork is the last selected configuration,
            // so keep it above connect choices (+/-60) and
            // above RSSI/scorer based selection of linked configuration (+/- 50)
            // by reducing order by -100
            order = order - 100;
            if (VDBG) {
                logDbg("     ...and prefers -100 " + currentNetwork.configKey()
                        + " over " + candidate.configKey()
                        + " because it is the last selected -> "
                        + Integer.toString(order));
            }
        } else if ((lastSelectedConfiguration != null)
                && candidate.configKey().equals(lastSelectedConfiguration)) {
            // candidate is the last selected configuration,
            // so keep it above connect choices (+/-60) and
            // above RSSI/scorer based selection of linked configuration (+/- 50)
            // by increasing order by +100
            order = order + 100;
            if (VDBG) {
                logDbg("     ...and prefers +100 " + candidate.configKey()
                        + " over " + currentNetwork.configKey()
                        + " because it is the last selected -> "
                        + Integer.toString(order));
            }
        }

        return order;
    }

    /**
     * update the network history fields fo that configuration
     * - if userTriggered, we mark the configuration as "non selfAdded" since the user has seen it
     * and took over management
     * - if it is a "connect", remember which network were there at the point of the connect, so
     * as those networks get a relative lower score than the selected configuration
     *
     * @param netId
     * @param userTriggered : if the update come from WiFiManager
     * @param connect       : if the update includes a connect
     */
    public void updateConfigurationHistory(int netId, boolean userTriggered, boolean connect) {
        WifiConfiguration selected = mWifiConfigStore.getWifiConfiguration(netId);
        if (selected == null) {
            logDbg("updateConfigurationHistory nid=" + netId + " no selected configuration!");
            return;
        }

        if (selected.SSID == null) {
            logDbg("updateConfigurationHistory nid=" + netId +
                    " no SSID in selected configuration!");
            return;
        }

        if (userTriggered) {
            // Reenable autojoin for this network,
            // since the user want to connect to this configuration
            selected.setAutoJoinStatus(WifiConfiguration.AUTO_JOIN_ENABLED);
            selected.selfAdded = false;
            selected.dirty = true;
        }

        if (DBG && userTriggered) {
            if (selected.connectChoices != null) {
                logDbg("updateConfigurationHistory will update "
                        + Integer.toString(netId) + " now: "
                        + Integer.toString(selected.connectChoices.size())
                        + " uid=" + Integer.toString(selected.creatorUid), true);
            } else {
                logDbg("updateConfigurationHistory will update "
                        + Integer.toString(netId)
                        + " uid=" + Integer.toString(selected.creatorUid), true);
            }
        }

        if (connect && userTriggered) {
            boolean found = false;
            int choice = 0;
            int size = 0;

            // Reset the triggered disabled count, because user wanted to connect to this
            // configuration, and we were not.
            selected.numUserTriggeredWifiDisableLowRSSI = 0;
            selected.numUserTriggeredWifiDisableBadRSSI = 0;
            selected.numUserTriggeredWifiDisableNotHighRSSI = 0;
            selected.numUserTriggeredJoinAttempts++;

            List<WifiConfiguration> networks =
                    mWifiConfigStore.getRecentConfiguredNetworks(12000, false);
            if (networks != null) size = networks.size();
            logDbg("updateConfigurationHistory found " + size + " networks");
            if (networks != null) {
                for (WifiConfiguration config : networks) {
                    if (DBG) {
                        logDbg("updateConfigurationHistory got " + config.SSID + " nid="
                                + Integer.toString(config.networkId));
                    }

                    if (selected.configKey(true).equals(config.configKey(true))) {
                        found = true;
                        continue;
                    }

                    // If the selection was made while config was visible with reasonably good RSSI
                    // then register the user preference, else ignore
                    if (config.visibility == null ||
                            (config.visibility.rssi24 < mWifiConfigStore.thresholdBadRssi24.get()
                            && config.visibility.rssi5 < mWifiConfigStore.thresholdBadRssi5.get())
                    ) {
                        continue;
                    }

                    choice = MAX_RSSI_DELTA + 10; // Make sure the choice overrides the RSSI diff

                    // The selected configuration was preferred over a recently seen config
                    // hence remember the user's choice:
                    // add the recently seen config to the selected's connectChoices array

                    if (selected.connectChoices == null) {
                        selected.connectChoices = new HashMap<String, Integer>();
                    }

                    logDbg("updateConfigurationHistory add a choice " + selected.configKey(true)
                            + " over " + config.configKey(true)
                            + " choice " + Integer.toString(choice));

                    // Add the visible config to the selected's connect choice list
                    selected.connectChoices.put(config.configKey(true), choice);

                    if (config.connectChoices != null) {
                        if (VDBG) {
                            logDbg("updateConfigurationHistory will remove "
                                    + selected.configKey(true) + " from " + config.configKey(true));
                        }
                        // Remove the selected from the recently seen config's connectChoice list
                        config.connectChoices.remove(selected.configKey(true));

                        if (selected.linkedConfigurations != null) {
                            // Remove the selected's linked configuration from the
                            // recently seen config's connectChoice list
                            for (String key : selected.linkedConfigurations.keySet()) {
                                config.connectChoices.remove(key);
                            }
                        }
                    }
                }
                if (found == false) {
                    // We haven't found the configuration that the user just selected in our
                    // scan cache.
                    // In that case we will need a new scan before attempting to connect to this
                    // configuration anyhow and thus we can process the scan results then.
                    logDbg("updateConfigurationHistory try to connect to an old network!! : "
                            + selected.configKey());
                }

                if (selected.connectChoices != null) {
                    if (VDBG)
                        logDbg("updateConfigurationHistory " + Integer.toString(netId)
                                + " now: " + Integer.toString(selected.connectChoices.size()));
                }
            }
        }

        // TODO: write only if something changed
        if (userTriggered || connect) {
            mWifiConfigStore.writeKnownNetworkHistory(false);
        }
    }

    int getConnectChoice(WifiConfiguration source, WifiConfiguration target, boolean strict) {
        int choice = 0;
        if (source == null || target == null) {
            return 0;
        }

        if (source.connectChoices != null
                && source.connectChoices.containsKey(target.configKey(true))) {
            Integer val = source.connectChoices.get(target.configKey(true));
            if (val != null) {
                choice = val;
            }
        } else if (source.linkedConfigurations != null) {
            for (String key : source.linkedConfigurations.keySet()) {
                WifiConfiguration config = mWifiConfigStore.getWifiConfiguration(key);
                if (config != null) {
                    if (config.connectChoices != null) {
                        Integer val = config.connectChoices.get(target.configKey(true));
                        if (val != null) {
                            choice = val;
                        }
                    }
                }
            }
        }

        if (!strict && choice == 0) {
            // We didn't find the connect choice; fallback to some default choices
            int sourceScore = getSecurityScore(source);
            int targetScore = getSecurityScore(target);
            choice = sourceScore - targetScore;
        }

        return choice;
    }

    int compareWifiConfigurationsFromVisibility(WifiConfiguration.Visibility a, int aRssiBoost,
                                                String dbgA, WifiConfiguration.Visibility b, int bRssiBoost, String dbgB) {

        int aRssiBoost5 = 0; // 5GHz RSSI boost to apply for purpose band selection (5GHz pref)
        int bRssiBoost5 = 0; // 5GHz RSSI boost to apply for purpose band selection (5GHz pref)

        int aScore = 0;
        int bScore = 0;

        boolean aPrefers5GHz = false;
        boolean bPrefers5GHz = false;

        /**
         * Calculate a boost to apply to RSSI value of configuration we want to join on 5GHz:
         * Boost RSSI value of 5GHz bands iff the base value is better than threshold,
         * penalize the RSSI value of 5GHz band iff the base value is lower than threshold
         * This implements band preference where we prefer 5GHz if RSSI5 is good enough, whereas
         * we prefer 2.4GHz otherwise.
         */
        aRssiBoost5 = rssiBoostFrom5GHzRssi(a.rssi5, dbgA + "->");
        bRssiBoost5 = rssiBoostFrom5GHzRssi(b.rssi5, dbgB + "->");

        // Select which band to use for a
        if (a.rssi5 + aRssiBoost5 > a.rssi24) {
            // Prefer a's 5GHz
            aPrefers5GHz = true;
        }

        // Select which band to use for b
        if (b.rssi5 + bRssiBoost5 > b.rssi24) {
            // Prefer b's 5GHz
            bPrefers5GHz = true;
        }

        if (aPrefers5GHz) {
            if (bPrefers5GHz) {
                // If both a and b are on 5GHz then we don't apply the 5GHz RSSI boost to either
                // one, but directly compare the RSSI values, this improves stability,
                // since the 5GHz RSSI boost can introduce large fluctuations
                aScore = a.rssi5 + aRssiBoost;
            } else {
                // If only a is on 5GHz, then apply the 5GHz preference boost to a
                aScore = a.rssi5 + aRssiBoost + aRssiBoost5;
            }
        } else {
            aScore = a.rssi24 + aRssiBoost;
        }

        if (bPrefers5GHz) {
            if (aPrefers5GHz) {
                // If both a and b are on 5GHz then we don't apply the 5GHz RSSI boost to either
                // one, but directly compare the RSSI values, this improves stability,
                // since the 5GHz RSSI boost can introduce large fluctuations
                bScore = b.rssi5 + bRssiBoost;
            } else {
                // If only b is on 5GHz, then apply the 5GHz preference boost to b
                bScore = b.rssi5 + bRssiBoost + bRssiBoost5;
            }
        } else {
            bScore = b.rssi24 + bRssiBoost;
        }

        if (VDBG) {
            logDbg("        " + dbgA + " is5=" + aPrefers5GHz + " score=" + aScore
                    + " " + dbgB + " is5=" + bPrefers5GHz + " score=" + bScore);
        }

        // Debug only, record RSSI comparison parameters
        if (a != null) {
            a.score = aScore;
            a.currentNetworkBoost = aRssiBoost;
            a.bandPreferenceBoost = aRssiBoost5;
        }
        if (b != null) {
            b.score = bScore;
            b.currentNetworkBoost = bRssiBoost;
            b.bandPreferenceBoost = bRssiBoost5;
        }

        // Compare a and b
        // If a score is higher then a > b and the order is descending (negative)
        // If b score is higher then a < b and the order is ascending (positive)
        return bScore - aScore;
    }

    // Compare WifiConfiguration by RSSI, and return a comparison value in the range [-50, +50]
    // The result represents "approximately" an RSSI difference measured in dBM
    // Adjusted with various parameters:
    // +) current network gets a +15 boost
    // +) 5GHz signal, if they are strong enough, get a +15 or +25 boost, representing the
    // fact that at short range we prefer 5GHz band as it is cleaner of interference and
    // provides for wider channels
    int compareWifiConfigurationsRSSI(WifiConfiguration a, WifiConfiguration b,
                                      String currentConfiguration) {
        int order = 0;

        // Boost used so as to favor current config
        int aRssiBoost = 0;
        int bRssiBoost = 0;

        // Retrieve the visibility
        WifiConfiguration.Visibility astatus = a.visibility;
        WifiConfiguration.Visibility bstatus = b.visibility;
        if (astatus == null || bstatus == null) {
            // Error visibility wasn't set
            logDbg("    compareWifiConfigurations NULL band status!");
            return 0;
        }

        // Apply Hysteresis, boost RSSI of current configuration
        if (null != currentConfiguration) {
            if (a.configKey().equals(currentConfiguration)) {
                aRssiBoost = mWifiConfigStore.currentNetworkBoost;
            } else if (b.configKey().equals(currentConfiguration)) {
                bRssiBoost = mWifiConfigStore.currentNetworkBoost;
            }
        }

        if (VDBG) {
            logDbg("    compareWifiConfigurationsRSSI: " + a.configKey()
                            + " rssi=" + Integer.toString(astatus.rssi24)
                            + "," + Integer.toString(astatus.rssi5)
                            + " boost=" + Integer.toString(aRssiBoost)
                            + " " + b.configKey() + " rssi="
                            + Integer.toString(bstatus.rssi24) + ","
                            + Integer.toString(bstatus.rssi5)
                            + " boost=" + Integer.toString(bRssiBoost)
            );
        }

        order = compareWifiConfigurationsFromVisibility(
                a.visibility, aRssiBoost, a.configKey(),
                b.visibility, bRssiBoost, b.configKey());

        // Normalize the order to [-50, +50] = [ -MAX_RSSI_DELTA, MAX_RSSI_DELTA]
        if (order > MAX_RSSI_DELTA) order = MAX_RSSI_DELTA;
        else if (order < -MAX_RSSI_DELTA) order = -MAX_RSSI_DELTA;

        if (VDBG) {
            String prefer = " = ";
            if (order > 0) {
                prefer = " < "; // Ascending
            } else if (order < 0) {
                prefer = " > "; // Descending
            }
            logDbg("    compareWifiConfigurationsRSSI " + a.configKey()
                    + " rssi=(" + a.visibility.rssi24
                    + "," + a.visibility.rssi5
                    + ") num=(" + a.visibility.num24
                    + "," + a.visibility.num5 + ")"
                    + prefer + b.configKey()
                    + " rssi=(" + b.visibility.rssi24
                    + "," + b.visibility.rssi5
                    + ") num=(" + b.visibility.num24
                    + "," + b.visibility.num5 + ")"
                    + " -> " + order);
        }

        return order;
    }

    /**
     * b/18490330 only use scorer for untrusted networks
     * <p/>
     * int compareWifiConfigurationsWithScorer(WifiConfiguration a, WifiConfiguration b) {
     * <p/>
     * boolean aIsActive = false;
     * boolean bIsActive = false;
     * <p/>
     * // Apply Hysteresis : boost RSSI of current configuration before
     * // looking up the score
     * if (null != mCurrentConfigurationKey) {
     * if (a.configKey().equals(mCurrentConfigurationKey)) {
     * aIsActive = true;
     * } else if (b.configKey().equals(mCurrentConfigurationKey)) {
     * bIsActive = true;
     * }
     * }
     * int scoreA = getConfigNetworkScore(a, mScanResultAutoJoinAge, aIsActive);
     * int scoreB = getConfigNetworkScore(b, mScanResultAutoJoinAge, bIsActive);
     * <p/>
     * // Both configurations need to have a score for the scorer to be used
     * // ...and the scores need to be different:-)
     * if (scoreA == WifiNetworkScoreCache.INVALID_NETWORK_SCORE
     * || scoreB == WifiNetworkScoreCache.INVALID_NETWORK_SCORE) {
     * if (VDBG)  {
     * logDbg("    compareWifiConfigurationsWithScorer no-scores: "
     * + a.configKey()
     * + " "
     * + b.configKey());
     * }
     * return 0;
     * }
     * <p/>
     * if (VDBG) {
     * String prefer = " = ";
     * if (scoreA < scoreB) {
     * prefer = " < ";
     * } if (scoreA > scoreB) {
     * prefer = " > ";
     * }
     * logDbg("    compareWifiConfigurationsWithScorer " + a.configKey()
     * + " rssi=(" + a.visibility.rssi24
     * + "," + a.visibility.rssi5
     * + ") num=(" + a.visibility.num24
     * + "," + a.visibility.num5 + ")"
     * + " sc=" + scoreA
     * + prefer + b.configKey()
     * + " rssi=(" + b.visibility.rssi24
     * + "," + b.visibility.rssi5
     * + ") num=(" + b.visibility.num24
     * + "," + b.visibility.num5 + ")"
     * + " sc=" + scoreB
     * + " -> " + Integer.toString(scoreB - scoreA));
     * }
     * <p/>
     * // If scoreA > scoreB, the comparison is descending hence the return value is negative
     * return scoreB - scoreA;
     * }
     */

    int getSecurityScore(WifiConfiguration config) {

        if (TextUtils.isEmpty(config.SSID) == false) {
            if (config.allowedKeyManagement.get(KeyMgmt.WPA_EAP)
                    || config.allowedKeyManagement.get(KeyMgmt.WPA_PSK)
                    || config.allowedKeyManagement.get(KeyMgmt.WPA2_PSK)) {
                /* enterprise or PSK networks get highest score */
                return 100;
            } else if (config.allowedKeyManagement.get(KeyMgmt.NONE)) {
                /* open networks have lowest score */
                return 33;
            }
        } else if (TextUtils.isEmpty(config.FQDN) == false) {
            /* passpoint networks have medium preference */
            return 66;
        }

        /* bad network */
        return 0;
    }

    int compareWifiConfigurations(WifiConfiguration a, WifiConfiguration b) {
        int order = 0;
        boolean linked = false;

        if ((a.linkedConfigurations != null) && (b.linkedConfigurations != null)
                && (a.autoJoinStatus == WifiConfiguration.AUTO_JOIN_ENABLED)
                && (b.autoJoinStatus == WifiConfiguration.AUTO_JOIN_ENABLED)) {
            if ((a.linkedConfigurations.get(b.configKey(true)) != null)
                    && (b.linkedConfigurations.get(a.configKey(true)) != null)) {
                linked = true;
            }
        }

        if (a.ephemeral && b.ephemeral == false) {
            if (VDBG) {
                logDbg("    compareWifiConfigurations ephemeral and prefers " + b.configKey()
                        + " over " + a.configKey());
            }
            return 1; // b is of higher priority - ascending
        }
        if (b.ephemeral && a.ephemeral == false) {
            if (VDBG) {
                logDbg("    compareWifiConfigurations ephemeral and prefers " + a.configKey()
                        + " over " + b.configKey());
            }
            return -1; // a is of higher priority - descending
        }

        // Apply RSSI, in the range [-5, +5]
        // after band adjustment, +n difference roughly corresponds to +10xn dBm
        order = order + compareWifiConfigurationsRSSI(a, b, mCurrentConfigurationKey);

        // If the configurations are not linked, compare by user's choice, only a
        // very high RSSI difference can then override the choice
        if (!linked) {
            int choice;

            choice = getConnectChoice(a, b, false);
            if (choice > 0) {
                // a is of higher priority - descending
                order = order - choice;
                if (VDBG) {
                    logDbg("    compareWifiConfigurations prefers " + a.configKey()
                            + " over " + b.configKey()
                            + " due to user choice of " + choice
                            + " order -> " + Integer.toString(order));
                }
                if (a.visibility != null) {
                    a.visibility.lastChoiceBoost = choice;
                    a.visibility.lastChoiceConfig = b.configKey();
                }
            }

            choice = getConnectChoice(b, a, false);
            if (choice > 0) {
                // a is of lower priority - ascending
                order = order + choice;
                if (VDBG) {
                    logDbg("    compareWifiConfigurations prefers " + b.configKey() + " over "
                            + a.configKey() + " due to user choice of " + choice
                            + " order ->" + Integer.toString(order));
                }
                if (b.visibility != null) {
                    b.visibility.lastChoiceBoost = choice;
                    b.visibility.lastChoiceConfig = a.configKey();
                }
            }
        }

        if (order == 0) {
            // We don't know anything - pick the last seen i.e. K behavior
            // we should do this only for recently picked configurations
            if (a.priority > b.priority) {
                // a is of higher priority - descending
                if (VDBG) {
                    logDbg("    compareWifiConfigurations prefers -1 " + a.configKey() + " over "
                            + b.configKey() + " due to priority");
                }

                order = -1;
            } else if (a.priority < b.priority) {
                // a is of lower priority - ascending
                if (VDBG) {
                    logDbg("    compareWifiConfigurations prefers +1 " + b.configKey() + " over "
                            + a.configKey() + " due to priority");
                }
                order = 1;
            }
        }

        String sorder = " == ";
        if (order > 0) {
            sorder = " < ";
        } else if (order < 0) {
            sorder = " > ";
        }

        if (VDBG) {
            logDbg("compareWifiConfigurations: " + a.configKey() + sorder
                    + b.configKey() + " order " + Integer.toString(order));
        }

        return order;
    }

    boolean isBadCandidate(int rssi5, int rssi24) {
        return (rssi5 < -80 && rssi24 < -90);
    }

    /*
    int compareWifiConfigurationsTop(WifiConfiguration a, WifiConfiguration b) {
        int scorerOrder = compareWifiConfigurationsWithScorer(a, b);
        int order = compareWifiConfigurations(a, b);

        if (scorerOrder * order < 0) {
            if (VDBG) {
                logDbg("    -> compareWifiConfigurationsTop: " +
                        "scorer override " + scorerOrder + " " + order);
            }
            // For debugging purpose, remember that an override happened
            // during that autojoin Attempt
            didOverride = true;
            a.numScorerOverride++;
            b.numScorerOverride++;
        }

        if (scorerOrder != 0) {
            // If the scorer came up with a result then use the scorer's result, else use
            // the order provided by the base comparison function
            order = scorerOrder;
        }
        return order;
    }
    */

    public int rssiBoostFrom5GHzRssi(int rssi, String dbg) {
        if (!mWifiConfigStore.enable5GHzPreference) {
            return 0;
        }
        if (mWifiStateMachine.getFrequencyBand()
               == WifiManager.WIFI_FREQUENCY_BAND_2GHZ) {
            return 0;
        }
        if (rssi
                > mWifiConfigStore.bandPreferenceBoostThreshold5.get()) {
            // Boost by 2 dB for each point
            //    Start boosting at -65
            //    Boost by 20 if above -55
            //    Boost by 40 if abore -45
            int boost = mWifiConfigStore.bandPreferenceBoostFactor5
                    * (rssi - mWifiConfigStore.bandPreferenceBoostThreshold5.get());
            if (boost > 50) {
                // 50 dB boost allows jumping from 2.4 to 5GHz
                // consistently
                boost = 50;
            }
            if (VDBG && dbg != null) {
                logDbg("        " + dbg + ":    rssi5 " + rssi + " 5GHz-boost " + boost);
            }
            return boost;
        }

        if (rssi
                < mWifiConfigStore.bandPreferencePenaltyThreshold5.get()) {
            // penalize if < -75
            int boost = mWifiConfigStore.bandPreferencePenaltyFactor5
                    * (rssi - mWifiConfigStore.bandPreferencePenaltyThreshold5.get());
            return boost;
        }
        return 0;
    }

    /**
     * attemptRoam() function implements the core of the same SSID switching algorithm
     * <p/>
     * Run thru all recent scan result of a WifiConfiguration and select the
     * best one.
     */
    public ScanResult attemptRoam(ScanResult a,
                                  WifiConfiguration current, int age, String currentBSSID) {
        if (current == null) {
            if (VDBG) {
                logDbg("attemptRoam not associated");
            }
            return a;
        }

        ScanDetailCache scanDetailCache =
                mWifiConfigStore.getScanDetailCache(current);

        if (scanDetailCache == null) {
            if (VDBG) {
                logDbg("attemptRoam no scan cache");
            }
            return a;
        }
        if (scanDetailCache.size() > 6) {
            if (VDBG) {
                logDbg("attemptRoam scan cache size "
                        + scanDetailCache.size() + " --> bail");
            }
            // Implement same SSID roaming only for configurations
            // that have less than 4 BSSIDs
            return a;
        }

        if (current.BSSID != null && !current.BSSID.equals("any")) {
            if (DBG) {
                logDbg("attemptRoam() BSSID is set "
                        + current.BSSID + " -> bail");
            }
            return a;
        }

        // Determine which BSSID we want to associate to, taking account
        // relative strength of 5 and 2.4 GHz BSSIDs
        long nowMs = System.currentTimeMillis();
        int currentBand = mWifiStateMachine.getFrequencyBand();

        for (ScanDetail sd : scanDetailCache.values()) {
            ScanResult b = sd.getScanResult();
            int bRssiBoost5 = 0;
            int aRssiBoost5 = 0;
            int bRssiBoost = 0;
            int aRssiBoost = 0;
            if (b.is5GHz()
                    && (currentBand == WifiManager.WIFI_FREQUENCY_BAND_2GHZ)) {
                continue;
           }
           if (b.is24GHz()
                   && (currentBand == WifiManager.WIFI_FREQUENCY_BAND_5GHZ)) {
                continue;
           }
            if ((sd.getSeen() == 0) || (b.BSSID == null)
                    || ((nowMs - sd.getSeen()) > age)
                    || b.autoJoinStatus != ScanResult.ENABLED
                    || b.numIpConfigFailures > 8) {
                continue;
            }

            // Pick first one
            if (a == null) {
                a = b;
                continue;
            }

            if (b.numIpConfigFailures < (a.numIpConfigFailures - 1)) {
                // Prefer a BSSID that doesn't have less number of Ip config failures
                logDbg("attemptRoam: "
                        + b.BSSID + " rssi=" + b.level + " ipfail=" + b.numIpConfigFailures
                        + " freq=" + b.frequency
                        + " > "
                        + a.BSSID + " rssi=" + a.level + " ipfail=" + a.numIpConfigFailures
                        + " freq=" + a.frequency);
                a = b;
                continue;
            }

            // Apply hysteresis: we favor the currentBSSID by giving it a boost
            if (currentBSSID != null && currentBSSID.equals(b.BSSID)) {
                // Reduce the benefit of hysteresis if RSSI <= -75
                if (b.level <= mWifiConfigStore.bandPreferencePenaltyThreshold5.get()) {
                    bRssiBoost = mWifiConfigStore.associatedHysteresisLow;
                } else {
                    bRssiBoost = mWifiConfigStore.associatedHysteresisHigh;
                }
            }
            if (currentBSSID != null && currentBSSID.equals(a.BSSID)) {
                if (a.level <= mWifiConfigStore.bandPreferencePenaltyThreshold5.get()) {
                    // Reduce the benefit of hysteresis if RSSI <= -75
                    aRssiBoost = mWifiConfigStore.associatedHysteresisLow;
                } else {
                    aRssiBoost = mWifiConfigStore.associatedHysteresisHigh;
                }
            }

            // Favor 5GHz: give a boost to 5GHz BSSIDs, with a slightly progressive curve
            //   Boost the BSSID if it is on 5GHz, above a threshold
            //   But penalize it if it is on 5GHz and below threshold
            //
            //   With he current threshold values, 5GHz network with RSSI above -55
            //   Are given a boost of 30DB which is enough to overcome the current BSSID
            //   hysteresis (+14) plus 2.4/5 GHz signal strength difference on most cases
            //
            // The "current BSSID" Boost must be added to the BSSID's level so as to introduce\
            // soem amount of hysteresis
            if (b.is5GHz()) {
                bRssiBoost5 = rssiBoostFrom5GHzRssi(b.level + bRssiBoost, b.BSSID);
            }
            if (a.is5GHz()) {
                aRssiBoost5 = rssiBoostFrom5GHzRssi(a.level + aRssiBoost, a.BSSID);
            }

            if (VDBG) {
                String comp = " < ";
                if (b.level + bRssiBoost + bRssiBoost5 > a.level + aRssiBoost + aRssiBoost5) {
                    comp = " > ";
                }
                logDbg("attemptRoam: "
                        + b.BSSID + " rssi=" + b.level + " boost=" + Integer.toString(bRssiBoost)
                        + "/" + Integer.toString(bRssiBoost5) + " freq=" + b.frequency
                        + comp
                        + a.BSSID + " rssi=" + a.level + " boost=" + Integer.toString(aRssiBoost)
                        + "/" + Integer.toString(aRssiBoost5) + " freq=" + a.frequency);
            }

            // Compare the RSSIs after applying the hysteresis boost and the 5GHz
            // boost if applicable
            if (b.level + bRssiBoost + bRssiBoost5 > a.level + aRssiBoost + aRssiBoost5) {
                // b is the better BSSID
                a = b;
            }
        }
        if (a != null) {
            if (VDBG) {
                StringBuilder sb = new StringBuilder();
                sb.append("attemptRoam: " + current.configKey() +
                        " Found " + a.BSSID + " rssi=" + a.level + " freq=" + a.frequency);
                if (currentBSSID != null) {
                    sb.append(" Current: " + currentBSSID);
                }
                sb.append("\n");
                logDbg(sb.toString());
            }
        }
        return a;
    }

    /**
     * getNetworkScore()
     * <p/>
     * if scorer is present, get the network score of a WifiConfiguration
     * <p/>
     * Note: this should be merge with setVisibility
     *
     * @param config
     * @return score
     */
    int getConfigNetworkScore(WifiConfiguration config, int age, boolean isActive) {

        if (mNetworkScoreCache == null) {
            if (VDBG) {
                logDbg("       getConfigNetworkScore for " + config.configKey()
                        + "  -> no scorer, hence no scores");
            }
            return WifiNetworkScoreCache.INVALID_NETWORK_SCORE;
        }

        if (mWifiConfigStore.getScanDetailCache(config) == null) {
            if (VDBG) {
                logDbg("       getConfigNetworkScore for " + config.configKey()
                        + " -> no scan cache");
            }
            return WifiNetworkScoreCache.INVALID_NETWORK_SCORE;
        }

        // Get current date
        long nowMs = System.currentTimeMillis();

        int startScore = -10000;
        int currentBand = mWifiStateMachine.getFrequencyBand();

        // Run thru all cached scan results
        for (ScanDetail sd : mWifiConfigStore.getScanDetailCache(config).values()) {
            ScanResult result = sd.getScanResult();
            if (result.is5GHz()
                  && (currentBand == WifiManager.WIFI_FREQUENCY_BAND_2GHZ)) {
                continue;
            }
            if (result.is24GHz()
                  && (currentBand == WifiManager.WIFI_FREQUENCY_BAND_5GHZ)) {
                continue;
            }
            if ((nowMs - sd.getSeen()) < age) {
                int sc = mNetworkScoreCache.getNetworkScore(result, isActive);
                if (sc > startScore) {
                    startScore = sc;
                }
            }
        }
        if (startScore == -10000) {
            startScore = WifiNetworkScoreCache.INVALID_NETWORK_SCORE;
        }
        if (VDBG) {
            if (startScore == WifiNetworkScoreCache.INVALID_NETWORK_SCORE) {
                logDbg("    getConfigNetworkScore for " + config.configKey()
                        + " -> no available score");
            } else {
                logDbg("    getConfigNetworkScore for " + config.configKey()
                        + " isActive=" + isActive
                        + " score = " + Integer.toString(startScore));
            }
        }

        return startScore;
    }

    /**
     * Add or remove the BSSID from list of blacklisted BSSID's
     *
     * @param enable
     * @param bssid
     * @param reason
     */
    void handleBSSIDBlackList(boolean enable, String bssid, int reason) {
        if( reason == 5 ) // Enable Auto Join for all BSSIDs
        {
            mBlacklistedBssids.clear();
            return;
        }
        if( !enable ) {
            if( !mBlacklistedBssids.contains(bssid) )
            {
                mBlacklistedBssids.add(bssid);
            }
        }
        else {
            if( mBlacklistedBssids.contains(bssid) ) {
                mBlacklistedBssids.remove(bssid);
            }
        }
    }

    /**
     * Is BSSID blacklisted
     *
     * @param bssid
     *
     * @return boolean
     */
    boolean isBlacklistedBSSID( String bssid ) {
        return mBlacklistedBssids.contains(bssid);
    }

    /**
     * Set whether connections to untrusted connections are allowed.
     */
    void setAllowUntrustedConnections(boolean allow) {
        boolean changed = mAllowUntrustedConnections != allow;
        mAllowUntrustedConnections = allow;
        if (changed) {
            // Trigger a scan so as to reattempt autojoin
            mWifiStateMachine.startScanForUntrustedSettingChange();
        }
    }

    private boolean isOpenNetwork(ScanResult result) {
        return !result.capabilities.contains("WEP") &&
                !result.capabilities.contains("PSK") &&
                !result.capabilities.contains("EAP");
    }

    private boolean haveRecentlySeenScoredBssid(WifiConfiguration config) {
        long ephemeralOutOfRangeTimeoutMs = Settings.Global.getLong(
                mContext.getContentResolver(),
                Settings.Global.WIFI_EPHEMERAL_OUT_OF_RANGE_TIMEOUT_MS,
                DEFAULT_EPHEMERAL_OUT_OF_RANGE_TIMEOUT_MS);

        // Check whether the currently selected network has a score curve. If
        // ephemeralOutOfRangeTimeoutMs is <= 0, then this is all we check, and we stop here.
        // Otherwise, we stop here if the currently selected network has a score. If it doesn't, we
        // keep going - it could be that another BSSID is in range (has been seen recently) which
        // has a score, even if the one we're immediately connected to doesn't.
        ScanResult currentScanResult = mWifiStateMachine.getCurrentScanResult();
        boolean currentNetworkHasScoreCurve = currentScanResult != null
                && mNetworkScoreCache.hasScoreCurve(currentScanResult);
        if (ephemeralOutOfRangeTimeoutMs <= 0 || currentNetworkHasScoreCurve) {
            if (DBG) {
                if (currentNetworkHasScoreCurve) {
                    logDbg("Current network has a score curve, keeping network: "
                            + currentScanResult);
                } else {
                    logDbg("Current network has no score curve, giving up: " + config.SSID);
                }
            }
            return currentNetworkHasScoreCurve;
        }

        if (mWifiConfigStore.getScanDetailCache(config) == null
                || mWifiConfigStore.getScanDetailCache(config).isEmpty()) {
            return false;
        }

        long currentTimeMs = System.currentTimeMillis();
        for (ScanDetail sd : mWifiConfigStore.getScanDetailCache(config).values()) {
            ScanResult result = sd.getScanResult();
            if (currentTimeMs > sd.getSeen()
                    && currentTimeMs - sd.getSeen() < ephemeralOutOfRangeTimeoutMs
                    && mNetworkScoreCache.hasScoreCurve(result)) {
                if (DBG) {
                    logDbg("Found scored BSSID, keeping network: " + result.BSSID);
                }
                return true;
            }
        }

        if (DBG) {
            logDbg("No recently scored BSSID found, giving up connection: " + config.SSID);
        }
        return false;
    }

    // After WifiStateMachine ask the supplicant to associate or reconnect
    // we might still obtain scan results from supplicant
    // however the supplicant state in the mWifiInfo and supplicant state tracker
    // are updated when we get the supplicant state change message which can be
    // processed after the SCAN_RESULT message, so at this point the framework doesn't
    // know that supplicant is ASSOCIATING.
    // A good fix for this race condition would be for the WifiStateMachine to add
    // a new transient state where it expects to get the supplicant message indicating
    // that it started the association process and within which critical operations
    // like autojoin should be deleted.

    // This transient state would remove the need for the roam Wathchdog which
    // basically does that.

    // At the moment, we just query the supplicant state synchronously with the
    // mWifiNative.status() command, which allow us to know that
    // supplicant has started association process, even though we didnt yet get the
    // SUPPLICANT_STATE_CHANGE message.

    private static final List<String> ASSOC_STATES = Arrays.asList(
            "ASSOCIATING",
            "ASSOCIATED",
            "FOUR_WAY_HANDSHAKE",
            "GROUP_KEY_HANDSHAKE");

    private int getNetID(String wpaStatus) {
        if (VDBG) {
            logDbg("attemptAutoJoin() status=" + wpaStatus);
        }

        if (wpaStatus == null) {
            if (VDBG) {
                logDbg("wpaStatus is null");
            }
            return WifiConfiguration.INVALID_NETWORK_ID;
        }

        try {
            int id = WifiConfiguration.INVALID_NETWORK_ID;
            String state = null;
            BufferedReader br = new BufferedReader(new StringReader(wpaStatus));
            String line;
            while ((line = br.readLine()) != null) {
                int split = line.indexOf('=');
                if (split < 0) {
                    continue;
                }

                String name = line.substring(0, split);
                if (name.equals("id")) {
                    try {
                        id = Integer.parseInt(line.substring(split + 1));
                        if (state != null) {
                            break;
                        }
                    } catch (NumberFormatException nfe) {
                        return WifiConfiguration.INVALID_NETWORK_ID;
                    }
                } else if (name.equals("wpa_state")) {
                    state = line.substring(split + 1);
                    if (ASSOC_STATES.contains(state)) {
                        return WifiConfiguration.INVALID_NETWORK_ID;
                    } else if (id >= 0) {
                        break;
                    }
                }
            }
            return id;
        } catch (IOException ioe) {
            return WifiConfiguration.INVALID_NETWORK_ID;    // Won't happen
        }
    }

    private boolean setCurrentConfigurationKey(WifiConfiguration currentConfig,
                                               int supplicantNetId) {
        if (currentConfig != null) {
            if (supplicantNetId != currentConfig.networkId
                    // https://b.corp.google.com/issue?id=16484607
                    // mark this condition as an error only if the mismatched networkId are valid
                    && supplicantNetId != WifiConfiguration.INVALID_NETWORK_ID
                    && currentConfig.networkId != WifiConfiguration.INVALID_NETWORK_ID) {
                logDbg("attemptAutoJoin() ERROR wpa_supplicant out of sync nid="
                        + Integer.toString(supplicantNetId) + " WifiStateMachine="
                        + Integer.toString(currentConfig.networkId));
                mWifiStateMachine.disconnectCommand();
                return false;
            } else if (currentConfig.ephemeral && (!mAllowUntrustedConnections ||
                    !haveRecentlySeenScoredBssid(currentConfig))) {
                // The current connection is untrusted (the framework added it), but we're either
                // no longer allowed to connect to such networks, the score has been nullified
                // since we connected, or the scored BSSID has gone out of range.
                // Drop the current connection and perform the rest of autojoin.
                logDbg("attemptAutoJoin() disconnecting from unwanted ephemeral network");
                mWifiStateMachine.disconnectCommand(Process.WIFI_UID,
                        mAllowUntrustedConnections ? 1 : 0);
                return false;
            } else {
                mCurrentConfigurationKey = currentConfig.configKey();
                return true;
            }
        } else {
            // If not invalid, then maybe in the process of associating, skip this attempt
            return supplicantNetId == WifiConfiguration.INVALID_NETWORK_ID;
        }
    }

    private void updateBlackListStatus(WifiConfiguration config, long now) {
        // Wait for 5 minutes before reenabling config that have known,
        // repeated connection or DHCP failures
        if (config.disableReason == WifiConfiguration.DISABLED_DHCP_FAILURE
                || config.disableReason
                == WifiConfiguration.DISABLED_ASSOCIATION_REJECT
                || config.disableReason
                == WifiConfiguration.DISABLED_AUTH_FAILURE) {
            if (config.blackListTimestamp == 0
                    || (config.blackListTimestamp > now)) {
                // Sanitize the timestamp
                config.blackListTimestamp = now;
            }
            if ((now - config.blackListTimestamp) >
                    mWifiConfigStore.wifiConfigBlacklistMinTimeMilli) {
                // Re-enable the WifiConfiguration
                config.status = WifiConfiguration.Status.ENABLED;

                // Reset the blacklist condition
                config.numConnectionFailures = 0;
                config.numIpConfigFailures = 0;
                config.numAuthFailures = 0;
                config.setAutoJoinStatus(WifiConfiguration.AUTO_JOIN_ENABLED);

                config.dirty = true;
            } else {
                if (VDBG) {
                    long delay = mWifiConfigStore.wifiConfigBlacklistMinTimeMilli
                            - (now - config.blackListTimestamp);
                    logDbg("attemptautoJoin " + config.configKey()
                            + " dont unblacklist yet, waiting for "
                            + delay + " ms");
                }
            }
        }
        // Avoid networks disabled because of AUTH failure altogether
        if (DBG) {
            logDbg("attemptAutoJoin skip candidate due to auto join status "
                    + Integer.toString(config.autoJoinStatus) + " key "
                    + config.configKey(true)
                    + " reason " + config.disableReason);
        }
    }

    boolean underSoftThreshold(WifiConfiguration config) {
        return config.visibility.rssi24 < mWifiConfigStore.thresholdUnblacklistThreshold24Soft.get()
                && config.visibility.rssi5 < mWifiConfigStore.thresholdUnblacklistThreshold5Soft.get();
    }

    boolean underHardThreshold(WifiConfiguration config) {
        return config.visibility.rssi24 < mWifiConfigStore.thresholdUnblacklistThreshold24Hard.get()
                && config.visibility.rssi5 < mWifiConfigStore.thresholdUnblacklistThreshold5Hard.get();
    }

    boolean underThreshold(WifiConfiguration config, int rssi24, int rssi5) {
        return config.visibility.rssi24 < rssi24 && config.visibility.rssi5 < rssi5;
    }

    /**
     * attemptAutoJoin() function implements the core of the a network switching algorithm
     * Return false if no acceptable networks were found.
     */
    boolean attemptAutoJoin() {
        boolean found = false;
        didOverride = false;
        didBailDueToWeakRssi = false;
        int networkSwitchType = AUTO_JOIN_IDLE;
        int age = mScanResultAutoJoinAge;

        long now = System.currentTimeMillis();

        String lastSelectedConfiguration = mWifiConfigStore.getLastSelectedConfiguration();
        if (lastSelectedConfiguration != null) {
            age = 14000;
        }
        // Reset the currentConfiguration Key, and set it only if WifiStateMachine and
        // supplicant agree
        mCurrentConfigurationKey = null;
        WifiConfiguration currentConfiguration = mWifiStateMachine.getCurrentWifiConfiguration();

        WifiConfiguration candidate = null;
        // Obtain the subset of recently seen networks
        List<WifiConfiguration> list =
                mWifiConfigStore.getRecentConfiguredNetworks(age, false);
        if (list == null) {
            if (VDBG) logDbg("attemptAutoJoin nothing known=" +
                    mWifiConfigStore.getConfiguredNetworksSize());
            return false;
        }

        // Find the currently connected network: ask the supplicant directly
        int supplicantNetId = getNetID(mWifiNative.status(true));

        if (DBG) {
            String conf = "";
            String last = "";
            if (currentConfiguration != null) {
                conf = " current=" + currentConfiguration.configKey();
            }
            if (lastSelectedConfiguration != null) {
                last = " last=" + lastSelectedConfiguration;
            }
            logDbg("attemptAutoJoin() num recent config " + Integer.toString(list.size())
                    + conf + last
                    + " ---> suppNetId=" + Integer.toString(supplicantNetId));
        }

        if (!setCurrentConfigurationKey(currentConfiguration, supplicantNetId)) {
            return false;
        }

        int currentNetId = -1;
        if (currentConfiguration != null) {
            // If we are associated to a configuration, it will
            // be compared thru the compareNetwork function
            currentNetId = currentConfiguration.networkId;
        }

        /**
         * Run thru all visible configurations without looking at the one we
         * are currently associated to
         * select Best Network candidate from known WifiConfigurations
         */
        for (WifiConfiguration config : list) {
            if (config.SSID == null) {
                continue;
            }

            if ( this.isBlacklistedBSSID(config.BSSID) ) {
                if (DBG) {
                    logDbg("attemptAutoJoin skip candidate as AP is Blacklisted config.SSID = "
                        + config.SSID + " config.BSSID=" + config.BSSID);
                }
                continue;
            }

            if (config.autoJoinStatus >= WifiConfiguration.AUTO_JOIN_DISABLED_ON_AUTH_FAILURE) {
                updateBlackListStatus(config, now);
                continue;
            }

            if (config.userApproved == WifiConfiguration.USER_PENDING ||
                    config.userApproved == WifiConfiguration.USER_BANNED) {
                if (DBG) {
                    logDbg("attemptAutoJoin skip candidate due to user approval status "
                            + WifiConfiguration.userApprovedAsString(config.userApproved) + " key "
                            + config.configKey(true));
                }
                continue;
            }

            // Try to un-blacklist based on elapsed time
            if (config.blackListTimestamp > 0) {
                if (now < config.blackListTimestamp) {
                    /**
                     * looks like there was a change in the system clock since we black listed, and
                     * timestamp is not meaningful anymore, hence lose it.
                     * this event should be rare enough so that we still want to lose the black list
                     */
                    config.setAutoJoinStatus(WifiConfiguration.AUTO_JOIN_ENABLED);
                } else {
                    if ((now - config.blackListTimestamp) > loseBlackListHardMilli) {
                        // Reenable it after 18 hours, i.e. next day
                        config.setAutoJoinStatus(WifiConfiguration.AUTO_JOIN_ENABLED);
                    } else if ((now - config.blackListTimestamp) > loseBlackListSoftMilli) {
                        // Lose blacklisting due to bad link
                        config.setAutoJoinStatus(config.autoJoinStatus - 8);
                    }
                }
            }

            if (config.visibility == null) {
                continue;
            }

            // Try to unblacklist based on good visibility
            if (underSoftThreshold(config)) {
                if (DBG) {
                    logDbg("attemptAutoJoin do not unblacklist due to low visibility " +
                            config.configKey() + " status=" + config.autoJoinStatus);
                }
            } else if (underHardThreshold(config)) {
                // If the network is simply temporary disabled, don't allow reconnect until
                // RSSI becomes good enough
                config.setAutoJoinStatus(config.autoJoinStatus - 1);
                if (DBG) {
                    logDbg("attemptAutoJoin good candidate seen, bumped soft -> status=" +
                            config.configKey() + " status=" + config.autoJoinStatus);
                }
            } else {
                config.setAutoJoinStatus(config.autoJoinStatus - 3);
                if (DBG) {
                    logDbg("attemptAutoJoin good candidate seen, bumped hard -> status=" +
                            config.configKey() + " status=" + config.autoJoinStatus);
                }
            }

            if (config.autoJoinStatus >=
                    WifiConfiguration.AUTO_JOIN_TEMPORARY_DISABLED) {
                // Network is blacklisted, skip
                if (DBG) {
                    logDbg("attemptAutoJoin skip blacklisted -> status=" +
                            config.configKey() + " status=" + config.autoJoinStatus);
                }
                continue;
            }
            if (config.networkId == currentNetId) {
                if (DBG) {
                    logDbg("attemptAutoJoin skip current candidate  "
                            + Integer.toString(currentNetId)
                            + " key " + config.configKey(true));
                }
                continue;
            }

            boolean isLastSelected = false;
            if (lastSelectedConfiguration != null &&
                    config.configKey().equals(lastSelectedConfiguration)) {
                isLastSelected = true;
            }

            if (config.lastRoamingFailure != 0
                    && currentConfiguration != null
                    && (lastSelectedConfiguration == null
                    || !config.configKey().equals(lastSelectedConfiguration))) {
                // Apply blacklisting for roaming to this config if:
                //   - the target config had a recent roaming failure
                //   - we are currently associated
                //   - the target config is not the last selected
                if (now > config.lastRoamingFailure
                        && (now - config.lastRoamingFailure)
                        < config.roamingFailureBlackListTimeMilli) {
                    if (DBG) {
                        logDbg("compareNetwork not switching to " + config.configKey()
                                + " from current " + currentConfiguration.configKey()
                                + " because it is blacklisted due to roam failure, "
                                + " blacklist remain time = "
                                + (now - config.lastRoamingFailure) + " ms");
                    }
                    continue;
                }
            }

            int boost = config.autoJoinUseAggressiveJoinAttemptThreshold + weakRssiBailCount;
            if (underThreshold(config,
                    mWifiConfigStore.thresholdInitialAutoJoinAttemptMin24RSSI.get() - boost,
                    mWifiConfigStore.thresholdInitialAutoJoinAttemptMin5RSSI.get() - boost)) {

                if (DBG) {
                    logDbg("attemptAutoJoin skip due to low visibility " + config.configKey());
                }

                // Don't try to autojoin a network that is too far but
                // If that configuration is a user's choice however, try anyway
                if (!isLastSelected) {
                    config.autoJoinBailedDueToLowRssi = true;
                    didBailDueToWeakRssi = true;
                    continue;
                } else {
                    // Next time, try to be a bit more aggressive in auto-joining
                    if (config.autoJoinUseAggressiveJoinAttemptThreshold
                            < WifiConfiguration.MAX_INITIAL_AUTO_JOIN_RSSI_BOOST
                            && config.autoJoinBailedDueToLowRssi) {
                        config.autoJoinUseAggressiveJoinAttemptThreshold += 4;
                    }
                }
            }
            // NOTE: If this condition is updated, update NETWORK_STATUS_UNWANTED_DISABLE_AUTOJOIN.
            if (config.numNoInternetAccessReports > 0
                    && !isLastSelected
                    && !config.validatedInternetAccess) {
                // Avoid autoJoining this network because last time we used it, it didn't
                // have internet access, and we never manage to validate internet access on this
                // network configuration
                if (DBG) {
                    logDbg("attemptAutoJoin skip candidate due to no InternetAccess  "
                            + config.configKey(true)
                            + " num reports " + config.numNoInternetAccessReports);
                }
                continue;
            }

            if (DBG) {
                String cur = "";
                if (candidate != null) {
                    cur = " current candidate " + candidate.configKey();
                }
                logDbg("attemptAutoJoin trying id="
                        + Integer.toString(config.networkId) + " "
                        + config.configKey(true)
                        + " status=" + config.autoJoinStatus
                        + cur);
            }

            if (candidate == null) {
                candidate = config;
            } else {
                if (VDBG) {
                    logDbg("attemptAutoJoin will compare candidate  " + candidate.configKey()
                            + " with " + config.configKey());
                }

                int order = compareWifiConfigurations(candidate, config);
                if (VDBG) {
                    logDbg("attemptAutoJoin compareWifiConfigurations returned " + order);
                }

                // The lastSelectedConfiguration is the configuration the user has manually selected
                // thru WifiPicker, or that a 3rd party app asked us to connect to via the
                // enableNetwork with disableOthers=true WifiManager API
                // As this is a direct user choice, we strongly prefer this configuration,
                // hence give +/-100
                if ((lastSelectedConfiguration != null)
                        && candidate.configKey().equals(lastSelectedConfiguration)) {
                    // candidate is the last selected configuration,
                    // so keep it above connect choices (+/-60) and
                    // above RSSI/scorer based selection of linked configuration (+/- 50)
                    // by reducing order by -100
                    order = order - 100;
                    if (VDBG) {
                        logDbg("     ...and prefers -100 " + candidate.configKey()
                                + " over " + config.configKey()
                                + " because it is the last selected -> "
                                + Integer.toString(order));
                    }
                } else if ((lastSelectedConfiguration != null)
                        && config.configKey().equals(lastSelectedConfiguration)) {
                    // config is the last selected configuration,
                    // so keep it above connect choices (+/-60) and
                    // above RSSI/scorer based selection of linked configuration (+/- 50)
                    // by increasing order by +100
                    order = order + 100;
                    if (VDBG) {
                        logDbg("     ...and prefers +100 " + config.configKey()
                                + " over " + candidate.configKey()
                                + " because it is the last selected -> "
                                + Integer.toString(order));
                    }
                }

                if (order > 0) {
                    // Ascending : candidate < config
                    candidate = config;
                }
            }
        }

        // Now, go thru scan result to try finding a better untrusted network
        if (mNetworkScoreCache != null && mAllowUntrustedConnections) {
            int rssi5 = WifiConfiguration.INVALID_RSSI;
            int rssi24 = WifiConfiguration.INVALID_RSSI;
            if (candidate != null) {
                rssi5 = candidate.visibility.rssi5;
                rssi24 = candidate.visibility.rssi24;
            }

            // Get current date
            long nowMs = System.currentTimeMillis();
            int currentScore = -10000;
            // The untrusted network with highest score
            ScanDetail untrustedCandidate = null;
            // Look for untrusted scored network only if the current candidate is bad
            if (isBadCandidate(rssi24, rssi5)) {
                for (ScanDetail scanDetail : scanResultCache.values()) {
                    ScanResult result = scanDetail.getScanResult();
                    // We look only at untrusted networks with a valid SSID
                    // A trusted result would have been looked at thru it's Wificonfiguration
                    if (TextUtils.isEmpty(result.SSID) || !result.untrusted ||
                            !isOpenNetwork(result)) {
                        continue;
                    }
                    String quotedSSID = "\"" + result.SSID + "\"";
                    if (mWifiConfigStore.mDeletedEphemeralSSIDs.contains(quotedSSID)) {
                        // SSID had been Forgotten by user, then don't score it
                        continue;
                    }
                    if ((nowMs - result.seen) < mScanResultAutoJoinAge) {
                        // Increment usage count for the network
                        mWifiConnectionStatistics.incrementOrAddUntrusted(quotedSSID, 0, 1);

                        boolean isActiveNetwork = currentConfiguration != null
                                && currentConfiguration.SSID.equals(quotedSSID);
                        int score = mNetworkScoreCache.getNetworkScore(result, isActiveNetwork);
                        if (score != WifiNetworkScoreCache.INVALID_NETWORK_SCORE
                                && score > currentScore) {
                            // Highest score: Select this candidate
                            currentScore = score;
                            untrustedCandidate = scanDetail;
                            if (VDBG) {
                                logDbg("AutoJoinController: found untrusted candidate "
                                        + result.SSID
                                        + " RSSI=" + result.level
                                        + " freq=" + result.frequency
                                        + " score=" + score);
                            }
                        }
                    }
                }
            }
            if (untrustedCandidate != null) {
                // At this point, we have an untrusted network candidate.
                // Create the new ephemeral configuration and see if we should switch over
                candidate =
                        mWifiConfigStore.wifiConfigurationFromScanResult(untrustedCandidate);
                candidate.allowedKeyManagement.set(KeyMgmt.NONE);
                candidate.ephemeral = true;
                candidate.dirty = true;
            }
        }

        long lastUnwanted =
                System.currentTimeMillis()
                        - mWifiConfigStore.lastUnwantedNetworkDisconnectTimestamp;
        if (candidate == null
                && lastSelectedConfiguration == null
                && currentConfiguration == null
                && didBailDueToWeakRssi
                && (mWifiConfigStore.lastUnwantedNetworkDisconnectTimestamp == 0
                || lastUnwanted > (1000 * 60 * 60 * 24 * 7))
                ) {
            // We are bailing out of autojoin although we are seeing a weak configuration, and
            // - we didn't find another valid candidate
            // - we are not connected
            // - without a user network selection choice
            // - ConnectivityService has not triggered an unwanted network disconnect
            //       on this device for a week (hence most likely there is no SIM card or cellular)
            // If all those conditions are met, then boost the RSSI of the weak networks
            // that we are seeing so as we will eventually pick one
            if (weakRssiBailCount < 10)
                weakRssiBailCount += 1;
        } else {
            if (weakRssiBailCount > 0)
                weakRssiBailCount -= 1;
        }

        /**
         *  If candidate is found, check the state of the connection so as
         *  to decide if we should be acting on this candidate and switching over
         */
        int networkDelta = compareNetwork(candidate, lastSelectedConfiguration);
        if (DBG && candidate != null) {
            String doSwitch = "";
            String current = "";
            if (networkDelta < 0) {
                doSwitch = " -> not switching";
            }
            if (currentConfiguration != null) {
                current = " with current " + currentConfiguration.configKey();
            }
            logDbg("attemptAutoJoin networkSwitching candidate "
                    + candidate.configKey()
                    + current
                    + " linked=" + (currentConfiguration != null
                    && currentConfiguration.isLinked(candidate))
                    + " : delta="
                    + Integer.toString(networkDelta) + " "
                    + doSwitch);
        }

        /**
         * Ask WifiStateMachine permission to switch :
         * if user is currently streaming voice traffic,
         * then we should not be allowed to switch regardless of the delta
         */
        if (mWifiStateMachine.shouldSwitchNetwork(networkDelta)) {      // !!! JNo: Here!
            if (mStaStaSupported) {
                logDbg("mStaStaSupported --> error do nothing now ");
            } else {
                if (currentConfiguration != null && currentConfiguration.isLinked(candidate)) {
                    networkSwitchType = AUTO_JOIN_EXTENDED_ROAMING;
                } else {
                    networkSwitchType = AUTO_JOIN_OUT_OF_NETWORK_ROAMING;
                }
                if (DBG) {
                    logDbg("AutoJoin auto connect with netId "
                            + Integer.toString(candidate.networkId)
                            + " to " + candidate.configKey());
                }
                if (didOverride) {
                    candidate.numScorerOverrideAndSwitchedNetwork++;
                }
                candidate.numAssociation++;
                mWifiConnectionStatistics.numAutoJoinAttempt++;

                if (candidate.ephemeral) {
                    // We found a new candidate that we are going to connect to, then
                    // increase its connection count
                    mWifiConnectionStatistics.
                            incrementOrAddUntrusted(candidate.SSID, 1, 0);
                }

                if (candidate.BSSID == null || candidate.BSSID.equals("any")) {
                    // First step we selected the configuration we want to connect to
                    // Second step: Look for the best Scan result for this configuration
                    // TODO this algorithm should really be done in one step
                    String currentBSSID = mWifiStateMachine.getCurrentBSSID();
                    ScanResult roamCandidate =
                            attemptRoam(null, candidate, mScanResultAutoJoinAge, null);
                    if (roamCandidate != null && currentBSSID != null
                            && currentBSSID.equals(roamCandidate.BSSID)) {
                        // Sanity, we were already asociated to that candidate
                        roamCandidate = null;
                    }
                    if (roamCandidate != null && roamCandidate.is5GHz()) {
                        // If the configuration hasn't a default BSSID selected, and the best
                        // candidate is 5GHZ, then select this candidate so as WifiStateMachine and
                        // supplicant will pick it first
                        candidate.autoJoinBSSID = roamCandidate.BSSID;
                        if (VDBG) {
                            logDbg("AutoJoinController: lock to 5GHz "
                                    + candidate.autoJoinBSSID
                                    + " RSSI=" + roamCandidate.level
                                    + " freq=" + roamCandidate.frequency);
                        }
                    } else {
                        // We couldnt find a roam candidate
                        candidate.autoJoinBSSID = "any";
                    }
                }
                mWifiStateMachine.sendMessage(WifiStateMachine.CMD_AUTO_CONNECT,
                        candidate.networkId, networkSwitchType, candidate);
                found = true;
            }
        }

        if (networkSwitchType == AUTO_JOIN_IDLE && !mWifiConfigStore.enableHalBasedPno.get()) {
            String currentBSSID = mWifiStateMachine.getCurrentBSSID();
            // Attempt same WifiConfiguration roaming
            ScanResult roamCandidate =
                    attemptRoam(null, currentConfiguration, mScanResultAutoJoinAge, currentBSSID);
            if (roamCandidate != null && currentBSSID != null
                    && currentBSSID.equals(roamCandidate.BSSID)) {
                roamCandidate = null;
            }
            if (roamCandidate != null && mWifiStateMachine.shouldSwitchNetwork(999)) {
                if (DBG) {
                    logDbg("AutoJoin auto roam with netId "
                            + Integer.toString(currentConfiguration.networkId)
                            + " " + currentConfiguration.configKey() + " to BSSID="
                            + roamCandidate.BSSID + " freq=" + roamCandidate.frequency
                            + " RSSI=" + roamCandidate.level);
                }
                networkSwitchType = AUTO_JOIN_ROAMING;
                mWifiConnectionStatistics.numAutoRoamAttempt++;

                mWifiStateMachine.sendMessage(WifiStateMachine.CMD_AUTO_ROAM,
                        currentConfiguration.networkId, 1, roamCandidate);
                found = true;
            }
        }
        if (VDBG) logDbg("Done attemptAutoJoin status=" + Integer.toString(networkSwitchType));
        return found;
    }

    private void logDenial(String reason, WifiConfiguration config) {
        if (!DBG) {
            return;
        }
        logDbg(reason + config.toString());
    }

    WifiConfiguration getWifiConfiguration(WifiNative.WifiPnoNetwork network) {
        if (network.configKey != null) {
            return mWifiConfigStore.getWifiConfiguration(network.configKey);
        }
        return null;
    }

    ArrayList<WifiNative.WifiPnoNetwork> getPnoList(WifiConfiguration current) {
        int size = -1;
        ArrayList<WifiNative.WifiPnoNetwork> list = new ArrayList<WifiNative.WifiPnoNetwork>();

        if (mWifiConfigStore.mCachedPnoList != null) {
            size = mWifiConfigStore.mCachedPnoList.size();
        }

        if (DBG) {
            String s = "";
            if (current != null) {
                s = " for: " + current.configKey();
            }
            Log.e(TAG, " get Pno List total size:" + size + s);
        }
        if (current != null) {
            String configKey = current.configKey();
            /**
             * If we are currently associated to a WifiConfiguration then include
             * only those networks that have a higher priority
             */
            for (WifiNative.WifiPnoNetwork network : mWifiConfigStore.mCachedPnoList) {
                WifiConfiguration config = getWifiConfiguration(network);
                if (config == null) {
                    continue;
                }
                if (config.autoJoinStatus
                        >= WifiConfiguration.AUTO_JOIN_DISABLED_NO_CREDENTIALS) {
                     continue;
                }

                if (!configKey.equals(network.configKey)) {
                    int choice = getConnectChoice(config, current, true);
                    if (choice > 0) {
                        // config is of higher priority
                        if (DBG) {
                            Log.e(TAG, " Pno List adding:" + network.configKey
                                    + " choice " + choice);
                        }
                        list.add(network);
                        network.rssi_threshold = mWifiConfigStore.thresholdGoodRssi24.get();
                    }
                }
            }
        } else {
            for (WifiNative.WifiPnoNetwork network : mWifiConfigStore.mCachedPnoList) {
                WifiConfiguration config = getWifiConfiguration(network);
                if (config == null) {
                    continue;
                }
                if (config.autoJoinStatus
                        >= WifiConfiguration.AUTO_JOIN_DISABLED_NO_CREDENTIALS) {
                    continue;
                }
                list.add(network);
                network.rssi_threshold = mWifiConfigStore.thresholdGoodRssi24.get();
            }
        }
        return list;
    }
}