aboutsummaryrefslogtreecommitdiffstats
path: root/src/station.c
blob: 73de26bbde9ca029d94a8ca3f182b370ad356fb8 (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
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
/*
 *
 *  Wireless daemon for Linux
 *
 *  Copyright (C) 2018-2019  Intel Corporation. All rights reserved.
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License as published by the Free Software Foundation; either
 *  version 2.1 of the License, or (at your option) any later version.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 */

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#define _GNU_SOURCE
#include <stdio.h>
#include <errno.h>
#include <time.h>
#include <sys/time.h>
#include <limits.h>
#include <linux/if_ether.h>

#include <ell/ell.h>

#include "ell/useful.h"
#include "src/util.h"
#include "src/iwd.h"
#include "src/module.h"
#include "src/common.h"
#include "src/watchlist.h"
#include "src/scan.h"
#include "src/netdev.h"
#include "src/dbus.h"
#include "src/wiphy.h"
#include "src/network.h"
#include "src/knownnetworks.h"
#include "src/ie.h"
#include "src/handshake.h"
#include "src/station.h"
#include "src/blacklist.h"
#include "src/mpdu.h"
#include "src/erp.h"
#include "src/netconfig.h"
#include "src/anqp.h"
#include "src/anqputil.h"
#include "src/diagnostic.h"
#include "src/frame-xchg.h"
#include "src/sysfs.h"
#include "src/band.h"
#include "src/ft.h"
#include "src/eap.h"
#include "src/eap-tls-common.h"
#include "src/storage.h"

static struct l_queue *station_list;
static uint32_t netdev_watch;
static uint32_t mfp_setting;
static uint32_t roam_retry_interval;
static bool anqp_disabled;
static bool supports_arp_evict_nocarrier;
static bool supports_ndisc_evict_nocarrier;
static struct watchlist event_watches;
static uint32_t known_networks_watch;
static uint32_t allowed_bands;

struct station {
	enum station_state state;
	struct watchlist state_watches;
	struct scan_bss *connected_bss;
	struct network *connected_network;
	struct scan_bss *connect_pending_bss;
	struct network *connect_pending_network;
	struct l_queue *autoconnect_list;
	struct l_queue *bss_list;
	struct l_queue *hidden_bss_list_sorted;
	struct l_hashmap *networks;
	struct l_queue *networks_sorted;
	struct l_dbus_message *connect_pending;
	struct l_dbus_message *hidden_pending;
	struct l_dbus_message *disconnect_pending;
	struct l_dbus_message *scan_pending;
	struct l_dbus_message *get_station_pending;
	struct signal_agent *signal_agent;
	uint32_t dbus_scan_id;
	uint32_t quick_scan_id;
	uint32_t hidden_network_scan_id;
	struct l_queue *owe_hidden_scan_ids;

	/* Roaming related members */
	struct timespec roam_min_time;
	struct l_timeout *roam_trigger_timeout;
	uint32_t roam_scan_id;
	uint8_t preauth_bssid[6];

	struct wiphy *wiphy;
	struct netdev *netdev;

	struct l_queue *anqp_pending;

	struct netconfig *netconfig;

	/* Set of frequencies to scan first when attempting a roam */
	struct scan_freq_set *roam_freqs;
	struct l_queue *roam_bss_list;

	/* Frequencies split into subsets by priority */
	struct scan_freq_set *scan_freqs_order[3];
	unsigned int dbus_scan_subset_idx;

	uint32_t wiphy_watch;

	struct wiphy_radio_work_item ft_work;

	uint64_t last_roam_scan;

	bool preparing_roam : 1;
	bool roam_scan_full : 1;
	bool signal_low : 1;
	bool ap_directed_roaming : 1;
	bool scanning : 1;
	bool autoconnect : 1;
	bool autoconnect_can_start : 1;
	bool netconfig_after_roam : 1;
};

struct anqp_entry {
	struct station *station;
	struct network *network;
	uint32_t pending;
};

/*
 * Used as entries for the roam list since holding scan_bss pointers directly
 * from station->bss_list is not 100% safe due to the possibility of the
 * hardware scanning and overwriting station->bss_list.
 */
struct roam_bss {
	uint8_t addr[6];
	uint16_t rank;
	int32_t signal_strength;
	bool ft_failed: 1;
};

static struct roam_bss *roam_bss_from_scan_bss(const struct scan_bss *bss,
						uint16_t rank)
{
	struct roam_bss *rbss = l_new(struct roam_bss, 1);

	memcpy(rbss->addr, bss->addr, 6);
	rbss->rank = rank;
	rbss->signal_strength = bss->signal_strength;
	rbss->ft_failed = false;

	return rbss;
}

static int roam_bss_rank_compare(const void *a, const void *b, void *user_data)
{
	const struct roam_bss *new_bss = a, *bss = b;

	if (bss->rank == new_bss->rank)
		return (bss->signal_strength >
					new_bss->signal_strength) ? 1 : -1;

	return (bss->rank > new_bss->rank) ? 1 : -1;
}

struct wiphy *station_get_wiphy(struct station *station)
{
	return station->wiphy;
}

struct netdev *station_get_netdev(struct station *station)
{
	return station->netdev;
}

struct network *station_get_connected_network(struct station *station)
{
	return station->connected_network;
}

bool station_is_busy(struct station *station)
{
	return station->state != STATION_STATE_DISCONNECTED &&
			station->state != STATION_STATE_AUTOCONNECT_FULL &&
			station->state != STATION_STATE_AUTOCONNECT_QUICK;
}

static bool station_is_autoconnecting(struct station *station)
{
	return station->state == STATION_STATE_AUTOCONNECT_FULL ||
			station->state == STATION_STATE_AUTOCONNECT_QUICK;
}

static bool station_is_roaming(struct station *station)
{
	return station->state == STATION_STATE_ROAMING ||
			station->state == STATION_STATE_FT_ROAMING ||
			station->state == STATION_STATE_FW_ROAMING;
}

static bool station_debug_event(struct station *station, const char *name)
{
	struct l_dbus_message *signal;

	if (!iwd_is_developer_mode())
		return true;

	l_debug("StationDebug.Event(%s)", name);

	signal = l_dbus_message_new_signal(dbus_get_bus(),
					netdev_get_path(station->netdev),
					IWD_STATION_DEBUG_INTERFACE, "Event");

	l_dbus_message_set_arguments(signal, "sav", name, 0);

	return l_dbus_send(dbus_get_bus(), signal) != 0;
}

static void station_property_set_scanning(struct station *station,
								bool scanning)
{
	if (station->scanning == scanning)
		return;

	station->scanning = scanning;

	l_dbus_property_changed(dbus_get_bus(),
				netdev_get_path(station->netdev),
					IWD_STATION_INTERFACE, "Scanning");
}

static void station_enter_state(struct station *station,
						enum station_state state);

static void network_add_foreach(struct network *network, void *user_data)
{
	struct station *station = user_data;

	l_queue_insert(station->autoconnect_list, network,
				network_rank_compare, NULL);
}

static int station_autoconnect_next(struct station *station)
{
	struct network *network;
	int r;

	if (!station->autoconnect_list)
		return -ENOENT;

	while ((network = l_queue_pop_head(station->autoconnect_list))) {
		const char *ssid = network_get_ssid(network);
		struct scan_bss *bss = network_bss_select(network, false);

		l_debug("autoconnect: Trying SSID: %s", ssid);

		if (!bss) {
			l_debug("autoconnect: No suitable BSSes found");
			continue;
		}

		l_debug("autoconnect: '%s' freq: %u, rank: %u, strength: %i",
			util_address_to_string(bss->addr),
			bss->frequency, bss->rank,
			bss->signal_strength);

		r = network_autoconnect(network, bss);
		if (!r) {
			if (station->quick_scan_id) {
				scan_cancel(netdev_get_wdev_id(station->netdev),
						station->quick_scan_id);
				station->quick_scan_id = 0;
				station_property_set_scanning(station, false);
			}

			return 0;
		}

		l_debug("autoconnect: network_autoconnect: %s (%d)",
							strerror(-r), r);
	}

	return -ENOENT;
}

static void station_autoconnect_start(struct station *station)
{
	if (!station->autoconnect_can_start)
		return;

	if (!station_is_autoconnecting(station))
		return;

	if (!l_queue_isempty(station->anqp_pending))
		return;

	if (!l_queue_isempty(station->owe_hidden_scan_ids))
		return;

	if (L_WARN_ON(station->autoconnect_list))
		l_queue_destroy(station->autoconnect_list, NULL);

	l_debug("");

	station->autoconnect_list = l_queue_new();
	station_network_foreach(station, network_add_foreach, station);
	station_autoconnect_next(station);
	station->autoconnect_can_start = false;
}

static void bss_free(void *data)
{
	struct scan_bss *bss = data;

	scan_bss_free(bss);
}

static void network_free(void *data)
{
	struct network *network = data;

	network_remove(network, -ESHUTDOWN);
}

static bool process_network(const void *key, void *data, void *user_data)
{
	struct network *network = data;
	struct station *station = user_data;

	if (!network_bss_list_isempty(network)) {
		bool connected = network == station->connected_network;

		/* Build the network list ordered by rank */
		network_rank_update(network, connected);

		l_queue_insert(station->networks_sorted, network,
				network_rank_compare, NULL);

		return false;
	}

	/* Drop networks that have no more BSSs in range */
	l_debug("No remaining BSSs for SSID: %s -- Removing network",
			network_get_ssid(network));
	network_remove(network, -ERANGE);

	return true;
}

static const char *iwd_network_get_path(struct station *station,
					const char *ssid,
					enum security security)
{
	static char path[256];
	unsigned int pos, i;

	pos = snprintf(path, sizeof(path), "%s/",
					netdev_get_path(station->netdev));

	for (i = 0; ssid[i] && pos < sizeof(path); i++)
		pos += snprintf(path + pos, sizeof(path) - pos, "%02hhx",
					ssid[i]);

	snprintf(path + pos, sizeof(path) - pos, "_%s",
				security_to_str(security));

	return path;
}

struct network *station_network_find(struct station *station, const char *ssid,
					enum security security)
{
	const char *path = iwd_network_get_path(station, ssid, security);

	return l_hashmap_lookup(station->networks, path);
}

static int bss_signal_strength_compare(const void *a, const void *b, void *user)
{
	const struct scan_bss *new_bss = a;
	const struct scan_bss *bss = b;

	return (bss->signal_strength > new_bss->signal_strength) ? 1 : -1;
}

/*
 * Returns the network object the BSS was added to or NULL if ignored.
 */
static struct network *station_add_seen_bss(struct station *station,
						struct scan_bss *bss)
{
	struct network *network;
	enum security security;
	const char *path;
	char ssid[33];
	uint32_t kbps100 = DIV_ROUND_CLOSEST(bss->data_rate, 100000);

	l_debug("Processing BSS '%s' with SSID: %s, freq: %u, rank: %u, "
			"strength: %i, data_rate: %u.%u",
			util_address_to_string(bss->addr),
			util_ssid_to_utf8(bss->ssid_len, bss->ssid),
			bss->frequency, bss->rank, bss->signal_strength,
			kbps100 / 10, kbps100 % 10);

	if (util_ssid_is_hidden(bss->ssid_len, bss->ssid)) {
		l_debug("BSS has hidden SSID");

		l_queue_insert(station->hidden_bss_list_sorted, bss,
					bss_signal_strength_compare, NULL);
		return NULL;
	}

	memcpy(ssid, bss->ssid, bss->ssid_len);
	ssid[bss->ssid_len] = '\0';

	if (!(bss->capability & IE_BSS_CAP_ESS)) {
		l_debug("Ignoring non-ESS BSS \"%s\"", ssid);
		return NULL;
	}

	if (scan_bss_get_security(bss, &security) < 0)
		return NULL;

	/* Hidden OWE transition network */
	if (security == SECURITY_NONE && bss->rsne && bss->owe_trans) {
		struct ie_owe_transition_info *info = bss->owe_trans;
		/*
		 * WiFi Alliance OWE Specification v1.1 - Section 2.2.1:
		 *
		 * "2. An OWE AP shall use two different SSIDs, one for OWE
		 *     and one for Open"
		 *
		 * "4. The OWE BSS shall include the OWE Transition Mode element
		 *     in all Beacon and Probe Response frames to encapsulate
		 *     the BSSID and SSID of the Open BSS"
		 *
		 * Meaning the hidden SSID should not match the SSID in the
		 * hidden network's OWE IE. Might as well restrict BSSID as well
		 * to be safe.
		 *
		 * In addition this SSID must be a valid utf8 string otherwise
		 * we could not look up the network. Note that this is not true
		 * for the open BSS IE, it can be non-utf8.
		 */
		if (!util_ssid_is_utf8(info->ssid_len, info->ssid))
			return NULL;

		if (!memcmp(info->ssid, bss->ssid, bss->ssid_len))
			return NULL;

		if (!memcmp(info->bssid, bss->addr, 6))
			return NULL;

		memcpy(ssid, info->ssid, info->ssid_len);
		ssid[info->ssid_len] = '\0';

		l_debug("Found hidden OWE network, using %s for network lookup",
				ssid);
	}

	path = iwd_network_get_path(station, ssid, security);

	network = l_hashmap_lookup(station->networks, path);
	if (!network) {
		network = network_create(station, ssid, security);

		if (!network_register(network, path)) {
			network_remove(network, -EINVAL);
			return NULL;
		}

		l_hashmap_insert(station->networks,
					network_get_path(network), network);
		l_debug("Added new Network \"%s\" security %s",
			network_get_ssid(network), security_to_str(security));
	}

	network_bss_add(network, bss);

	return network;
}

static bool bss_match(const void *a, const void *b)
{
	const struct scan_bss *bss_a = a;
	const struct scan_bss *bss_b = b;

	if (memcmp(bss_a->addr, bss_b->addr, sizeof(bss_a->addr)))
		return false;

	if (bss_a->ssid_len != bss_b->ssid_len)
		return false;

	return !memcmp(bss_a->ssid, bss_b->ssid, bss_a->ssid_len);
}

struct bss_expiration_data {
	struct scan_bss *connected_bss;
	uint64_t now;
	const struct scan_freq_set *freqs;
};

#define SCAN_RESULT_BSS_RETENTION_TIME (30 * 1000000)

static bool bss_free_if_expired(void *data, void *user_data)
{
	struct scan_bss *bss = data;
	struct bss_expiration_data *expiration_data = user_data;

	if (bss == expiration_data->connected_bss)
		/* Do not expire the currently connected BSS. */
		return false;

	/* Keep any BSSes that are not on the frequency list */
	if (!scan_freq_set_contains(expiration_data->freqs, bss->frequency))
		return false;

	if (l_time_before(expiration_data->now,
			bss->time_stamp + SCAN_RESULT_BSS_RETENTION_TIME))
		return false;

	bss_free(bss);

	return true;
}

static void station_bss_list_remove_expired_bsses(struct station *station,
					const struct scan_freq_set *freqs)
{
	struct bss_expiration_data data = {
		.now = l_time_now(),
		.connected_bss = station->connected_bss,
		.freqs = freqs,
	};

	l_queue_foreach_remove(station->bss_list, bss_free_if_expired, &data);
}

struct nai_search {
	struct network *network;
	const char **realms;
};

static bool match_nai_realms(const struct network_info *info, void *user_data)
{
	struct nai_search *search = user_data;

	if (!network_info_match_nai_realm(info, search->realms))
		return false;

	network_set_info(search->network, (struct network_info *) info);

	return true;
}

static bool match_pending(const void *a, const void *b)
{
	const struct anqp_entry *entry = a;

	return entry->pending != 0;
}

static void remove_anqp(void *data)
{
	struct anqp_entry *entry = data;

	if (entry->pending)
		anqp_cancel(entry->pending);

	l_free(entry);
}

static bool anqp_entry_foreach(void *data, void *user_data)
{
	struct anqp_entry *e = data;

	WATCHLIST_NOTIFY(&event_watches, station_event_watch_func_t,
				STATION_EVENT_ANQP_FINISHED, e->network);

	remove_anqp(e);

	return true;
}

static void station_anqp_response_cb(enum anqp_result result,
					const void *anqp, size_t anqp_len,
					void *user_data)
{
	struct anqp_entry *entry = user_data;
	struct station *station = entry->station;
	struct network *network = entry->network;
	struct anqp_iter iter;
	uint16_t id;
	uint16_t len;
	const void *data;
	char **realms = NULL;
	struct nai_search search;

	l_debug("");

	if (result != ANQP_SUCCESS) {
		/* TODO: try next BSS */
		goto request_done;
	}

	anqp_iter_init(&iter, anqp, anqp_len);

	while (anqp_iter_next(&iter, &id, &len, &data)) {
		switch (id) {
		case ANQP_NAI_REALM:
			if (realms)
				break;

			realms = anqp_parse_nai_realms(data, len);
			if (!realms)
				goto request_done;

			break;
		default:
			continue;
		}
	}

	if (!realms)
		goto request_done;

	search.network = network;
	search.realms = (const char **)realms;

	known_networks_foreach(match_nai_realms, &search);

	l_strv_free(realms);

request_done:
	entry->pending = 0;

	/* Return if there are other pending requests */
	if (l_queue_find(station->anqp_pending, match_pending, NULL))
		return;

	/* Notify all watchers now that every ANQP request has finished */
	l_queue_foreach_remove(station->anqp_pending, anqp_entry_foreach, NULL);

	station_autoconnect_start(station);
}

static bool station_start_anqp(struct station *station, struct network *network,
					struct scan_bss *bss)
{
	uint8_t anqp[256];
	uint8_t *ptr = anqp;
	struct anqp_entry *entry;

	if (!bss->hs20_capable)
		return false;

	/* Network already has ANQP data/HESSID */
	if (network_get_info(network))
		return false;

	if (anqp_disabled) {
		l_debug("Not querying AP for ANQP data (disabled)");
		return false;
	}

	entry = l_new(struct anqp_entry, 1);
	entry->station = station;
	entry->network = network;

	l_put_le16(ANQP_QUERY_LIST, ptr);
	ptr += 2;
	l_put_le16(2, ptr);
	ptr += 2;
	l_put_le16(ANQP_NAI_REALM, ptr);
	ptr += 2;
	l_put_le16(ANQP_VENDOR_SPECIFIC, ptr);
	ptr += 2;
	/* vendor length */
	l_put_le16(7, ptr);
	ptr += 2;
	*ptr++ = 0x50;
	*ptr++ = 0x6f;
	*ptr++ = 0x9a;
	*ptr++ = 0x11; /* HS20 ANQP Element type */
	*ptr++ = ANQP_HS20_QUERY_LIST;
	*ptr++ = 0; /* reserved */
	*ptr++ = ANQP_HS20_OSU_PROVIDERS_NAI_LIST;

	/*
	 * TODO: Additional roaming consortiums can be queried if indicated
	 * by the roaming consortium IE. The IE contains up to the first 3, and
	 * these are checked in hs20_find_settings_file.
	 */

	entry->pending = anqp_request(netdev_get_wdev_id(station->netdev),
				netdev_get_address(station->netdev), bss, anqp,
				ptr - anqp, station_anqp_response_cb,
				entry, NULL);
	if (!entry->pending) {
		l_free(entry);
		return false;
	}

	l_queue_push_head(station->anqp_pending, entry);

	WATCHLIST_NOTIFY(&event_watches, station_event_watch_func_t,
				STATION_EVENT_ANQP_STARTED, network);
	return true;
}

static bool network_has_open_pair(struct network *network, struct scan_bss *owe)
{
	const struct l_queue_entry *entry;
	struct ie_owe_transition_info *owe_info = owe->owe_trans;

	for (entry = network_bss_list_get_entries(network); entry;
				entry = entry->next) {
		struct scan_bss *open = entry->data;
		struct ie_owe_transition_info *open_info = open->owe_trans;

		/* AP does not advertise owe transition */
		if (!open_info)
			continue;

		/*
		 * Check if this is an Open/Hidden pair:
		 *
		 * Open SSID equals the SSID in OWE IE
		 * Open BSSID equals the BSSID in OWE IE
		 *
		 * OWE SSID equals the SSID in Open IE
		 * OWE BSSID equals the BSSID in Open IE
		 */
		if (open->ssid_len == owe_info->ssid_len &&
				open_info->ssid_len == owe->ssid_len &&
				!memcmp(open->ssid, owe_info->ssid,
					open->ssid_len) &&
				!memcmp(open_info->ssid, owe->ssid,
					owe->ssid_len) &&
				!memcmp(open->addr, owe_info->bssid, 6) &&
				!memcmp(open_info->bssid, owe->addr, 6))
			return true;
	}

	return false;
}

static bool station_owe_transition_results(int err, struct l_queue *bss_list,
					const struct scan_freq_set *freqs,
					void *userdata)
{
	struct network *network = userdata;
	struct station *station = network_get_station(network);
	struct scan_bss *bss;

	station_property_set_scanning(station, false);

	if (err)
		goto done;

	while ((bss = l_queue_pop_head(bss_list))) {
		/*
		 * Don't handle the open BSS, hidden BSS, BSS with no OWE
		 * Transition IE, or an IE with a non-utf8 SSID
		 */
		if (!bss->rsne || !bss->owe_trans ||
				util_ssid_is_hidden(bss->ssid_len, bss->ssid) ||
				!util_ssid_is_utf8(bss->owe_trans->ssid_len,
							bss->owe_trans->ssid))
			goto free;

		/* Check if we have an open BSS that matches */
		if (!network_has_open_pair(network, bss))
			goto free;

		l_debug("Adding OWE transition network "MAC" to %s",
				MAC_STR(bss->addr), network_get_ssid(network));

		l_queue_push_tail(station->bss_list, bss);
		network_bss_add(network, bss);

		continue;

free:
		scan_bss_free(bss);
	}

	l_queue_destroy(bss_list, NULL);

done:
	l_queue_pop_head(station->owe_hidden_scan_ids);

	WATCHLIST_NOTIFY(&event_watches, station_event_watch_func_t,
				STATION_EVENT_OWE_HIDDEN_FINISHED, network);

	station_autoconnect_start(station);

	return err == 0;
}

static void station_owe_transition_triggered(int err, void *user_data)
{
	struct network *network = user_data;
	struct station *station = network_get_station(network);

	if (err < 0) {
		l_debug("OWE transition scan trigger failed: %i", err);

		l_queue_pop_head(station->owe_hidden_scan_ids);

		WATCHLIST_NOTIFY(&event_watches, station_event_watch_func_t,
				STATION_EVENT_OWE_HIDDEN_FINISHED, network);

		return;
	}

	l_debug("OWE transition scan triggered");

	station_property_set_scanning(station, true);
}

static void foreach_add_owe_scan(struct network *network, void *data)
{
	struct station *station = data;
	const struct l_queue_entry *entry;
	struct l_queue *list = NULL;
	uint32_t id;

	if (network_get_security(network) != SECURITY_NONE)
		return;

	for (entry = network_bss_list_get_entries(network); entry;
				entry = entry->next) {
		struct scan_bss *open = entry->data;

		if (!open->owe_trans)
			continue;

		/* only want the open networks with WFA OWE IE */
		if (open->rsne)
			continue;

		/* BSS already in network object */
		if (network_bss_find_by_addr(network, open->owe_trans->bssid))
			continue;

		if (!list)
			list = l_queue_new();

		l_queue_push_tail(list, open);
	}

	if (!list)
		return;

	id = scan_owe_hidden(netdev_get_wdev_id(station->netdev), list,
				station_owe_transition_triggered,
				station_owe_transition_results, network, NULL);

	l_queue_destroy(list, NULL);

	if (!id)
		return;

	if (!station->owe_hidden_scan_ids)
		station->owe_hidden_scan_ids = l_queue_new();

	l_queue_push_tail(station->owe_hidden_scan_ids, L_UINT_TO_PTR(id));

	WATCHLIST_NOTIFY(&event_watches, station_event_watch_func_t,
				STATION_EVENT_OWE_HIDDEN_STARTED, network);
}

static void station_process_owe_transition_networks(struct station *station)
{
	station_network_foreach(station, foreach_add_owe_scan, station);
}

static bool bss_free_if_ssid_not_utf8(void *data, void *user_data)
{
	struct scan_bss *bss = data;

	if (util_ssid_is_hidden(bss->ssid_len, bss->ssid))
		return false;

	if (util_ssid_is_utf8(bss->ssid_len, bss->ssid))
		return false;

	l_debug("Dropping scan_bss '%s', with non-utf8 SSID",
			util_address_to_string(bss->addr));
	bss_free(bss);
	return true;
}

/*
 * Used when scan results were obtained; either from scan running
 * inside station module or scans running in other state machines, e.g. wsc
 */
void station_set_scan_results(struct station *station,
					struct l_queue *new_bss_list,
					const struct scan_freq_set *freqs,
					bool trigger_autoconnect)
{
	const struct l_queue_entry *bss_entry;
	struct network *network;

	l_queue_foreach_remove(new_bss_list, bss_free_if_ssid_not_utf8, NULL);

	while ((network = l_queue_pop_head(station->networks_sorted)))
		network_bss_list_clear(network);

	l_queue_clear(station->hidden_bss_list_sorted, NULL);

	l_queue_destroy(station->autoconnect_list, NULL);
	station->autoconnect_list = NULL;

	station_bss_list_remove_expired_bsses(station, freqs);

	for (bss_entry = l_queue_get_entries(station->bss_list); bss_entry;
						bss_entry = bss_entry->next) {
		struct scan_bss *old_bss = bss_entry->data;
		struct scan_bss *new_bss;

		new_bss = l_queue_find(new_bss_list, bss_match, old_bss);
		if (new_bss) {
			if (old_bss == station->connected_bss)
				station->connected_bss = new_bss;

			bss_free(old_bss);

			continue;
		}

		if (old_bss == station->connected_bss) {
			l_warn("Connected BSS not in scan results");
			station->connected_bss->rank = 0;
		}

		l_queue_push_tail(new_bss_list, old_bss);
	}

	l_queue_destroy(station->bss_list, NULL);

	for (bss_entry = l_queue_get_entries(new_bss_list); bss_entry;
						bss_entry = bss_entry->next) {
		struct scan_bss *bss = bss_entry->data;
		struct network *network = station_add_seen_bss(station, bss);

		if (!network)
			continue;

		/* Cached BSS entry, this should have been processed already */
		if (!scan_freq_set_contains(freqs, bss->frequency))
			continue;

		station_start_anqp(station, network, bss);
	}

	station->bss_list = new_bss_list;

	l_hashmap_foreach_remove(station->networks, process_network, station);

	station->autoconnect_can_start = trigger_autoconnect;
	station_autoconnect_start(station);
}

static void station_reconnect(struct station *station);

static void station_handshake_event(struct handshake_state *hs,
					enum handshake_event event,
					void *user_data, ...)
{
	struct station *station = user_data;
	struct network *network = station->connected_network;
	va_list args;

	va_start(args, user_data);

	switch (event) {
	case HANDSHAKE_EVENT_STARTED:
		l_debug("Handshaking");
		break;
	case HANDSHAKE_EVENT_SETTING_KEYS:
		l_debug("Setting keys");

		/* If we got here, then our settings work.  Update if needed */
		network_sync_settings(network);
		break;
	case HANDSHAKE_EVENT_FAILED:
		netdev_handshake_failed(hs, va_arg(args, int));
		break;
	case HANDSHAKE_EVENT_REKEY_FAILED:
		l_warn("Unable to securely rekey on this hw/kernel...");
		station_reconnect(station);
		break;
	case HANDSHAKE_EVENT_TRANSITION_DISABLE:
	{
		const uint8_t *td = va_arg(args, const uint8_t *);
		size_t len = va_arg(args, size_t);

		network_set_transition_disable(network, td, len);
		break;
	}
	case HANDSHAKE_EVENT_COMPLETE:
	case HANDSHAKE_EVENT_SETTING_KEYS_FAILED:
	case HANDSHAKE_EVENT_EAP_NOTIFY:
	case HANDSHAKE_EVENT_P2P_IP_REQUEST:
	case HANDSHAKE_EVENT_REKEY_COMPLETE:
		/*
		 * currently we don't care about any other events. The
		 * netdev_connect_cb will notify us when the connection is
		 * complete.
		 */
		break;
	}

	va_end(args);
}

static int station_build_handshake_rsn(struct handshake_state *hs,
					struct wiphy *wiphy,
					struct network *network,
					struct scan_bss *bss)
{
	const struct l_settings *settings = iwd_get_config();
	enum security security = network_get_security(network);
	bool add_mde = false;
	struct erp_cache_entry *erp_cache = NULL;
	struct ie_rsn_info bss_info;
	uint8_t rsne_buf[256];
	struct ie_rsn_info info;
	uint8_t *ap_ie;
	bool disable_ocv;
	enum band_freq band;

	memset(&info, 0, sizeof(info));

	if (!band_freq_to_channel(bss->frequency, &band))
		goto not_supported;

	memset(&bss_info, 0, sizeof(bss_info));
	scan_bss_get_rsn_info(bss, &bss_info);

	if (bss_info.akm_suites & (IE_RSN_AKM_SUITE_FILS_SHA256 |
				IE_RSN_AKM_SUITE_FILS_SHA384))
		hs->support_fils = true;

	/*
	 * If this network 8021x we might have a set of cached EAP keys. If so
	 * wiphy may select FILS if supported by the AP.
	 */
	if (security == SECURITY_8021X && hs->support_fils)
		erp_cache = network_get_erp_cache(network);

	info.akm_suites = wiphy_select_akm(wiphy, bss, security,
						&bss_info, erp_cache != NULL);

	/*
	 * Special case for OWE. With OWE we still need to build up the
	 * handshake object with AKM/cipher info since OWE does the full 4-way
	 * handshake. But if this is a non-OWE open network, we can skip this.
	 */
	if (security == SECURITY_NONE &&
			!(info.akm_suites & IE_RSN_AKM_SUITE_OWE))
		goto open_network;

	if (!info.akm_suites)
		goto not_supported;

	info.pairwise_ciphers = wiphy_select_cipher(wiphy,
					bss_info.pairwise_ciphers);
	info.group_cipher = wiphy_select_cipher(wiphy,
					bss_info.group_cipher);

	if (!info.pairwise_ciphers || !info.group_cipher)
		goto not_supported;

	/* Management frame protection is explicitly off for OSEN */
	if (info.akm_suites & IE_RSN_AKM_SUITE_OSEN) {
		info.group_management_cipher =
					IE_RSN_CIPHER_SUITE_NO_GROUP_TRAFFIC;
		goto build_ie;
	}

	switch (mfp_setting) {
	case 0:
		if (band != BAND_FREQ_6_GHZ)
			break;

		l_error("MFP turned off by [General].ManagementFrameProtection,"
				" 6GHz frequencies are disabled");
		goto not_supported;
	case 1:
		info.group_management_cipher =
			wiphy_select_cipher(wiphy,
				bss_info.group_management_cipher);
		info.mfpc = info.group_management_cipher != 0;

		if (band != BAND_FREQ_6_GHZ)
			break;

		if (!info.mfpc)
			goto not_supported;

		/*
		 * 802.11ax Section 12.12.2
		 * The STA shall use management frame protection
		 * (MFPR=1) when using RSN.
		 */
		info.mfpr = true;

		break;
	case 2:
		info.group_management_cipher =
			wiphy_select_cipher(wiphy,
				bss_info.group_management_cipher);

		/*
		 * MFP required on our side, but AP doesn't support MFP
		 * or cipher mismatch
		 */
		if (info.group_management_cipher == 0)
			goto not_supported;

		info.mfpc = true;
		info.mfpr = true;
		break;
	}

	if (bss_info.mfpr && !info.mfpc)
		goto not_supported;

build_ie:
	if (!l_settings_get_bool(settings, "General", "DisableOCV",
					&disable_ocv))
		disable_ocv = false;

	/*
	 * Obviously do not enable OCV if explicitly disabled or no AP support.
	 *
	 * Not obviously hostapd rejects OCV support if MFPC is not enabled.
	 * This is not really specified by the spec, but we have to work around
	 * this limitation.
	 *
	 * Another limitation is full mac cards. With limited testing it was
	 * seen that they do not include the OCI in the 4-way handshake yet
	 * still advertise the capability. Because of this OCV is disabled if
	 * any offload features are detected (since IWD prefers to use offload).
	 *
	 * TODO: For now OCV is disabled if the network is FT capable. This is
	 *       being done until support in the kernel is added to
	 *       automatically include the OCI element for the association
	 *       request.
	 */
	info.ocvc = !disable_ocv && bss_info.ocvc && info.mfpc &&
			!wiphy_can_offload(wiphy) &&
			!IE_AKM_IS_FT(info.akm_suites);

	/*
	 * IEEE 802.11-2020 9.4.2.24.4 states extended key IDs can only be used
	 * with CCMP/GCMP cipher suites. We also only enable support if the AP
	 * also indicates support.
	 */
	if (wiphy_supports_ext_key_id(wiphy) && bss_info.extended_key_id &&
			IE_CIPHER_IS_GCMP_CCMP(info.pairwise_ciphers))
		info.extended_key_id = true;

	/* RSN takes priority */
	if (bss->rsne) {
		ap_ie = bss->rsne;
		ie_build_rsne(&info, rsne_buf);
	} else if (bss->wpa) {
		ap_ie = bss->wpa;
		ie_build_wpa(&info, rsne_buf);
	} else if (bss->osen) {
		ap_ie = bss->osen;
		ie_build_osen(&info, rsne_buf);
	} else
		goto not_supported;

	if (!handshake_state_set_authenticator_ie(hs, ap_ie))
		goto not_supported;

	if (!handshake_state_set_supplicant_ie(hs, rsne_buf))
		goto not_supported;

	if (IE_AKM_IS_FT(info.akm_suites))
		add_mde = true;

	/*
	 * If FILS was chosen, the ERP cache has been verified to exist. Take
	 * a reference now so it remains valid (in case of expiration) until
	 * FILS starts.
	 */
	if (IE_AKM_IS_FILS(hs->akm_suite))
		hs->erp_cache = erp_cache;
	else if (erp_cache)
		erp_cache_put(erp_cache);

open_network:
	if (security == SECURITY_NONE)
		/* Perform FT association if available */
		add_mde = bss->mde_present;

	if (add_mde) {
		uint8_t mde[5];

		/* The MDE advertised by the BSS must be passed verbatim */
		mde[0] = IE_TYPE_MOBILITY_DOMAIN;
		mde[1] = 3;
		memcpy(mde + 2, bss->mde, 3);

		handshake_state_set_mde(hs, mde);
	}

	return 0;

not_supported:
	if (erp_cache)
		erp_cache_put(erp_cache);

	return -ENOTSUP;
}

static struct handshake_state *station_handshake_setup(struct station *station,
							struct network *network,
							struct scan_bss *bss)
{
	struct wiphy *wiphy = station->wiphy;
	const struct network_info *info = network_get_info(network);
	struct handshake_state *hs;
	const struct iovec *vendor_ies;
	size_t iov_elems = 0;
	struct ie_fils_ip_addr_request_info fils_ip_req;

	hs = netdev_handshake_state_new(station->netdev);

	handshake_state_set_event_func(hs, station_handshake_event, station);

	if (station_build_handshake_rsn(hs, wiphy, network, bss) < 0)
		goto not_supported;

	handshake_state_set_authenticator_rsnxe(hs, bss->rsnxe);

	if (network_handshake_setup(network, bss, hs) < 0)
		goto not_supported;

	vendor_ies = network_info_get_extra_ies(info, bss, &iov_elems);
	handshake_state_set_vendor_ies(hs, vendor_ies, iov_elems);

	/*
	 * It can't hurt to try the FILS IP Address Assigment independent of
	 * which auth-proto is actually used.
	 */
	if (station->netconfig && netconfig_get_fils_ip_req(station->netconfig,
								&fils_ip_req)) {
		hs->fils_ip_req_ie = l_malloc(32);
		ie_build_fils_ip_addr_request(&fils_ip_req, hs->fils_ip_req_ie);
	}

	return hs;

not_supported:
	handshake_state_free(hs);
	return NULL;
}

static bool new_scan_results(int err, struct l_queue *bss_list,
				const struct scan_freq_set *freqs,
				void *userdata)
{
	struct station *station = userdata;

	station_property_set_scanning(station, false);

	if (err)
		return false;

	station_set_scan_results(station, bss_list, freqs, false);

	station_process_owe_transition_networks(station);

	station->autoconnect_can_start = true;
	station_autoconnect_start(station);

	return true;
}

static void periodic_scan_trigger(int err, void *user_data)
{
	struct station *station = user_data;

	station_property_set_scanning(station, true);
}

static void periodic_scan_stop(struct station *station)
{
	uint64_t id = netdev_get_wdev_id(station->netdev);

	if (scan_periodic_stop(id))
		station_property_set_scanning(station, false);
}

static bool station_needs_hidden_network_scan(struct station *station)
{
	if (!known_networks_has_hidden())
		return false;

	if (station_is_autoconnecting(station))
		return true;

	return !l_queue_isempty(station->hidden_bss_list_sorted);
}

static struct scan_freq_set *station_get_allowed_freqs(struct station *station)
{
	const struct scan_freq_set *supported =
				wiphy_get_supported_freqs(station->wiphy);
	struct scan_freq_set *allowed = scan_freq_set_clone(supported,
							allowed_bands);

	if (scan_freq_set_isempty(allowed)) {
		scan_freq_set_free(allowed);
		allowed = NULL;
	}

	return allowed;
}

static uint32_t station_scan_trigger(struct station *station,
					struct scan_freq_set *freqs,
					scan_trigger_func_t triggered,
					scan_notify_func_t notify,
					scan_destroy_func_t destroy)
{
	uint64_t id = netdev_get_wdev_id(station->netdev);
	struct scan_parameters params;

	memset(&params, 0, sizeof(params));
	params.flush = true;
	params.freqs = freqs;

	if (wiphy_can_randomize_mac_addr(station->wiphy) ||
			station->connected_bss ||
				station_needs_hidden_network_scan(station)) {
		/* If we're connected, HW cannot randomize our MAC */
		if (!station->connected_bss)
			params.randomize_mac_addr_hint = true;

		return scan_active_full(id, &params, triggered, notify,
					station, destroy);
	}

	return scan_passive_full(id, &params, triggered, notify,
					station, destroy);
}

static bool station_quick_scan_results(int err, struct l_queue *bss_list,
					const struct scan_freq_set *freqs,
					void *userdata)
{
	struct station *station = userdata;

	station_property_set_scanning(station, false);

	if (err)
		goto done;

	station_set_scan_results(station, bss_list, freqs, false);

	station_process_owe_transition_networks(station);

	station->autoconnect_can_start = true;
	station_autoconnect_start(station);

done:
	if (station->state == STATION_STATE_AUTOCONNECT_QUICK)
		/*
		 * If we're still in AUTOCONNECT_QUICK state, then autoconnect
		 * failed to find any candidates. Transition to AUTOCONNECT_FULL
		 */
		station_enter_state(station, STATION_STATE_AUTOCONNECT_FULL);

	return err == 0;
}

static void station_quick_scan_triggered(int err, void *user_data)
{
	struct station *station = user_data;

	if (err < 0) {
		l_debug("Quick scan trigger failed: %i", err);

		station_enter_state(station, STATION_STATE_AUTOCONNECT_FULL);

		return;
	}

	l_debug("Quick scan triggered for %s",
					netdev_get_name(station->netdev));

	station_property_set_scanning(station, true);
}

static void station_quick_scan_destroy(void *userdata)
{
	struct station *station = userdata;

	station->quick_scan_id = 0;
}

static int station_quick_scan_trigger(struct station *station)
{
	_auto_(scan_freq_set_free) struct scan_freq_set *known_freq_set = NULL;
	_auto_(scan_freq_set_free) struct scan_freq_set *allowed = NULL;
	bool known_6ghz;

	if (wiphy_regdom_is_updating(station->wiphy)) {
		l_debug("regdom is updating, delaying quick scan");
		return -EAGAIN;
	}

	known_freq_set = known_networks_get_recent_frequencies(5);
	if (!known_freq_set)
		return -ENODATA;

	known_6ghz = scan_freq_set_get_bands(known_freq_set) & BAND_FREQ_6_GHZ;

	/*
	 * This means IWD has previously connected to a 6GHz AP before, but now
	 * the regulatory domain disallows 6GHz likely caused by a reboot, the
	 * firmware going down, or a regulatory update. The only way to
	 * re-enable 6GHz is to get enough beacons via scanning for the firmware
	 * to set the regulatory domain. A quick scan is very unlikely to do
	 * this since its so limited, so return an error which will fall back to
	 * full autoconnect.
	 */
	if (wiphy_band_is_disabled(station->wiphy, BAND_FREQ_6_GHZ) == 1 &&
			wiphy_country_is_unknown(station->wiphy) &&
			known_6ghz)
		return -ENOTSUP;

	allowed = station_get_allowed_freqs(station);
	if (L_WARN_ON(!allowed))
		return -ENOTSUP;

	scan_freq_set_constrain(known_freq_set, allowed);

	if (scan_freq_set_isempty(known_freq_set))
		return -ENOTSUP;

	station->quick_scan_id = station_scan_trigger(station,
						known_freq_set,
						station_quick_scan_triggered,
						station_quick_scan_results,
						station_quick_scan_destroy);
	if (!station->quick_scan_id)
		return -EIO;

	return 0;
}

static const char *station_state_to_string(enum station_state state)
{
	switch (state) {
	case STATION_STATE_DISCONNECTED:
		return "disconnected";
	case STATION_STATE_AUTOCONNECT_QUICK:
		return "autoconnect_quick";
	case STATION_STATE_AUTOCONNECT_FULL:
		return "autoconnect_full";
	case STATION_STATE_CONNECTING:
		return "connecting";
	case STATION_STATE_CONNECTING_AUTO:
		return "connecting (auto)";
	case STATION_STATE_CONNECTED:
		return "connected";
	case STATION_STATE_DISCONNECTING:
		return "disconnecting";
	case STATION_STATE_ROAMING:
		return "roaming";
	case STATION_STATE_FT_ROAMING:
		return "ft-roaming";
	case STATION_STATE_FW_ROAMING:
		return "fw-roaming";
	}

	return "invalid";
}

static void station_set_evict_nocarrier(struct station *station, bool value)
{
	char *v = value ? "1" : "0";

	if (supports_arp_evict_nocarrier)
		sysfs_write_ipv4_setting(netdev_get_name(station->netdev),
					"arp_evict_nocarrier", v);

	if (supports_ndisc_evict_nocarrier)
		sysfs_write_ipv6_setting(netdev_get_name(station->netdev),
					"ndisc_evict_nocarrier", v);
}

/*
 * Handles dropping ARP (IPv4) and neighbor advertisements (IPv6) settings.
 */
static void station_set_drop_neighbor_discovery(struct station *station,
						bool value)
{
	char *v = value ? "1" : "0";

	sysfs_write_ipv4_setting(netdev_get_name(station->netdev),
				"drop_gratuitous_arp", v);
	sysfs_write_ipv6_setting(netdev_get_name(station->netdev),
				"drop_unsolicited_na", v);
}

static void station_set_drop_unicast_l2_multicast(struct station *station,
							bool value)
{
	char *v = value ? "1" : "0";

	sysfs_write_ipv4_setting(netdev_get_name(station->netdev),
				"drop_unicast_in_l2_multicast", v);
	sysfs_write_ipv6_setting(netdev_get_name(station->netdev),
				"drop_unicast_in_l2_multicast", v);
}

static void station_signal_agent_notify(struct station *station);

static void station_enter_state(struct station *station,
						enum station_state state)
{
	uint64_t id = netdev_get_wdev_id(station->netdev);
	struct l_dbus *dbus = dbus_get_bus();
	bool disconnected;
	int ret;

	l_debug("Old State: %s, new state: %s",
			station_state_to_string(station->state),
			station_state_to_string(state));

	disconnected = !station_is_busy(station);

	if ((disconnected && state > STATION_STATE_AUTOCONNECT_FULL) ||
			(!disconnected && state != station->state))
		l_dbus_property_changed(dbus, netdev_get_path(station->netdev),
					IWD_STATION_INTERFACE, "State");

	station->state = state;

	switch (state) {
	case STATION_STATE_AUTOCONNECT_QUICK:
		ret = station_quick_scan_trigger(station);
		if (ret == 0 || ret == -EAGAIN)
			break;

		station->state = STATION_STATE_AUTOCONNECT_FULL;
		/* Fall through */
	case STATION_STATE_AUTOCONNECT_FULL:
		scan_periodic_start(id, periodic_scan_trigger,
					new_scan_results, station);
		break;
	case STATION_STATE_CONNECTING:
	case STATION_STATE_CONNECTING_AUTO:
		/* Refresh the ordered network list */
		network_rank_update(station->connected_network, true);
		l_queue_remove(station->networks_sorted,
					station->connected_network);
		l_queue_insert(station->networks_sorted,
					station->connected_network,
					network_rank_compare, NULL);

		l_dbus_property_changed(dbus, netdev_get_path(station->netdev),
				IWD_STATION_INTERFACE, "ConnectedNetwork");
		l_dbus_property_changed(dbus,
				network_get_path(station->connected_network),
				IWD_NETWORK_INTERFACE, "Connected");

		if (station->signal_agent)
			station_signal_agent_notify(station);

		periodic_scan_stop(station);
		break;
	case STATION_STATE_CONNECTED:
		l_dbus_object_add_interface(dbus,
					netdev_get_path(station->netdev),
					IWD_STATION_DIAGNOSTIC_INTERFACE,
					station);
		periodic_scan_stop(station);

		station_set_evict_nocarrier(station, true);

		/*
		 * Hotspot Specification 2.0 - Section 6.5
		 *
		 * " - Shall drop all received {gratuitous ARP, unsolicited
		 *     Neighbor Advertisement} messages when the Proxy ARP field
		 *     is set to 1 in the Extended Capabilities element of the
		 *     serving AP.
		 *
		 *   - When the serving AP transmits frames containing an HS2.0
		 *     Indication element in which the value of the DGAF Disable
		 *     bit subfield is set to 0, the mobile device should
		 *     discard all received unicast IP packets that were
		 *     decrypted using the GTK"
		 */
		if (station->connected_bss->proxy_arp)
			station_set_drop_neighbor_discovery(station, true);
		if (station->connected_bss->hs20_dgaf_disable)
			station_set_drop_unicast_l2_multicast(station, true);

		break;
	case STATION_STATE_DISCONNECTED:
		periodic_scan_stop(station);

		station_set_evict_nocarrier(station, true);
		station_set_drop_neighbor_discovery(station, false);
		station_set_drop_unicast_l2_multicast(station, false);
		break;
	case STATION_STATE_DISCONNECTING:
		break;
	case STATION_STATE_ROAMING:
	case STATION_STATE_FT_ROAMING:
	case STATION_STATE_FW_ROAMING:
		station_set_evict_nocarrier(station, false);
		break;
	}

	WATCHLIST_NOTIFY(&station->state_watches,
				station_state_watch_func_t, station->state);
}

enum station_state station_get_state(struct station *station)
{
	return station->state;
}

uint32_t station_add_state_watch(struct station *station,
					station_state_watch_func_t func,
					void *user_data,
					station_destroy_func_t destroy)
{
	return watchlist_add(&station->state_watches, func, user_data, destroy);
}

bool station_remove_state_watch(struct station *station, uint32_t id)
{
	return watchlist_remove(&station->state_watches, id);
}

uint32_t station_add_event_watch(station_event_watch_func_t func,
				void *user_data,
				station_destroy_func_t destroy)
{
	return watchlist_add(&event_watches, func, user_data, destroy);
}

void station_remove_event_watch(uint32_t id)
{
	watchlist_remove(&event_watches, id);
}

bool station_set_autoconnect(struct station *station, bool autoconnect)
{
	if (station->autoconnect == autoconnect)
		return true;

	station->autoconnect = autoconnect;

	if (station->state == STATION_STATE_DISCONNECTED && autoconnect)
		station_enter_state(station, STATION_STATE_AUTOCONNECT_QUICK);

	if (station_is_autoconnecting(station) && !autoconnect)
		station_enter_state(station, STATION_STATE_DISCONNECTED);

	if (iwd_is_developer_mode())
		l_dbus_property_changed(dbus_get_bus(),
				netdev_get_path(station->netdev),
				IWD_STATION_DEBUG_INTERFACE, "AutoConnect");

	return true;
}

static void station_roam_state_clear(struct station *station)
{
	l_debug("%u", netdev_get_ifindex(station->netdev));

	l_timeout_remove(station->roam_trigger_timeout);
	station->roam_trigger_timeout = NULL;
	station->preparing_roam = false;
	station->roam_scan_full = false;
	station->signal_low = false;
	station->roam_min_time.tv_sec = 0;
	station->netconfig_after_roam = false;
	station->last_roam_scan = 0;

	if (station->roam_scan_id)
		scan_cancel(netdev_get_wdev_id(station->netdev),
						station->roam_scan_id);

	if (station->roam_freqs) {
		scan_freq_set_free(station->roam_freqs);
		station->roam_freqs = NULL;
	}

	l_queue_clear(station->roam_bss_list, l_free);

	ft_clear_authentications(netdev_get_ifindex(station->netdev));

	if (station->ft_work.id)
		wiphy_radio_work_done(station->wiphy, station->ft_work.id);
}

static void station_reset_connection_state(struct station *station)
{
	struct network *network = station->connected_network;
	struct l_dbus *dbus = dbus_get_bus();

	l_debug("%u", netdev_get_ifindex(station->netdev));

	if (!network)
		return;

	station_roam_state_clear(station);

	if (station->netconfig)
		netconfig_reset(station->netconfig);

	/* Refresh the ordered network list */
	network_rank_update(station->connected_network, false);
	l_queue_remove(station->networks_sorted, station->connected_network);
	l_queue_insert(station->networks_sorted, station->connected_network,
				network_rank_compare, NULL);

	station->connected_bss = NULL;
	station->connected_network = NULL;

	l_dbus_property_changed(dbus, netdev_get_path(station->netdev),
				IWD_STATION_INTERFACE, "ConnectedNetwork");
	l_dbus_property_changed(dbus, network_get_path(network),
				IWD_NETWORK_INTERFACE, "Connected");
	l_dbus_object_remove_interface(dbus, netdev_get_path(station->netdev),
				IWD_STATION_DIAGNOSTIC_INTERFACE);

	/*
	 * Perform this step last since calling network_disconnected() might
	 * result in the removal of the network (for example if provisioning
	 * a new hidden network fails with an incorrect pasword).
	 */
	if (station->state == STATION_STATE_CONNECTED ||
			station->state == STATION_STATE_CONNECTING ||
			station->state == STATION_STATE_CONNECTING_AUTO ||
			station_is_roaming(station))
		network_disconnected(network);
}

static void station_disassociated(struct station *station)
{
	l_debug("%u", netdev_get_ifindex(station->netdev));

	station_reset_connection_state(station);

	station_enter_state(station, STATION_STATE_DISCONNECTED);

	if (station->autoconnect)
		station_enter_state(station, STATION_STATE_AUTOCONNECT_QUICK);
}

static void station_roam_timeout_rearm(struct station *station, int seconds);
static int station_roam_scan(struct station *station,
				struct scan_freq_set *freq_set);

static uint32_t station_freq_from_neighbor_report(const uint8_t *country,
		struct ie_neighbor_report_info *info, enum band_freq *out_band)
{
	enum band_freq band;
	uint32_t freq;

	if (info->oper_class == 0) {
		/*
		 * Some Cisco APs report all operating class values as 0
		 * in the Neighbor Report Responses.  Work around this by
		 * using the most likely operating class for the channel
		 * number as the 2.4GHz and 5GHz bands happen to mostly
		 * use channels in two disjoint ranges.
		 */
		if (info->channel_num >= 1 && info->channel_num <= 14)
			band = BAND_FREQ_2_4_GHZ;
		else if (info->channel_num >= 36 && info->channel_num <= 169)
			band = BAND_FREQ_5_GHZ;
		else {
			l_debug("Ignored: 0 oper class with an unusual "
				"channel number");

			return 0;
		}
	} else {
		band = band_oper_class_to_band(country, info->oper_class);
		if (!band) {
			l_debug("Ignored: unsupported oper class");

			return 0;
		}
	}

	freq = band_channel_to_freq(info->channel_num, band);
	if (!freq) {
		l_debug("Ignored: unsupported channel");

		return 0;
	}

	if (out_band)
		*out_band = band;

	return freq;
}

static void parse_neighbor_report(struct station *station,
					const uint8_t *reports,
					size_t reports_len,
					struct scan_freq_set **set)
{
	struct ie_tlv_iter iter;
	int count_md = 0, count_no_md = 0;
	struct scan_freq_set *freq_set_md, *freq_set_no_md;
	uint32_t current_freq = 0;
	struct handshake_state *hs = netdev_get_handshake(station->netdev);

	freq_set_md = scan_freq_set_new();
	freq_set_no_md = scan_freq_set_new();

	ie_tlv_iter_init(&iter, reports, reports_len);

	/* First see if any of the reports contain the MD bit set */
	while (ie_tlv_iter_next(&iter)) {
		struct ie_neighbor_report_info info;
		uint32_t freq;
		enum band_freq band;
		const uint8_t *cc = NULL;
		const struct band_freq_attrs *attr;

		if (ie_tlv_iter_get_tag(&iter) != IE_TYPE_NEIGHBOR_REPORT)
			continue;

		if (ie_parse_neighbor_report(&iter, &info) < 0)
			continue;

		l_debug("Neighbor report received for %s: ch %i "
				"(oper class %i), %s",
				util_address_to_string(info.addr),
				(int) info.channel_num, (int) info.oper_class,
				info.md ? "MD set" : "MD not set");

		if (station->connected_bss->cc_present)
			cc = station->connected_bss->cc;

		freq = station_freq_from_neighbor_report(cc, &info, &band);
		if (!freq)
			continue;

		/* Skip if the band is not supported */
		if (!(band & wiphy_get_supported_bands(station->wiphy)))
			continue;

		/* Skip if frequency is not supported or disabled */
		attr = wiphy_get_frequency_info(station->wiphy, freq);
		if (!attr || attr->disabled)
			continue;

		if (!memcmp(info.addr,
				station->connected_bss->addr, ETH_ALEN)) {
			/*
			 * If this report is for the current AP, don't add
			 * it to any of the lists yet.  We will need to scan
			 * its channel because it may still be the best ranked
			 * or the only visible AP.
			 */
			current_freq = freq;

			continue;
		}

		/* Add the frequency to one of the lists */
		if (info.md && hs->mde) {
			scan_freq_set_add(freq_set_md, freq);

			count_md += 1;
		} else {
			scan_freq_set_add(freq_set_no_md, freq);

			count_no_md += 1;
		}
	}

	if (!current_freq)
		current_freq = station->connected_bss->frequency;

	/*
	 * If there are neighbor reports with the MD bit set then the bit
	 * is probably valid so scan only the frequencies of the neighbors
	 * with that bit set, which will allow us to use Fast Transition.
	 * Some APs, such as those based on hostapd do not set the MD bit
	 * even if the neighbor is within the MD.
	 *
	 * In any case we only select the frequencies here and will check
	 * the IEs in the scan results as the authoritative information
	 * on whether we can use Fast Transition, and rank BSSes based on
	 * that.
	 *
	 * TODO: possibly save the neighbors from outside the MD and if
	 * none of the ones in the MD end up working, try a non-FT
	 * transition to those neighbors.  We should be using a
	 * blacklisting mechanism (for both initial connection and
	 * transitions) so that cound_md would not count the
	 * BSSes already used and when it goes down to 0 we'd
	 * automatically fall back to the non-FT candidates and then to
	 * full scan.
	 */
	if (count_md) {
		scan_freq_set_add(freq_set_md, current_freq);
		*set = freq_set_md;
		scan_freq_set_free(freq_set_no_md);
	} else if (count_no_md) {
		scan_freq_set_add(freq_set_no_md, current_freq);
		*set = freq_set_no_md;
		scan_freq_set_free(freq_set_md);
	} else {
		scan_freq_set_free(freq_set_no_md);
		scan_freq_set_free(freq_set_md);
		*set = NULL;
	}
}

static void station_early_neighbor_report_cb(struct netdev *netdev, int err,
						const uint8_t *reports,
						size_t reports_len,
						void *user_data)
{
	struct station *station = user_data;

	if (err == -ENODEV)
		return;

	l_debug("ifindex: %u, error: %d(%s)",
			netdev_get_ifindex(station->netdev),
			err, err < 0 ? strerror(-err) : "");

	if (!reports || err)
		return;

	parse_neighbor_report(station, reports, reports_len,
				&station->roam_freqs);
}

static bool station_can_fast_transition(struct handshake_state *hs,
					struct scan_bss *bss)
{
	uint16_t mdid;

	if (!hs->mde)
		return false;

	if (ie_parse_mobility_domain_from_data(hs->mde, hs->mde[1] + 2,
						&mdid, NULL, NULL) < 0)
		return false;

	if (!(bss->mde_present && l_get_le16(bss->mde) == mdid))
		return false;

	if (hs->supplicant_ie != NULL) {
		struct ie_rsn_info rsn_info;

		if (!IE_AKM_IS_FT(hs->akm_suite))
			return false;

		if (scan_bss_get_rsn_info(bss, &rsn_info) < 0)
			return false;

		if (!IE_AKM_IS_FT(rsn_info.akm_suites))
			return false;
	}

	return true;
}

static void station_disconnect_on_error_cb(struct netdev *netdev, bool success,
					void *user_data)
{
	struct station *station = user_data;
	bool continue_autoconnect;

	station_enter_state(station, STATION_STATE_DISCONNECTED);

	continue_autoconnect = station->state == STATION_STATE_CONNECTING_AUTO;

	if (continue_autoconnect) {
		if (station_autoconnect_next(station) < 0) {
			l_debug("Nothing left on autoconnect list");
			station_enter_state(station,
					STATION_STATE_AUTOCONNECT_FULL);
		}

		return;
	}

	if (station->autoconnect)
		station_enter_state(station, STATION_STATE_AUTOCONNECT_QUICK);
}

static void station_netconfig_event_handler(enum netconfig_event event,
							void *user_data)
{
	struct station *station = user_data;

	switch (event) {
	case NETCONFIG_EVENT_CONNECTED:
		station_enter_state(station, STATION_STATE_CONNECTED);
		break;
	case NETCONFIG_EVENT_FAILED:
		if (station->connect_pending) {
			struct l_dbus_message *reply = dbus_error_failed(
						station->connect_pending);

			dbus_pending_reply(&station->connect_pending, reply);
		}

		if (L_IN_SET(station->state, STATION_STATE_CONNECTING,
				STATION_STATE_CONNECTING_AUTO))
			network_connect_failed(station->connected_network,
						false);

		netdev_disconnect(station->netdev,
					station_disconnect_on_error_cb,
					station);
		station_reset_connection_state(station);

		station_enter_state(station, STATION_STATE_DISCONNECTING);
		break;
	default:
		l_error("station: Unsupported netconfig event: %d.", event);
		break;
	}
}

static bool netconfig_after_roam(struct station *station)
{
	const struct network *network = station_get_connected_network(station);

	/* Netconfig was reset which frees all settings, reload now */
	if (!netconfig_load_settings(station->netconfig,
					network_get_settings(network)))
		return false;

	return netconfig_configure(station->netconfig,
					station_netconfig_event_handler,
					station);
}

static void station_roamed(struct station *station)
{
	station->roam_scan_full = false;

	/*
	 * Schedule another roaming attempt in case the signal continues to
	 * remain low. A subsequent high signal notification will cancel it.
	 */
	if (station->signal_low)
		station_roam_timeout_rearm(station, roam_retry_interval);

	if (station->netconfig)
		netconfig_reconfigure(station->netconfig,
					!supports_arp_evict_nocarrier);

	if (station->roam_freqs) {
		scan_freq_set_free(station->roam_freqs);
		station->roam_freqs = NULL;
	}

	if (station->connected_bss->cap_rm_neighbor_report) {
		if (netdev_neighbor_report_req(station->netdev,
					station_early_neighbor_report_cb) < 0)
			l_warn("Could not request neighbor report");
	}

	l_queue_clear(station->roam_bss_list, l_free);

	/* Re-enable netconfig if it never finished on the last BSS */
	if (station->netconfig_after_roam) {
		station->netconfig_after_roam = false;
		L_WARN_ON(!netconfig_after_roam(station));
	} else
		station_enter_state(station, STATION_STATE_CONNECTED);
}

static void station_roam_retry(struct station *station)
{
	/*
	 * If we're still connected to the old BSS, only clear preparing_roam
	 * and reattempt in 60 seconds if signal level is still low at that
	 * time.
	 */
	station->preparing_roam = false;
	station->roam_scan_full = false;
	station->ap_directed_roaming = false;

	if (station->signal_low)
		station_roam_timeout_rearm(station, roam_retry_interval);
}

static void station_roam_failed(struct station *station)
{
	l_debug("%u", netdev_get_ifindex(station->netdev));

	l_queue_clear(station->roam_bss_list, l_free);

	/*
	 * If we attempted a reassociation or a fast transition, and ended up
	 * here then we are now disconnected.
	 */
	if (station_is_roaming(station)) {
		station_disassociated(station);
		return;
	}

	/* Re-enable netconfig if needed, even on a failed roam */
	if (station->netconfig_after_roam) {
		station->netconfig_after_roam = false;
		L_WARN_ON(!netconfig_after_roam(station));
	}

	/*
	 * We were told by the AP to roam, but failed.  Try ourselves or
	 * wait for the AP to tell us to roam again
	 */
	if (station->ap_directed_roaming)
		goto delayed_retry;

	/*
	 * If we tried a limited scan, failed and the signal is still low,
	 * repeat with a full scan right away
	 */
	if (station->signal_low && !station->roam_scan_full) {
		/*
		 * Since we're re-using roam_scan_id, explicitly cancel
		 * the scan here, so that the destroy callback is not called
		 * after the return of this function
		 */
		scan_cancel(netdev_get_wdev_id(station->netdev),
						station->roam_scan_id);

		if (!station_roam_scan(station, NULL))
			return;
	}

delayed_retry:
	station_roam_retry(station);
}

static void station_reassociate_cb(struct netdev *netdev,
					enum netdev_result result,
					void *event_data,
					void *user_data)
{
	struct station *station = user_data;

	l_debug("%u, result: %d", netdev_get_ifindex(station->netdev), result);

	if (station->state != STATION_STATE_ROAMING &&
			station->state != STATION_STATE_FT_ROAMING)
		return;

	if (result == NETDEV_RESULT_OK)
		station_roamed(station);
	else
		station_roam_failed(station);
}

static void station_netdev_event(struct netdev *netdev, enum netdev_event event,
					void *event_data, void *user_data);

static int station_transition_reassociate(struct station *station,
						struct scan_bss *bss,
						struct handshake_state *new_hs)
{
	int ret;

	ret = netdev_reassociate(station->netdev, bss, station->connected_bss,
				new_hs, station_netdev_event,
				station_reassociate_cb, station);
	if (ret < 0)
		return ret;

	l_debug("");

	station->connected_bss = bss;
	station->preparing_roam = false;
	station_enter_state(station, STATION_STATE_ROAMING);

	station_debug_event(station, "reassoc-roam");

	return 0;
}

static bool bss_match_bssid(const void *a, const void *b)
{
	const struct scan_bss *bss = a;
	const uint8_t *bssid = b;

	return !memcmp(bss->addr, bssid, sizeof(bss->addr));
}

static void station_preauthenticate_cb(struct netdev *netdev,
					enum netdev_result result,
					const uint8_t *pmk, void *user_data)
{
	struct station *station = user_data;
	struct network *connected = station->connected_network;
	struct scan_bss *bss;
	struct handshake_state *new_hs;

	l_debug("%u, result: %d", netdev_get_ifindex(station->netdev), result);

	if (!station->preparing_roam || result == NETDEV_RESULT_ABORTED)
		return;

	bss = network_bss_find_by_addr(station->connected_network,
						station->preauth_bssid);
	if (!bss) {
		l_error("Roam target BSS not found");
		station_roam_failed(station);
		return;
	}

	new_hs = station_handshake_setup(station, connected, bss);
	if (!new_hs) {
		l_error("station_handshake_setup failed");

		station_roam_failed(station);
		return;
	}

	if (result == NETDEV_RESULT_OK) {
		uint8_t pmkid[16];
		uint8_t rsne_buf[300];
		struct ie_rsn_info rsn_info;

		handshake_state_set_pmk(new_hs, pmk, 32);
		handshake_state_set_authenticator_address(new_hs,
					station->preauth_bssid);
		handshake_state_set_supplicant_address(new_hs,
					netdev_get_address(station->netdev));

		/*
		 * Rebuild the RSNE to include the negotiated PMKID.  Note
		 * supplicant_ie can't be a WPA IE here, including because
		 * the WPA IE doesn't have a capabilities field and
		 * target_rsne->preauthentication would have been false in
		 * station_transition_start.
		 */
		ie_parse_rsne_from_data(new_hs->supplicant_ie,
					new_hs->supplicant_ie[1] + 2,
					&rsn_info);

		/*
		 * IEEE 802.11 Section 12.7.1.3:
		 *
		 * "When the PMKID is calculated for the PMKSA as part of
		 * preauthentication, the AKM has not yet been negotiated.
		 * In this case, the HMAC-SHA-1 based derivation is used for
		 * the PMKID calculation."
		 */
		handshake_state_get_pmkid(new_hs, pmkid, L_CHECKSUM_SHA1);

		rsn_info.num_pmkids = 1;
		rsn_info.pmkids = pmkid;

		ie_build_rsne(&rsn_info, rsne_buf);
		handshake_state_set_supplicant_ie(new_hs, rsne_buf);
	}

	if (station_transition_reassociate(station, bss, new_hs) < 0) {
		handshake_state_free(new_hs);
		station_roam_failed(station);
	}
}

static void station_transition_start(struct station *station);

static bool station_ft_work_ready(struct wiphy_radio_work_item *item)
{
	struct station *station = l_container_of(item, struct station, ft_work);
	_auto_(l_free) struct roam_bss *rbss = l_queue_pop_head(
							station->roam_bss_list);
	struct scan_bss *bss;
	int ret;

	/* Very unlikely, but the BSS could have gone away */
	bss = network_bss_find_by_addr(station->connected_network, rbss->addr);
	if (!bss)
		goto try_next;

	ret = ft_handshake_setup(netdev_get_ifindex(station->netdev),
					bss->addr);
	switch (ret) {
	case MMPDU_STATUS_CODE_INVALID_PMKID:
		/*
		 * Re-insert removing FT from the ranking (scan_bss does not
		 * take into account FT, so we can use that rank directly).
		 * If the BSS is still the best reassociation will be used,
		 * otherwise we'll try more FT candidates that are better ranked
		 */
		rbss->rank = bss->rank;
		rbss->ft_failed = true;

		l_debug("Re-inserting BSS "MAC" using reassociation, rank: %u",
					MAC_STR(rbss->addr), rbss->rank);

		l_queue_insert(station->roam_bss_list, rbss,
				roam_bss_rank_compare, NULL);

		station_debug_event(station, "ft-fallback-to-reassoc");

		station_transition_start(station);
		l_steal_ptr(rbss);
		break;
	case -ENOENT:
		station_debug_event(station, "ft-roam-failed");
try_next:
		station_transition_start(station);
		break;
	case 0:
		ret = netdev_ft_reassociate(station->netdev, bss,
					station->connected_bss,
					station_netdev_event,
					station_reassociate_cb, station);
		if (ret < 0)
			goto disassociate;

		station->connected_bss = bss;
		station->preparing_roam = false;
		station_enter_state(station, STATION_STATE_FT_ROAMING);

		station_debug_event(station, "ft-roam");

		break;
	case -EINVAL:
		/*
		 * Likely an impossible situation, but since ft_handshake_setup
		 * rederived the handshake keys we can't do anything but
		 * disconnect.
		 */
disassociate:
		station_disassociated(station);
		break;
	default:
		if (ret > 0)
			goto try_next;

		station_roam_failed(station);
		break;
	}

	return true;
}

static const struct wiphy_radio_work_item_ops ft_work_ops = {
	.do_work = station_ft_work_ready,
};

static bool station_fast_transition(struct station *station,
					struct scan_bss *bss)
{
	struct handshake_state *hs = netdev_get_handshake(station->netdev);
	struct network *connected = station->connected_network;
	const struct network_info *info = network_get_info(connected);
	const struct iovec *vendor_ies;
	size_t iov_elems = 0;

	/* Rebuild handshake RSN for target AP */
	if (station_build_handshake_rsn(hs, station->wiphy,
				station->connected_network, bss) < 0)
		return false;

	/* Reset the vendor_ies in case they're different */
	vendor_ies = network_info_get_extra_ies(info, bss, &iov_elems);
	handshake_state_set_vendor_ies(hs, vendor_ies, iov_elems);

	if (station->roam_trigger_timeout) {
		l_timeout_remove(station->roam_trigger_timeout);
		station->roam_trigger_timeout = NULL;
	}

	/* Both ft_action/ft_authenticate will gate the associate work item */
	if ((hs->mde[4] & 1)) {
		ft_action(netdev_get_ifindex(station->netdev),
				station->connected_bss->frequency, bss);
		goto done;
	}

	if (station->connected_bss->frequency == bss->frequency) {
		ft_authenticate_onchannel(netdev_get_ifindex(station->netdev),
						bss);
		goto done;
	}

	ft_authenticate(netdev_get_ifindex(station->netdev), bss);

done:
	if (station->ft_work.id)
		wiphy_radio_work_reschedule(station->wiphy, &station->ft_work);
	else
		wiphy_radio_work_insert(station->wiphy, &station->ft_work,
					WIPHY_WORK_PRIORITY_CONNECT,
					&ft_work_ops);

	return true;
}

static bool station_try_next_transition(struct station *station,
					struct scan_bss *bss,
					bool no_ft)
{
	struct handshake_state *hs = netdev_get_handshake(station->netdev);
	struct network *connected = station->connected_network;
	enum security security = network_get_security(connected);
	struct handshake_state *new_hs;
	struct ie_rsn_info cur_rsne, target_rsne;

	l_debug("%u, target %s", netdev_get_ifindex(station->netdev),
			util_address_to_string(bss->addr));

	/* Reset AP roam flag, at this point the roaming behaves the same */
	station->ap_directed_roaming = false;

	/* Can we use Fast Transition? */
	if (station_can_fast_transition(hs, bss) && !no_ft)
		return station_fast_transition(station, bss);

	/* Non-FT transition */

	/*
	 * FT not available, we can try preauthentication if available.
	 * 802.11-2012 section 11.5.9.2:
	 * "A STA shall not use preauthentication within the same mobility
	 * domain if AKM suite type 00-0F-AC:3 or 00-0F-AC:4 is used in
	 * the current association."
	 */
	if (security == SECURITY_8021X &&
			scan_bss_get_rsn_info(station->connected_bss,
						&cur_rsne) >= 0 &&
			scan_bss_get_rsn_info(bss, &target_rsne) >= 0 &&
			cur_rsne.preauthentication &&
			target_rsne.preauthentication) {
		/*
		 * Both the current and the target AP support
		 * pre-authentication and we're using 8021x authentication so
		 * attempt to pre-authenticate and reassociate afterwards.
		 * If the pre-authentication fails or times out we simply
		 * won't supply any PMKID when reassociating.
		 * Remain in the preparing_roam state.
		 */
		memcpy(station->preauth_bssid, bss->addr, ETH_ALEN);

		if (netdev_preauthenticate(station->netdev, bss,
						station_preauthenticate_cb,
						station) >= 0)
			return true;
	}

	new_hs = station_handshake_setup(station, connected, bss);
	if (!new_hs) {
		l_error("station_handshake_setup failed in reassociation");
		return false;
	}

	if (station_transition_reassociate(station, bss, new_hs) < 0) {
		handshake_state_free(new_hs);
		return false;
	}

	return true;
}

static void station_transition_start(struct station *station)
{
	struct roam_bss *rbss;
	bool roaming = false;
	bool connected = (station->state == STATION_STATE_CONNECTED);

	/*
	 * For each failed attempt pop the BSS leaving the head of the queue
	 * with the current roam candidate.
	 */
	while ((rbss = l_queue_peek_head(station->roam_bss_list))) {
		struct scan_bss *bss = network_bss_find_by_addr(
					station->connected_network, rbss->addr);

		roaming = station_try_next_transition(station, bss,
							rbss->ft_failed);
		if (roaming)
			break;

		l_queue_pop_head(station->roam_bss_list);
		l_free(rbss);
	}

	if (!roaming) {
		station_roam_failed(station);
		return;
	}

	/*
	 * Netconfig could potentially be running and not completed yet. We
	 * still should roam in this case but need to restart netconfig once the
	 * roam is finished.
	 */
	if (station->netconfig && !connected) {
		netconfig_reset(station->netconfig);
		station->netconfig_after_roam = true;
	}
}

static void station_roam_scan_triggered(int err, void *user_data)
{
	struct station *station = user_data;

	if (err) {
		station_roam_failed(station);
		return;
	}

	station_debug_event(station, "roam-scan-triggered");

	/*
	 * Do not update the Scanning property as we won't be updating the
	 * list of networks.
	 */
}

static void station_update_roam_bss(struct station *station,
					struct scan_bss *bss)
{
	struct network *network = station->connected_network;
	struct scan_bss *old =
		l_queue_remove_if(station->bss_list, bss_match, bss);

	network_bss_update(network, bss);
	l_queue_push_tail(station->bss_list, bss);

	if (old)
		scan_bss_free(old);
}

static bool station_roam_scan_notify(int err, struct l_queue *bss_list,
					const struct scan_freq_set *freqs,
					void *userdata)
{
	struct station *station = userdata;
	struct network *network = station->connected_network;
	struct handshake_state *hs = netdev_get_handshake(station->netdev);
	struct scan_bss *current_bss = station->connected_bss;
	struct scan_bss *bss;
	double cur_bss_rank = 0.0;
	static const double RANK_FT_FACTOR = 1.3;
	uint16_t mdid;
	enum security orig_security, security;

	if (err) {
		station_roam_failed(station);
		return false;
	}

	/*
	 * Do not call station_set_scan_results because this may have been
	 * a partial scan.  We could at most update the current networks' BSS
	 * list in its station->networks entry.
	 */

	orig_security = network_get_security(network);

	if (hs->mde)
		ie_parse_mobility_domain_from_data(hs->mde, hs->mde[1] + 2,
							&mdid, NULL, NULL);

	/*
	 * Find the current BSS rank, use the updated result if it exists. If
	 * this is an AP roam keep the current rank as zero to force the roam
	 * to occur.
	 */
	bss = l_queue_find(bss_list, bss_match_bssid, current_bss->addr);
	if (bss && !station->ap_directed_roaming) {
		cur_bss_rank = bss->rank;

		if (hs->mde && bss->mde_present && l_get_le16(bss->mde) == mdid)
			cur_bss_rank *= RANK_FT_FACTOR;
	}

	/*
	 * BSSes in the bss_list come already ranked with their initial
	 * association preference rank value.  We only need to add preference
	 * for BSSes that are within the FT Mobility Domain so as to favor
	 * Fast Roaming, if it is supported.
	 */
	l_debug("Current BSS '%s' with SSID: %s",
		util_address_to_string(current_bss->addr),
		util_ssid_to_utf8(current_bss->ssid_len, current_bss->ssid));

	while ((bss = l_queue_pop_head(bss_list))) {
		double rank;
		uint32_t kbps100 = DIV_ROUND_CLOSEST(bss->data_rate, 100000);
		struct roam_bss *rbss;

		l_debug("Processing BSS '%s' with SSID: %s, freq: %u, rank: %u,"
				" strength: %i, data_rate: %u.%u",
				util_address_to_string(bss->addr),
				util_ssid_to_utf8(bss->ssid_len, bss->ssid),
				bss->frequency, bss->rank, bss->signal_strength,
				kbps100 / 10, kbps100 % 10);

		/* Skip the BSS we are connected to */
		if (!memcmp(bss->addr, station->connected_bss->addr, 6))
			goto next;

		/* Skip result if it is not part of the ESS */
		if (bss->ssid_len != hs->ssid_len ||
				memcmp(bss->ssid, hs->ssid, hs->ssid_len))
			goto next;

		if (scan_bss_get_security(bss, &security) < 0)
			goto next;

		if (security != orig_security)
			goto next;

		if (network_can_connect_bss(network, bss) < 0)
			goto next;

		if (blacklist_contains_bss(bss->addr))
			goto next;

		rank = bss->rank;

		if (hs->mde && bss->mde_present && l_get_le16(bss->mde) == mdid)
			rank *= RANK_FT_FACTOR;

		if (rank <= cur_bss_rank)
			goto next;

		/*
		 * We need to update/add any potential roam candidate so
		 * station/network know it exists.
		 */
		station_update_roam_bss(station, bss);

		rbss = roam_bss_from_scan_bss(bss, rank);

		l_queue_insert(station->roam_bss_list, rbss,
				roam_bss_rank_compare, NULL);

		continue;

next:
		scan_bss_free(bss);
	}

	l_queue_destroy(bss_list, NULL);

	/* See if we have anywhere to roam to */
	if (l_queue_isempty(station->roam_bss_list)) {
		station_debug_event(station, "no-roam-candidates");
		goto fail;
	}

	station_transition_start(station);

	return true;

fail:
	station_roam_failed(station);

	return true;
}

static void station_roam_scan_destroy(void *userdata)
{
	struct station *station = userdata;

	station->roam_scan_id = 0;
}

static int station_roam_scan(struct station *station,
				struct scan_freq_set *freq_set)
{
	struct scan_parameters params = { .freqs = freq_set, .flush = true };
	_auto_(scan_freq_set_free) struct scan_freq_set *allowed =
					station_get_allowed_freqs(station);

	if (L_WARN_ON(!allowed))
		return -ENOTSUP;

	l_debug("ifindex: %u", netdev_get_ifindex(station->netdev));

	if (station->connected_network) {
		const char *ssid = network_get_ssid(station->connected_network);
		/* Use direct probe request */
		params.ssid = (const uint8_t *)ssid;
		params.ssid_len = strlen(ssid);
	}

	if (!freq_set) {
		station->roam_scan_full = true;
		params.freqs = allowed;
	} else
		scan_freq_set_constrain(freq_set, allowed);

	if (L_WARN_ON(scan_freq_set_isempty(params.freqs)))
		return -ENOTSUP;

	station->last_roam_scan = l_time_now();

	station->roam_scan_id =
		scan_active_full(netdev_get_wdev_id(station->netdev), &params,
					station_roam_scan_triggered,
					station_roam_scan_notify, station,
					station_roam_scan_destroy);

	if (!station->roam_scan_id)
		return -EIO;

	return 0;
}

static int station_roam_scan_known_freqs(struct station *station)
{
	const struct network_info *info = network_get_info(
						station->connected_network);
	struct scan_freq_set *freqs = network_info_get_roam_frequencies(info,
					station->connected_bss->frequency, 5);
	int r = -ENODATA;

	if (!freqs)
		return r;

	if (!wiphy_constrain_freq_set(station->wiphy, freqs))
		goto free_set;

	r = station_roam_scan(station, freqs);

free_set:
	scan_freq_set_free(freqs);
	return r;
}

static void station_neighbor_report_cb(struct netdev *netdev, int err,
					const uint8_t *reports,
					size_t reports_len, void *user_data)
{
	struct station *station = user_data;
	struct scan_freq_set *freq_set;
	int r;

	if (err == -ENODEV)
		return;

	l_debug("ifindex: %u, error: %d(%s)",
			netdev_get_ifindex(station->netdev),
			err, err < 0 ? strerror(-err) : "");

	/*
	 * Check if we're still attempting to roam -- if dbus Disconnect
	 * had been called in the meantime we just abort the attempt.
	 */
	if (!station->preparing_roam || err == -ENODEV)
		return;

	if (!reports || err) {
		r = station_roam_scan_known_freqs(station);

		if (r == -ENODATA)
			l_debug("no neighbor report results or known freqs");

		if (r < 0)
			station_roam_failed(station);

		return;
	}

	parse_neighbor_report(station, reports, reports_len, &freq_set);

	r = station_roam_scan(station, freq_set);

	if (freq_set)
		scan_freq_set_free(freq_set);

	if (r < 0)
		station_roam_failed(station);
}

static void station_start_roam(struct station *station)
{
	int r;

	station->preparing_roam = true;

	/*
	 * If current BSS supports Neighbor Reports, narrow the scan down
	 * to channels occupied by known neighbors in the ESS. If no neighbor
	 * report was obtained upon connection, request one now. This isn't
	 * 100% reliable as the neighbor lists are not required to be
	 * complete or current.  It is likely still better than doing a
	 * full scan.  10.11.10.1: "A neighbor report may not be exhaustive
	 * either by choice, or due to the fact that there may be neighbor
	 * APs not known to the AP."
	 */
	if (station->roam_freqs) {
		if (station_roam_scan(station, station->roam_freqs) == 0) {
			l_debug("Using cached neighbor report for roam");
			return;
		}
	} else if (station->connected_bss->cap_rm_neighbor_report) {
		if (netdev_neighbor_report_req(station->netdev,
					station_neighbor_report_cb) == 0) {
			l_debug("Requesting neighbor report for roam");
			return;
		}
	}

	r = station_roam_scan_known_freqs(station);
	if (r == -ENODATA)
		l_debug("No neighbor report or known frequencies, roam failed");

	if (r < 0)
		station_roam_failed(station);
}

static bool station_cannot_roam(struct station *station)
{
	const struct l_settings *config = iwd_get_config();
	bool disabled;

	/*
	 * Disable roaming with hardware that can roam automatically. Note this
	 * is now required for recent kernels which have CQM event support on
	 * this type of hardware (e.g. brcmfmac).
	 */
	if (wiphy_supports_firmware_roam(station->wiphy))
		return true;

	if (!l_settings_get_bool(config, "Scan", "DisableRoamingScan",
								&disabled))
		disabled = false;

	return disabled || station->preparing_roam ||
				station->state == STATION_STATE_ROAMING ||
				station->state == STATION_STATE_FT_ROAMING ||
				station->ft_work.id;
}

static void station_roam_trigger_cb(struct l_timeout *timeout, void *user_data)
{
	struct station *station = user_data;

	l_debug("%u", netdev_get_ifindex(station->netdev));

	l_timeout_remove(station->roam_trigger_timeout);
	station->roam_trigger_timeout = NULL;

	if (station_cannot_roam(station))
		return;

	station_start_roam(station);
}

static void station_roam_timeout_rearm(struct station *station, int seconds)
{
	struct timespec now, min_timeout;

	clock_gettime(CLOCK_MONOTONIC, &now);

	min_timeout = now;
	min_timeout.tv_sec += seconds;

	if (station->roam_min_time.tv_sec < min_timeout.tv_sec ||
			(station->roam_min_time.tv_sec == min_timeout.tv_sec &&
			 station->roam_min_time.tv_nsec < min_timeout.tv_nsec))
		station->roam_min_time = min_timeout;

	seconds = station->roam_min_time.tv_sec - now.tv_sec +
		(station->roam_min_time.tv_nsec > now.tv_nsec ? 1 : 0);

	station->roam_trigger_timeout =
		l_timeout_create(seconds, station_roam_trigger_cb,
								station, NULL);
}

#define WNM_REQUEST_MODE_PREFERRED_CANDIDATE_LIST	(1 << 0)
#define WNM_REQUEST_MODE_DISASSOCIATION_IMMINENT	(1 << 2)
#define WNM_REQUEST_MODE_TERMINATION_IMMINENT		(1 << 3)
#define WNM_REQUEST_MODE_ESS_DISASSOCIATION_IMMINENT	(1 << 4)

static void station_ap_directed_roam(struct station *station,
					const struct mmpdu_header *hdr,
					const void *body, size_t body_len)
{
	uint32_t pos = 0;
	uint8_t req_mode;
	uint16_t dtimer;
	uint8_t valid_interval;

	l_debug("ifindex: %u", netdev_get_ifindex(station->netdev));

	if (station_cannot_roam(station))
		return;

	if (station->state != STATION_STATE_CONNECTED) {
		l_debug("roam: unexpected AP directed roam -- ignore");
		return;
	}

	/*
	 * Sanitize the frame to check that it is from our current AP.
	 *
	 * 802.11-2020 Section 9.3.3.1 about Address2:
	 * "If the STA is an AP with dot11MultiBSSDImplemented set to false,
	 * then this address is the BSSID."
	 *
	 * Address3:
	 * "If the STA is an AP or PCP, the Address 3 field is the same as the
	 * Address 2 field."
	 *
	 * For now check that Address2 & Address3 is the same as the connected
	 * BSS address.
	 */
	if (memcmp(hdr->address_2, station->connected_bss, ETH_ALEN) ||
			memcmp(hdr->address_2, hdr->address_3, ETH_ALEN)) {
		l_debug("roam: AP directed roam not from our AP -- ignore");
		return;
	}

	if (body_len < 7)
		goto format_error;

	/*
	 * First two bytes are checked by the frame watch (WNM category and
	 * WNM action). The third is the dialog token which is not relevant
	 * because we did not send a BSS transition query -- so skip these
	 * first three bytes.
	 */
	pos += 3;

	req_mode = l_get_u8(body + pos);
	pos++;

	/*
	 * TODO: Disassociation timer and validity interval are currently not
	 * used since the BSS transition request is being handled immediately.
	 */
	dtimer = l_get_le16(body + pos);
	pos += 2;
	valid_interval = l_get_u8(body + pos);
	pos++;

	l_debug("roam: BSS transition received from AP: " MAC", "
			"Disassociation Time: %u, "
			"Validity interval: %u, Address3: " MAC,
			MAC_STR(hdr->address_2),
			dtimer, valid_interval,
			MAC_STR(hdr->address_3));

	/*
	 * The ap_directed_roaming flag forces IWD to roam if there are any
	 * candidates, even if they are worse than the current BSS. This isn't
	 * always a good idea since we may be associated to the best BSS. Where
	 * this does matter is if the AP indicates its going down or will be
	 * disassociating us. If either of these bits are set, set the
	 * ap_directed_roaming flag. Otherwise still try roaming but don't
	 * treat it any different than a normal roam.
	 */
	if (req_mode & (WNM_REQUEST_MODE_DISASSOCIATION_IMMINENT |
			WNM_REQUEST_MODE_TERMINATION_IMMINENT |
			WNM_REQUEST_MODE_ESS_DISASSOCIATION_IMMINENT))
		station->ap_directed_roaming = true;

	if (req_mode & WNM_REQUEST_MODE_TERMINATION_IMMINENT) {
		if (pos + 12 > body_len)
			goto format_error;

		pos += 12;
	}

	if (req_mode & WNM_REQUEST_MODE_ESS_DISASSOCIATION_IMMINENT) {
		uint8_t url_len;

		if (pos + 1 > body_len)
			goto format_error;

		url_len = l_get_u8(body + pos);
		pos++;

		if (pos + url_len > body_len)
			goto format_error;

		pos += url_len;
	}

	station->preparing_roam = true;

	l_timeout_remove(station->roam_trigger_timeout);
	station->roam_trigger_timeout = NULL;

	if (req_mode & WNM_REQUEST_MODE_PREFERRED_CANDIDATE_LIST) {
		l_debug("roam: AP sent a preferred candidate list");
		station_neighbor_report_cb(station->netdev, 0, body + pos,
				body_len - pos, station);
	} else {
		l_debug("roam: AP did not include a preferred candidate list");
		if (station_roam_scan(station, NULL) < 0)
			station_roam_failed(station);
	}

	return;

format_error:
	l_debug("bad AP roam frame formatting");
}

static void station_low_rssi(struct station *station)
{
	if (station->signal_low)
		return;

	station->signal_low = true;

	if (station_cannot_roam(station))
		return;

	/* Set a 5-second initial timeout */
	station_roam_timeout_rearm(station, 5);
}

static void station_ok_rssi(struct station *station)
{
	l_timeout_remove(station->roam_trigger_timeout);
	station->roam_trigger_timeout = NULL;

	station->signal_low = false;
	station->roam_min_time.tv_sec = 0;
}

static void station_event_roamed(struct station *station, struct scan_bss *new)
{
	struct scan_bss *stale;

	network_bss_update(station->connected_network, new);

	/* Remove new BSS if it exists in past scan results */
	stale = l_queue_remove_if(station->bss_list, bss_match, new);
	if (stale)
		scan_bss_free(stale);

	station->connected_bss = new;

	l_queue_insert(station->bss_list, new, scan_bss_rank_compare, NULL);

	station_roamed(station);
}

static void station_event_channel_switched(struct station *station,
						const uint32_t freq)
{
	struct network *network = station->connected_network;

	station->connected_bss->frequency = freq;

	network_bss_update(network, station->connected_bss);
}

static bool station_try_next_bss(struct station *station)
{
	struct scan_bss *next;
	int ret;

	next = network_bss_select(station->connected_network, false);

	if (!next)
		return false;

	ret = __station_connect_network(station, station->connected_network,
						next, station->state);
	if (ret < 0)
		return false;

	l_debug("Attempting to connect to next BSS "MAC, MAC_STR(next->addr));

	return true;
}

static bool station_retry_owe_default_group(struct station *station)
{
	/*
	 * Shouldn't ever get here with classic open networks so its safe to
	 * assume if the security is none this is an OWE network.
	 */
	if (network_get_security(station->connected_network) != SECURITY_NONE)
		return false;

	/* If we already forced group 19, allow the BSS to be blacklisted */
	if (network_get_force_default_owe_group(station->connected_network))
		return false;

	l_warn("Failed to connect to OWE BSS "MAC" possibly because the AP is "
		"incorrectly deriving the PTK, this AP should be fixed. "
		"Retrying with group 19 as a workaround",
		MAC_STR(station->connected_bss->addr));

	network_set_force_default_owe_group(station->connected_network);

	return true;
}

static bool station_retry_with_reason(struct station *station,
					uint16_t reason_code)
{
	/*
	 * We don't want to cause a retry and blacklist if the password was
	 * incorrect. Otherwise we would just continue to fail.
	 *
	 * Other reason codes can be added here if its decided we want to
	 * fail in those cases.
	 */
	switch (reason_code) {
	case MMPDU_REASON_CODE_PREV_AUTH_NOT_VALID:
		if (station_retry_owe_default_group(station))
			goto try_next;
		/* fall through */
	case MMPDU_REASON_CODE_IEEE8021X_FAILED:
		return false;
	default:
		break;
	}

	blacklist_add_bss(station->connected_bss->addr);

try_next:
	return station_try_next_bss(station);
}

/* A bit more concise for trying to fit these into 80 characters */
#define IS_TEMPORARY_STATUS(code) \
	((code) == MMPDU_STATUS_CODE_DENIED_UNSUFFICIENT_BANDWIDTH || \
	(code) == MMPDU_STATUS_CODE_DENIED_POOR_CHAN_CONDITIONS || \
	(code) == MMPDU_STATUS_CODE_REJECTED_WITH_SUGG_BSS_TRANS || \
	(code) == MMPDU_STATUS_CODE_DENIED_NO_MORE_STAS)

static bool station_retry_with_status(struct station *station,
					uint16_t status_code)
{
	/*
	 * Certain Auth/Assoc failures should not cause a timeout blacklist.
	 * In these cases we want to only temporarily blacklist the BSS until
	 * the connection is complete.
	 *
	 * TODO: The WITH_SUGG_BSS_TRANS case should also include a neighbor
	 *       report IE in the frame. This would allow us to target a
	 *       specific BSS on our next attempt. There is currently no way to
	 *       obtain that IE, but this should be done in the future.
	 */
	if (IS_TEMPORARY_STATUS(status_code))
		network_blacklist_add(station->connected_network,
						station->connected_bss);
	else
		blacklist_add_bss(station->connected_bss->addr);

	return station_try_next_bss(station);
}

static void station_connect_ok(struct station *station)
{
	struct handshake_state *hs = netdev_get_handshake(station->netdev);

	l_debug("");

	if (station->connect_pending) {
		struct l_dbus_message *reply =
			l_dbus_message_new_method_return(
						station->connect_pending);
		dbus_pending_reply(&station->connect_pending, reply);
	}

	/*
	 * Get a neighbor report now so future roams can avoid waiting for
	 * a report at that time
	 */
	if (station->connected_bss->cap_rm_neighbor_report) {
		if (netdev_neighbor_report_req(station->netdev,
					station_early_neighbor_report_cb) < 0)
			l_warn("Could not request neighbor report");
	}

	network_connected(station->connected_network);

	if (station->netconfig) {
		if (hs->fils_ip_req_ie && hs->fils_ip_resp_ie) {
			struct ie_fils_ip_addr_response_info info;
			struct ie_tlv_iter iter;
			int r;

			ie_tlv_iter_init(&iter, hs->fils_ip_resp_ie,
						hs->fils_ip_resp_ie[1] + 2);
			if (!L_WARN_ON(unlikely(!ie_tlv_iter_next(&iter))))
				r = ie_parse_fils_ip_addr_response(&iter,
									&info);
			else
				r = -ENOMSG;

			if (r != 0)
				l_debug("Error parsing the FILS IP Address "
					"Assignment response: %s (%i)",
					strerror(-r), -r);
			else if (info.response_pending &&
					info.response_timeout)
				l_debug("FILS IP Address Assignment response "
					"is pending (unsupported)");
			else if (info.response_pending)
				l_debug("FILS IP Address Assignment failed");
			else {
				l_debug("FILS IP Address Assignment response "
					"OK");
				netconfig_handle_fils_ip_resp(
							station->netconfig,
							&info);
			}
		}

		if (L_WARN_ON(!netconfig_configure(station->netconfig,
						station_netconfig_event_handler,
						station)))
			return;
	} else
		station_enter_state(station, STATION_STATE_CONNECTED);
}

static void station_connect_cb(struct netdev *netdev, enum netdev_result result,
					void *event_data, void *user_data)
{
	struct station *station = user_data;
	bool continue_autoconnect;

	l_debug("%u, result: %d", netdev_get_ifindex(station->netdev), result);

	switch (result) {
	case NETDEV_RESULT_OK:
		blacklist_remove_bss(station->connected_bss->addr);
		station_connect_ok(station);
		return;
	case NETDEV_RESULT_HANDSHAKE_FAILED:
		/* reason code in this case */
		if (station_retry_with_reason(station, l_get_u16(event_data)))
			return;

		break;
	case NETDEV_RESULT_AUTHENTICATION_FAILED:
	case NETDEV_RESULT_ASSOCIATION_FAILED:
		/* status code in this case */
		if (station_retry_with_status(station, l_get_u16(event_data)))
			return;

		break;
	default:
		break;
	}

	if (station->connect_pending) {
		struct l_dbus_message *reply;

		if (result == NETDEV_RESULT_ABORTED)
			reply = dbus_error_aborted(station->connect_pending);
		else
			reply = dbus_error_failed(station->connect_pending);

		dbus_pending_reply(&station->connect_pending, reply);
	}

	if (result == NETDEV_RESULT_ABORTED)
		return;

	continue_autoconnect = station->state == STATION_STATE_CONNECTING_AUTO;

	if (station->state == STATION_STATE_CONNECTING) {
		bool during_eapol = result == NETDEV_RESULT_HANDSHAKE_FAILED;
		network_connect_failed(station->connected_network,
								during_eapol);
	}

	station_reset_connection_state(station);
	station_enter_state(station, STATION_STATE_DISCONNECTED);

	if (continue_autoconnect) {
		if (station_autoconnect_next(station) < 0) {
			l_debug("Nothing left on autoconnect list");
			station_enter_state(station,
					STATION_STATE_AUTOCONNECT_FULL);
		}

		return;
	}

	if (station->autoconnect)
		station_enter_state(station, STATION_STATE_AUTOCONNECT_QUICK);
}

static void station_disconnect_event(struct station *station, void *event_data)
{
	l_debug("%u", netdev_get_ifindex(station->netdev));

	/*
	 * If we're connecting, AP deauthenticated us, most likely because
	 * we provided the wrong password or otherwise failed authentication
	 * during the handshaking phase.  Treat this as a connection failure
	 */
	switch (station->state) {
	case STATION_STATE_CONNECTING:
	case STATION_STATE_CONNECTING_AUTO:
		station_connect_cb(station->netdev,
					NETDEV_RESULT_HANDSHAKE_FAILED,
					event_data, station);
		return;
	case STATION_STATE_CONNECTED:
	case STATION_STATE_FT_ROAMING:
	case STATION_STATE_FW_ROAMING:
		station_disassociated(station);
		return;
	default:
		break;
	}

	l_warn("Unexpected disconnect event");
}

#define STATION_PKT_LOSS_THRESHOLD	10
#define LOSS_ROAM_RATE_LIMIT		2

static void station_packets_lost(struct station *station, uint32_t num_pkts)
{
	uint64_t elapsed;

	l_debug("Packets lost event: %u", num_pkts);

	if (num_pkts < STATION_PKT_LOSS_THRESHOLD)
		return;

	if (station_cannot_roam(station))
		return;

	station_debug_event(station, "packet-loss-roam");

	elapsed = l_time_diff(station->last_roam_scan, l_time_now());

	/*
	 * If we just issued a roam scan, delay the roam to avoid constant
	 * scanning.
	 */
	if (LOSS_ROAM_RATE_LIMIT > l_time_to_secs(elapsed)) {
		l_debug("Too many roam attempts in %u second timeframe, "
			"delaying roam", LOSS_ROAM_RATE_LIMIT);

		if (station->roam_trigger_timeout)
			return;

		station_roam_timeout_rearm(station, LOSS_ROAM_RATE_LIMIT);

		return;
	}

	station_start_roam(station);
}

static void station_beacon_lost(struct station *station)
{
	l_debug("Beacon lost event");

	if (station_cannot_roam(station))
		return;

	station_debug_event(station, "beacon-loss-roam");

	if (station->roam_trigger_timeout)
		return;

	station_roam_timeout_rearm(station, LOSS_ROAM_RATE_LIMIT);
}

static void station_netdev_event(struct netdev *netdev, enum netdev_event event,
					void *event_data, void *user_data)
{
	struct station *station = user_data;

	switch (event) {
	case NETDEV_EVENT_AUTHENTICATING:
		l_debug("Authenticating");
		break;
	case NETDEV_EVENT_ASSOCIATING:
		l_debug("Associating");
		break;
	case NETDEV_EVENT_DISCONNECT_BY_AP:
	case NETDEV_EVENT_DISCONNECT_BY_SME:
		station_disconnect_event(station, event_data);
		break;
	case NETDEV_EVENT_RSSI_THRESHOLD_LOW:
		station_low_rssi(station);
		break;
	case NETDEV_EVENT_RSSI_THRESHOLD_HIGH:
		station_ok_rssi(station);
		break;
	case NETDEV_EVENT_RSSI_LEVEL_NOTIFY:
		if (station->signal_agent)
			station_signal_agent_notify(station);
		break;
	case NETDEV_EVENT_ROAMING:
		station_enter_state(station, STATION_STATE_FW_ROAMING);
		break;
	case NETDEV_EVENT_ROAMED:
		station_event_roamed(station, (struct scan_bss *) event_data);
		break;
	case NETDEV_EVENT_CHANNEL_SWITCHED:
		station_event_channel_switched(station, l_get_u32(event_data));
		break;
	case NETDEV_EVENT_PACKET_LOSS_NOTIFY:
		station_packets_lost(station, l_get_u32(event_data));
		break;
	case NETDEV_EVENT_BEACON_LOSS_NOTIFY:
		station_beacon_lost(station);
		break;
	}
}

int __station_connect_network(struct station *station, struct network *network,
				struct scan_bss *bss, enum station_state state)
{
	struct handshake_state *hs;
	int r;

	if (station->netconfig && !netconfig_load_settings(
					station->netconfig,
					network_get_settings(network)))
		return -EINVAL;

	hs = station_handshake_setup(station, network, bss);
	if (!hs)
		return -ENOTSUP;

	r = netdev_connect(station->netdev, bss, hs,
				station_netdev_event,
				station_connect_cb, station);
	if (r < 0) {
		handshake_state_free(hs);
		return r;
	}

	l_debug("connecting to BSS "MAC, MAC_STR(bss->addr));

	station->connected_bss = bss;
	station->connected_network = network;

	if (station->state != state)
		station_enter_state(station, state);

	return 0;
}

static void station_disconnect_onconnect_cb(struct netdev *netdev, bool success,
					void *user_data)
{
	struct station *station = user_data;
	int err;

	station_enter_state(station, STATION_STATE_DISCONNECTED);

	err = __station_connect_network(station,
					station->connect_pending_network,
					station->connect_pending_bss,
					STATION_STATE_CONNECTING);

	station->connect_pending_network = NULL;
	station->connect_pending_bss = NULL;

	if (err < 0) {
		dbus_pending_reply(&station->connect_pending,
					dbus_error_from_errno(err,
						station->connect_pending));
		return;
	}
}

static void station_disconnect_onconnect(struct station *station,
					struct network *network,
					struct scan_bss *bss,
					struct l_dbus_message *message)
{
	if (netdev_disconnect(station->netdev, station_disconnect_onconnect_cb,
								station) < 0) {
		l_dbus_send(dbus_get_bus(),
					dbus_error_from_errno(-EIO, message));
		return;
	}

	station_reset_connection_state(station);

	station_enter_state(station, STATION_STATE_DISCONNECTING);

	station->connect_pending_network = network;
	station->connect_pending_bss = bss;

	station->connect_pending = l_dbus_message_ref(message);
}

void station_connect_network(struct station *station, struct network *network,
				struct scan_bss *bss,
				struct l_dbus_message *message)
{
	struct l_dbus *dbus = dbus_get_bus();
	int err;

	/*
	 * If a hidden scan is not completed, station_is_busy would not
	 * indicate anything is going on so we need to cancel the scan and
	 * fail the connection now.
	 */
	if (station->hidden_network_scan_id) {
		scan_cancel(netdev_get_wdev_id(station->netdev),
				station->hidden_network_scan_id);

		dbus_pending_reply(&station->hidden_pending,
				dbus_error_failed(station->hidden_pending));
	}

	if (station->quick_scan_id) {
		scan_cancel(netdev_get_wdev_id(station->netdev),
				station->quick_scan_id);
		station->quick_scan_id = 0;
		station_property_set_scanning(station, false);
	}

	if (station_is_busy(station)) {
		station_disconnect_onconnect(station, network, bss, message);

		return;
	}

	err = __station_connect_network(station, network, bss,
					STATION_STATE_CONNECTING);
	if (err < 0)
		goto error;

	station->connect_pending = l_dbus_message_ref(message);

	station_set_autoconnect(station, true);

	return;

error:
	l_dbus_send(dbus, dbus_error_from_errno(err, message));
}

static void station_hidden_network_scan_triggered(int err, void *user_data)
{
	struct station *station = user_data;

	l_debug("");

	if (!err)
		return;

	dbus_pending_reply(&station->hidden_pending,
				dbus_error_failed(station->hidden_pending));
}

static bool station_hidden_network_scan_results(int err,
					struct l_queue *bss_list,
					const struct scan_freq_set *freqs,
					void *userdata)
{
	struct station *station = userdata;
	struct network *network_psk;
	struct network *network_open;
	const char *ssid;
	uint8_t ssid_len;
	struct l_dbus_message *msg;
	struct l_dbus_message *error;
	struct scan_bss *bss;

	l_debug("");

	msg = station->hidden_pending;
	station->hidden_pending = NULL;
	/* Zero this now so station_connect_network knows the scan is done */
	station->hidden_network_scan_id = 0;

	if (err) {
		dbus_pending_reply(&msg, dbus_error_failed(msg));
		return false;
	}

	if (!l_dbus_message_get_arguments(msg, "s", &ssid)) {
		dbus_pending_reply(&msg, dbus_error_invalid_args(msg));
		return false;
	}

	ssid_len = strlen(ssid);

	while ((bss = l_queue_pop_head(bss_list))) {
		if (bss->ssid_len != ssid_len ||
					memcmp(bss->ssid, ssid, ssid_len))
			goto next;

		if (bss->owe_trans)
			goto next;

		/*
		 * Override time_stamp so that this entry is removed on
		 * the next scan
		 */
		bss->time_stamp = 0;

		if (station_add_seen_bss(station, bss)) {
			l_queue_push_tail(station->bss_list, bss);

			continue;
		}

next:
		scan_bss_free(bss);
	}

	l_queue_destroy(bss_list, NULL);

	network_psk = station_network_find(station, ssid, SECURITY_PSK);
	network_open = station_network_find(station, ssid, SECURITY_NONE);

	if (!network_psk && !network_open) {
		dbus_pending_reply(&msg, dbus_error_not_found(msg));
		return true;
	}

	if (network_psk && network_open) {
		station_hide_network(station, network_psk);
		station_hide_network(station, network_open);
		dbus_pending_reply(&msg, dbus_error_service_set_overlap(msg));
		return true;
	}

	error = network_connect_new_hidden_network(network_psk ?: network_open,
							msg);

	if (error)
		dbus_pending_reply(&msg, error);
	else
		l_dbus_message_unref(msg);

	return true;
}

static void station_hidden_network_scan_destroy(void *userdata)
{
	struct station *station = userdata;

	station->hidden_network_scan_id = 0;
}

static struct l_dbus_message *station_dbus_connect_hidden_network(
						struct l_dbus *dbus,
						struct l_dbus_message *message,
						void *user_data)
{
	struct station *station = user_data;
	uint64_t id = netdev_get_wdev_id(station->netdev);
	struct scan_parameters params = {
		.flush = true,
		.randomize_mac_addr_hint = false,
	};
	const char *ssid;
	struct network *network;
	_auto_(scan_freq_set_free) struct scan_freq_set *allowed = NULL;

	l_debug("");

	if (station->hidden_pending)
		return dbus_error_busy(message);

	if (!l_dbus_message_get_arguments(message, "s", &ssid))
		return dbus_error_invalid_args(message);

	if (strlen(ssid) > 32)
		return dbus_error_invalid_args(message);

	if (known_networks_find(ssid, SECURITY_PSK) ||
			known_networks_find(ssid, SECURITY_NONE))
		return dbus_error_already_provisioned(message);

	network = station_network_find(station, ssid, SECURITY_PSK);
	if (!network)
		network = station_network_find(station, ssid, SECURITY_NONE);

	/*
	 * This checks for a corner case where the hidden network was already
	 * found and is in our scan results, but the initial connection failed.
	 * For example, the password was given incorrectly.  In this case the
	 * entry will also be found on the hidden bss list.
	 */
	if (network) {
		const struct l_queue_entry *entry =
			l_queue_get_entries(station->hidden_bss_list_sorted);
		struct scan_bss *target = network_bss_select(network, true);

		/* Treat OWE transition networks special */
		if (target->owe_trans)
			goto not_hidden;

		for (; entry; entry = entry->next) {
			struct scan_bss *bss = entry->data;

			if (!scan_bss_addr_eq(target, bss))
				continue;

			/* We can skip the scan and try to connect right away */
			return network_connect_new_hidden_network(network,
								message);
		}

not_hidden:
		return dbus_error_not_hidden(message);
	}

	allowed = station_get_allowed_freqs(station);
	if (L_WARN_ON(!allowed))
		return dbus_error_not_supported(message);

	params.freqs = allowed;
	params.ssid = (const uint8_t *)ssid;
	params.ssid_len = strlen(ssid);

	/* HW cannot randomize our MAC if connected */
	if (!station->connected_bss)
		params.randomize_mac_addr_hint = true;

	station->hidden_network_scan_id = scan_active_full(id, &params,
				station_hidden_network_scan_triggered,
				station_hidden_network_scan_results,
				station, station_hidden_network_scan_destroy);
	if (!station->hidden_network_scan_id)
		return dbus_error_failed(message);

	station->hidden_pending = l_dbus_message_ref(message);

	return NULL;
}

static void station_disconnect_reconnect_cb(struct netdev *netdev, bool success,
					void *user_data)
{
	struct station *station = user_data;

	if (__station_connect_network(station, station->connected_network,
					station->connected_bss,
					STATION_STATE_ROAMING) < 0)
		station_disassociated(station);
}

static void station_reconnect(struct station *station)
{
	/*
	 * Rather than doing 4 or so state changes, lets just go into
	 * roaming for the duration of this reconnect.
	 */
	station_enter_state(station, STATION_STATE_ROAMING);

	netdev_disconnect(station->netdev, station_disconnect_reconnect_cb,
				station);
}

static void station_disconnect_cb(struct netdev *netdev, bool success,
					void *user_data)
{
	struct station *station = user_data;

	l_debug("%u, success: %d",
			netdev_get_ifindex(station->netdev), success);

	if (station->disconnect_pending) {
		struct l_dbus_message *reply;

		if (success) {
			reply = l_dbus_message_new_method_return(
						station->disconnect_pending);
			l_dbus_message_set_arguments(reply, "");
		} else
			reply = dbus_error_failed(station->disconnect_pending);

		dbus_pending_reply(&station->disconnect_pending, reply);
	}

	station_enter_state(station, STATION_STATE_DISCONNECTED);

	if (station->autoconnect)
		station_enter_state(station, STATION_STATE_AUTOCONNECT_QUICK);
}

int station_disconnect(struct station *station)
{
	if (station->state == STATION_STATE_DISCONNECTING)
		return -EBUSY;

	if (!station->connected_bss)
		return -ENOTCONN;

	/*
	 * If the disconnect somehow fails we won't know if we're still
	 * connected so we may as well indicate now that we're no longer
	 * connected.
	 */
	station_reset_connection_state(station);

	station_enter_state(station, STATION_STATE_DISCONNECTING);

	if (netdev_disconnect(station->netdev,
					station_disconnect_cb, station) < 0)
		return -EIO;

	return 0;
}

static struct l_dbus_message *station_dbus_disconnect(struct l_dbus *dbus,
						struct l_dbus_message *message,
						void *user_data)
{
	struct station *station = user_data;
	int result;

	l_debug("");

	/*
	 * Disconnect was triggered by the user, don't autoconnect. Wait for
	 * the user's explicit instructions to scan and connect to the network
	 */
	station_set_autoconnect(station, false);

	if (station->hidden_network_scan_id) {
		scan_cancel(netdev_get_wdev_id(station->netdev),
				station->hidden_network_scan_id);
		dbus_pending_reply(&station->hidden_pending,
				dbus_error_aborted(station->hidden_pending));

		return l_dbus_message_new_method_return(message);
	}

	if (!station_is_busy(station))
		return l_dbus_message_new_method_return(message);

	result = station_disconnect(station);
	if (result < 0)
		return dbus_error_from_errno(result, message);

	station->disconnect_pending = l_dbus_message_ref(message);

	return NULL;
}

static struct l_dbus_message *station_dbus_get_networks(struct l_dbus *dbus,
						struct l_dbus_message *message,
						void *user_data)
{
	struct station *station = user_data;
	struct l_dbus_message *reply =
				l_dbus_message_new_method_return(message);
	struct l_dbus_message_builder *builder =
				l_dbus_message_builder_new(reply);
	struct l_queue *sorted = station->networks_sorted;
	const struct l_queue_entry *entry;

	l_dbus_message_builder_enter_array(builder, "(on)");

	for (entry = l_queue_get_entries(sorted); entry; entry = entry->next) {
		const struct network *network = entry->data;
		int16_t signal_strength = network_get_signal_strength(network);

		l_dbus_message_builder_enter_struct(builder, "on");
		l_dbus_message_builder_append_basic(builder, 'o',
						network_get_path(network));
		l_dbus_message_builder_append_basic(builder, 'n',
							&signal_strength);
		l_dbus_message_builder_leave_struct(builder);
	}

	l_dbus_message_builder_leave_array(builder);

	l_dbus_message_builder_finalize(builder);
	l_dbus_message_builder_destroy(builder);

	return reply;
}

static struct l_dbus_message *station_dbus_get_hidden_access_points(
						struct l_dbus *dbus,
						struct l_dbus_message *message,
						void *user_data)
{
	struct station *station = user_data;
	struct l_dbus_message *reply =
				l_dbus_message_new_method_return(message);
	struct l_dbus_message_builder *builder =
				l_dbus_message_builder_new(reply);
	const struct l_queue_entry *entry;

	l_dbus_message_builder_enter_array(builder, "(sns)");

	for (entry = l_queue_get_entries(station->hidden_bss_list_sorted);
						entry; entry = entry->next) {
		struct scan_bss *bss = entry->data;
		int16_t signal_strength = bss->signal_strength;
		enum security security;

		if (scan_bss_get_security(bss, &security) < 0)
			continue;

		l_dbus_message_builder_enter_struct(builder, "sns");
		l_dbus_message_builder_append_basic(builder, 's',
					util_address_to_string(bss->addr));
		l_dbus_message_builder_append_basic(builder, 'n',
							&signal_strength);
		l_dbus_message_builder_append_basic(builder, 's',
						security_to_str(security));
		l_dbus_message_builder_leave_struct(builder);
	}

	l_dbus_message_builder_leave_array(builder);

	l_dbus_message_builder_finalize(builder);
	l_dbus_message_builder_destroy(builder);

	return reply;
}

static void station_dbus_scan_done(struct station *station,
							bool try_autoconnect)
{
	station->dbus_scan_id = 0;
	station_property_set_scanning(station, false);

	station_process_owe_transition_networks(station);

	if (try_autoconnect) {
		station->autoconnect_can_start = true;
		station_autoconnect_start(station);
	}
}

static void station_dbus_scan_triggered(int err, void *user_data)
{
	struct station *station = user_data;
	struct l_dbus_message *reply;

	l_debug("station_scan_triggered: %i", err);

	if (err < 0) {
		if (station->scan_pending) {
			reply = dbus_error_from_errno(err,
							station->scan_pending);
			dbus_pending_reply(&station->scan_pending, reply);
		}

		station_dbus_scan_done(station, true);
		return;
	}

	l_debug("Scan triggered for %s subset %i",
		netdev_get_name(station->netdev),
		station->dbus_scan_subset_idx);

	if (station->scan_pending) {
		reply = l_dbus_message_new_method_return(station->scan_pending);
		l_dbus_message_set_arguments(reply, "");
		dbus_pending_reply(&station->scan_pending, reply);
	}

	station_property_set_scanning(station, true);
}

static bool station_dbus_scan_subset(struct station *station);

static bool station_dbus_scan_results(int err, struct l_queue *bss_list,
					const struct scan_freq_set *freqs,
					void *userdata)
{
	struct station *station = userdata;
	unsigned int next_idx = station->dbus_scan_subset_idx + 1;
	bool last_subset;

	if (err) {
		station_dbus_scan_done(station, true);
		return false;
	}

	last_subset = next_idx >= L_ARRAY_SIZE(station->scan_freqs_order) ||
		station->scan_freqs_order[next_idx] == NULL;
	station->dbus_scan_subset_idx = next_idx;

	station_set_scan_results(station, bss_list, freqs, false);

	if (last_subset || !station_dbus_scan_subset(station))
		station_dbus_scan_done(station, true);

	return true;
}

static bool station_dbus_scan_subset(struct station *station)
{
	unsigned int idx = station->dbus_scan_subset_idx;

	station->dbus_scan_id = station_scan_trigger(station,
						station->scan_freqs_order[idx],
						station_dbus_scan_triggered,
						station_dbus_scan_results,
						NULL);

	return station->dbus_scan_id != 0;
}

static struct l_dbus_message *station_dbus_scan(struct l_dbus *dbus,
						struct l_dbus_message *message,
						void *user_data)
{
	struct station *station = user_data;

	l_debug("Scan called from DBus");

	if (station->dbus_scan_id)
		return dbus_error_busy(message);

	if (station->state == STATION_STATE_CONNECTING ||
			station->state == STATION_STATE_CONNECTING_AUTO)
		return dbus_error_busy(message);

	station->dbus_scan_subset_idx = 0;

	if (!station_dbus_scan_subset(station))
		return dbus_error_failed(message);

	station->scan_pending = l_dbus_message_ref(message);

	return NULL;
}

struct signal_agent {
	char *owner;
	char *path;
	unsigned int disconnect_watch;
};

static void station_signal_agent_notify(struct station *station)
{
	struct signal_agent *agent = station->signal_agent;
	struct netdev *netdev = station->netdev;
	const char *device_path = netdev_get_path(netdev);
	uint8_t level = netdev_get_rssi_level_idx(netdev);

	struct l_dbus_message *msg;

	msg = l_dbus_message_new_method_call(dbus_get_bus(),
						agent->owner, agent->path,
						IWD_SIGNAL_AGENT_INTERFACE,
						"Changed");
	l_dbus_message_set_arguments(msg, "oy", device_path, level);
	l_dbus_message_set_no_reply(msg, true);

	l_dbus_send(dbus_get_bus(), msg);
}

static void station_signal_agent_release(struct signal_agent *agent,
						const char *device_path)
{
	struct l_dbus_message *msg;

	msg = l_dbus_message_new_method_call(dbus_get_bus(),
						agent->owner, agent->path,
						IWD_SIGNAL_AGENT_INTERFACE,
						"Release");
	l_dbus_message_set_arguments(msg, "o", device_path);
	l_dbus_message_set_no_reply(msg, true);

	l_dbus_send(dbus_get_bus(), msg);
}

static void signal_agent_free(void *data)
{
	struct signal_agent *agent = data;

	l_free(agent->owner);
	l_free(agent->path);
	l_dbus_remove_watch(dbus_get_bus(), agent->disconnect_watch);
	l_free(agent);
}

static void signal_agent_disconnect(struct l_dbus *dbus, void *user_data)
{
	struct station *station = user_data;

	l_debug("signal_agent %s disconnected", station->signal_agent->owner);

	l_idle_oneshot(signal_agent_free, station->signal_agent, NULL);
	station->signal_agent = NULL;

	netdev_set_rssi_report_levels(station->netdev, NULL, 0);
}

static struct l_dbus_message *station_dbus_signal_agent_register(
						struct l_dbus *dbus,
						struct l_dbus_message *message,
						void *user_data)
{
	struct station *station = user_data;
	const char *path, *sender;
	struct l_dbus_message *reply;
	struct l_dbus_message_iter level_iter;
	int8_t levels[16];
	int err;
	int16_t val;
	size_t count = 0;

	if (station->signal_agent)
		return dbus_error_already_exists(message);

	l_debug("signal agent register called");

	if (!l_dbus_message_get_arguments(message, "oan", &path, &level_iter))
		return dbus_error_invalid_args(message);

	while (l_dbus_message_iter_next_entry(&level_iter, &val)) {
		if (count >= L_ARRAY_SIZE(levels) || val > 127 || val < -127)
			return dbus_error_invalid_args(message);

		levels[count++] = val;
	}

	if (count < 1)
		return dbus_error_invalid_args(message);

	err = netdev_set_rssi_report_levels(station->netdev, levels, count);
	if (err == -ENOTSUP)
		return dbus_error_not_supported(message);
	else if (err < 0)
		return dbus_error_failed(message);

	sender = l_dbus_message_get_sender(message);

	station->signal_agent = l_new(struct signal_agent, 1);
	station->signal_agent->owner = l_strdup(sender);
	station->signal_agent->path = l_strdup(path);
	station->signal_agent->disconnect_watch =
		l_dbus_add_disconnect_watch(dbus, sender,
						signal_agent_disconnect,
						station, NULL);

	l_debug("agent %s path %s", sender, path);

	reply = l_dbus_message_new_method_return(message);
	l_dbus_send(dbus, reply);

	if (station->connected_network)
		station_signal_agent_notify(station);

	return NULL;
}

static struct l_dbus_message *station_dbus_signal_agent_unregister(
						struct l_dbus *dbus,
						struct l_dbus_message *message,
						void *user_data)
{
	struct station *station = user_data;
	const char *path, *sender;

	if (!station->signal_agent)
		return dbus_error_failed(message);

	l_debug("signal agent unregister");

	if (!l_dbus_message_get_arguments(message, "o", &path))
		return dbus_error_invalid_args(message);

	if (strcmp(station->signal_agent->path, path))
		return dbus_error_not_found(message);

	sender = l_dbus_message_get_sender(message);

	if (strcmp(station->signal_agent->owner, sender))
		return dbus_error_not_found(message);

	signal_agent_free(station->signal_agent);
	station->signal_agent = NULL;

	netdev_set_rssi_report_levels(station->netdev, NULL, 0);

	return l_dbus_message_new_method_return(message);
}

static bool station_property_get_connected_network(struct l_dbus *dbus,
					struct l_dbus_message *message,
					struct l_dbus_message_builder *builder,
					void *user_data)
{
	struct station *station = user_data;

	if (!station->connected_network)
		return false;

	l_dbus_message_builder_append_basic(builder, 'o',
				network_get_path(station->connected_network));

	return true;
}

static bool station_property_get_scanning(struct l_dbus *dbus,
					struct l_dbus_message *message,
					struct l_dbus_message_builder *builder,
					void *user_data)
{
	struct station *station = user_data;
	bool scanning = station->scanning;

	l_dbus_message_builder_append_basic(builder, 'b', &scanning);

	return true;
}

static bool station_property_get_state(struct l_dbus *dbus,
					struct l_dbus_message *message,
					struct l_dbus_message_builder *builder,
					void *user_data)
{
	struct station *station = user_data;
	const char *statestr = "invalid";

	switch (station->state) {
	case STATION_STATE_AUTOCONNECT_QUICK:
	case STATION_STATE_AUTOCONNECT_FULL:
	case STATION_STATE_DISCONNECTED:
		statestr = "disconnected";
		break;
	case STATION_STATE_CONNECTING:
	case STATION_STATE_CONNECTING_AUTO:
		statestr = "connecting";
		break;
	case STATION_STATE_CONNECTED:
		statestr = "connected";
		break;
	case STATION_STATE_DISCONNECTING:
		statestr = "disconnecting";
		break;
	case STATION_STATE_ROAMING:
	case STATION_STATE_FT_ROAMING:
	case STATION_STATE_FW_ROAMING:
		statestr = "roaming";
		break;
	}

	l_dbus_message_builder_append_basic(builder, 's', statestr);
	return true;
}

void station_foreach(station_foreach_func_t func, void *user_data)
{
	const struct l_queue_entry *entry;

	for (entry = l_queue_get_entries(station_list); entry;
					entry = entry->next) {
		struct station *station = entry->data;

		func(station, user_data);
	}
}

struct station *station_find(uint32_t ifindex)
{
	const struct l_queue_entry *entry;

	for (entry = l_queue_get_entries(station_list); entry;
				entry = entry->next) {
		struct station *station = entry->data;

		if (netdev_get_ifindex(station->netdev) == ifindex)
			return station;
	}

	return NULL;
}

struct network_foreach_data {
	station_network_foreach_func_t func;
	void *user_data;
};

static void network_foreach(const void *key, void *value, void *user_data)
{
	struct network_foreach_data *data = user_data;
	struct network *network = value;

	data->func(network, data->user_data);
}

void station_network_foreach(struct station *station,
				station_network_foreach_func_t func,
				void *user_data)
{
	struct network_foreach_data data = {
		.func = func,
		.user_data = user_data,
	};

	l_hashmap_foreach(station->networks, network_foreach, &data);
}

struct l_queue *station_get_bss_list(struct station *station)
{
	return station->bss_list;
}

struct scan_bss *station_get_connected_bss(struct station *station)
{
	return station->connected_bss;
}

int station_hide_network(struct station *station, struct network *network)
{
	const char *path = network_get_path(network);
	struct scan_bss *bss;

	l_debug("%s", path);

	if (station->connected_network == network)
		return -EBUSY;

	if (!l_hashmap_lookup(station->networks, path))
		return -ENOENT;

	l_queue_remove(station->networks_sorted, network);
	l_hashmap_remove(station->networks, path);

	while ((bss = network_bss_list_pop(network))) {
		memset(bss->ssid, 0, bss->ssid_len);
		l_queue_remove_if(station->hidden_bss_list_sorted,
					bss_match_bssid, bss->addr);
		l_queue_insert(station->hidden_bss_list_sorted, bss,
					bss_signal_strength_compare, NULL);
	}

	network_remove(network, -ESRCH);

	return 0;
}

static void station_add_2_4ghz_freq(uint32_t freq, void *user_data)
{
	struct scan_freq_set *set = user_data;

	/* exclude social channels added in initial scan request */
	if (freq < 3000 && freq != 2412 && freq != 2437 && freq != 2462)
		scan_freq_set_add(set, freq);
}

static void station_fill_scan_freq_subsets(struct station *station)
{
	const struct scan_freq_set *supported =
				wiphy_get_supported_freqs(station->wiphy);
	unsigned int subset_idx = 0;

	/*
	 * Scan the 2.4GHz "social channels" first, 5GHz second, if supported,
	 * all other 2.4GHz channels last.  To be refined as needed.
	 */
	if (allowed_bands & BAND_FREQ_2_4_GHZ) {
		station->scan_freqs_order[subset_idx] = scan_freq_set_new();
		scan_freq_set_add(station->scan_freqs_order[subset_idx], 2412);
		scan_freq_set_add(station->scan_freqs_order[subset_idx], 2437);
		scan_freq_set_add(station->scan_freqs_order[subset_idx], 2462);
		subset_idx++;
	}

	/*
	 * TODO: It may might sense to split up 5 and 6ghz into separate subsets
	 *       since the channel set is so large.
	 */
	if (allowed_bands & (BAND_FREQ_5_GHZ | BAND_FREQ_6_GHZ)) {
		uint32_t mask = allowed_bands &
					(BAND_FREQ_5_GHZ | BAND_FREQ_6_GHZ);
		struct scan_freq_set *set = scan_freq_set_clone(supported,
								mask);

		/* 5/6ghz didn't add any frequencies */
		if (scan_freq_set_isempty(set)) {
			scan_freq_set_free(set);
		} else
			station->scan_freqs_order[subset_idx++] = set;
	}

	/* Add remaining 2.4ghz channels to subset */
	if (allowed_bands & BAND_FREQ_2_4_GHZ) {
		station->scan_freqs_order[subset_idx] = scan_freq_set_new();
		scan_freq_set_foreach(supported, station_add_2_4ghz_freq,
					station->scan_freqs_order[subset_idx]);
	}

	/*
	 * This has the unintended consequence of allowing DBus scans to
	 * scan the entire spectrum rather than cause IWD to be completely
	 * non-functional. Rather than prevent DBus scans from working at all
	 * print a warning here.
	 */
	if (station->scan_freqs_order[0] == NULL)
		l_warn("All supported bands were disabled by user! IWD will not"
			" function as expected");

}

static void station_wiphy_watch(struct wiphy *wiphy,
				enum wiphy_state_watch_event event,
				void *user_data)
{
	struct station *station = user_data;
	int ret;

	if (event != WIPHY_STATE_WATCH_EVENT_REGDOM_DONE)
		return;

	/*
	 * The only state that requires special handling is for
	 * quick scans since the previous quick scan was delayed until
	 * the regulatory domain updated. Try again in case 6GHz is now
	 * unlocked (unlikely), or advance to full autoconnect. Just in
	 * case this update came during a quick scan, ignore it.
	 */
	if (station->state != STATION_STATE_AUTOCONNECT_QUICK ||
			station->quick_scan_id)
		return;

	ret = station_quick_scan_trigger(station);
	if (!ret)
		return;

	L_WARN_ON(ret == -EAGAIN);
	station_enter_state(station, STATION_STATE_AUTOCONNECT_FULL);
}

static struct station *station_create(struct netdev *netdev)
{
	struct station *station;
	struct l_dbus *dbus = dbus_get_bus();
	bool autoconnect = true;

	station = l_new(struct station, 1);
	watchlist_init(&station->state_watches, NULL);

	station->bss_list = l_queue_new();
	station->hidden_bss_list_sorted = l_queue_new();
	station->networks = l_hashmap_new();
	l_hashmap_set_hash_function(station->networks, l_str_hash);
	l_hashmap_set_compare_function(station->networks,
				(l_hashmap_compare_func_t) strcmp);
	station->networks_sorted = l_queue_new();

	station->wiphy = netdev_get_wiphy(netdev);
	station->netdev = netdev;

	station->wiphy_watch = wiphy_state_watch_add(station->wiphy,
							station_wiphy_watch,
							station, NULL);

	l_queue_push_head(station_list, station);

	l_dbus_object_add_interface(dbus, netdev_get_path(netdev),
					IWD_STATION_INTERFACE, station);

	if (netconfig_enabled())
		station->netconfig = netconfig_new(netdev_get_ifindex(netdev));

	station->anqp_pending = l_queue_new();

	station_fill_scan_freq_subsets(station);

	if (iwd_is_developer_mode()) {
		l_dbus_object_add_interface(dbus,
					netdev_get_path(station->netdev),
					IWD_STATION_DEBUG_INTERFACE,
					station);
		autoconnect = false;
	}

	station_set_autoconnect(station, autoconnect);

	station->roam_bss_list = l_queue_new();

	return station;
}

static void station_free(struct station *station)
{
	l_debug("");

	if (!l_queue_remove(station_list, station))
		return;

	l_dbus_object_remove_interface(dbus_get_bus(),
					netdev_get_path(station->netdev),
					IWD_STATION_DIAGNOSTIC_INTERFACE);
	if (iwd_is_developer_mode())
		l_dbus_object_remove_interface(dbus_get_bus(),
					netdev_get_path(station->netdev),
					IWD_STATION_DEBUG_INTERFACE);

	if (station->netconfig) {
		netconfig_destroy(station->netconfig);
		station->netconfig = NULL;
	}

	periodic_scan_stop(station);

	if (station->signal_agent) {
		station_signal_agent_release(station->signal_agent,
					netdev_get_path(station->netdev));
		signal_agent_free(station->signal_agent);
	}

	if (station->connect_pending)
		dbus_pending_reply(&station->connect_pending,
				dbus_error_aborted(station->connect_pending));

	if (station->hidden_pending)
		dbus_pending_reply(&station->hidden_pending,
				dbus_error_aborted(station->hidden_pending));

	if (station->disconnect_pending)
		dbus_pending_reply(&station->disconnect_pending,
			dbus_error_aborted(station->disconnect_pending));

	if (station->scan_pending)
		dbus_pending_reply(&station->scan_pending,
			dbus_error_aborted(station->scan_pending));

	if (station->dbus_scan_id)
		scan_cancel(netdev_get_wdev_id(station->netdev),
				station->dbus_scan_id);

	if (station->quick_scan_id)
		scan_cancel(netdev_get_wdev_id(station->netdev),
				station->quick_scan_id);

	if (station->hidden_network_scan_id)
		scan_cancel(netdev_get_wdev_id(station->netdev),
				station->hidden_network_scan_id);

	if (station->owe_hidden_scan_ids) {
		void *ptr;

		while ((ptr = l_queue_pop_head(station->owe_hidden_scan_ids)))
			scan_cancel(netdev_get_wdev_id(station->netdev),
					L_PTR_TO_UINT(ptr));

		l_queue_destroy(station->owe_hidden_scan_ids, NULL);
	}

	station_roam_state_clear(station);

	l_queue_destroy(station->networks_sorted, NULL);
	l_hashmap_destroy(station->networks, network_free);
	l_queue_destroy(station->bss_list, bss_free);
	l_queue_destroy(station->hidden_bss_list_sorted, NULL);
	l_queue_destroy(station->autoconnect_list, NULL);

	watchlist_destroy(&station->state_watches);

	l_queue_destroy(station->anqp_pending, remove_anqp);

	scan_freq_set_free(station->scan_freqs_order[0]);
	scan_freq_set_free(station->scan_freqs_order[1]);

	if (station->scan_freqs_order[2])
		scan_freq_set_free(station->scan_freqs_order[2]);

	wiphy_state_watch_remove(station->wiphy, station->wiphy_watch);

	l_queue_destroy(station->roam_bss_list, l_free);

	l_free(station);
}

static void station_setup_interface(struct l_dbus_interface *interface)
{
	l_dbus_interface_method(interface, "ConnectHiddenNetwork", 0,
				station_dbus_connect_hidden_network,
				"", "s", "name");
	l_dbus_interface_method(interface, "Disconnect", 0,
				station_dbus_disconnect, "", "");
	l_dbus_interface_method(interface, "GetOrderedNetworks", 0,
				station_dbus_get_networks, "a(on)", "",
				"networks");
	l_dbus_interface_method(interface, "GetHiddenAccessPoints", 0,
				station_dbus_get_hidden_access_points,
				"a(sns)", "",
				"accesspoints");
	l_dbus_interface_method(interface, "Scan", 0,
				station_dbus_scan, "", "");
	l_dbus_interface_method(interface, "RegisterSignalLevelAgent", 0,
				station_dbus_signal_agent_register,
				"", "oan", "path", "levels");
	l_dbus_interface_method(interface, "UnregisterSignalLevelAgent", 0,
				station_dbus_signal_agent_unregister,
				"", "o", "path");

	l_dbus_interface_property(interface, "ConnectedNetwork", 0, "o",
					station_property_get_connected_network,
					NULL);
	l_dbus_interface_property(interface, "Scanning", 0, "b",
					station_property_get_scanning, NULL);
	l_dbus_interface_property(interface, "State", 0, "s",
					station_property_get_state, NULL);
}

static void station_destroy_interface(void *user_data)
{
	struct station *station = user_data;

	station_free(station);
}

static void station_get_diagnostic_cb(
				const struct diagnostic_station_info *info,
				void *user_data)
{
	struct station *station = user_data;
	struct l_dbus_message *reply;
	struct l_dbus_message_builder *builder;
	struct handshake_state *hs = netdev_get_handshake(station->netdev);

	if (!info) {
		reply = dbus_error_aborted(station->get_station_pending);
		goto done;
	}

	reply = l_dbus_message_new_method_return(station->get_station_pending);

	builder = l_dbus_message_builder_new(reply);

	l_dbus_message_builder_enter_array(builder, "{sv}");

	dbus_append_dict_basic(builder, "ConnectedBss", 's',
					util_address_to_string(info->addr));
	dbus_append_dict_basic(builder, "Frequency", 'u',
				&station->connected_bss->frequency);
	dbus_append_dict_basic(builder, "Security", 's',
				diagnostic_akm_suite_to_security(hs->akm_suite,
								hs->wpa_ie));

	if (hs->pairwise_cipher) {
		const char *str;

		if (hs->pairwise_cipher ==
				IE_RSN_CIPHER_SUITE_USE_GROUP_CIPHER)
			str = ie_rsn_cipher_suite_to_string(hs->group_cipher);
		else
			str = ie_rsn_cipher_suite_to_string(
							hs->pairwise_cipher);

		if (str)
			dbus_append_dict_basic(builder, "PairwiseCipher",
						's', str);
	}

	diagnostic_info_to_dict(info, builder);

	l_dbus_message_builder_leave_array(builder);
	l_dbus_message_builder_finalize(builder);
	l_dbus_message_builder_destroy(builder);

done:
	dbus_pending_reply(&station->get_station_pending, reply);
}

static void station_get_diagnostic_destroy(void *user_data)
{
	struct station *station = user_data;
	struct l_dbus_message *reply;

	if (station->get_station_pending) {
		reply = dbus_error_aborted(station->get_station_pending);
		dbus_pending_reply(&station->get_station_pending, reply);
	}
}

static struct l_dbus_message *station_get_diagnostics(struct l_dbus *dbus,
						struct l_dbus_message *message,
						void *user_data)
{
	struct station *station = user_data;
	int ret;

	if (station->get_station_pending)
		return dbus_error_busy(message);

	ret = netdev_get_current_station(station->netdev,
				station_get_diagnostic_cb, station,
				station_get_diagnostic_destroy);
	if (ret < 0)
		return dbus_error_from_errno(ret, message);

	station->get_station_pending = l_dbus_message_ref(message);

	return NULL;
}

struct station_roam_data {
	struct station *station;
	struct l_dbus_message *pending;
	uint8_t bssid[6];
};

static void station_force_roam_scan_triggered(int err, void *user_data)
{
	struct station_roam_data *data = user_data;
	struct station *station = data->station;

	if (err)
		station_roam_failed(station);
}

static bool station_force_roam_scan_notify(int err, struct l_queue *bss_list,
					const struct scan_freq_set *freqs,
					void *user_data)
{
	struct station_roam_data *data = user_data;
	struct station *station = data->station;
	struct scan_bss *target;
	struct l_dbus_message *reply;

	if (err) {
		reply = dbus_error_from_errno(err, data->pending);
		goto reply;
	}

	target = l_queue_remove_if(bss_list, bss_match_bssid, data->bssid);
	if (!target) {
		reply = dbus_error_not_found(data->pending);
		goto reply;
	}

	l_debug("Attempting forced roam to BSS "MAC, MAC_STR(target->addr));

	/* The various roam routines expect this to be set from scanning */
	station->preparing_roam = true;
	l_queue_push_tail(station->roam_bss_list,
				roam_bss_from_scan_bss(target, target->rank));

	station_update_roam_bss(station, target);

	station_transition_start(station);

	reply = l_dbus_message_new_method_return(data->pending);

reply:
	dbus_pending_reply(&data->pending, reply);

	return false;
}

static void station_force_roam_scan_destroy(void *user_data)
{
	struct station_roam_data *data = user_data;

	data->station->roam_scan_id = 0;

	if (data->pending)
		l_dbus_message_unref(data->pending);

	l_free(data);
}

static struct l_dbus_message *station_force_roam(struct l_dbus *dbus,
						struct l_dbus_message *message,
						void *user_data)
{
	struct station *station = user_data;
	struct scan_bss *target;
	struct l_dbus_message_iter iter;
	uint8_t *mac;
	uint32_t mac_len;
	struct scan_parameters params = { 0 };
	struct scan_freq_set *freqs = NULL;
	struct station_roam_data *data;

	if (!l_dbus_message_get_arguments(message, "ay", &iter))
		goto invalid_args;

	if (!l_dbus_message_iter_get_fixed_array(&iter, &mac, &mac_len))
		goto invalid_args;

	if (mac_len != 6)
		return dbus_error_invalid_args(message);

	if (!station->connected_network)
		return dbus_error_not_connected(message);

	target = network_bss_find_by_addr(station->connected_network, mac);
	if (!target)
		goto full_scan;

	if (target && target == station->connected_bss)
		return dbus_error_already_exists(message);

	if (station->connected_bss->ssid_len != target->ssid_len)
		goto invalid_args;

	if (memcmp(station->connected_bss->ssid, target->ssid,
				target->ssid_len))
		goto invalid_args;

	/*
	 * Always scan before a roam to ensure the kernel has the BSS in its
	 * cache. If we already see the BSS only scan that frequency
	 */
	freqs = scan_freq_set_new();
	scan_freq_set_add(freqs, target->frequency);

	params.freqs = freqs;

full_scan:
	params.flush = true;

	data = l_new(struct station_roam_data, 1);
	data->station = station;
	data->pending = l_dbus_message_ref(message);
	memcpy(data->bssid, mac, 6);

	station->roam_scan_id = scan_active_full(
					netdev_get_wdev_id(station->netdev),
					&params,
					station_force_roam_scan_triggered,
					station_force_roam_scan_notify, data,
					station_force_roam_scan_destroy);

	if (freqs)
		scan_freq_set_free(freqs);

	if (!station->roam_scan_id) {
		l_free(data);
		return dbus_error_failed(message);
	}

	if (freqs)
		l_debug("Scanning on %u for BSS "MAC, target->frequency,
			MAC_STR(mac));
	else
		l_debug("Full scan for BSS "MAC, MAC_STR(mac));

	return NULL;

invalid_args:
	return dbus_error_invalid_args(message);
}

static struct network *station_find_network_from_bss(struct station *station,
						struct scan_bss *bss)
{
	enum security security;
	char ssid[33];

	memcpy(ssid, bss->ssid, bss->ssid_len);
	ssid[bss->ssid_len] = '\0';

	if (scan_bss_get_security(bss, &security) < 0)
		return NULL;

	return station_network_find(station, ssid, security);
}

static void station_setup_diagnostic_interface(
					struct l_dbus_interface *interface)
{
	l_dbus_interface_method(interface, "GetDiagnostics", 0,
				station_get_diagnostics, "a{sv}", "",
				"diagnostics");
}

static void station_destroy_diagnostic_interface(void *user_data)
{
}

static struct l_dbus_message *station_force_connect_bssid(struct l_dbus *dbus,
						struct l_dbus_message *message,
						void *user_data)
{
	struct station *station = user_data;
	struct l_queue *bss_list;
	struct scan_bss *target;
	struct network *network;
	struct l_dbus_message_iter iter;
	uint8_t *mac;
	uint32_t mac_len;

	if (!l_dbus_message_get_arguments(message, "ay", &iter))
		goto invalid_args;

	if (!l_dbus_message_iter_get_fixed_array(&iter, &mac, &mac_len))
		goto invalid_args;

	if (mac_len != 6)
		return dbus_error_invalid_args(message);

	bss_list = station_get_bss_list(station);

	target = l_queue_find(bss_list, bss_match_bssid, mac);
	if (!target)
		return dbus_error_invalid_args(message);

	if (util_ssid_is_hidden(target->ssid_len, target->ssid))
		return dbus_error_not_found(message);

	network = station_find_network_from_bss(station, target);
	if (!network)
		return dbus_error_invalid_args(message);

	l_debug("Attempting forced connection to BSS "MAC, MAC_STR(mac));

	return __network_connect(network, target, message);

invalid_args:
	return dbus_error_invalid_args(message);
}

static void station_debug_scan_triggered(int err, void *user_data)
{
	struct station *station = user_data;
	struct l_dbus_message *reply;

	if (err < 0) {
		if (station->scan_pending) {
			reply = dbus_error_from_errno(err,
							station->scan_pending);
			dbus_pending_reply(&station->scan_pending, reply);
		}

		station_dbus_scan_done(station, false);
		return;
	}

	l_debug("debug scan triggered for %s",
			netdev_get_name(station->netdev));

	if (station->scan_pending) {
		reply = l_dbus_message_new_method_return(station->scan_pending);
		l_dbus_message_set_arguments(reply, "");
		dbus_pending_reply(&station->scan_pending, reply);
	}

	station_property_set_scanning(station, true);
}

static bool station_debug_scan_results(int err, struct l_queue *bss_list,
					const struct scan_freq_set *freqs,
					void *userdata)
{
	struct station *station = userdata;

	if (err) {
		station_dbus_scan_done(station, false);
		return false;
	}

	station_set_scan_results(station, bss_list, freqs, false);
	station_dbus_scan_done(station, false);

	return true;
}

static struct l_dbus_message *station_debug_scan(struct l_dbus *dbus,
						struct l_dbus_message *message,
						void *user_data)
{
	struct station *station = user_data;
	struct l_dbus_message_iter iter;
	uint16_t *freqs;
	uint32_t freqs_len;
	struct scan_freq_set *freq_set;
	unsigned int i;

	if (station->dbus_scan_id)
		return dbus_error_busy(message);

	if (station->state == STATION_STATE_CONNECTING ||
			station->state == STATION_STATE_CONNECTING_AUTO)
		return dbus_error_busy(message);

	if (!l_dbus_message_get_arguments(message, "aq", &iter))
		goto invalid_args;

	if (!l_dbus_message_iter_get_fixed_array(&iter, &freqs, &freqs_len))
		goto invalid_args;

	freq_set = scan_freq_set_new();

	for (i = 0; i < freqs_len; i++) {
		if (scan_freq_set_contains(freq_set, (uint32_t)freqs[i]))
			continue;

		if (!scan_freq_set_add(freq_set, (uint32_t)freqs[i])) {
			scan_freq_set_free(freq_set);
			goto invalid_args;
		}

		l_debug("added frequency %u", freqs[i]);
	}

	station->dbus_scan_id = station_scan_trigger(station, freq_set,
						station_debug_scan_triggered,
						station_debug_scan_results,
						NULL);

	scan_freq_set_free(freq_set);

	if (!station->dbus_scan_id)
		goto failed;

	station->scan_pending = l_dbus_message_ref(message);

	return NULL;

failed:
	return dbus_error_failed(message);
invalid_args:
	return dbus_error_invalid_args(message);
}

static bool station_property_get_autoconnect(struct l_dbus *dbus,
					struct l_dbus_message *message,
					struct l_dbus_message_builder *builder,
					void *user_data)
{
	struct station *station = user_data;
	bool autoconnect;

	autoconnect = station->autoconnect;

	l_dbus_message_builder_append_basic(builder, 'b', &autoconnect);

	return true;
}

static struct l_dbus_message *station_property_set_autoconnect(
					struct l_dbus *dbus,
					struct l_dbus_message *message,
					struct l_dbus_message_iter *new_value,
					l_dbus_property_complete_cb_t complete,
					void *user_data)
{
	struct station *station = user_data;
	bool autoconnect;

	if (!l_dbus_message_iter_get_variant(new_value, "b", &autoconnect))
		return dbus_error_invalid_args(message);

	l_debug("Setting autoconnect %s", autoconnect ? "true" : "false");

	station_set_autoconnect(station, autoconnect);

	return l_dbus_message_new_method_return(message);
}

static void station_append_byte_array(struct l_dbus_message_builder *builder,
					const char *name,
					const uint8_t *bytes, size_t len)
{
	size_t i;

	l_dbus_message_builder_enter_dict(builder, "sv");
	l_dbus_message_builder_append_basic(builder, 's', name);
	l_dbus_message_builder_enter_variant(builder, "ay");
	l_dbus_message_builder_enter_array(builder, "y");

	for (i = 0; i < len; i++)
		l_dbus_message_builder_append_basic(builder, 'y', &bytes[i]);

	l_dbus_message_builder_leave_array(builder);
	l_dbus_message_builder_leave_variant(builder);
	l_dbus_message_builder_leave_dict(builder);
}

static void station_append_bss_list(struct l_dbus_message_builder *builder,
					const struct l_queue_entry *entry)
{
	for (; entry; entry = entry->next) {
		struct scan_bss *bss = entry->data;
		int32_t rssi = bss->signal_strength / 100;

		l_dbus_message_builder_enter_array(builder, "{sv}");

		dbus_append_dict_basic(builder, "Frequency", 'u',
						&bss->frequency);
		dbus_append_dict_basic(builder, "RSSI", 'i',
						&rssi);
		dbus_append_dict_basic(builder, "Rank", 'q', &bss->rank);

		dbus_append_dict_basic(builder, "Address", 's',
					util_address_to_string(bss->addr));

		station_append_byte_array(builder, "MDE", bss->mde, 3);

		l_dbus_message_builder_leave_array(builder);
	}
}

static struct l_dbus_message *station_debug_get_networks(struct l_dbus *dbus,
						struct l_dbus_message *message,
						void *user_data)
{
	struct station *station = user_data;
	struct l_dbus_message *reply =
				l_dbus_message_new_method_return(message);
	struct l_dbus_message_builder *builder =
				l_dbus_message_builder_new(reply);
	const struct l_queue_entry *entry;

	l_dbus_message_builder_enter_array(builder, "{oaa{sv}}");

	if (l_queue_isempty(station->networks_sorted))
		goto done;

	for (entry = l_queue_get_entries(station->networks_sorted); entry;
							entry = entry->next) {
		const struct network *network = entry->data;

		l_dbus_message_builder_enter_dict(builder, "oaa{sv}");
		l_dbus_message_builder_append_basic(builder, 'o',
						network_get_path(network));
		l_dbus_message_builder_enter_array(builder, "a{sv}");

		station_append_bss_list(builder,
					network_bss_list_get_entries(network));

		l_dbus_message_builder_leave_array(builder);
		l_dbus_message_builder_leave_dict(builder);
	}

done:
	l_dbus_message_builder_leave_array(builder);

	l_dbus_message_builder_finalize(builder);
	l_dbus_message_builder_destroy(builder);

	return reply;
}

static void station_setup_debug_interface(
					struct l_dbus_interface *interface)
{
	l_dbus_interface_method(interface, "ConnectBssid", 0,
					station_force_connect_bssid, "", "ay",
					"mac");
	l_dbus_interface_method(interface, "Roam", 0,
					station_force_roam, "", "ay", "mac");

	l_dbus_interface_method(interface, "Scan", 0,
					station_debug_scan, "", "aq",
					"frequencies");
	l_dbus_interface_method(interface, "GetNetworks", 0,
				station_debug_get_networks, "a{oaa{sv}}", "",
				"networks");

	l_dbus_interface_signal(interface, "Event", 0, "sav", "name", "data");

	l_dbus_interface_property(interface, "AutoConnect", 0, "b",
					station_property_get_autoconnect,
					station_property_set_autoconnect);
}

static void ap_roam_frame_event(const struct mmpdu_header *hdr,
					const void *body, size_t body_len,
					int rssi, void *user_data)
{
	uint32_t ifindex = L_PTR_TO_UINT(user_data);
	struct station *station = station_find(ifindex);

	if (!station)
		return;

	station_ap_directed_roam(station, hdr, body, body_len);
}

static void add_frame_watches(struct netdev *netdev)
{
	static const uint8_t action_ap_roam_prefix[2] = { 0x0a, 0x07 };

	/*
	 * register for AP roam transition watch
	 */
	frame_watch_add(netdev_get_wdev_id(netdev), 0, 0x00d0,
			action_ap_roam_prefix, sizeof(action_ap_roam_prefix),
			ap_roam_frame_event,
			L_UINT_TO_PTR(netdev_get_ifindex(netdev)), NULL);
}

static void station_netdev_watch(struct netdev *netdev,
				enum netdev_watch_event event, void *userdata)
{
	switch (event) {
	case NETDEV_WATCH_EVENT_NEW:
		if (netdev_get_iftype(netdev) == NETDEV_IFTYPE_STATION) {
			add_frame_watches(netdev);

			if (netdev_get_is_up(netdev))
				station_create(netdev);
		}
		break;
	case NETDEV_WATCH_EVENT_UP:
		if (netdev_get_iftype(netdev) == NETDEV_IFTYPE_STATION)
			station_create(netdev);

		break;
	case NETDEV_WATCH_EVENT_DOWN:
	case NETDEV_WATCH_EVENT_DEL:
		l_dbus_object_remove_interface(dbus_get_bus(),
						netdev_get_path(netdev),
						IWD_STATION_INTERFACE);
		break;
	case NETDEV_WATCH_EVENT_IFTYPE_CHANGE:
		if (netdev_get_iftype(netdev) == NETDEV_IFTYPE_STATION)
			add_frame_watches(netdev);

		break;
	default:
		break;
	}
}

static void station_known_networks_changed(enum known_networks_event event,
						const struct network_info *info,
						void *user_data)
{
	_auto_(l_free) char *network_id = NULL;

	if (event != KNOWN_NETWORKS_EVENT_REMOVED)
		return;

	if (info->type != SECURITY_8021X)
		return;

	network_id = l_util_hexstring(info->ssid, strlen(info->ssid));
	eap_tls_forget_peer(network_id);
}

static int station_init(void)
{
	if (scan_get_band_rank_modifier(BAND_FREQ_2_4_GHZ))
		allowed_bands |= BAND_FREQ_2_4_GHZ;
	if (scan_get_band_rank_modifier(BAND_FREQ_5_GHZ))
		allowed_bands |= BAND_FREQ_5_GHZ;
	if (scan_get_band_rank_modifier(BAND_FREQ_6_GHZ))
		allowed_bands |= BAND_FREQ_6_GHZ;

	if (!(allowed_bands & (BAND_FREQ_2_4_GHZ | BAND_FREQ_5_GHZ))) {
		l_error("At least 2.4GHz and 5GHz bands must be enabled for "
			"IWD to start, check [Rank].BandModifier* setting");
		return -ENOTSUP;
	}

	station_list = l_queue_new();
	netdev_watch = netdev_watch_add(station_netdev_watch, NULL, NULL);
	l_dbus_register_interface(dbus_get_bus(), IWD_STATION_INTERFACE,
					station_setup_interface,
					station_destroy_interface, false);
	l_dbus_register_interface(dbus_get_bus(),
					IWD_STATION_DIAGNOSTIC_INTERFACE,
					station_setup_diagnostic_interface,
					station_destroy_diagnostic_interface,
					false);
	if (iwd_is_developer_mode())
		l_dbus_register_interface(dbus_get_bus(),
					IWD_STATION_DEBUG_INTERFACE,
					station_setup_debug_interface,
					NULL,
					false);

	if (!l_settings_get_uint(iwd_get_config(), "General",
					"ManagementFrameProtection",
					&mfp_setting))
		mfp_setting = 1;

	if (mfp_setting > 2) {
		l_error("Invalid [General].ManagementFrameProtection value: %d,"
				" using default of 1", mfp_setting);
		mfp_setting = 1;
	}

	if (!l_settings_get_uint(iwd_get_config(), "General",
				"RoamRetryInterval",
				&roam_retry_interval))
		roam_retry_interval = 60;

	if (roam_retry_interval > INT_MAX)
		roam_retry_interval = INT_MAX;

	if (!l_settings_get_bool(iwd_get_config(), "General", "DisableANQP",
				&anqp_disabled))
		anqp_disabled = true;

	if (!netconfig_enabled())
		l_info("station: Network configuration is disabled.");

	supports_arp_evict_nocarrier = sysfs_supports_ipv4_setting("all",
						"arp_evict_nocarrier");
	supports_ndisc_evict_nocarrier = sysfs_supports_ipv6_setting("all",
						"ndisc_evict_nocarrier");

	watchlist_init(&event_watches, NULL);

	eap_tls_set_session_cache_ops(storage_eap_tls_cache_load,
					storage_eap_tls_cache_sync);
	known_networks_watch = known_networks_watch_add(
						station_known_networks_changed,
						NULL, NULL);

	return 0;
}

static void station_exit(void)
{
	l_dbus_unregister_interface(dbus_get_bus(),
					IWD_STATION_DIAGNOSTIC_INTERFACE);
	if (iwd_is_developer_mode())
		l_dbus_unregister_interface(dbus_get_bus(),
					IWD_STATION_DEBUG_INTERFACE);
	l_dbus_unregister_interface(dbus_get_bus(), IWD_STATION_INTERFACE);
	netdev_watch_remove(netdev_watch);
	l_queue_destroy(station_list, NULL);
	station_list = NULL;
	watchlist_destroy(&event_watches);
	known_networks_watch_remove(known_networks_watch);
	known_networks_watch = 0;
}

IWD_MODULE(station, station_init, station_exit)
IWD_MODULE_DEPENDS(station, known_networks)
IWD_MODULE_DEPENDS(station, netdev);
IWD_MODULE_DEPENDS(station, netconfig);
IWD_MODULE_DEPENDS(station, frame_xchg);
IWD_MODULE_DEPENDS(station, wiphy);