summaryrefslogtreecommitdiff
path: root/src/nm-device-wifi.c
blob: 278d9a0631caf5d60aa8907225509ffd587dfff1 (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
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- */
/* NetworkManager -- Network link manager
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Copyright (C) 2005 - 2011 Red Hat, Inc.
 * Copyright (C) 2006 - 2008 Novell, Inc.
 */

#include <glib.h>
#include <glib/gi18n.h>
#include <dbus/dbus.h>
#include <netinet/in.h>
#include <string.h>
#include <net/ethernet.h>
#include <iwlib.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <signal.h>
#include <unistd.h>
#include <linux/sockios.h>
#include <linux/ethtool.h>
#include <sys/ioctl.h>
#include <netinet/ether.h>

#include "nm-glib-compat.h"
#include "nm-device.h"
#include "nm-device-wifi.h"
#include "nm-device-interface.h"
#include "nm-device-private.h"
#include "nm-utils.h"
#include "nm-logging.h"
#include "nm-marshal.h"
#include "NetworkManagerUtils.h"
#include "nm-activation-request.h"
#include "nm-supplicant-manager.h"
#include "nm-supplicant-interface.h"
#include "nm-supplicant-config.h"
#include "nm-properties-changed-signal.h"
#include "nm-setting-connection.h"
#include "nm-setting-wireless.h"
#include "nm-setting-wireless-security.h"
#include "nm-setting-8021x.h"
#include "nm-setting-ip4-config.h"
#include "nm-setting-ip6-config.h"
#include "nm-system.h"
#include "nm-settings-connection.h"

static gboolean impl_device_get_access_points (NMDeviceWifi *device,
                                               GPtrArray **aps,
                                               GError **err);

#include "nm-device-wifi-glue.h"


/* All of these are in seconds */
#define SCAN_INTERVAL_MIN 0
#define SCAN_INTERVAL_STEP 20
#define SCAN_INTERVAL_MAX 120

#define WIRELESS_SECRETS_TRIES "wireless-secrets-tries"

static void device_interface_init (NMDeviceInterface *iface_class);

G_DEFINE_TYPE_EXTENDED (NMDeviceWifi, nm_device_wifi, NM_TYPE_DEVICE, 0,
                        G_IMPLEMENT_INTERFACE (NM_TYPE_DEVICE_INTERFACE, device_interface_init))

#define NM_DEVICE_WIFI_GET_PRIVATE(o) (G_TYPE_INSTANCE_GET_PRIVATE ((o), NM_TYPE_DEVICE_WIFI, NMDeviceWifiPrivate))


enum {
	PROP_0,
	PROP_HW_ADDRESS,
	PROP_PERM_HW_ADDRESS,
	PROP_MODE,
	PROP_BITRATE,
	PROP_ACTIVE_ACCESS_POINT,
	PROP_CAPABILITIES,
	PROP_SCANNING,
	PROP_IPW_RFKILL_STATE,

	LAST_PROP
};

enum {
	ACCESS_POINT_ADDED,
	ACCESS_POINT_REMOVED,
	HIDDEN_AP_FOUND,
	PROPERTIES_CHANGED,
	SCANNING_ALLOWED,

	LAST_SIGNAL
};

static guint signals[LAST_SIGNAL] = { 0 };

#define SUP_SIG_ID_LEN 5

typedef struct Supplicant {
	NMSupplicantManager *mgr;
	NMSupplicantInterface *iface;

	guint sig_ids[SUP_SIG_ID_LEN];
	guint iface_error_id;

	/* Timeouts and idles */
	guint iface_con_error_cb_id;
	guint con_timeout_id;
} Supplicant;

struct _NMDeviceWifiPrivate {
	gboolean          disposed;

	guint8            hw_addr[ETH_ALEN];         /* Currently set MAC address */
	guint8            perm_hw_addr[ETH_ALEN];    /* Permanent MAC address */
	guint8            initial_hw_addr[ETH_ALEN]; /* Initial MAC address (as seen when NM starts) */

	/* Legacy rfkill for ipw2x00; will be fixed with 2.6.33 kernel */
	char *            ipw_rfkill_path;
	guint             ipw_rfkill_id;
	RfKillState       ipw_rfkill_state;

	GByteArray *      ssid;
	gint8             invalid_strength_counter;
	iwqual            max_qual;

	gint8             num_freqs;
	guint32           freqs[IW_MAX_FREQUENCIES];

	GSList *          ap_list;
	NMAccessPoint *   current_ap;
	guint32           rate;
	gboolean          enabled; /* rfkilled or not */
	
	glong             scheduled_scan_time;
	guint8            scan_interval; /* seconds */
	guint             pending_scan_id;

	Supplicant        supplicant;

	guint32           failed_link_count;
	guint             periodic_source_id;
	guint             link_timeout_id;

	/* Static options from driver */
	guint32           capabilities;
	gboolean          has_scan_capa_ssid;
};

static guint32 nm_device_wifi_get_frequency (NMDeviceWifi *self);

static gboolean request_wireless_scan (gpointer user_data);

static void schedule_scan (NMDeviceWifi *self, gboolean backoff);

static void cancel_pending_scan (NMDeviceWifi *self);

static void cleanup_association_attempt (NMDeviceWifi * self,
                                         gboolean disconnect);

static void remove_supplicant_timeouts (NMDeviceWifi *self);

static void supplicant_iface_state_cb (NMSupplicantInterface *iface,
                                       guint32 new_state,
                                       guint32 old_state,
                                       gpointer user_data);

static void supplicant_iface_new_bss_cb (NMSupplicantInterface * iface,
                                         GHashTable *properties,
                                         NMDeviceWifi * self);

static void supplicant_iface_scan_done_cb (NMSupplicantInterface * iface,
                                           gboolean success,
                                           NMDeviceWifi * self);

static void supplicant_iface_notify_scanning_cb (NMSupplicantInterface * iface,
                                                 GParamSpec * pspec,
                                                 NMDeviceWifi * self);

static guint32 nm_device_wifi_get_bitrate (NMDeviceWifi *self);

static void cull_scan_list (NMDeviceWifi *self);

/*****************************************************************/

typedef enum {
	NM_WIFI_ERROR_CONNECTION_NOT_WIRELESS = 0,
	NM_WIFI_ERROR_CONNECTION_INVALID,
	NM_WIFI_ERROR_CONNECTION_INCOMPATIBLE,
	NM_WIFI_ERROR_ACCESS_POINT_NOT_FOUND,
} NMWifiError;

#define NM_WIFI_ERROR (nm_wifi_error_quark ())
#define NM_TYPE_WIFI_ERROR (nm_wifi_error_get_type ())

static GQuark
nm_wifi_error_quark (void)
{
	static GQuark quark = 0;
	if (!quark)
		quark = g_quark_from_static_string ("nm-wifi-error");
	return quark;
}

/* This should really be standard. */
#define ENUM_ENTRY(NAME, DESC) { NAME, "" #NAME "", DESC }

static GType
nm_wifi_error_get_type (void)
{
	static GType etype = 0;

	if (etype == 0) {
		static const GEnumValue values[] = {
			/* Connection was not a wireless connection. */
			ENUM_ENTRY (NM_WIFI_ERROR_CONNECTION_NOT_WIRELESS, "ConnectionNotWireless"),
			/* Connection was not a valid wireless connection. */
			ENUM_ENTRY (NM_WIFI_ERROR_CONNECTION_INVALID, "ConnectionInvalid"),
			/* Connection does not apply to this device. */
			ENUM_ENTRY (NM_WIFI_ERROR_CONNECTION_INCOMPATIBLE, "ConnectionIncompatible"),
			/* Given access point was not in this device's scan list. */
			ENUM_ENTRY (NM_WIFI_ERROR_ACCESS_POINT_NOT_FOUND, "AccessPointNotFound"),
			{ 0, 0, 0 }
		};
		etype = g_enum_register_static ("NMWifiError", values);
	}
	return etype;
}

/*****************************************************************/

/* IPW rfkill handling (until 2.6.33) */
RfKillState
nm_device_wifi_get_ipw_rfkill_state (NMDeviceWifi *self)
{
	NMDeviceWifiPrivate *priv = NM_DEVICE_WIFI_GET_PRIVATE (self);
	char *contents = NULL;
	RfKillState state = RFKILL_UNBLOCKED;
	const char *str_state = NULL;

	if (   priv->ipw_rfkill_path
	    && g_file_get_contents (priv->ipw_rfkill_path, &contents, NULL, NULL)) {
		contents = g_strstrip (contents);

		/* 0 - RF kill not enabled
		 * 1 - SW based RF kill active (sysfs)
		 * 2 - HW based RF kill active
		 * 3 - Both HW and SW baed RF kill active
		 */
		switch (contents[0]) {
		case '1':
			state = RFKILL_SOFT_BLOCKED;
			str_state = "soft-blocked";
			break;
		case '2':
		case '3':
			state = RFKILL_HARD_BLOCKED;
			str_state = "hard-blocked";
			break;
		case '0':
			str_state = "unblocked";
		default:
			break;
		}
		g_free (contents);

		nm_log_dbg (LOGD_RFKILL, "(%s): ipw rfkill state '%s'",
		            nm_device_get_iface (NM_DEVICE (self)),
		            str_state ? str_state : "(unknown)");
	}

	return state;
}

static gboolean
ipw_rfkill_state_work (gpointer user_data)
{
	NMDeviceWifi *self = NM_DEVICE_WIFI (user_data);
	NMDeviceWifiPrivate *priv = NM_DEVICE_WIFI_GET_PRIVATE (self);
	RfKillState old_state;

	old_state = priv->ipw_rfkill_state;
	priv->ipw_rfkill_state = nm_device_wifi_get_ipw_rfkill_state (self);
	if (priv->ipw_rfkill_state != old_state)
		g_object_notify (G_OBJECT (self), NM_DEVICE_WIFI_IPW_RFKILL_STATE);

	return TRUE;
}

/*****************************************************************/

/*
 * wireless_qual_to_percent
 *
 * Convert an iw_quality structure from SIOCGIWSTATS into a magical signal
 * strength percentage.
 *
 */
static int
wireless_qual_to_percent (const struct iw_quality *qual,
                          const struct iw_quality *max_qual)
{
	int percent = -1;
	int level_percent = -1;

	g_return_val_if_fail (qual != NULL, -1);
	g_return_val_if_fail (max_qual != NULL, -1);

	nm_log_dbg (LOGD_WIFI,
	            "QL: qual %d/%u/0x%X, level %d/%u/0x%X, noise %d/%u/0x%X, updated: 0x%X  ** MAX: qual %d/%u/0x%X, level %d/%u/0x%X, noise %d/%u/0x%X, updated: 0x%X",
	            (__s8) qual->qual, qual->qual, qual->qual,
	            (__s8) qual->level, qual->level, qual->level,
	            (__s8) qual->noise, qual->noise, qual->noise,
	            qual->updated,
	            (__s8) max_qual->qual, max_qual->qual, max_qual->qual,
	            (__s8) max_qual->level, max_qual->level, max_qual->level,
	            (__s8) max_qual->noise, max_qual->noise, max_qual->noise,
	            max_qual->updated);

	/* Try using the card's idea of the signal quality first as long as it tells us what the max quality is.
	 * Drivers that fill in quality values MUST treat them as percentages, ie the "Link Quality" MUST be 
	 * bounded by 0 and max_qual->qual, and MUST change in a linear fashion.  Within those bounds, drivers
	 * are free to use whatever they want to calculate "Link Quality".
	 */
	if ((max_qual->qual != 0) && !(max_qual->updated & IW_QUAL_QUAL_INVALID) && !(qual->updated & IW_QUAL_QUAL_INVALID))
		percent = (int)(100 * ((double)qual->qual / (double)max_qual->qual));

	/* If the driver doesn't specify a complete and valid quality, we have two options:
	 *
	 * 1) dBm: driver must specify max_qual->level = 0, and have valid values for
	 *        qual->level and (qual->noise OR max_qual->noise)
	 * 2) raw RSSI: driver must specify max_qual->level > 0, and have valid values for
	 *        qual->level and max_qual->level
	 *
	 * This is the WEXT spec.  If this interpretation is wrong, I'll fix it.  Otherwise,
	 * If drivers don't conform to it, they are wrong and need to be fixed.
	 */

	if (    (max_qual->level == 0) && !(max_qual->updated & IW_QUAL_LEVEL_INVALID)          /* Valid max_qual->level == 0 */
		&& !(qual->updated & IW_QUAL_LEVEL_INVALID)                                     /* Must have valid qual->level */
		&& (    ((max_qual->noise > 0) && !(max_qual->updated & IW_QUAL_NOISE_INVALID)) /* Must have valid max_qual->noise */
			|| ((qual->noise > 0) && !(qual->updated & IW_QUAL_NOISE_INVALID)))     /*    OR valid qual->noise */
	   ) {
		/* Absolute power values (dBm) */

		/* Reasonable fallbacks for dumb drivers that don't specify either level. */
		#define FALLBACK_NOISE_FLOOR_DBM  -90
		#define FALLBACK_SIGNAL_MAX_DBM   -20
		int max_level = FALLBACK_SIGNAL_MAX_DBM;
		int noise = FALLBACK_NOISE_FLOOR_DBM;
		int level = qual->level - 0x100;

		level = CLAMP (level, FALLBACK_NOISE_FLOOR_DBM, FALLBACK_SIGNAL_MAX_DBM);

		if ((qual->noise > 0) && !(qual->updated & IW_QUAL_NOISE_INVALID))
			noise = qual->noise - 0x100;
		else if ((max_qual->noise > 0) && !(max_qual->updated & IW_QUAL_NOISE_INVALID))
			noise = max_qual->noise - 0x100;
		noise = CLAMP (noise, FALLBACK_NOISE_FLOOR_DBM, FALLBACK_SIGNAL_MAX_DBM);

		/* A sort of signal-to-noise ratio calculation */
		level_percent = (int)(100 - 70 *(
		                                ((double)max_level - (double)level) /
		                                ((double)max_level - (double)noise)));
		nm_log_dbg (LOGD_WIFI, "QL1: level_percent is %d.  max_level %d, level %d, noise_floor %d.",
		            level_percent, max_level, level, noise);
	} else if (   (max_qual->level != 0)
	           && !(max_qual->updated & IW_QUAL_LEVEL_INVALID) /* Valid max_qual->level as upper bound */
	           && !(qual->updated & IW_QUAL_LEVEL_INVALID)) {
		/* Relative power values (RSSI) */

		int level = qual->level;

		/* Signal level is relavtive (0 -> max_qual->level) */
		level = CLAMP (level, 0, max_qual->level);
		level_percent = (int)(100 * ((double)level / (double)max_qual->level));
		nm_log_dbg (LOGD_WIFI, "QL2: level_percent is %d.  max_level %d, level %d.",
		            level_percent, max_qual->level, level);
	} else if (percent == -1) {
		nm_log_dbg (LOGD_WIFI, "QL: Could not get quality %% value from driver.  Driver is probably buggy.");
	}

	/* If the quality percent was 0 or doesn't exist, then try to use signal levels instead */
	if ((percent < 1) && (level_percent >= 0))
		percent = level_percent;

	nm_log_dbg (LOGD_WIFI, "QL: Final quality percent is %d (%d).",
	            percent, CLAMP (percent, 0, 100));
	return (CLAMP (percent, 0, 100));
}


/*
 * nm_device_wifi_update_signal_strength
 *
 * Update the device's idea of the strength of its connection to the
 * current access point.
 *
 */
static void
nm_device_wifi_update_signal_strength (NMDeviceWifi *self,
                                       NMAccessPoint *ap)
{
	NMDeviceWifiPrivate *priv = NM_DEVICE_WIFI_GET_PRIVATE (self);
	const char *iface = nm_device_get_iface (NM_DEVICE (self));
	int fd, percent = -1;

	fd = socket (PF_INET, SOCK_DGRAM, 0);
	if (fd >= 0) {
		struct iwreq wrq;
		struct iw_statistics stats;

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

		wrq.u.data.pointer = &stats;
		wrq.u.data.length = sizeof (stats);
		wrq.u.data.flags = 1;  /* Clear updated flag */
		strncpy (wrq.ifr_name, iface, IFNAMSIZ);

		if (ioctl (fd, SIOCGIWSTATS, &wrq) == 0)
			percent = wireless_qual_to_percent (&stats.qual, &priv->max_qual);
		close (fd);
	}

	/* Try to smooth out the strength.  Atmel cards, for example, will give no strength
	 * one second and normal strength the next.
	 */
	if (percent >= 0 || ++priv->invalid_strength_counter > 3) {
		nm_ap_set_strength (ap, (gint8) percent);
		priv->invalid_strength_counter = 0;
	}
}


static gboolean
wireless_get_range (NMDeviceWifi *self,
                    struct iw_range *range,
                    guint32 *response_len)
{
	int fd, i = 26;
	gboolean success = FALSE;
	const char *iface;
	struct iwreq wrq;

	g_return_val_if_fail (NM_IS_DEVICE_WIFI (self), FALSE);
	g_return_val_if_fail (range != NULL, FALSE);

	iface = nm_device_get_iface (NM_DEVICE (self));

	fd = socket (PF_INET, SOCK_DGRAM, 0);
	if (fd < 0) {
		nm_log_err (LOGD_HW, "(%s): couldn't open control socket.", iface);
		return FALSE;
	}

	memset (&wrq, 0, sizeof (struct iwreq));
	strncpy (wrq.ifr_name, iface, IFNAMSIZ);
	wrq.u.data.pointer = (caddr_t) range;
	wrq.u.data.length = sizeof (struct iw_range);

	/* Need to give some drivers time to recover after suspend/resume
	 * (ex ipw3945 takes a few seconds to talk to its regulatory daemon;
	 * see rh bz#362421)
	 */
	while (i-- > 0) {
		if (ioctl (fd, SIOCGIWRANGE, &wrq) == 0) {
			if (response_len)
				*response_len = wrq.u.data.length;
			success = TRUE;
			break;
		} else if (errno != EAGAIN) {
			nm_log_err (LOGD_HW | LOGD_WIFI,
			            "(%s): couldn't get driver range information (%d).",
			            iface, errno);
			break;
		}

		g_usleep (G_USEC_PER_SEC / 4);
	}

	if (i <= 0) {
		nm_log_warn (LOGD_HW | LOGD_WIFI,
		             "(%s): driver took too long to respond to IWRANGE query.",
		             iface);
	}

	close (fd);
	return success;
}

static guint32
real_get_generic_capabilities (NMDevice *dev)
{
	int fd, err;
	guint32 caps = NM_DEVICE_CAP_NONE;
	struct iwreq wrq;
	const char *iface = nm_device_get_iface (dev);

	fd = socket (PF_INET, SOCK_DGRAM, 0);
	if (fd < 0) {
		nm_log_err (LOGD_HW, "(%s): couldn't open control socket.", iface);
		return NM_DEVICE_CAP_NONE;
	}

	/* Cards that don't scan aren't supported */
	memset (&wrq, 0, sizeof (struct iwreq));
	strncpy (wrq.ifr_name, iface, IFNAMSIZ);
	err = ioctl (fd, SIOCSIWSCAN, &wrq);
	close (fd);
	if ((err < 0) && (errno == EOPNOTSUPP))
		caps = NM_DEVICE_CAP_NONE;
	else
		caps |= NM_DEVICE_CAP_NM_SUPPORTED;

	return caps;
}

#define WPA_CAPS (NM_WIFI_DEVICE_CAP_CIPHER_TKIP | \
                  NM_WIFI_DEVICE_CAP_CIPHER_CCMP | \
                  NM_WIFI_DEVICE_CAP_WPA | \
                  NM_WIFI_DEVICE_CAP_RSN)

static guint32
get_wireless_capabilities (NMDeviceWifi *self, iwrange *range)
{
	guint32 caps = NM_WIFI_DEVICE_CAP_NONE;
	const char * iface;

	g_return_val_if_fail (self != NULL, NM_WIFI_DEVICE_CAP_NONE);
	g_return_val_if_fail (range != NULL, NM_WIFI_DEVICE_CAP_NONE);

	iface = nm_device_get_iface (NM_DEVICE (self));

	/* All drivers should support WEP by default */
	caps |= NM_WIFI_DEVICE_CAP_CIPHER_WEP40 | NM_WIFI_DEVICE_CAP_CIPHER_WEP104;

	if (range->enc_capa & IW_ENC_CAPA_CIPHER_TKIP)
		caps |= NM_WIFI_DEVICE_CAP_CIPHER_TKIP;

	if (range->enc_capa & IW_ENC_CAPA_CIPHER_CCMP)
		caps |= NM_WIFI_DEVICE_CAP_CIPHER_CCMP;

	if (range->enc_capa & IW_ENC_CAPA_WPA)
		caps |= NM_WIFI_DEVICE_CAP_WPA;

	if (range->enc_capa & IW_ENC_CAPA_WPA2)
		caps |= NM_WIFI_DEVICE_CAP_RSN;

	/* Check for cipher support but not WPA support */
	if (    (caps & (NM_WIFI_DEVICE_CAP_CIPHER_TKIP | NM_WIFI_DEVICE_CAP_CIPHER_CCMP))
	    && !(caps & (NM_WIFI_DEVICE_CAP_WPA | NM_WIFI_DEVICE_CAP_RSN))) {
		nm_log_warn (LOGD_WIFI, "%s: device supports WPA ciphers but not WPA protocol; "
		             "WPA unavailable.", iface);
		caps &= ~WPA_CAPS;
	}

	/* Check for WPA support but not cipher support */
	if (    (caps & (NM_WIFI_DEVICE_CAP_WPA | NM_WIFI_DEVICE_CAP_RSN))
	    && !(caps & (NM_WIFI_DEVICE_CAP_CIPHER_TKIP | NM_WIFI_DEVICE_CAP_CIPHER_CCMP))) {
		nm_log_warn (LOGD_WIFI, "%s: device supports WPA protocol but not WPA ciphers; "
		             "WPA unavailable.", iface);
		caps &= ~WPA_CAPS;
	}

	return caps;
}


static guint32 iw_freq_to_uint32 (struct iw_freq *freq)
{
	if (freq->e == 0) {
		/* Some drivers report channel not frequency.  Convert to a
		 * frequency; but this assumes that the device is in b/g mode.
		 */
		if ((freq->m >= 1) && (freq->m <= 13))
			return 2407 + (5 * freq->m);
		else if (freq->m == 14)
			return 2484;
	}

	return (guint32) (((double) freq->m) * pow (10, freq->e) / 1000000);
}


/* Until a new wireless-tools comes out that has the defs and the structure,
 * need to copy them here.
 */
/* Scan capability flags - in (struct iw_range *)->scan_capa */
#define NM_IW_SCAN_CAPA_NONE    0x00
#define NM_IW_SCAN_CAPA_ESSID   0x01

struct iw_range_with_scan_capa
{
	guint32 throughput;
	guint32 min_nwid;
	guint32 max_nwid;
	guint16 old_num_channels;
	guint8  old_num_frequency;

	guint8  scan_capa;
/* don't need the rest... */
};


static GObject*
constructor (GType type,
             guint n_construct_params,
             GObjectConstructParam *construct_params)
{
	GObject *object;
	GObjectClass *klass;
	NMDeviceWifi *self;
	NMDeviceWifiPrivate *priv;
	struct iw_range range;
	struct iw_range_with_scan_capa *scan_capa_range;
	guint32 response_len = 0;
	gboolean success;
	int i;

	klass = G_OBJECT_CLASS (nm_device_wifi_parent_class);
	object = klass->constructor (type, n_construct_params, construct_params);
	if (!object)
		return NULL;

	self = NM_DEVICE_WIFI (object);
	priv = NM_DEVICE_WIFI_GET_PRIVATE (self);

	nm_log_dbg (LOGD_HW | LOGD_WIFI, "(%s): kernel ifindex %d",
	            nm_device_get_iface (NM_DEVICE (self)),
	            nm_device_get_ifindex (NM_DEVICE (self)));

	memset (&range, 0, sizeof (struct iw_range));
	success = wireless_get_range (NM_DEVICE_WIFI (object), &range, &response_len);
	if (!success) {
		nm_log_info (LOGD_HW | LOGD_WIFI, "(%s): driver WEXT range request failed",
		             nm_device_get_iface (NM_DEVICE (self)));
		goto error;
	}

	if ((response_len < 300) || (range.we_version_compiled < 21)) {
		nm_log_info (LOGD_HW | LOGD_WIFI,
		             "(%s): driver WEXT version too old (got %d, expected >= 21)",
		             nm_device_get_iface (NM_DEVICE (self)),
		             range.we_version_compiled);
		goto error;
	}

	priv->max_qual.qual = range.max_qual.qual;
	priv->max_qual.level = range.max_qual.level;
	priv->max_qual.noise = range.max_qual.noise;
	priv->max_qual.updated = range.max_qual.updated;

	priv->num_freqs = MIN (range.num_frequency, IW_MAX_FREQUENCIES);
	for (i = 0; i < priv->num_freqs; i++)
		priv->freqs[i] = iw_freq_to_uint32 (&range.freq[i]);

	/* Check for the ability to scan specific SSIDs.  Until the scan_capa
	 * field gets added to wireless-tools, need to work around that by casting
	 * to the custom structure.
	 */
	scan_capa_range = (struct iw_range_with_scan_capa *) &range;
	if (scan_capa_range->scan_capa & NM_IW_SCAN_CAPA_ESSID) {
		priv->has_scan_capa_ssid = TRUE;
		nm_log_info (LOGD_HW | LOGD_WIFI,
		             "(%s): driver supports SSID scans (scan_capa 0x%02X).",
		             nm_device_get_iface (NM_DEVICE (self)),
		             scan_capa_range->scan_capa);
	} else {
		nm_log_info (LOGD_HW | LOGD_WIFI,
		             "(%s): driver does not support SSID scans (scan_capa 0x%02X).",
		             nm_device_get_iface (NM_DEVICE (self)),
		             scan_capa_range->scan_capa);
	}

	/* 802.11 wireless-specific capabilities */
	priv->capabilities = get_wireless_capabilities (self, &range);

	/* Connect to the supplicant manager */
	priv->supplicant.mgr = nm_supplicant_manager_get ();
	g_assert (priv->supplicant.mgr);

	/* The ipw2x00 drivers don't integrate with the kernel rfkill subsystem until
	 * 2.6.33.  Thus all our nice libgudev magic is useless.  So we get to poll.
	 *
	 * FIXME: when 2.6.33 comes lands, we can do some sysfs parkour to figure out
	 * if we need to poll or not by matching /sys/class/net/ethX/device to one
	 * of the /sys/class/rfkill/rfkillX/device links.  If there's a match, we
	 * don't have to poll.
	 */
	priv->ipw_rfkill_path = g_strdup_printf ("/sys/class/net/%s/device/rf_kill",
	                                         nm_device_get_iface (NM_DEVICE (self)));
	if (!g_file_test (priv->ipw_rfkill_path, G_FILE_TEST_IS_REGULAR)) {
		g_free (priv->ipw_rfkill_path);
		priv->ipw_rfkill_path = NULL;
	}
	priv->ipw_rfkill_state = nm_device_wifi_get_ipw_rfkill_state (self);

	return object;

error:
	g_object_unref (object);
	return NULL;
}

static gboolean
supplicant_interface_acquire (NMDeviceWifi *self)
{
	NMDeviceWifiPrivate *priv = NM_DEVICE_WIFI_GET_PRIVATE (self);
	guint id, i = 0;

	g_return_val_if_fail (self != NULL, FALSE);
	/* interface already acquired? */
	g_return_val_if_fail (priv->supplicant.iface == NULL, TRUE);

	priv->supplicant.iface = nm_supplicant_manager_iface_get (priv->supplicant.mgr,
	                                                          nm_device_get_iface (NM_DEVICE (self)),
	                                                          TRUE);
	if (priv->supplicant.iface == NULL) {
		nm_log_err (LOGD_WIFI, "Couldn't initialize supplicant interface for %s.",
		            nm_device_get_iface (NM_DEVICE (self)));
		return FALSE;
	}

	memset (priv->supplicant.sig_ids, 0, sizeof (priv->supplicant.sig_ids));

	id = g_signal_connect (priv->supplicant.iface,
	                       NM_SUPPLICANT_INTERFACE_STATE,
	                       G_CALLBACK (supplicant_iface_state_cb),
	                       self);
	priv->supplicant.sig_ids[i++] = id;

	id = g_signal_connect (priv->supplicant.iface,
	                       NM_SUPPLICANT_INTERFACE_NEW_BSS,
	                       G_CALLBACK (supplicant_iface_new_bss_cb),
	                       self);
	priv->supplicant.sig_ids[i++] = id;

	id = g_signal_connect (priv->supplicant.iface,
	                       NM_SUPPLICANT_INTERFACE_SCAN_DONE,
	                       G_CALLBACK (supplicant_iface_scan_done_cb),
	                       self);
	priv->supplicant.sig_ids[i++] = id;

	id = g_signal_connect (priv->supplicant.iface,
	                       "notify::scanning",
	                       G_CALLBACK (supplicant_iface_notify_scanning_cb),
	                       self);
	priv->supplicant.sig_ids[i++] = id;

	return TRUE;
}

static void
remove_supplicant_interface_error_handler (NMDeviceWifi *self)
{
	NMDeviceWifiPrivate *priv = NM_DEVICE_WIFI_GET_PRIVATE (self);

	if (!priv->supplicant.iface)
		return;

	if (priv->supplicant.iface_error_id > 0) {
		g_signal_handler_disconnect (priv->supplicant.iface, priv->supplicant.iface_error_id);
		priv->supplicant.iface_error_id = 0;
	}

	if (priv->supplicant.iface_con_error_cb_id > 0) {
		g_source_remove (priv->supplicant.iface_con_error_cb_id);
		priv->supplicant.iface_con_error_cb_id = 0;
	}
}

static void
supplicant_interface_release (NMDeviceWifi *self)
{
	NMDeviceWifiPrivate *priv;
	guint i;

	g_return_if_fail (self != NULL);

	priv = NM_DEVICE_WIFI_GET_PRIVATE (self);

	cancel_pending_scan (self);

	/* Reset the scan interval to be pretty frequent when disconnected */
	priv->scan_interval = SCAN_INTERVAL_MIN + SCAN_INTERVAL_STEP;
	nm_log_dbg (LOGD_WIFI_SCAN, "(%s): reset scanning interval to %d seconds",
	            nm_device_get_iface (NM_DEVICE (self)),
	            priv->scan_interval);

	remove_supplicant_interface_error_handler (self);

	/* Clear supplicant interface signal handlers */
	for (i = 0; i < SUP_SIG_ID_LEN; i++) {
		if (priv->supplicant.sig_ids[i] > 0)
			g_signal_handler_disconnect (priv->supplicant.iface, priv->supplicant.sig_ids[i]);
	}
	memset (priv->supplicant.sig_ids, 0, sizeof (priv->supplicant.sig_ids));

	if (priv->supplicant.iface) {
		/* Tell the supplicant to disconnect from the current AP */
		nm_supplicant_interface_disconnect (priv->supplicant.iface);

		nm_supplicant_manager_iface_release (priv->supplicant.mgr, priv->supplicant.iface);
		priv->supplicant.iface = NULL;
	}
}


static NMAccessPoint *
get_ap_by_path (NMDeviceWifi *self, const char *path)
{
	NMDeviceWifiPrivate *priv = NM_DEVICE_WIFI_GET_PRIVATE (self);
	GSList *iter;

	for (iter = priv->ap_list; iter; iter = g_slist_next (iter)) {
		if (strcmp (path, nm_ap_get_dbus_path (NM_AP (iter->data))) == 0)
			return NM_AP (iter->data);
	}
	return NULL;
}

static NMAccessPoint *
get_active_ap (NMDeviceWifi *self,
               NMAccessPoint *ignore_ap,
               gboolean match_hidden)
{
	NMDeviceWifiPrivate *priv = NM_DEVICE_WIFI_GET_PRIVATE (self);
	const char *iface = nm_device_get_iface (NM_DEVICE (self));
	struct ether_addr bssid;
	const GByteArray *ssid;
	GSList *iter;
	int i = 0;
	NMAccessPoint *match_nofreq = NULL;
	gboolean found_a_band = FALSE;
	gboolean found_bg_band = FALSE;
	NM80211Mode devmode;
	guint32 devfreq;

	nm_device_wifi_get_bssid (self, &bssid);
	nm_log_dbg (LOGD_WIFI, "(%s): active BSSID: %02x:%02x:%02x:%02x:%02x:%02x",
	            iface,
	            bssid.ether_addr_octet[0], bssid.ether_addr_octet[1],
	            bssid.ether_addr_octet[2], bssid.ether_addr_octet[3],
	            bssid.ether_addr_octet[4], bssid.ether_addr_octet[5]);

	if (!nm_ethernet_address_is_valid (&bssid))
		return NULL;

	ssid = nm_device_wifi_get_ssid (self);
	nm_log_dbg (LOGD_WIFI, "(%s): active SSID: %s%s%s",
	            iface,
	            ssid ? "'" : "",
	            ssid ? nm_utils_escape_ssid (ssid->data, ssid->len) : "(none)",
	            ssid ? "'" : "");

	devmode = nm_device_wifi_get_mode (self);
	devfreq = nm_device_wifi_get_frequency (self);

	/* When matching hidden APs, do a second pass that ignores the SSID check,
	 * because NM might not yet know the SSID of the hidden AP in the scan list
	 * and therefore it won't get matched the first time around.
	 */
	while (i++ < (match_hidden ? 2 : 1)) {
		nm_log_dbg (LOGD_WIFI, "  Pass #%d %s", i, i > 1 ? "(ignoring SSID)" : "");

		/* Find this SSID + BSSID in the device's AP list */
		for (iter = priv->ap_list; iter; iter = g_slist_next (iter)) {
			NMAccessPoint *ap = NM_AP (iter->data);
			const struct ether_addr	*ap_bssid = nm_ap_get_address (ap);
			const GByteArray *ap_ssid = nm_ap_get_ssid (ap);
			NM80211Mode apmode;
			guint32 apfreq;

			nm_log_dbg (LOGD_WIFI, "    AP: %s%s%s  %02x:%02x:%02x:%02x:%02x:%02x",
			            ap_ssid ? "'" : "",
			            ap_ssid ? nm_utils_escape_ssid (ap_ssid->data, ap_ssid->len) : "(none)",
			            ap_ssid ? "'" : "",
			            ap_bssid->ether_addr_octet[0], ap_bssid->ether_addr_octet[1],
			            ap_bssid->ether_addr_octet[2], ap_bssid->ether_addr_octet[3],
			            ap_bssid->ether_addr_octet[4], ap_bssid->ether_addr_octet[5]);

			if (ignore_ap && (ap == ignore_ap)) {
				nm_log_dbg (LOGD_WIFI, "      ignored");
				continue;
			}

			if (memcmp (bssid.ether_addr_octet, ap_bssid->ether_addr_octet, ETH_ALEN)) {
				nm_log_dbg (LOGD_WIFI, "      BSSID mismatch");
				continue;
			}

			if ((i == 0) && !nm_utils_same_ssid (ssid, ap_ssid, TRUE)) {
				nm_log_dbg (LOGD_WIFI, "      SSID mismatch");
				continue;
			}

			apmode = nm_ap_get_mode (ap);
			if (devmode != apmode) {
				nm_log_dbg (LOGD_WIFI, "      mode mismatch (device %d, ap %d)",
				            devmode, apmode);
				continue;
			}

			apfreq = nm_ap_get_freq (ap);
			if (devfreq != apfreq) {
				nm_log_dbg (LOGD_WIFI, "      frequency mismatch (device %u, ap %u)",
				            devfreq, apfreq);

				if (match_nofreq == NULL)
					match_nofreq = ap;

				if (apfreq > 4000)
					found_a_band = TRUE;
				else if (apfreq > 2000)
					found_bg_band = TRUE;
				continue;
			}

			// FIXME: handle security settings here too
			nm_log_dbg (LOGD_WIFI, "      matched");
			return ap;
		}
	}

	/* Some proprietary drivers (wl.o) report tuned frequency (like when
	 * scanning) instead of the associated AP's frequency.  This is a great
	 * example of how WEXT is underspecified.  We use frequency to find the
	 * active AP in the scan list because some configurations use the same
	 * SSID/BSSID on the 2GHz and 5GHz bands simultaneously, and we need to
	 * make sure we get the right AP in the right band.  This configuration
	 * is uncommon though, and the frequency check penalizes closed drivers we
	 * can't fix.  Because we're not total dicks, ignore the frequency condition
	 * if the associated BSSID/SSID exists only in one band since that's most
	 * likely the AP we want.
	 */
	if (match_nofreq && (found_a_band != found_bg_band)) {
		const struct ether_addr	*ap_bssid = nm_ap_get_address (match_nofreq);
		const GByteArray *ap_ssid = nm_ap_get_ssid (match_nofreq);

		nm_log_dbg (LOGD_WIFI, "    matched %s%s%s  %02x:%02x:%02x:%02x:%02x:%02x",
		            ap_ssid ? "'" : "",
		            ap_ssid ? nm_utils_escape_ssid (ap_ssid->data, ap_ssid->len) : "(none)",
		            ap_ssid ? "'" : "",
		            ap_bssid->ether_addr_octet[0], ap_bssid->ether_addr_octet[1],
		            ap_bssid->ether_addr_octet[2], ap_bssid->ether_addr_octet[3],
		            ap_bssid->ether_addr_octet[4], ap_bssid->ether_addr_octet[5]);

		return match_nofreq;
	}

	nm_log_dbg (LOGD_WIFI, "  No matching AP found.");
	return NULL;
}

static void
update_seen_bssids_cache (NMDeviceWifi *self, NMAccessPoint *ap)
{
	NMActRequest *req;
	NMConnection *connection;

	g_return_if_fail (NM_IS_DEVICE_WIFI (self));
	
	if (ap == NULL)
		return;

	/* Don't cache the BSSID for Ad-Hoc APs */
	if (nm_ap_get_mode (ap) != NM_802_11_MODE_INFRA)
		return;

	if (nm_device_get_state (NM_DEVICE (self)) == NM_DEVICE_STATE_ACTIVATED) {
		req = nm_device_get_act_request (NM_DEVICE (self));
		if (req) {
			connection = nm_act_request_get_connection (req);
			nm_settings_connection_add_seen_bssid (NM_SETTINGS_CONNECTION (connection),
			                                       nm_ap_get_address (ap));
		}
	}
}

static void
set_current_ap (NMDeviceWifi *self, NMAccessPoint *new_ap)
{
	NMDeviceWifiPrivate *priv;
	char *old_path = NULL;
	NMAccessPoint *old_ap;

	g_return_if_fail (NM_IS_DEVICE_WIFI (self));

	priv = NM_DEVICE_WIFI_GET_PRIVATE (self);
	old_ap = priv->current_ap;

	if (old_ap) {
		old_path = g_strdup (nm_ap_get_dbus_path (old_ap));
		priv->current_ap = NULL;
	}

	if (new_ap) {
		priv->current_ap = g_object_ref (new_ap);

		/* Move the current AP to the front of the scan list.  Since we
		 * do a lot of searches looking for the current AP, it saves
		 * time to have it in front.
		 */
		priv->ap_list = g_slist_remove (priv->ap_list, new_ap);
		priv->ap_list = g_slist_prepend (priv->ap_list, new_ap);

		/* Update seen BSSIDs cache */
		update_seen_bssids_cache (self, priv->current_ap);
	}

	/* Unref old AP here to ensure object lives if new_ap == old_ap */
	if (old_ap)
		g_object_unref (old_ap);

	/* Only notify if it's really changed */
	if (   (!old_path && new_ap)
	    || (old_path && !new_ap)
	    || (old_path && new_ap && strcmp (old_path, nm_ap_get_dbus_path (new_ap))))
		g_object_notify (G_OBJECT (self), NM_DEVICE_WIFI_ACTIVE_ACCESS_POINT);

	g_free (old_path);
}

static void
periodic_update (NMDeviceWifi *self)
{
	NMDeviceWifiPrivate *priv = NM_DEVICE_WIFI_GET_PRIVATE (self);
	NMAccessPoint *new_ap;
	guint32 new_rate;

	/* In IBSS mode, most newer firmware/drivers do "BSS coalescing" where
	 * multiple IBSS stations using the same SSID will eventually switch to
	 * using the same BSSID to avoid network segmentation.  When this happens,
	 * the card's reported BSSID will change, but the the new BSS may not
	 * be in the scan list, since scanning isn't done in ad-hoc mode for
	 * various reasons.  So pull the BSSID from the card and update the
	 * current AP with it, if the current AP is adhoc.
	 */
	if (priv->current_ap && (nm_ap_get_mode (priv->current_ap) == NM_802_11_MODE_ADHOC)) {
		struct ether_addr bssid = { {0x0, 0x0, 0x0, 0x0, 0x0, 0x0} };

		nm_device_wifi_get_bssid (self, &bssid);
		/* 0x02 means "locally administered" and should be OR-ed into
		 * the first byte of IBSS BSSIDs.
		 */
		if (   (bssid.ether_addr_octet[0] & 0x02)
		    && nm_ethernet_address_is_valid (&bssid))
			nm_ap_set_address (priv->current_ap, &bssid);
	}

	new_ap = get_active_ap (self, NULL, FALSE);
	if (new_ap)
		nm_device_wifi_update_signal_strength (self, new_ap);

	if ((new_ap || priv->current_ap) && (new_ap != priv->current_ap)) {
		const struct ether_addr *new_bssid = NULL;
		const GByteArray *new_ssid = NULL;
		const struct ether_addr *old_bssid = NULL;
		const GByteArray *old_ssid = NULL;
		char *old_addr = NULL, *new_addr = NULL;

		if (new_ap) {
			new_bssid = nm_ap_get_address (new_ap);
			new_addr = nm_ether_ntop (new_bssid);
			new_ssid = nm_ap_get_ssid (new_ap);
		}

		if (priv->current_ap) {
			old_bssid = nm_ap_get_address (priv->current_ap);
			old_addr = nm_ether_ntop (old_bssid);
			old_ssid = nm_ap_get_ssid (priv->current_ap);
		}

		nm_log_info (LOGD_WIFI, "(%s): roamed from BSSID %s (%s) to %s (%s)",
		             nm_device_get_iface (NM_DEVICE (self)),
		             old_addr ? old_addr : "(none)",
		             old_ssid ? nm_utils_escape_ssid (old_ssid->data, old_ssid->len) : "(none)",
		             new_addr ? new_addr : "(none)",
		             new_ssid ? nm_utils_escape_ssid (new_ssid->data, new_ssid->len) : "(none)");
		g_free (old_addr);
		g_free (new_addr);

		set_current_ap (self, new_ap);
	}

	new_rate = nm_device_wifi_get_bitrate (self);
	if (new_rate != priv->rate) {
		priv->rate = new_rate;
		g_object_notify (G_OBJECT (self), NM_DEVICE_WIFI_BITRATE);
	}
}

/*
 * nm_device_wifi_periodic_update
 *
 * Periodically update device statistics.
 *
 */
static gboolean
nm_device_wifi_periodic_update (gpointer data)
{
	NMDeviceWifi *self = NM_DEVICE_WIFI (data);
	NMDeviceWifiPrivate *priv = NM_DEVICE_WIFI_GET_PRIVATE (self);
	NMDeviceState state;

	/* BSSID and signal strength have meaningful values only if the device
	   is activated and not scanning */
	state = nm_device_get_state (NM_DEVICE (self));
	if (state != NM_DEVICE_STATE_ACTIVATED)
		goto out;

	if (nm_supplicant_interface_get_scanning (priv->supplicant.iface))
		goto out;

	periodic_update (self);

out:
	return TRUE;
}

static gboolean
real_hw_is_up (NMDevice *device)
{
	return nm_system_device_is_up (device);
}

static gboolean
real_hw_bring_up (NMDevice *device, gboolean *no_firmware)
{
	if (!NM_DEVICE_WIFI_GET_PRIVATE (device)->enabled)
		return FALSE;

	return nm_system_device_set_up_down (device, TRUE, no_firmware);
}

static void
real_hw_take_down (NMDevice *dev)
{
	nm_system_device_set_up_down (dev, FALSE, NULL);
}

static gboolean
real_is_up (NMDevice *device)
{
	if (!NM_DEVICE_WIFI_GET_PRIVATE (device)->periodic_source_id)
		return FALSE;

	return TRUE;
}

static gboolean
real_bring_up (NMDevice *dev)
{
	NMDeviceWifi *self = NM_DEVICE_WIFI (dev);
	NMDeviceWifiPrivate *priv = NM_DEVICE_WIFI_GET_PRIVATE (self);

	priv->periodic_source_id = g_timeout_add_seconds (6, nm_device_wifi_periodic_update, self);
	return TRUE;
}

static void
_update_hw_addr (NMDeviceWifi *self, const guint8 *addr)
{
	NMDeviceWifiPrivate *priv = NM_DEVICE_WIFI_GET_PRIVATE (self);

	g_return_if_fail (addr != NULL);

	if (memcmp (&priv->hw_addr, addr, ETH_ALEN)) {
		memcpy (&priv->hw_addr, addr, ETH_ALEN);
		g_object_notify (G_OBJECT (self), NM_DEVICE_WIFI_HW_ADDRESS);
	}
}

static gboolean
_set_hw_addr (NMDeviceWifi *self, const guint8 *addr, const char *detail)
{
	NMDevice *dev = NM_DEVICE (self);
	NMDeviceWifiPrivate *priv = NM_DEVICE_WIFI_GET_PRIVATE (self);
	const char *iface;
	char *mac_str = NULL;
	gboolean success = FALSE;

	g_return_val_if_fail (addr != NULL, FALSE);

	iface = nm_device_get_iface (dev);

	mac_str = g_strdup_printf ("%02X:%02X:%02X:%02X:%02X:%02X",
	                           addr[0], addr[1], addr[2], addr[3], addr[4], addr[5]);

	/* Do nothing if current MAC is same */
	if (!memcmp (&priv->hw_addr, addr, ETH_ALEN)) {
		nm_log_dbg (LOGD_DEVICE | LOGD_ETHER, "(%s): no MAC address change needed", iface);
		g_free (mac_str);
		return TRUE;
	}

	/* Can't change MAC address while device is up */
	real_hw_take_down (dev);

	success = nm_system_device_set_mac (iface, (struct ether_addr *) addr);
	if (success) {
		/* MAC address succesfully changed; update the current MAC to match */
		_update_hw_addr (self, addr);
		nm_log_info (LOGD_DEVICE | LOGD_ETHER, "(%s): %s MAC address to %s",
		             iface, detail, mac_str);
	} else {
		nm_log_warn (LOGD_DEVICE | LOGD_ETHER, "(%s): failed to %s MAC address to %s",
		             iface, detail, mac_str);
	}
	real_hw_bring_up (dev, NULL);
	g_free (mac_str);

	return success;
}

static void
access_point_removed (NMDeviceWifi *device, NMAccessPoint *ap)
{
	g_signal_emit (device, signals[ACCESS_POINT_REMOVED], 0, ap);
}

static void
remove_all_aps (NMDeviceWifi *self)
{
	NMDeviceWifiPrivate *priv = NM_DEVICE_WIFI_GET_PRIVATE (self);

	/* Remove outdated APs */
	while (g_slist_length (priv->ap_list)) {
		NMAccessPoint *ap = NM_AP (priv->ap_list->data);

		access_point_removed (self, ap);
		priv->ap_list = g_slist_remove (priv->ap_list, ap);
		g_object_unref (ap);
	}
	g_slist_free (priv->ap_list);
	priv->ap_list = NULL;
}

static void
real_take_down (NMDevice *dev)
{
	NMDeviceWifi *self = NM_DEVICE_WIFI (dev);
	NMDeviceWifiPrivate *priv = NM_DEVICE_WIFI_GET_PRIVATE (self);

	if (priv->periodic_source_id) {
		g_source_remove (priv->periodic_source_id);
		priv->periodic_source_id = 0;
	}

	cleanup_association_attempt (self, TRUE);
	set_current_ap (self, NULL);
	remove_all_aps (self);
}

static void
real_deactivate (NMDevice *dev)
{
	NMDeviceWifi *self = NM_DEVICE_WIFI (dev);
	NMDeviceWifiPrivate *priv = NM_DEVICE_WIFI_GET_PRIVATE (self);
	NMAccessPoint *orig_ap = nm_device_wifi_get_activation_ap (self);
	NMActRequest *req;
	NMConnection *connection;

	req = nm_device_get_act_request (dev);
	if (req) {
		connection = nm_act_request_get_connection (req);
		/* Clear wireless secrets tries when deactivating */
		g_object_set_data (G_OBJECT (connection), WIRELESS_SECRETS_TRIES, NULL);
	}

	cleanup_association_attempt (self, TRUE);

	set_current_ap (self, NULL);
	priv->rate = 0;

	/* If the AP is 'fake', i.e. it wasn't actually found from
	 * a scan but the user tried to connect to it manually (maybe it
	 * was non-broadcasting or something) get rid of it, because 'fake'
	 * APs should only live for as long as we're connected to them.  Fixes
	 * a bug where user-created Ad-Hoc APs are never removed from the scan
	 * list, because scanning is disabled while in Ad-Hoc mode (for stability),
	 * and thus the AP culling never happens. (bgo #569241)
	 */
	if (orig_ap && nm_ap_get_fake (orig_ap)) {
		access_point_removed (self, orig_ap);
		priv->ap_list = g_slist_remove (priv->ap_list, orig_ap);
		g_object_unref (orig_ap);
	}

	/* Reset MAC address back to initial address */
	_set_hw_addr (self, priv->initial_hw_addr, "reset");

	/* Ensure we're in infrastructure mode after deactivation; some devices
	 * (usually older ones) don't scan well in adhoc mode.
	 */
	nm_device_wifi_set_mode (self, NM_802_11_MODE_INFRA);
}

static gboolean
real_check_connection_compatible (NMDevice *device,
                                  NMConnection *connection,
                                  GError **error)
{
	NMDeviceWifi *self = NM_DEVICE_WIFI (device);
	NMDeviceWifiPrivate *priv = NM_DEVICE_WIFI_GET_PRIVATE (self);
	NMSettingConnection *s_con;
	NMSettingWireless *s_wireless;
	const GByteArray *mac;
	const GSList *mac_blacklist, *mac_blacklist_iter;

	s_con = NM_SETTING_CONNECTION (nm_connection_get_setting (connection, NM_TYPE_SETTING_CONNECTION));
	g_assert (s_con);

	if (strcmp (nm_setting_connection_get_connection_type (s_con), NM_SETTING_WIRELESS_SETTING_NAME)) {
		g_set_error (error,
		             NM_WIFI_ERROR, NM_WIFI_ERROR_CONNECTION_NOT_WIRELESS,
		             "The connection was not a WiFi connection.");
		return FALSE;
	}

	s_wireless = NM_SETTING_WIRELESS (nm_connection_get_setting (connection, NM_TYPE_SETTING_WIRELESS));
	if (!s_wireless) {
		g_set_error (error,
		             NM_WIFI_ERROR, NM_WIFI_ERROR_CONNECTION_INVALID,
		             "The connection was not a valid WiFi connection.");
		return FALSE;
	}

	mac = nm_setting_wireless_get_mac_address (s_wireless);
	if (mac && memcmp (mac->data, &priv->perm_hw_addr, ETH_ALEN)) {
		g_set_error (error,
		             NM_WIFI_ERROR, NM_WIFI_ERROR_CONNECTION_INCOMPATIBLE,
		             "The connection's MAC address did not match this device.");
		return FALSE;
	}

	/* Check for MAC address blacklist */
	mac_blacklist = nm_setting_wireless_get_mac_address_blacklist (s_wireless);
	for (mac_blacklist_iter = mac_blacklist; mac_blacklist_iter;
	     mac_blacklist_iter = g_slist_next (mac_blacklist_iter)) {
		struct ether_addr addr;

		if (!ether_aton_r (mac_blacklist_iter->data, &addr)) {
			g_warn_if_reached ();
			continue;
		}
		if (memcmp (&addr, &priv->perm_hw_addr, ETH_ALEN) == 0) {
			g_set_error (error,
			             NM_WIFI_ERROR, NM_WIFI_ERROR_CONNECTION_INCOMPATIBLE,
			             "The connection's MAC address (%s) is blacklisted in %s.",
			             (char *) mac_blacklist_iter->data, NM_SETTING_WIRELESS_MAC_ADDRESS_BLACKLIST);
			return FALSE;
		}
	}

	// FIXME: check channel/freq/band against bands the hardware supports
	// FIXME: check encryption against device capabilities
	// FIXME: check bitrate against device capabilities

	return TRUE;
}

/*
 * List of manufacturer default SSIDs that are often unchanged by users.
 *
 * NOTE: this list should *not* contain networks that you would like to
 * automatically roam to like "Starbucks" or "AT&T" or "T-Mobile HotSpot".
 */
static const char *
manf_defaults[] = {
	"linksys",
	"linksys-a",
	"linksys-g",
	"default",
	"belkin54g",
	"NETGEAR",
	"o2DSL",
	"WLAN",
	"ALICE-WLAN",
};

#define ARRAY_SIZE(a)  (sizeof (a) / sizeof (a[0]))

static gboolean
is_manf_default_ssid (const GByteArray *ssid)
{
	int i;

	for (i = 0; i < ARRAY_SIZE (manf_defaults); i++) {
		if (ssid->len == strlen (manf_defaults[i])) {
			if (memcmp (manf_defaults[i], ssid->data, ssid->len) == 0)
				return TRUE;
		}
	}
	return FALSE;
}

static gboolean
real_complete_connection (NMDevice *device,
                          NMConnection *connection,
                          const char *specific_object,
                          const GSList *existing_connections,
                          GError **error)
{
	NMDeviceWifi *self = NM_DEVICE_WIFI (device);
	NMDeviceWifiPrivate *priv = NM_DEVICE_WIFI_GET_PRIVATE (self);
	NMSettingWireless *s_wifi;
	NMSettingWirelessSecurity *s_wsec;
	NMSetting8021x *s_8021x;
	const GByteArray *setting_mac;
	char *format, *str_ssid = NULL;
	NMAccessPoint *ap = NULL;
	const GByteArray *ssid = NULL;
	GSList *iter;

	s_wifi = nm_connection_get_setting_wireless (connection);
	s_wsec = nm_connection_get_setting_wireless_security (connection);
	s_8021x = nm_connection_get_setting_802_1x (connection);

	if (!specific_object) {
		/* If not given a specific object, we need at minimum an SSID */
		if (!s_wifi) {
			g_set_error_literal (error,
			                     NM_WIFI_ERROR,
			                     NM_WIFI_ERROR_CONNECTION_INVALID,
			                     "A 'wireless' setting is required if no AP path was given.");
			return FALSE;
		}

		ssid = nm_setting_wireless_get_ssid (s_wifi);
		if (!ssid || !ssid->len) {
			g_set_error_literal (error,
			                     NM_WIFI_ERROR,
			                     NM_WIFI_ERROR_CONNECTION_INVALID,
			                     "A 'wireless' setting with a valid SSID is required if no AP path was given.");
			return FALSE;
		}

		/* Find a compatible AP in the scan list */
		for (iter = priv->ap_list; iter; iter = g_slist_next (iter)) {
			if (nm_ap_check_compatible (NM_AP (iter->data), connection)) {
				ap = NM_AP (iter->data);
				break;
			}
		}

		/* If we still don't have an AP, then the WiFI settings needs to be
		 * fully specified by the client.  Might not be able to find an AP
		 * if the network isn't broadcasting the SSID for example.
		 */
		if (!ap) {
			GSList *settings = NULL;
			gboolean valid;

			settings = g_slist_prepend (settings, s_wifi);
			if (s_wsec)
				settings = g_slist_prepend (settings, s_wsec);
			if (s_8021x)
				settings = g_slist_prepend (settings, s_8021x);
			valid = nm_setting_verify (NM_SETTING (s_wifi), settings, error);
			g_slist_free (settings);
			if (!valid)
				return FALSE;
		}
	} else {
		ap = get_ap_by_path (self, specific_object);
		if (!ap) {
			g_set_error (error,
			             NM_WIFI_ERROR,
			             NM_WIFI_ERROR_ACCESS_POINT_NOT_FOUND,
			             "The access point %s was not in the scan list.",
			             specific_object);
			return FALSE;
		}
	}

	/* Add a wifi setting if one doesn't exist yet */
	if (!s_wifi) {
		s_wifi = (NMSettingWireless *) nm_setting_wireless_new ();
		nm_connection_add_setting (connection, NM_SETTING (s_wifi));
	}

	if (ap) {
		ssid = nm_ap_get_ssid (ap);

		if (ssid == NULL) {
			/* The AP must be hidden.  Connecting to a WiFi AP requires the SSID
			 * as part of the initial handshake, so check the connection details
			 * for the SSID.  The AP object will still be used for encryption
			 * settings and such.
			 */
			ssid = nm_setting_wireless_get_ssid (s_wifi);
		}

		if (ssid == NULL) {
			/* If there's no SSID on the AP itself, and no SSID in the
			 * connection data, then we cannot connect at all.  Return an error.
			 */
			g_set_error_literal (error,
			                     NM_WIFI_ERROR,
			                     NM_WIFI_ERROR_CONNECTION_INVALID,
			                     "A 'wireless' setting with a valid SSID is required for hidden access points.");
			return FALSE;
		}

		/* If the SSID is a well-known SSID, lock the connection to the AP's
		 * specific BSSID so NM doesn't autoconnect to some random wifi net.
		 */
		if (!nm_ap_complete_connection (ap,
		                                connection,
		                                is_manf_default_ssid (ssid),
		                                error))
			return FALSE;
	}

	g_assert (ssid);
	str_ssid = nm_utils_ssid_to_utf8 (ssid);
	format = g_strdup_printf ("%s %%d", str_ssid);

	nm_utils_complete_generic (connection,
	                           NM_SETTING_WIRELESS_SETTING_NAME,
	                           existing_connections,
	                           format,
	                           str_ssid,
	                           TRUE);
	g_free (str_ssid);
	g_free (format);

	setting_mac = nm_setting_wireless_get_mac_address (s_wifi);
	if (setting_mac) {
		/* Make sure the setting MAC (if any) matches the device's permanent MAC */
		if (memcmp (setting_mac->data, priv->perm_hw_addr, ETH_ALEN)) {
			g_set_error (error,
				         NM_SETTING_WIRELESS_ERROR,
				         NM_SETTING_WIRELESS_ERROR_INVALID_PROPERTY,
				         NM_SETTING_WIRELESS_MAC_ADDRESS);
			return FALSE;
		}
	} else {
		GByteArray *mac;
		const guint8 null_mac[ETH_ALEN] = { 0, 0, 0, 0, 0, 0 };

		/* Lock the connection to this device by default */
		if (memcmp (priv->perm_hw_addr, null_mac, ETH_ALEN)) {
			mac = g_byte_array_sized_new (ETH_ALEN);
			g_byte_array_append (mac, priv->perm_hw_addr, ETH_ALEN);
			g_object_set (G_OBJECT (s_wifi), NM_SETTING_WIRELESS_MAC_ADDRESS, mac, NULL);
			g_byte_array_free (mac, TRUE);
		}
	}

	return TRUE;
}

static gboolean
real_is_available (NMDevice *dev)
{
	NMDeviceWifi *self = NM_DEVICE_WIFI (dev);
	NMDeviceWifiPrivate *priv = NM_DEVICE_WIFI_GET_PRIVATE (self);
	NMSupplicantInterface *sup_iface;
	guint32 state;

	if (!priv->enabled) {
		nm_log_dbg (LOGD_WIFI, "(%s): not available because not enabled",
		            nm_device_get_iface (dev));
		return FALSE;
	}

	sup_iface = priv->supplicant.iface;
	if (!sup_iface) {
		nm_log_dbg (LOGD_WIFI, "(%s): not available because supplicant not running",
		            nm_device_get_iface (dev));
		return FALSE;
	}

	state = nm_supplicant_interface_get_state (sup_iface);
	if (state != NM_SUPPLICANT_INTERFACE_STATE_READY) {
		nm_log_dbg (LOGD_WIFI, "(%s): not available because supplicant interface not ready",
		            nm_device_get_iface (dev));
		return FALSE;
	}

	return TRUE;
}

static NMConnection *
real_get_best_auto_connection (NMDevice *dev,
                               GSList *connections,
                               char **specific_object)
{
	NMDeviceWifi *self = NM_DEVICE_WIFI (dev);
	NMDeviceWifiPrivate *priv = NM_DEVICE_WIFI_GET_PRIVATE (self);
	GSList *iter, *ap_iter;

	for (iter = connections; iter; iter = g_slist_next (iter)) {
		NMConnection *connection = NM_CONNECTION (iter->data);
		NMSettingConnection *s_con;
		NMSettingWireless *s_wireless;
		const GByteArray *mac;
		const GSList *mac_blacklist, *mac_blacklist_iter;
		gboolean mac_blacklist_found = FALSE;
		NMSettingIP4Config *s_ip4;
		const char *method = NULL;

		s_con = (NMSettingConnection *) nm_connection_get_setting (connection, NM_TYPE_SETTING_CONNECTION);
		if (s_con == NULL)
			continue;
		if (strcmp (nm_setting_connection_get_connection_type (s_con), NM_SETTING_WIRELESS_SETTING_NAME))
			continue;
		if (!nm_setting_connection_get_autoconnect (s_con))
			continue;

		s_wireless = (NMSettingWireless *) nm_connection_get_setting (connection, NM_TYPE_SETTING_WIRELESS);
		if (!s_wireless)
			continue;

		mac = nm_setting_wireless_get_mac_address (s_wireless);
		if (mac && memcmp (mac->data, &priv->perm_hw_addr, ETH_ALEN))
			continue;

		/* Check for MAC address blacklist */
		mac_blacklist = nm_setting_wireless_get_mac_address_blacklist (s_wireless);
		for (mac_blacklist_iter = mac_blacklist; mac_blacklist_iter;
		     mac_blacklist_iter = g_slist_next (mac_blacklist_iter)) {
			struct ether_addr addr;

			if (!ether_aton_r (mac_blacklist_iter->data, &addr)) {
				g_warn_if_reached ();
				continue;
			}
			if (memcmp (&addr, &priv->perm_hw_addr, ETH_ALEN) == 0) {
				mac_blacklist_found = TRUE;
				break;
			}
		}
		/* Found device MAC address in the blacklist - do not use this connection */
		if (mac_blacklist_found)
			continue;

		/* Use the connection if it's a shared connection */
		s_ip4 = (NMSettingIP4Config *) nm_connection_get_setting (connection, NM_TYPE_SETTING_IP4_CONFIG);
		if (s_ip4)
			method = nm_setting_ip4_config_get_method (s_ip4);

		if (s_ip4 && !strcmp (method, NM_SETTING_IP4_CONFIG_METHOD_SHARED))
			return connection;

		for (ap_iter = priv->ap_list; ap_iter; ap_iter = g_slist_next (ap_iter)) {
			NMAccessPoint *ap = NM_AP (ap_iter->data);

			if (nm_ap_check_compatible (ap, connection)) {
				/* All good; connection is usable */
				*specific_object = (char *) nm_ap_get_dbus_path (ap);
				return connection;
			}
		}
	}
	return NULL;
}

/*
 * nm_device_wifi_get_address
 *
 * Get a device's hardware address
 *
 */
void
nm_device_wifi_get_address (NMDeviceWifi *self,
                            struct ether_addr *addr)
{
	NMDeviceWifiPrivate *priv;

	g_return_if_fail (self != NULL);
	g_return_if_fail (addr != NULL);

	priv = NM_DEVICE_WIFI_GET_PRIVATE (self);
	memcpy (addr, &priv->hw_addr, sizeof (struct ether_addr));
}

static void
nm_device_wifi_ap_list_print (NMDeviceWifi *self)
{
	NMDeviceWifiPrivate *priv = NM_DEVICE_WIFI_GET_PRIVATE (self);
	GSList * elt;
	int i = 0;

	g_return_if_fail (NM_IS_DEVICE_WIFI (self));

	nm_log_dbg (LOGD_WIFI_SCAN, "Current AP list:");
	for (elt = priv->ap_list; elt; elt = g_slist_next (elt), i++) {
		NMAccessPoint * ap = NM_AP (elt->data);
		nm_ap_print_self (ap, "AP: ");
	}
	nm_log_dbg (LOGD_WIFI_SCAN, "Current AP list: done");
}

static gboolean
impl_device_get_access_points (NMDeviceWifi *self,
                               GPtrArray **aps,
                               GError **err)
{
	NMDeviceWifiPrivate *priv = NM_DEVICE_WIFI_GET_PRIVATE (self);
	GSList *elt;

	*aps = g_ptr_array_new ();

	for (elt = priv->ap_list; elt; elt = g_slist_next (elt)) {
		NMAccessPoint * ap = NM_AP (elt->data);

		if (nm_ap_get_ssid (ap))
			g_ptr_array_add (*aps, g_strdup (nm_ap_get_dbus_path (ap)));
	}
	return TRUE;
}

/*
 * nm_device_get_mode
 *
 * Get managed/infrastructure/adhoc mode on a device
 *
 */
NM80211Mode
nm_device_wifi_get_mode (NMDeviceWifi *self)
{
	int fd;
	NM80211Mode mode = NM_802_11_MODE_UNKNOWN;
	const char *iface;
	struct iwreq wrq;

	g_return_val_if_fail (self != NULL, NM_802_11_MODE_UNKNOWN);

	fd = socket (PF_INET, SOCK_DGRAM, 0);
	if (fd < 0)
		goto out;

	memset (&wrq, 0, sizeof (struct iwreq));
	iface = nm_device_get_iface (NM_DEVICE (self));
	strncpy (wrq.ifr_name, iface, IFNAMSIZ);

	if (ioctl (fd, SIOCGIWMODE, &wrq) == 0) {
		switch (wrq.u.mode) {
		case IW_MODE_ADHOC:
			mode = NM_802_11_MODE_ADHOC;
			break;
		case IW_MODE_INFRA:
			mode = NM_802_11_MODE_INFRA;
			break;
		default:
			break;
		}
	} else {
		if (errno != ENODEV)
			nm_log_warn (LOGD_HW | LOGD_WIFI, "(%s): error %d getting card mode", iface, errno);
	}
	close (fd);

out:
	return mode;
}


/*
 * nm_device_wifi_set_mode
 *
 * Set managed/infrastructure/adhoc mode on a device
 *
 */
gboolean
nm_device_wifi_set_mode (NMDeviceWifi *self, const NM80211Mode mode)
{
	int fd;
	const char *iface;
	gboolean success = FALSE;
	struct iwreq wrq;

	g_return_val_if_fail (self != NULL, FALSE);
	g_return_val_if_fail ((mode == NM_802_11_MODE_INFRA) || (mode == NM_802_11_MODE_ADHOC), FALSE);

	if (nm_device_wifi_get_mode (self) == mode)
		return TRUE;

	fd = socket (PF_INET, SOCK_DGRAM, 0);
	if (fd < 0)
		goto out;

	memset (&wrq, 0, sizeof (struct iwreq));
	switch (mode) {
	case NM_802_11_MODE_ADHOC:
		wrq.u.mode = IW_MODE_ADHOC;
		break;
	case NM_802_11_MODE_INFRA:
		wrq.u.mode = IW_MODE_INFRA;
		break;
	default:
		goto out;
	}

	iface = nm_device_get_iface (NM_DEVICE (self));
	strncpy (wrq.ifr_name, iface, IFNAMSIZ);

	if (ioctl (fd, SIOCSIWMODE, &wrq) < 0) {
		if (errno != ENODEV)
			nm_log_err (LOGD_HW | LOGD_WIFI, "(%s): error setting mode %d", iface, mode);
	} else
		success = TRUE;
	close (fd);

out:
	return success;
}


/*
 * nm_device_wifi_get_frequency
 *
 * Get current frequency
 *
 */
static guint32
nm_device_wifi_get_frequency (NMDeviceWifi *self)
{
	int fd;
	guint32 freq = 0;
	const char *iface;
	struct iwreq wrq;

	g_return_val_if_fail (self != NULL, 0);

	fd = socket (PF_INET, SOCK_DGRAM, 0);
	if (fd < 0)
		return 0;

	memset (&wrq, 0, sizeof (struct iwreq));
	iface = nm_device_get_iface (NM_DEVICE (self));
	strncpy (wrq.ifr_name, iface, IFNAMSIZ);

	if (ioctl (fd, SIOCGIWFREQ, &wrq) < 0) {
		nm_log_warn (LOGD_HW | LOGD_WIFI,
		             "(%s): error getting frequency: %s",
		             iface, strerror (errno));
	} else
		freq = iw_freq_to_uint32 (&wrq.u.freq);

	close (fd);
	return freq;
}

/*
 * nm_device_wifi_get_ssid
 *
 * If a device is wireless, return the ssid that it is attempting
 * to use.
 */
const GByteArray *
nm_device_wifi_get_ssid (NMDeviceWifi *self)
{
	NMDeviceWifiPrivate *priv;
	int sk;
	struct iwreq wrq;
	char ssid[IW_ESSID_MAX_SIZE + 2];
	guint32 len;

	g_return_val_if_fail (self != NULL, NULL);
	priv = NM_DEVICE_WIFI_GET_PRIVATE (self);

	sk = socket (AF_INET, SOCK_DGRAM, 0);
	if (sk == -1) {
		nm_log_err (LOGD_HW, "couldn't create socket: %d.", errno);
		return NULL;
	}

	memset (ssid, 0, sizeof (ssid));
	wrq.u.essid.pointer = (caddr_t) &ssid;
	wrq.u.essid.length = sizeof (ssid);
	wrq.u.essid.flags = 0;
	strncpy (wrq.ifr_name, nm_device_get_iface (NM_DEVICE (self)), IFNAMSIZ);

	if (ioctl (sk, SIOCGIWESSID, &wrq) < 0) {
		nm_log_err (LOGD_HW | LOGD_WIFI, "(%s): couldn't get SSID: %d",
		            nm_device_get_iface (NM_DEVICE (self)), errno);
		goto out;
	}

	if (priv->ssid) {
		g_byte_array_free (priv->ssid, TRUE);
		priv->ssid = NULL;
	}

	len = wrq.u.essid.length;
	if (!nm_utils_is_empty_ssid ((guint8 *) ssid, len)) {
		priv->ssid = g_byte_array_sized_new (len);
		g_byte_array_append (priv->ssid, (const guint8 *) ssid, len);
	}

out:
	close (sk);
	return priv->ssid;
}


/*
 * nm_device_wifi_get_bitrate
 *
 * For wireless devices, get the bitrate to broadcast/receive at.
 * Returned value is rate in Kb/s.
 *
 */
static guint32
nm_device_wifi_get_bitrate (NMDeviceWifi *self)
{
	int err = -1, fd;
	struct iwreq wrq;

	g_return_val_if_fail (self != NULL, 0);

	fd = socket (PF_INET, SOCK_DGRAM, 0);
	if (fd < 0)
		return 0;

	memset (&wrq, 0, sizeof (wrq));
	strncpy (wrq.ifr_name, nm_device_get_iface (NM_DEVICE (self)), IFNAMSIZ);
	err = ioctl (fd, SIOCGIWRATE, &wrq);
	close (fd);

	return ((err == 0) ? wrq.u.bitrate.value / 1000 : 0);
}

/*
 * nm_device_get_bssid
 *
 * If a device is wireless, get the access point's ethernet address
 * that the card is associated with.
 */
void
nm_device_wifi_get_bssid (NMDeviceWifi *self,
                          struct ether_addr *bssid)
{
	int fd;
	struct iwreq wrq;

	g_return_if_fail (self != NULL);
	g_return_if_fail (bssid != NULL);

	memset (bssid, 0, sizeof (struct ether_addr));

	fd = socket (PF_INET, SOCK_DGRAM, 0);
	if (fd < 0) {
		nm_log_err (LOGD_WIFI, "failed to open control socket.");
		return;
	}

	memset (&wrq, 0, sizeof (wrq));
	strncpy (wrq.ifr_name, nm_device_get_iface (NM_DEVICE (self)), IFNAMSIZ);
	if (ioctl (fd, SIOCGIWAP, &wrq) == 0)
		memcpy (bssid->ether_addr_octet, &(wrq.u.ap_addr.sa_data), ETH_ALEN);

	close (fd);
}


static gboolean
scanning_allowed (NMDeviceWifi *self)
{
	NMDeviceWifiPrivate *priv = NM_DEVICE_WIFI_GET_PRIVATE (self);
	guint32 sup_state;
	NMActRequest *req;

	g_return_val_if_fail (priv->supplicant.iface != NULL, FALSE);

	switch (nm_device_get_state (NM_DEVICE (self))) {
	case NM_DEVICE_STATE_UNKNOWN:
	case NM_DEVICE_STATE_UNMANAGED:
	case NM_DEVICE_STATE_UNAVAILABLE:
	case NM_DEVICE_STATE_PREPARE:
	case NM_DEVICE_STATE_CONFIG:
	case NM_DEVICE_STATE_NEED_AUTH:
	case NM_DEVICE_STATE_IP_CONFIG:
	case NM_DEVICE_STATE_IP_CHECK:
	case NM_DEVICE_STATE_SECONDARIES:
	case NM_DEVICE_STATE_DEACTIVATING:
		/* Don't scan when unusable or activating */
		return FALSE;
	case NM_DEVICE_STATE_DISCONNECTED:
	case NM_DEVICE_STATE_FAILED:
		/* Can always scan when disconnected */
		return TRUE;
	case NM_DEVICE_STATE_ACTIVATED:
		/* Need to do further checks when activated */
		break;
	}

	/* Don't scan if the supplicant is busy */
	sup_state = nm_supplicant_interface_get_state (priv->supplicant.iface);
	if (   sup_state == NM_SUPPLICANT_INTERFACE_STATE_ASSOCIATING
	    || sup_state == NM_SUPPLICANT_INTERFACE_STATE_ASSOCIATED
	    || sup_state == NM_SUPPLICANT_INTERFACE_STATE_4WAY_HANDSHAKE
	    || sup_state == NM_SUPPLICANT_INTERFACE_STATE_GROUP_HANDSHAKE
	    || nm_supplicant_interface_get_scanning (priv->supplicant.iface))
		return FALSE;

	req = nm_device_get_act_request (NM_DEVICE (self));
	if (req) {
		NMConnection *connection;
		NMSettingIP4Config *s_ip4;
		NMSettingWireless *s_wifi;
		const char *ip4_method = NULL;
		const GByteArray *bssid;

		/* Don't scan when a shared connection is active; it makes drivers mad */
		connection = nm_act_request_get_connection (req);
		s_ip4 = (NMSettingIP4Config *) nm_connection_get_setting (connection, NM_TYPE_SETTING_IP4_CONFIG);
		if (s_ip4)
			ip4_method = nm_setting_ip4_config_get_method (s_ip4);

		if (s_ip4 && !strcmp (ip4_method, NM_SETTING_IP4_CONFIG_METHOD_SHARED))
			return FALSE;

		/* Don't scan when the connection is locked to a specifc AP, since
		 * intra-ESS roaming (which requires periodic scanning) isn't being
		 * used due to the specific AP lock. (bgo #513820)
		 */
		s_wifi = (NMSettingWireless *) nm_connection_get_setting (connection, NM_TYPE_SETTING_WIRELESS);
		g_assert (s_wifi);
		bssid = nm_setting_wireless_get_bssid (s_wifi);
		if (bssid && bssid->len == ETH_ALEN)
			return FALSE;
	}

	return TRUE;
}

static gboolean
scanning_allowed_accumulator (GSignalInvocationHint *ihint,
                              GValue *return_accu,
                              const GValue *handler_return,
                              gpointer data)
{
	if (!g_value_get_boolean (handler_return))
		g_value_set_boolean (return_accu, FALSE);
	return TRUE;
}

static gboolean
check_scanning_allowed (NMDeviceWifi *self)
{
	GValue instance = { 0, };
	GValue retval = { 0, };

	g_value_init (&instance, G_TYPE_OBJECT);
	g_value_take_object (&instance, self);

	g_value_init (&retval, G_TYPE_BOOLEAN);
	g_value_set_boolean (&retval, TRUE);

	/* Use g_signal_emitv() rather than g_signal_emit() to avoid the return
	 * value being changed if no handlers are connected */
	g_signal_emitv (&instance, signals[SCANNING_ALLOWED], 0, &retval);

	return g_value_get_boolean (&retval);
}

static gboolean
request_wireless_scan (gpointer user_data)
{
	NMDeviceWifi *self = NM_DEVICE_WIFI (user_data);
	NMDeviceWifiPrivate *priv = NM_DEVICE_WIFI_GET_PRIVATE (self);
	gboolean backoff = FALSE;

	if (check_scanning_allowed (self)) {
		nm_log_dbg (LOGD_WIFI_SCAN, "(%s): scanning requested",
		            nm_device_get_iface (NM_DEVICE (self)));

		if (nm_supplicant_interface_request_scan (priv->supplicant.iface)) {
			/* success */
			backoff = TRUE;
		}
	} else {
		nm_log_dbg (LOGD_WIFI_SCAN, "(%s): scan requested but not allowed at this time",
		            nm_device_get_iface (NM_DEVICE (self)));
	}

	priv->pending_scan_id = 0;
	schedule_scan (self, backoff);
	return FALSE;
}


/*
 * schedule_scan
 *
 * Schedule a wireless scan.
 *
 */
static void
schedule_scan (NMDeviceWifi *self, gboolean backoff)
{
	NMDeviceWifiPrivate *priv = NM_DEVICE_WIFI_GET_PRIVATE (self);
	GTimeVal now;

	g_get_current_time (&now);

	/* Cancel the pending scan if it would happen later than (now + the scan_interval) */
	if (priv->pending_scan_id) {
		if (now.tv_sec + priv->scan_interval < priv->scheduled_scan_time)
			cancel_pending_scan (self);
	}

	if (!priv->pending_scan_id) {
		guint factor = 2, next_scan = priv->scan_interval;

		if (    nm_device_is_activating (NM_DEVICE (self))
		    || (nm_device_get_state (NM_DEVICE (self)) == NM_DEVICE_STATE_ACTIVATED))
			factor = 1;

		priv->pending_scan_id = g_timeout_add_seconds (next_scan,
		                                               request_wireless_scan,
		                                               self);

		priv->scheduled_scan_time = now.tv_sec + priv->scan_interval;
		if (backoff && (priv->scan_interval < (SCAN_INTERVAL_MAX / factor))) {
				priv->scan_interval += (SCAN_INTERVAL_STEP / factor);
				/* Ensure the scan interval will never be less than 20s... */
				priv->scan_interval = MAX(priv->scan_interval, SCAN_INTERVAL_MIN + SCAN_INTERVAL_STEP);
				/* ... or more than 120s */
				priv->scan_interval = MIN(priv->scan_interval, SCAN_INTERVAL_MAX);
		} else if (!backoff && (priv->scan_interval == 0)) {
			/* Invalid combination; would cause continual rescheduling of
			 * the scan and hog CPU.  Reset to something minimally sane.
			 */
			priv->scan_interval = 5;
		}

		nm_log_dbg (LOGD_WIFI_SCAN, "(%s): scheduled scan in %d seconds (interval now %d seconds)",
		            nm_device_get_iface (NM_DEVICE (self)),
		            next_scan,
		            priv->scan_interval);

	}
}


static void
cancel_pending_scan (NMDeviceWifi *self)
{
	NMDeviceWifiPrivate *priv = NM_DEVICE_WIFI_GET_PRIVATE (self);

	if (priv->pending_scan_id) {
		g_source_remove (priv->pending_scan_id);
		priv->pending_scan_id = 0;
	}
}

static void
supplicant_iface_scan_done_cb (NMSupplicantInterface *iface,
                               gboolean success,
                               NMDeviceWifi *self)
{
	nm_log_dbg (LOGD_WIFI_SCAN, "(%s): scan %s",
	            nm_device_get_iface (NM_DEVICE (self)),
	            success ? "successful" : "failed");

	if (check_scanning_allowed (self))
		schedule_scan (self, TRUE);

#if 0
	if (num_results == 0) {
		/* ensure that old APs get culled, which otherwise only
		 * happens when there are actual scan results to process.
		 */
		cull_scan_list (self);
		nm_device_wifi_ap_list_print (self);
	}
#endif
}

static gboolean
is_encrypted (guint32 flags, guint32 wpa_flags, guint32 rsn_flags)
{
	if (flags & NM_802_11_AP_FLAGS_PRIVACY)
		return TRUE;
	if (wpa_flags & (NM_802_11_AP_SEC_KEY_MGMT_PSK | NM_802_11_AP_SEC_KEY_MGMT_802_1X))
		return TRUE;
	if (rsn_flags & (NM_802_11_AP_SEC_KEY_MGMT_PSK | NM_802_11_AP_SEC_KEY_MGMT_802_1X))
		return TRUE;

	return FALSE;
}

/*
 * ap_auth_enforced
 *
 * Checks whether or not there is an encryption key present for
 * this connection, and whether or not the authentication method
 * in use will result in an authentication rejection if the key
 * is wrong.  For example, Ad Hoc mode networks don't have a
 * master node and therefore nothing exists to reject the station.
 * Similarly, Open System WEP access points don't reject a station
 * when the key is wrong.  Shared Key WEP access points will.
 *
 */
static gboolean
ap_auth_enforced (NMConnection *connection,
                  NMAccessPoint *ap,
                  gboolean *encrypted)
{
	guint32 flags, wpa_flags, rsn_flags;
	gboolean enforced = FALSE;

	g_return_val_if_fail (NM_IS_AP (ap), FALSE);
	g_return_val_if_fail (NM_IS_CONNECTION (connection), FALSE);
	g_return_val_if_fail (encrypted != NULL, FALSE);

	flags = nm_ap_get_flags (ap);
	wpa_flags = nm_ap_get_wpa_flags (ap);
	rsn_flags = nm_ap_get_rsn_flags (ap);

	if (nm_ap_get_mode (ap) == NM_802_11_MODE_ADHOC)
		goto out;

	/* Static WEP */
	if (   (flags & NM_802_11_AP_FLAGS_PRIVACY)
        && (wpa_flags == NM_802_11_AP_SEC_NONE)
        && (rsn_flags == NM_802_11_AP_SEC_NONE)) {
		NMSettingWirelessSecurity *s_wireless_sec;
		const char *auth_alg;

		/* No way to tell if the key is wrong with Open System
		 * auth mode in WEP.  Auth is not enforced like Shared Key.
		 */
		s_wireless_sec = (NMSettingWirelessSecurity *) nm_connection_get_setting (connection, 
																    NM_TYPE_SETTING_WIRELESS_SECURITY);
		if (s_wireless_sec) {
			auth_alg = nm_setting_wireless_security_get_auth_alg (s_wireless_sec);
			if (!auth_alg || !strcmp (auth_alg, "open"))
				goto out;
		}

		enforced = TRUE;
	} else if (wpa_flags != NM_802_11_AP_SEC_NONE) { /* WPA */
		enforced = TRUE;
	} else if (rsn_flags != NM_802_11_AP_SEC_NONE) { /* WPA2 */
		enforced = TRUE;
	}

out:
	*encrypted = is_encrypted (flags, wpa_flags, rsn_flags);
	return enforced;
}


/****************************************************************************
 * WPA Supplicant control stuff
 *
 */

/*
 * merge_scanned_ap
 *
 * If there is already an entry that matches the BSSID and ESSID of the
 * AP to merge, replace that entry with the scanned AP.  Otherwise, add
 * the scanned AP to the list.
 *
 * TODO: possibly need to differentiate entries based on security too; i.e. if
 * there are two scan results with the same BSSID and SSID but different
 * security options?
 *
 */
static void
merge_scanned_ap (NMDeviceWifi *self,
                  NMAccessPoint *merge_ap)
{
	NMDeviceWifiPrivate *priv = NM_DEVICE_WIFI_GET_PRIVATE (self);
	NMAccessPoint *found_ap = NULL;
	const GByteArray *ssid;
	gboolean strict_match = TRUE;
	NMAccessPoint *current_ap = NULL;

	/* Let the manager try to fill in the SSID from seen-bssids lists
	 * if it can
	 */
	ssid = nm_ap_get_ssid (merge_ap);
	if (!ssid || nm_utils_is_empty_ssid (ssid->data, ssid->len)) {
		g_signal_emit (self, signals[HIDDEN_AP_FOUND], 0, merge_ap);
		nm_ap_set_broadcast (merge_ap, FALSE);
	}

	/* If the incoming scan result matches the hidden AP that NM is currently
	 * connected to but hasn't been seen in the scan list yet, don't use
	 * strict matching.  Because the capabilities of the fake AP have to be
	 * constructed from the NMConnection of the activation request, they won't
	 * always be the same as the capabilities of the real AP from the scan.
	 */
	current_ap = nm_device_wifi_get_activation_ap (self);
	if (current_ap && nm_ap_get_fake (current_ap))
		strict_match = FALSE;

	found_ap = nm_ap_match_in_list (merge_ap, priv->ap_list, strict_match);
	if (found_ap) {
		nm_ap_set_flags (found_ap, nm_ap_get_flags (merge_ap));
		nm_ap_set_wpa_flags (found_ap, nm_ap_get_wpa_flags (merge_ap));
		nm_ap_set_rsn_flags (found_ap, nm_ap_get_rsn_flags (merge_ap));
		nm_ap_set_strength (found_ap, nm_ap_get_strength (merge_ap));
		nm_ap_set_last_seen (found_ap, nm_ap_get_last_seen (merge_ap));
		nm_ap_set_broadcast (found_ap, nm_ap_get_broadcast (merge_ap));
		nm_ap_set_freq (found_ap, nm_ap_get_freq (merge_ap));
		nm_ap_set_max_bitrate (found_ap, nm_ap_get_max_bitrate (merge_ap));

		/* If the AP is noticed in a scan, it's automatically no longer
		 * fake, since it clearly exists somewhere.
		 */
		nm_ap_set_fake (found_ap, FALSE);
	} else {
		/* New entry in the list */
		// FIXME: figure out if reference counts are correct here for AP objects
		g_object_ref (merge_ap);
		priv->ap_list = g_slist_prepend (priv->ap_list, merge_ap);
		nm_ap_export_to_dbus (merge_ap);
		g_signal_emit (self, signals[ACCESS_POINT_ADDED], 0, merge_ap);
	}
}

static void
cull_scan_list (NMDeviceWifi *self)
{
	NMDeviceWifiPrivate *priv;
	GTimeVal cur_time;
	GSList *outdated_list = NULL;
	GSList *elt;
	NMActRequest *req;
	const char *cur_ap_path = NULL;
	guint32 removed = 0, total = 0;

	g_return_if_fail (self != NULL);
	priv = NM_DEVICE_WIFI_GET_PRIVATE (self);

	g_get_current_time (&cur_time);

	req = nm_device_get_act_request (NM_DEVICE (self));
	if (req)
		cur_ap_path = nm_act_request_get_specific_object (req);

	nm_log_dbg (LOGD_WIFI_SCAN, "(%s): checking scan list for outdated APs",
	            nm_device_get_iface (NM_DEVICE (self)));

	/* Walk the access point list and remove any access points older than
	 * three times the inactive scan interval.
	 */
	for (elt = priv->ap_list; elt; elt = g_slist_next (elt), total++) {
		NMAccessPoint * ap = NM_AP (elt->data);
		const glong     ap_time = nm_ap_get_last_seen (ap);
		gboolean        keep = FALSE;
		const guint     prune_interval_s = SCAN_INTERVAL_MAX * 3;

		/* Don't ever prune the AP we're currently associated with */
		if (cur_ap_path && !strcmp (cur_ap_path, nm_ap_get_dbus_path (ap)))
			keep = TRUE;
		if (nm_ap_get_fake (ap))
			keep = TRUE;

		if (!keep && (ap_time + prune_interval_s < cur_time.tv_sec))
			outdated_list = g_slist_append (outdated_list, ap);
	}

	/* Remove outdated APs */
	for (elt = outdated_list; elt; elt = g_slist_next (elt)) {
		NMAccessPoint *outdated_ap = NM_AP (elt->data);
		const struct ether_addr *bssid;
		const GByteArray *ssid;

		bssid = nm_ap_get_address (outdated_ap);
		ssid = nm_ap_get_ssid (outdated_ap);
		nm_log_dbg (LOGD_WIFI_SCAN,
		            "   removing %02x:%02x:%02x:%02x:%02x:%02x (%s%s%s)",
		            bssid->ether_addr_octet[0], bssid->ether_addr_octet[1],
		            bssid->ether_addr_octet[2], bssid->ether_addr_octet[3],
		            bssid->ether_addr_octet[4], bssid->ether_addr_octet[5],
		            ssid ? "'" : "",
		            ssid ? nm_utils_escape_ssid (ssid->data, ssid->len) : "(none)",
		            ssid ? "'" : "");

		access_point_removed (self, outdated_ap);
		priv->ap_list = g_slist_remove (priv->ap_list, outdated_ap);
		g_object_unref (outdated_ap);
		removed++;
	}
	g_slist_free (outdated_list);

	nm_log_dbg (LOGD_WIFI_SCAN, "(%s): removed %d APs (of %d)",
	            nm_device_get_iface (NM_DEVICE (self)),
	            removed, total);
}

static void
supplicant_iface_new_bss_cb (NMSupplicantInterface *iface,
                             GHashTable *properties,
                             NMDeviceWifi *self)
{
	NMDeviceState state;
	NMAccessPoint *ap;

	g_return_if_fail (self != NULL);
	g_return_if_fail (properties != NULL);
	g_return_if_fail (iface != NULL);

	/* Ignore new APs when unavailable or unamnaged */
	state = nm_device_get_state (NM_DEVICE (self));
	if (state <= NM_DEVICE_STATE_UNAVAILABLE)
		return;

	ap = nm_ap_new_from_properties (properties);
	if (ap) {
		nm_ap_print_self (ap, "AP: ");

		/* Add the AP to the device's AP list */
		merge_scanned_ap (self, ap);
		g_object_unref (ap);

		/* Remove outdated access points */
		cull_scan_list (self);

		nm_device_wifi_ap_list_print (self);
	} else {
		nm_log_warn (LOGD_WIFI_SCAN, "(%s): invalid AP properties received",
		             nm_device_get_iface (NM_DEVICE (self)));
	}
}


static void
cleanup_association_attempt (NMDeviceWifi *self, gboolean disconnect)
{
	NMDeviceWifiPrivate *priv = NM_DEVICE_WIFI_GET_PRIVATE (self);

	remove_supplicant_interface_error_handler (self);
	remove_supplicant_timeouts (self);
	if (disconnect && priv->supplicant.iface)
		nm_supplicant_interface_disconnect (priv->supplicant.iface);
}

static void
wifi_secrets_cb (NMActRequest *req,
                 guint32 call_id,
                 NMConnection *connection,
                 GError *error,
                 gpointer user_data)
{
	NMDevice *dev = NM_DEVICE (user_data);

	g_return_if_fail (req == nm_device_get_act_request (dev));
	g_return_if_fail (nm_device_get_state (dev) == NM_DEVICE_STATE_NEED_AUTH);
	g_return_if_fail (nm_act_request_get_connection (req) == connection);

	if (error) {
		nm_log_warn (LOGD_WIFI, "%s", error->message);
		nm_device_state_changed (dev,
		                         NM_DEVICE_STATE_FAILED,
		                         NM_DEVICE_STATE_REASON_NO_SECRETS);
	} else
		nm_device_activate_schedule_stage1_device_prepare (dev);
}

static void
remove_link_timeout (NMDeviceWifi *self)
{
	NMDeviceWifiPrivate *priv;

	g_return_if_fail (self != NULL);
	priv = NM_DEVICE_WIFI_GET_PRIVATE (self);

	if (priv->link_timeout_id) {
		g_source_remove (priv->link_timeout_id);
		priv->link_timeout_id = 0;
	}
}


/*
 * link_timeout_cb
 *
 * Called when the link to the access point has been down for a specified
 * period of time.
 */
static gboolean
link_timeout_cb (gpointer user_data)
{
	NMDevice *dev = NM_DEVICE (user_data);

	nm_log_warn (LOGD_WIFI, "(%s): link timed out.", nm_device_get_iface (dev));

	NM_DEVICE_WIFI_GET_PRIVATE (dev)->link_timeout_id = 0;

	/* Disconnect event while activated; the supplicant hasn't been able
	 * to reassociate within the timeout period, so the connection must
	 * fail.
	 */
	if (nm_device_get_state (dev) == NM_DEVICE_STATE_ACTIVATED)
		nm_device_state_changed (dev, NM_DEVICE_STATE_DISCONNECTED, NM_DEVICE_STATE_REASON_SUPPLICANT_TIMEOUT);

	return FALSE;
}

static gboolean
handle_authenticate_fail (NMDeviceWifi *self, guint32 new_state, guint32 old_state)
{
	NMDevice *device = NM_DEVICE (self);
	NMSetting8021x *s_8021x;
	NMSettingWirelessSecurity *s_wsec;
	NMSettingSecretFlags secret_flags = NM_SETTING_SECRET_FLAG_NONE;
	NMActRequest *req;
	NMConnection *connection;
	const char *setting_name = NULL;
	gboolean handled = FALSE;

	g_return_val_if_fail (new_state == NM_SUPPLICANT_INTERFACE_STATE_DISCONNECTED, FALSE);

	/* Only care about ASSOCIATED -> DISCONNECTED transitions since 802.1x stuff
	 * happens between the ASSOCIATED and AUTHENTICATED states.
	 */
	if (old_state != NM_SUPPLICANT_INTERFACE_STATE_ASSOCIATED)
		return FALSE;

	req = nm_device_get_act_request (NM_DEVICE (self));
	g_return_val_if_fail (req != NULL, FALSE);

	connection = nm_act_request_get_connection (req);
	g_return_val_if_fail (connection != NULL, FALSE);

	/* If it's an 802.1x or LEAP connection with "always ask"/unsaved secrets
	 * then we need to ask again because it might be an OTP token and the PIN
	 * may have changed.
	 */
	s_8021x = nm_connection_get_setting_802_1x (connection);
	s_wsec = nm_connection_get_setting_wireless_security (connection);

	if (s_8021x) {
		nm_setting_get_secret_flags (NM_SETTING (s_8021x),
		                             NM_SETTING_802_1X_PASSWORD,
		                             &secret_flags,
		                             NULL);
		setting_name = NM_SETTING_802_1X_SETTING_NAME;
	} else if (s_wsec) {
		nm_setting_get_secret_flags (NM_SETTING (s_wsec),
		                             NM_SETTING_WIRELESS_SECURITY_LEAP_PASSWORD,
		                             &secret_flags,
		                             NULL);
		setting_name = NM_SETTING_WIRELESS_SECURITY_SETTING_NAME;
	}

	if (setting_name && (secret_flags & NM_SETTING_SECRET_FLAG_NOT_SAVED)) {
		NMSettingsGetSecretsFlags flags =   NM_SETTINGS_GET_SECRETS_FLAG_ALLOW_INTERACTION
		                                  | NM_SETTINGS_GET_SECRETS_FLAG_REQUEST_NEW;

		nm_connection_clear_secrets (connection);

		nm_log_info (LOGD_DEVICE | LOGD_WIFI,
		             "Activation (%s/wireless): disconnected during association,"
		             " asking for new key.", nm_device_get_iface (device));

		cleanup_association_attempt (self, TRUE);
		nm_device_state_changed (device, NM_DEVICE_STATE_NEED_AUTH, NM_DEVICE_STATE_REASON_SUPPLICANT_DISCONNECT);
		nm_act_request_get_secrets (req, setting_name, flags, NULL, wifi_secrets_cb, self);
		handled = TRUE;
	}

	return handled;
}

static void
supplicant_iface_state_cb (NMSupplicantInterface *iface,
                           guint32 new_state,
                           guint32 old_state,
                           gpointer user_data)
{
	NMDeviceWifi *self = NM_DEVICE_WIFI (user_data);
	NMDeviceWifiPrivate *priv = NM_DEVICE_WIFI_GET_PRIVATE (self);
	NMDevice *device = NM_DEVICE (self);
	NMDeviceState devstate;
	gboolean scanning;

	if (new_state == old_state)
		return;

	nm_log_info (LOGD_DEVICE | LOGD_WIFI,
	             "(%s): supplicant interface state: %s -> %s",
	             nm_device_get_iface (device),
	             nm_supplicant_interface_state_to_string (old_state),
	             nm_supplicant_interface_state_to_string (new_state));

	devstate = nm_device_get_state (device);
	scanning = nm_supplicant_interface_get_scanning (iface);

	switch (new_state) {
	case NM_SUPPLICANT_INTERFACE_STATE_READY:
		priv->scan_interval = SCAN_INTERVAL_MIN;

		/* If the interface can now be activated because the supplicant is now
		 * available, transition to DISCONNECTED.
		 */
		if ((devstate == NM_DEVICE_STATE_UNAVAILABLE) && nm_device_is_available (device)) {
			nm_device_state_changed (device,
			                         NM_DEVICE_STATE_DISCONNECTED,
			                         NM_DEVICE_STATE_REASON_SUPPLICANT_AVAILABLE);
		}

		nm_log_dbg (LOGD_WIFI_SCAN,
		            "(%s): supplicant ready, requesting initial scan",
		            nm_device_get_iface (device));

		/* Request a scan to get latest results */
		cancel_pending_scan (self);
		request_wireless_scan (self);
		break;
	case NM_SUPPLICANT_INTERFACE_STATE_COMPLETED:
		remove_supplicant_interface_error_handler (self);
		remove_supplicant_timeouts (self);

		/* If this is the initial association during device activation,
		 * schedule the next activation stage.
		 */
		if (devstate == NM_DEVICE_STATE_CONFIG) {
			NMAccessPoint *ap = nm_device_wifi_get_activation_ap (self);
			const GByteArray *ssid = nm_ap_get_ssid (ap);

			nm_log_info (LOGD_DEVICE | LOGD_WIFI,
			             "Activation (%s/wireless) Stage 2 of 5 (Device Configure) "
			             "successful.  Connected to wireless network '%s'.",
			             nm_device_get_iface (device),
			             ssid ? nm_utils_escape_ssid (ssid->data, ssid->len) : "(none)");
			nm_device_activate_schedule_stage3_ip_config_start (device);
		}
		break;
	case NM_SUPPLICANT_INTERFACE_STATE_DISCONNECTED:
		if ((devstate == NM_DEVICE_STATE_ACTIVATED) || nm_device_is_activating (device)) {
			/* Disconnect during authentication means the 802.1x password is wrong */
			if (handle_authenticate_fail (self, new_state, old_state))
				break;
		}

		if (devstate == NM_DEVICE_STATE_ACTIVATED) {
			/* If it's a disconnect while activated then start the link timer
			 * to let the supplicant reconnect for a bit and if that doesn't
			 * work kill the connection and try something else.  Allow a bit
			 * more time if the card is scanning since sometimes the link will
			 * drop while scanning and come back when the scan is done.
			 */
			if (priv->link_timeout_id == 0)
				priv->link_timeout_id = g_timeout_add_seconds (scanning ? 30 : 15, link_timeout_cb, self);
		}
		break;
	case NM_SUPPLICANT_INTERFACE_STATE_DOWN:
		cleanup_association_attempt (self, FALSE);
		supplicant_interface_release (self);
		nm_device_state_changed (device,
		                         NM_DEVICE_STATE_UNAVAILABLE,
		                         NM_DEVICE_STATE_REASON_SUPPLICANT_FAILED);
		break;
	default:
		break;
	}

	/* Signal scanning state changes */
	if (   new_state == NM_SUPPLICANT_INTERFACE_STATE_SCANNING
	    || old_state == NM_SUPPLICANT_INTERFACE_STATE_SCANNING)
		g_object_notify (G_OBJECT (self), "scanning");
}

struct iface_con_error_cb_data {
	NMDeviceWifi *self;
	char *name;
	char *message;
};

static gboolean
supplicant_iface_connection_error_cb_handler (gpointer user_data)
{
	NMDeviceWifi *self;
	NMDeviceWifiPrivate *priv;
	struct iface_con_error_cb_data * cb_data = (struct iface_con_error_cb_data *) user_data;

	g_return_val_if_fail (cb_data != NULL, FALSE);

	self = cb_data->self;
	priv = NM_DEVICE_WIFI_GET_PRIVATE (self);

	if (!nm_device_is_activating (NM_DEVICE (self)))
		goto out;

	nm_log_info (LOGD_DEVICE | LOGD_WIFI,
	             "Activation (%s/wireless): association request to the supplicant "
	             "failed: %s - %s",
	             nm_device_get_iface (NM_DEVICE (self)),
	             cb_data->name,
	             cb_data->message);

	cleanup_association_attempt (self, TRUE);
	nm_device_state_changed (NM_DEVICE (self), NM_DEVICE_STATE_FAILED, NM_DEVICE_STATE_REASON_SUPPLICANT_FAILED);

out:
	priv->supplicant.iface_con_error_cb_id = 0;
	g_free (cb_data->name);
	g_free (cb_data->message);
	g_slice_free (struct iface_con_error_cb_data, cb_data);
	return FALSE;
}


static void
supplicant_iface_connection_error_cb (NMSupplicantInterface * iface,
                                      const char * name,
                                      const char * message,
                                      NMDeviceWifi * self)
{
	NMDeviceWifiPrivate *priv;
	struct iface_con_error_cb_data *cb_data;
	guint id;

	g_return_if_fail (self != NULL);
	priv = NM_DEVICE_WIFI_GET_PRIVATE (self);

	cb_data = g_slice_new0 (struct iface_con_error_cb_data);
	if (cb_data == NULL) {
		nm_log_err (LOGD_WIFI, "Not enough memory to process supplicant connection error.");
		return;
	}

	cb_data->self = self;
	cb_data->name = g_strdup (name);
	cb_data->message = g_strdup (message);

	if (priv->supplicant.iface_con_error_cb_id)
		g_source_remove (priv->supplicant.iface_con_error_cb_id);

	id = g_idle_add (supplicant_iface_connection_error_cb_handler, cb_data);
	priv->supplicant.iface_con_error_cb_id = id;
}

static void
supplicant_iface_notify_scanning_cb (NMSupplicantInterface *iface,
                                     GParamSpec *pspec,
                                     NMDeviceWifi *self)
{
	gboolean scanning;

	scanning = nm_supplicant_interface_get_scanning (iface);
	nm_log_dbg (LOGD_WIFI_SCAN, "(%s): now %s",
	            nm_device_get_iface (NM_DEVICE (self)),
	            scanning ? "scanning" : "not scanning");

	g_object_notify (G_OBJECT (self), "scanning");
}

static void
remove_supplicant_connection_timeout (NMDeviceWifi *self)
{
	NMDeviceWifiPrivate *priv;

	g_return_if_fail (self != NULL);
	priv = NM_DEVICE_WIFI_GET_PRIVATE (self);

	/* Remove any pending timeouts on the request */
	if (priv->supplicant.con_timeout_id) {
		g_source_remove (priv->supplicant.con_timeout_id);
		priv->supplicant.con_timeout_id = 0;
	}
}

static NMActStageReturn
handle_auth_or_fail (NMDeviceWifi *self,
                     NMActRequest *req,
                     gboolean new_secrets)
{
	const char *setting_name;
	guint32 tries;
	NMAccessPoint *ap;
	NMConnection *connection;
	NMActStageReturn ret = NM_ACT_STAGE_RETURN_FAILURE;

	g_return_val_if_fail (NM_IS_DEVICE_WIFI (self), NM_ACT_STAGE_RETURN_FAILURE);

	if (!req) {
		req = nm_device_get_act_request (NM_DEVICE (self));
		g_assert (req);
	}

	connection = nm_act_request_get_connection (req);
	g_assert (connection);

	ap = nm_device_wifi_get_activation_ap (self);
	g_assert (ap);

	tries = GPOINTER_TO_UINT (g_object_get_data (G_OBJECT (connection), WIRELESS_SECRETS_TRIES));
	if (tries > 3)
		return NM_ACT_STAGE_RETURN_FAILURE;

	nm_device_state_changed (NM_DEVICE (self), NM_DEVICE_STATE_NEED_AUTH, NM_DEVICE_STATE_REASON_NONE);

	nm_connection_clear_secrets (connection);
	setting_name = nm_connection_need_secrets (connection, NULL);
	if (setting_name) {
		NMSettingsGetSecretsFlags flags = NM_SETTINGS_GET_SECRETS_FLAG_ALLOW_INTERACTION;

		/* If the caller doesn't necessarily want completely new secrets,
		 * only ask for new secrets after the first failure.
		 */
		if (new_secrets || tries)
			flags |= NM_SETTINGS_GET_SECRETS_FLAG_REQUEST_NEW;
		nm_act_request_get_secrets (req, setting_name, flags, NULL, wifi_secrets_cb, self);

		g_object_set_data (G_OBJECT (connection), WIRELESS_SECRETS_TRIES, GUINT_TO_POINTER (++tries));
		ret = NM_ACT_STAGE_RETURN_POSTPONE;
	} else
		nm_log_warn (LOGD_DEVICE, "Cleared secrets, but setting didn't need any secrets.");

	return ret;
}

/*
 * supplicant_connection_timeout_cb
 *
 * Called when the supplicant has been unable to connect to an access point
 * within a specified period of time.
 */
static gboolean
supplicant_connection_timeout_cb (gpointer user_data)
{
	NMDevice *              dev = NM_DEVICE (user_data);
	NMDeviceWifi * self = NM_DEVICE_WIFI (user_data);
	NMAccessPoint *         ap;
	NMActRequest *          req;
	gboolean                auth_enforced = FALSE, encrypted = FALSE;
	NMConnection *connection;

	cleanup_association_attempt (self, TRUE);

	if (!nm_device_is_activating (dev))
		return FALSE;

	/* Timed out waiting for authentication success; if the security in use
	 * does not require access point side authentication (Open System
	 * WEP, for example) then we are likely using the wrong authentication
	 * algorithm or key.  Request new one from the user.
	 */

	req = nm_device_get_act_request (dev);
	g_assert (req);

	connection = nm_act_request_get_connection (req);
	g_assert (connection);

	ap = nm_device_wifi_get_activation_ap (self);
	g_assert (ap);

	auth_enforced = ap_auth_enforced (connection, ap, &encrypted);
	if (!encrypted) {
		nm_log_warn (LOGD_DEVICE | LOGD_WIFI,
		             "Activation (%s/wireless): association took too long, "
		             "failing activation.",
		             nm_device_get_iface (dev));
		nm_device_state_changed (dev, NM_DEVICE_STATE_FAILED,
		                         NM_DEVICE_STATE_REASON_SUPPLICANT_TIMEOUT);
	} else {
		/* Authentication failed, encryption key is probably bad */
		nm_log_warn (LOGD_DEVICE | LOGD_WIFI,
		             "Activation (%s/wireless): association took too long.",
		             nm_device_get_iface (dev));

		if (handle_auth_or_fail (self, req, TRUE) == NM_ACT_STAGE_RETURN_POSTPONE) {
			nm_log_warn (LOGD_DEVICE | LOGD_WIFI,
			             "Activation (%s/wireless): asking for new secrets",
			             nm_device_get_iface (dev));
		} else {
			nm_device_state_changed (dev, NM_DEVICE_STATE_FAILED,
			                         NM_DEVICE_STATE_REASON_NO_SECRETS);
		}
	}

	return FALSE;
}


static gboolean
start_supplicant_connection_timeout (NMDeviceWifi *self)
{
	NMDeviceWifiPrivate *priv;
	guint id;

	g_return_val_if_fail (self != NULL, FALSE);

	priv = NM_DEVICE_WIFI_GET_PRIVATE (self);

	/* Set up a timeout on the connection attempt to fail it after 25 seconds */
	id = g_timeout_add_seconds (25, supplicant_connection_timeout_cb, self);
	if (id == 0) {
		nm_log_err (LOGD_DEVICE | LOGD_WIFI,
		            "Activation (%s/wireless): couldn't start supplicant "
		            "timeout timer.",
		            nm_device_get_iface (NM_DEVICE (self)));
		return FALSE;
	}
	priv->supplicant.con_timeout_id = id;
	return TRUE;
}


static void
remove_supplicant_timeouts (NMDeviceWifi *self)
{
	g_return_if_fail (self != NULL);

	remove_supplicant_connection_timeout (self);
	remove_link_timeout (self);
}

static guint32
find_supported_frequency (NMDeviceWifi *self, const guint32 *freqs)
{
	NMDeviceWifiPrivate *priv = NM_DEVICE_WIFI_GET_PRIVATE (self);
	int i;

	for (i = 0; i < priv->num_freqs; i++) {
		while (*freqs) {
			if (priv->freqs[i] == *freqs)
				return *freqs;
			freqs++;
		}
	}

	return 0;
}

static NMSupplicantConfig *
build_supplicant_config (NMDeviceWifi *self,
                         NMConnection *connection,
                         NMAccessPoint *ap)
{
	NMDeviceWifiPrivate *priv = NM_DEVICE_WIFI_GET_PRIVATE (self);
	NMSupplicantConfig *config = NULL;
	NMSettingWireless *s_wireless;
	NMSettingWirelessSecurity *s_wireless_sec;
	guint32 adhoc_freq = 0;

	g_return_val_if_fail (self != NULL, NULL);

	s_wireless = (NMSettingWireless *) nm_connection_get_setting (connection, NM_TYPE_SETTING_WIRELESS);
	g_return_val_if_fail (s_wireless != NULL, NULL);

	config = nm_supplicant_config_new ();
	if (!config)
		return NULL;

	/* Supplicant requires an initial frequency for Ad-Hoc networks; if the user
	 * didn't specify one and we didn't find an AP that matched the connection,
	 * just pick a frequency the device supports.
	 */
	if (nm_ap_get_mode (ap) == NM_802_11_MODE_ADHOC) {
		const char *band = nm_setting_wireless_get_band (s_wireless);
		const guint32 a_freqs[] = { 5180, 5200, 5220, 5745, 5765, 5785, 5805, 0 };
		const guint32 bg_freqs[] = { 2412, 2437, 2462, 2472, 0 };

		adhoc_freq = nm_ap_get_freq (ap);
		if (!adhoc_freq) {
			if (g_strcmp0 (band, "a") == 0)
				adhoc_freq = find_supported_frequency (self, a_freqs);
			else
				adhoc_freq = find_supported_frequency (self, bg_freqs);
		}

		if (!adhoc_freq) {
			if (g_strcmp0 (band, "a") == 0)
				adhoc_freq = 5180;
			else
				adhoc_freq = 2462;
		}
	}

	if (!nm_supplicant_config_add_setting_wireless (config,
	                                                s_wireless,
	                                                nm_ap_get_broadcast (ap),
	                                                adhoc_freq,
	                                                priv->has_scan_capa_ssid)) {
		nm_log_err (LOGD_WIFI, "Couldn't add 802-11-wireless setting to supplicant config.");
		goto error;
	}

	s_wireless_sec = (NMSettingWirelessSecurity *) nm_connection_get_setting (connection, NM_TYPE_SETTING_WIRELESS_SECURITY);
	if (s_wireless_sec) {
		NMSetting8021x *s_8021x;
		const char *con_path = nm_connection_get_path (connection);

		g_assert (con_path);
		s_8021x = (NMSetting8021x *) nm_connection_get_setting (connection, NM_TYPE_SETTING_802_1X);
		if (!nm_supplicant_config_add_setting_wireless_security (config,
		                                                         s_wireless_sec,
		                                                         s_8021x,
		                                                         con_path)) {
			nm_log_err (LOGD_WIFI, "Couldn't add 802-11-wireless-security setting to "
			            "supplicant config.");
			goto error;
		}
	} else {
		if (!nm_supplicant_config_add_no_security (config)) {
			nm_log_err (LOGD_WIFI, "Couldn't add unsecured option to supplicant config.");
			goto error;
		}
	}

	return config;

error:
	g_object_unref (config);
	return NULL;
}

/****************************************************************************/

static void
real_update_hw_address (NMDevice *dev)
{
	NMDeviceWifi *self = NM_DEVICE_WIFI (dev);
	struct ifreq req;
	int fd;

	fd = socket (PF_INET, SOCK_DGRAM, 0);
	if (fd < 0) {
		nm_log_err (LOGD_HW, "could not open control socket.");
		return;
	}

	memset (&req, 0, sizeof (struct ifreq));
	strncpy (req.ifr_name, nm_device_get_iface (dev), IFNAMSIZ);
	errno = 0;
	if (ioctl (fd, SIOCGIFHWADDR, &req) < 0) {
		nm_log_err (LOGD_HW | LOGD_WIFI, "(%s): unable to read hardware address (error %d)",
		            nm_device_get_iface (dev), errno);
	} else
		_update_hw_addr (self, (const guint8 *) &req.ifr_hwaddr.sa_data);

	close (fd);
}

static void
real_update_permanent_hw_address (NMDevice *dev)
{
	NMDeviceWifi *self = NM_DEVICE_WIFI (dev);
	NMDeviceWifiPrivate *priv = NM_DEVICE_WIFI_GET_PRIVATE (self);
	struct ifreq req;
	struct ethtool_perm_addr *epaddr = NULL;
	int fd, ret;

	fd = socket (PF_INET, SOCK_DGRAM, 0);
	if (fd < 0) {
		nm_log_err (LOGD_HW, "could not open control socket.");
		return;
	}

	/* Get permanent MAC address */
	memset (&req, 0, sizeof (struct ifreq));
	strncpy (req.ifr_name, nm_device_get_iface (dev), IFNAMSIZ);

	epaddr = g_malloc0 (sizeof (struct ethtool_perm_addr) + ETH_ALEN);
	epaddr->cmd = ETHTOOL_GPERMADDR;
	epaddr->size = ETH_ALEN;
	req.ifr_data = (void *) epaddr;

	errno = 0;
	ret = ioctl (fd, SIOCETHTOOL, &req);
	if ((ret < 0) || !nm_ethernet_address_is_valid ((struct ether_addr *) epaddr->data)) {
		nm_log_err (LOGD_HW | LOGD_ETHER, "(%s): unable to read permanent MAC address (error %d)",
		            nm_device_get_iface (dev), errno);
		/* Fall back to current address */
		memcpy (epaddr->data, &priv->hw_addr, ETH_ALEN);
	}

	if (memcmp (&priv->perm_hw_addr, epaddr->data, ETH_ALEN)) {
		memcpy (&priv->perm_hw_addr, epaddr->data, ETH_ALEN);
		g_object_notify (G_OBJECT (dev), NM_DEVICE_WIFI_PERMANENT_HW_ADDRESS);
	}

	g_free (epaddr);
	close (fd);
}

static void
real_update_initial_hw_address (NMDevice *dev)
{
	NMDeviceWifi *self = NM_DEVICE_WIFI (dev);
	NMDeviceWifiPrivate *priv = NM_DEVICE_WIFI_GET_PRIVATE (self);
	char *mac_str = NULL;
	guint8 *addr = priv->initial_hw_addr;
	guint8 zero[ETH_ALEN] = {0,0,0,0,0,0};

	/* This sets initial MAC address from current MAC address. It should only
	 * be called from NMDevice constructor() to really get the initial address.
	 */
	if (!memcmp (&priv->hw_addr, &zero, ETH_ALEN))
		real_update_hw_address (dev);

	if (memcmp (&priv->initial_hw_addr, &priv->hw_addr, ETH_ALEN))
		memcpy (&priv->initial_hw_addr, &priv->hw_addr, ETH_ALEN);

	mac_str = g_strdup_printf ("%02X:%02X:%02X:%02X:%02X:%02X",
	                           addr[0], addr[1], addr[2], addr[3], addr[4], addr[5]);

	nm_log_dbg (LOGD_DEVICE | LOGD_ETHER, "(%s): read initial MAC address %s",
	            nm_device_get_iface (dev), mac_str);

	g_free (mac_str);
}

static NMActStageReturn
real_act_stage1_prepare (NMDevice *dev, NMDeviceStateReason *reason)
{
	NMDeviceWifi *self = NM_DEVICE_WIFI (dev);
	NMDeviceWifiPrivate *priv = NM_DEVICE_WIFI_GET_PRIVATE (self);
	NMAccessPoint *ap = NULL;
	NMActRequest *req;
	NMConnection *connection;
	NMSettingWireless *s_wireless;
	const GByteArray *cloned_mac;
	GSList *iter;

	req = nm_device_get_act_request (NM_DEVICE (self));
	g_return_val_if_fail (req != NULL, NM_ACT_STAGE_RETURN_FAILURE);

	connection = nm_act_request_get_connection (req);
	g_return_val_if_fail (connection != NULL, NM_ACT_STAGE_RETURN_FAILURE);

	/* Set spoof MAC to the interface */
	s_wireless = (NMSettingWireless *) nm_connection_get_setting (connection, NM_TYPE_SETTING_WIRELESS);
	g_assert (s_wireless);

	cloned_mac = nm_setting_wireless_get_cloned_mac_address (s_wireless);
	if (cloned_mac && (cloned_mac->len == ETH_ALEN))
		_set_hw_addr (self, (const guint8 *) cloned_mac->data, "set");

	/* If the user is trying to connect to an AP that NM doesn't yet know about
	 * (hidden network or something), create an fake AP from the security
	 * settings in the connection to use until the AP is recognized from the
	 * scan list, which should show up when the connection is successful.
	 */
	ap = nm_device_wifi_get_activation_ap (self);
	if (ap)
		goto done;

	/* Find a compatible AP in the scan list */
	for (iter = priv->ap_list; iter; iter = g_slist_next (iter)) {
		NMAccessPoint *candidate = NM_AP (iter->data);

		if (nm_ap_check_compatible (candidate, connection)) {
			ap = candidate;
			break;
		}
	}

	/* If no compatible AP was found, create a fake AP (network is likely
	 * hidden) and try to use that.
	 */
	if (!ap) {
		ap = nm_ap_new_fake_from_connection (connection);
		g_return_val_if_fail (ap != NULL, NM_ACT_STAGE_RETURN_FAILURE);

		if (nm_ap_get_mode (ap) == NM_802_11_MODE_INFRA)
			nm_ap_set_broadcast (ap, FALSE);

		priv->ap_list = g_slist_prepend (priv->ap_list, ap);
		nm_ap_export_to_dbus (ap);
		g_signal_emit (self, signals[ACCESS_POINT_ADDED], 0, ap);
	}

	nm_act_request_set_specific_object (req, nm_ap_get_dbus_path (ap));

done:
	set_current_ap (self, ap);
	return NM_ACT_STAGE_RETURN_SUCCESS;
}

static NMActStageReturn
real_act_stage2_config (NMDevice *dev, NMDeviceStateReason *reason)
{
	NMDeviceWifi *self = NM_DEVICE_WIFI (dev);
	NMDeviceWifiPrivate *priv = NM_DEVICE_WIFI_GET_PRIVATE (self);
	NMActStageReturn ret = NM_ACT_STAGE_RETURN_FAILURE;
	const char *iface = nm_device_get_iface (dev);
	NMSupplicantConfig *config = NULL;
	gulong id = 0;
	NMActRequest *req;
	NMAccessPoint *ap;
	NMConnection *connection;
	const char *setting_name;
	NMSettingWireless *s_wireless;

	g_return_val_if_fail (reason != NULL, NM_ACT_STAGE_RETURN_FAILURE);

	remove_supplicant_timeouts (self);

	req = nm_device_get_act_request (dev);
	g_assert (req);

	ap = nm_device_wifi_get_activation_ap (self);
	g_assert (ap);

	connection = nm_act_request_get_connection (req);
	g_assert (connection);

	s_wireless = (NMSettingWireless *) nm_connection_get_setting (connection, NM_TYPE_SETTING_WIRELESS);
	g_assert (s_wireless);

	/* If we need secrets, get them */
	setting_name = nm_connection_need_secrets (connection, NULL);
	if (setting_name) {
		nm_log_info (LOGD_DEVICE | LOGD_WIFI,
		             "Activation (%s/wireless): access point '%s' has security,"
		             " but secrets are required.",
		             iface, nm_connection_get_id (connection));

		ret = handle_auth_or_fail (self, req, FALSE);
		if (ret == NM_ACT_STAGE_RETURN_FAILURE)
			*reason = NM_DEVICE_STATE_REASON_NO_SECRETS;
		goto out;
	}

	/* have secrets, or no secrets required */
	if (nm_setting_wireless_get_security (s_wireless)) {
		nm_log_info (LOGD_DEVICE | LOGD_WIFI,
		             "Activation (%s/wireless): connection '%s' has security"
		             ", and secrets exist.  No new secrets needed.",
		             iface, nm_connection_get_id (connection));
	} else {
		nm_log_info (LOGD_DEVICE | LOGD_WIFI,
		             "Activation (%s/wireless): connection '%s' requires no "
		             "security.  No secrets needed.",
		             iface, nm_connection_get_id (connection));
	}

	config = build_supplicant_config (self, connection, ap);
	if (config == NULL) {
		nm_log_err (LOGD_DEVICE | LOGD_WIFI,
		             "Activation (%s/wireless): couldn't build wireless configuration.",
		             iface);
		*reason = NM_DEVICE_STATE_REASON_SUPPLICANT_CONFIG_FAILED;
		goto out;
	}

	/* Hook up error signal handler to capture association errors */
	id = g_signal_connect (priv->supplicant.iface,
	                       NM_SUPPLICANT_INTERFACE_CONNECTION_ERROR,
	                       G_CALLBACK (supplicant_iface_connection_error_cb),
	                       self);
	priv->supplicant.iface_error_id = id;

	if (!nm_supplicant_interface_set_config (priv->supplicant.iface, config)) {
		nm_log_err (LOGD_DEVICE | LOGD_WIFI,
		            "Activation (%s/wireless): couldn't send wireless "
		            "configuration to the supplicant.", iface);
		*reason = NM_DEVICE_STATE_REASON_SUPPLICANT_CONFIG_FAILED;
		goto out;
	}

	if (!start_supplicant_connection_timeout (self)) {
		*reason = NM_DEVICE_STATE_REASON_SUPPLICANT_CONFIG_FAILED;
		goto out;
	}

	/* We'll get stage3 started when the supplicant connects */
	ret = NM_ACT_STAGE_RETURN_POSTPONE;

out:
	if (ret == NM_ACT_STAGE_RETURN_FAILURE)
		cleanup_association_attempt (self, TRUE);

	if (config) {
		/* Supplicant interface object refs the config; we no longer care about
		 * it after this function.
		 */
		g_object_unref (config);
	}
	return ret;
}

static NMActStageReturn
real_act_stage4_get_ip4_config (NMDevice *dev,
                                NMIP4Config **config,
                                NMDeviceStateReason *reason)
{
	NMActStageReturn ret = NM_ACT_STAGE_RETURN_FAILURE;
	NMDeviceClass *parent_class;

	g_return_val_if_fail (config != NULL, NM_ACT_STAGE_RETURN_FAILURE);
	g_return_val_if_fail (*config == NULL, NM_ACT_STAGE_RETURN_FAILURE);

	/* Chain up to parent */
	parent_class = NM_DEVICE_CLASS (nm_device_wifi_parent_class);
	ret = parent_class->act_stage4_get_ip4_config (dev, config, reason);

	if ((ret == NM_ACT_STAGE_RETURN_SUCCESS) && *config) {
		NMConnection *connection;
		NMSettingWireless *s_wireless;
		guint32 mtu;

		connection = nm_act_request_get_connection (nm_device_get_act_request (dev));
		g_assert (connection);
		s_wireless = NM_SETTING_WIRELESS (nm_connection_get_setting (connection, NM_TYPE_SETTING_WIRELESS));
		g_assert (s_wireless);

		/* MTU override */
		mtu = nm_setting_wireless_get_mtu (s_wireless);
		if (mtu)
			nm_ip4_config_set_mtu (*config, mtu);
	}

	return ret;
}


static NMActStageReturn
handle_ip_config_timeout (NMDeviceWifi *self,
                          NMConnection *connection,
                          gboolean may_fail,
                          gboolean *chain_up,
                          NMDeviceStateReason *reason)
{
	NMAccessPoint *ap;
	NMActStageReturn ret = NM_ACT_STAGE_RETURN_FAILURE;
	gboolean auth_enforced = FALSE, encrypted = FALSE;

	g_return_val_if_fail (connection != NULL, NM_ACT_STAGE_RETURN_FAILURE);

	ap = nm_device_wifi_get_activation_ap (self);
	g_assert (ap);

	/* If nothing checks the security authentication information (as in
	 * Open System WEP for example), and DHCP times out, then
	 * the encryption key is likely wrong.  Ask the user for a new one.
	 * Otherwise the failure likely happened after a successful authentication.
	 */
	auth_enforced = ap_auth_enforced (connection, ap, &encrypted);
	if (encrypted && !auth_enforced && !may_fail) {
		/* Activation failed, we must have bad encryption key */
		nm_log_warn (LOGD_DEVICE | LOGD_WIFI,
		             "Activation (%s/wireless): could not get IP configuration for "
		             "connection '%s'.",
		             nm_device_get_iface (NM_DEVICE (self)),
		             nm_connection_get_id (connection));

		ret = handle_auth_or_fail (self, NULL, TRUE);
		if (ret == NM_ACT_STAGE_RETURN_POSTPONE) {
			nm_log_info (LOGD_DEVICE | LOGD_WIFI,
			             "Activation (%s/wireless): asking for new secrets",
			             nm_device_get_iface (NM_DEVICE (self)));
		} else {
			*reason = NM_DEVICE_STATE_REASON_NO_SECRETS;
		}
	} else {
		/* Non-encrypted network or authentication is enforced by some
		 * entity (AP, RADIUS server, etc), but IP configure failed. Let the
		 * superclass handle it.
		 */
		*chain_up = TRUE;
	}

	return ret;
}


static NMActStageReturn
real_act_stage4_ip4_config_timeout (NMDevice *dev,
                                    NMIP4Config **config,
                                    NMDeviceStateReason *reason)
{
	NMActRequest *req;
	NMConnection *connection;
	NMSettingIP4Config *s_ip4;
	gboolean may_fail = FALSE, chain_up = FALSE;
	NMActStageReturn ret;

	req = nm_device_get_act_request (dev);
	g_assert (req);
	connection = nm_act_request_get_connection (req);
	g_assert (connection);

	s_ip4 = (NMSettingIP4Config *) nm_connection_get_setting (connection, NM_TYPE_SETTING_IP4_CONFIG);
	if (s_ip4)
		may_fail = nm_setting_ip4_config_get_may_fail (s_ip4);

	ret = handle_ip_config_timeout (NM_DEVICE_WIFI (dev), connection, may_fail, &chain_up, reason);
	if (chain_up)
		ret = NM_DEVICE_CLASS (nm_device_wifi_parent_class)->act_stage4_ip4_config_timeout (dev, config, reason);

	return ret;
}

static NMActStageReturn
real_act_stage4_ip6_config_timeout (NMDevice *dev,
                                    NMIP6Config **config,
                                    NMDeviceStateReason *reason)
{
	NMActRequest *req;
	NMConnection *connection;
	NMSettingIP6Config *s_ip6;
	gboolean may_fail = FALSE, chain_up = FALSE;
	NMActStageReturn ret;

	req = nm_device_get_act_request (dev);
	g_assert (req);
	connection = nm_act_request_get_connection (req);
	g_assert (connection);

	s_ip6 = (NMSettingIP6Config *) nm_connection_get_setting (connection, NM_TYPE_SETTING_IP6_CONFIG);
	if (s_ip6)
		may_fail = nm_setting_ip6_config_get_may_fail (s_ip6);

	ret = handle_ip_config_timeout (NM_DEVICE_WIFI (dev), connection, may_fail, &chain_up, reason);
	if (chain_up)
		ret = NM_DEVICE_CLASS (nm_device_wifi_parent_class)->act_stage4_ip6_config_timeout (dev, config, reason);

	return ret;
}

static void
activation_success_handler (NMDevice *dev)
{
	NMDeviceWifi *self = NM_DEVICE_WIFI (dev);
	NMDeviceWifiPrivate *priv = NM_DEVICE_WIFI_GET_PRIVATE (self);
	NMAccessPoint *ap;
	struct ether_addr bssid = { {0x0, 0x0, 0x0, 0x0, 0x0, 0x0} };
	NMAccessPoint *tmp_ap;
	NMActRequest *req;
	NMConnection *connection;

	req = nm_device_get_act_request (dev);
	g_assert (req);

	connection = nm_act_request_get_connection (req);
	g_assert (connection);

	/* Clear wireless secrets tries on success */
	g_object_set_data (G_OBJECT (connection), WIRELESS_SECRETS_TRIES, NULL);

	ap = nm_device_wifi_get_activation_ap (self);

	/* If the AP isn't fake, it was found in the scan list and all its
	 * details are known.
	 */
	if (!nm_ap_get_fake (ap))
		goto done;

	/* If the activate AP was fake, it probably won't have a BSSID at all.
	 * But if activation was successful, the card will know the BSSID.  Grab
	 * the BSSID off the card and fill in the BSSID of the activation AP.
	 */
	nm_device_wifi_get_bssid (self, &bssid);
	if (!nm_ethernet_address_is_valid (nm_ap_get_address (ap)))
		nm_ap_set_address (ap, &bssid);
	if (!nm_ap_get_freq (ap))
		nm_ap_set_freq (ap, nm_device_wifi_get_frequency (self));
	if (!nm_ap_get_max_bitrate (ap))
		nm_ap_set_max_bitrate (ap, nm_device_wifi_get_bitrate (self));

	tmp_ap = get_active_ap (self, ap, TRUE);
	if (tmp_ap) {
		const GByteArray *ssid = nm_ap_get_ssid (tmp_ap);

		/* Found a better match in the scan list than the fake AP.  Use it
		 * instead.
		 */

		/* If the better match was a hidden AP, update it's SSID */
		if (!ssid || nm_utils_is_empty_ssid (ssid->data, ssid->len))
			nm_ap_set_ssid (tmp_ap, nm_ap_get_ssid (ap));

		nm_act_request_set_specific_object (req, nm_ap_get_dbus_path (tmp_ap));

		priv->ap_list = g_slist_remove (priv->ap_list, ap);
		g_object_unref (ap);
	}

done:
	periodic_update (self);

	/* Update seen BSSIDs cache with the connected AP */
	update_seen_bssids_cache (self, priv->current_ap);

	/* Reset scan interval to something reasonable */
	priv->scan_interval = SCAN_INTERVAL_MIN + (SCAN_INTERVAL_STEP * 2);
}

static void
activation_failure_handler (NMDevice *dev)
{
	NMDeviceWifi *self = NM_DEVICE_WIFI (dev);
	NMDeviceWifiPrivate *priv = NM_DEVICE_WIFI_GET_PRIVATE (self);
	NMAccessPoint *ap;
	const GByteArray * ssid;
	NMActRequest *req;
	NMConnection *connection;

	req = nm_device_get_act_request (dev);
	g_assert (req);

	connection = nm_act_request_get_connection (req);
	g_assert (connection);

	/* Clear wireless secrets tries on failure */
	g_object_set_data (G_OBJECT (connection), WIRELESS_SECRETS_TRIES, NULL);

	if ((ap = nm_device_wifi_get_activation_ap (self))) {
		if (nm_ap_get_fake (ap)) {
			/* Fake APs are ones that don't show up in scans,
			 * but which the user explicitly attempted to connect to.
			 * However, if we fail on one of these, remove it from the
			 * list because we don't have any scan or capability info
			 * for it, and they are pretty much useless.
			 */
			access_point_removed (self, ap);
			priv->ap_list = g_slist_remove (priv->ap_list, ap);
			g_object_unref (ap);
		}
	}

	ssid = nm_ap_get_ssid (ap);
	nm_log_warn (LOGD_DEVICE | LOGD_WIFI,
	             "Activation (%s) failed for access point (%s)",
	             nm_device_get_iface (dev),
	             ssid ? nm_utils_escape_ssid (ssid->data, ssid->len) : "(none)");
}

static gboolean
real_can_interrupt_activation (NMDevice *dev)
{
	if (nm_device_get_state (dev) == NM_DEVICE_STATE_NEED_AUTH)
		return TRUE;

	return FALSE;
}


static guint32
real_get_type_capabilities (NMDevice *dev)
{
	return NM_DEVICE_WIFI_GET_PRIVATE (dev)->capabilities;
}


static gboolean
spec_match_list (NMDevice *device, const GSList *specs)
{
	NMDeviceWifiPrivate *priv = NM_DEVICE_WIFI_GET_PRIVATE (device);
	char *hwaddr;
	gboolean matched;

	hwaddr = nm_ether_ntop ((struct ether_addr *) &priv->perm_hw_addr);
	matched = nm_match_spec_hwaddr (specs, hwaddr);
	g_free (hwaddr);

	return matched;
}

static void
device_state_changed (NMDevice *device,
                      NMDeviceState new_state,
                      NMDeviceState old_state,
                      NMDeviceStateReason reason,
                      gpointer user_data)
{
	NMDeviceWifi *self = NM_DEVICE_WIFI (device);
	NMDeviceWifiPrivate *priv = NM_DEVICE_WIFI_GET_PRIVATE (self);
	gboolean clear_aps = FALSE;

	if (new_state <= NM_DEVICE_STATE_UNAVAILABLE) {
		/* Clean up the supplicant interface because in these states the
		 * device cannot be used.
		 */
		if (priv->supplicant.iface)
			supplicant_interface_release (self);
	}

	/* Start or stop the rfkill poll worker for ipw cards */
	if (priv->ipw_rfkill_path) {
		if (new_state > NM_DEVICE_STATE_UNMANAGED) {
			if (!priv->ipw_rfkill_id)
				priv->ipw_rfkill_id = g_timeout_add_seconds (3, ipw_rfkill_state_work, self);
		} else if (new_state <= NM_DEVICE_STATE_UNMANAGED) {
			if (priv->ipw_rfkill_id) {
				g_source_remove (priv->ipw_rfkill_id);
				priv->ipw_rfkill_id = 0;
			}
		}
	}

	switch (new_state) {
	case NM_DEVICE_STATE_UNMANAGED:
		clear_aps = TRUE;
		break;
	case NM_DEVICE_STATE_UNAVAILABLE:
		/* If the device is enabled and the supplicant manager is ready,
		 * acquire a supplicant interface and transition to DISCONNECTED because
		 * the device is now ready to use.
		 */
		if (priv->enabled && (nm_device_get_firmware_missing (device) == FALSE)) {
			gboolean success;
			struct iw_range range;

			/* Wait for some drivers like ipw3945 to come back to life */
			success = wireless_get_range (self, &range, NULL);

			if (!priv->supplicant.iface)
				supplicant_interface_acquire (self);
		}
		clear_aps = TRUE;
		break;
	case NM_DEVICE_STATE_NEED_AUTH:
		if (priv->supplicant.iface)
			nm_supplicant_interface_disconnect (priv->supplicant.iface);
		break;
	case NM_DEVICE_STATE_ACTIVATED:
		activation_success_handler (device);
		break;
	case NM_DEVICE_STATE_FAILED:
		activation_failure_handler (device);
		break;
	case NM_DEVICE_STATE_DISCONNECTED:
		// FIXME: ensure that the activation request is destroyed
		break;
	default:
		break;
	}

	if (clear_aps)
		remove_all_aps (self);
}

NMAccessPoint *
nm_device_wifi_get_activation_ap (NMDeviceWifi *self)
{
	NMActRequest *req;
	const char *ap_path;

	g_return_val_if_fail (NM_IS_DEVICE_WIFI (self), NULL);

	req = nm_device_get_act_request (NM_DEVICE (self));
	if (!req)
		return NULL;

	ap_path = nm_act_request_get_specific_object (req);

	return ap_path ? get_ap_by_path (self, ap_path) : NULL;
}

static void
real_set_enabled (NMDeviceInterface *device, gboolean enabled)
{
	NMDeviceWifi *self = NM_DEVICE_WIFI (device);
	NMDeviceWifiPrivate *priv = NM_DEVICE_WIFI_GET_PRIVATE (self);
	NMDeviceState state;

	if (priv->enabled == enabled)
		return;

	priv->enabled = enabled;

	nm_log_dbg (LOGD_WIFI, "(%s): device now %s",
	            nm_device_get_iface (NM_DEVICE (device)),
	            enabled ? "enabled" : "disabled");

	state = nm_device_interface_get_state (NM_DEVICE_INTERFACE (self));
	if (state < NM_DEVICE_STATE_UNAVAILABLE) {
		nm_log_dbg (LOGD_WIFI, "(%s): %s blocked by UNMANAGED state",
		            enabled ? "enable" : "disable",
		            nm_device_get_iface (NM_DEVICE (device)));
		return;
	}

	if (enabled) {
		gboolean no_firmware = FALSE, success;
		struct iw_range range;

		if (state != NM_DEVICE_STATE_UNAVAILABLE)
			nm_log_warn (LOGD_CORE, "not in expected unavailable state!");

		if (!nm_device_hw_bring_up (NM_DEVICE (self), TRUE, &no_firmware)) {
			nm_log_dbg (LOGD_WIFI, "(%s): enable blocked by failure to bring device up",
			            nm_device_get_iface (NM_DEVICE (device)));

			if (no_firmware)
				nm_device_set_firmware_missing (NM_DEVICE (device), TRUE);
			else {
				/* The device sucks, or the kernel was lying to us about the killswitch state */
				priv->enabled = FALSE;
			}
			return;
		}

		/* Wait for some drivers like ipw3945 to come back to life */
		success = wireless_get_range (self, &range, NULL);

		/* Re-initialize the supplicant interface and wait for it to be ready */
		if (priv->supplicant.iface)
			supplicant_interface_release (self);
		supplicant_interface_acquire (self);

		nm_log_dbg (LOGD_WIFI, "(%s): enable waiting on supplicant state",
		            nm_device_get_iface (NM_DEVICE (device)));
	} else {
		nm_device_state_changed (NM_DEVICE (self),
		                         NM_DEVICE_STATE_UNAVAILABLE,
		                         NM_DEVICE_STATE_REASON_NONE);
		nm_device_hw_take_down (NM_DEVICE (self), TRUE);
	}
}

/********************************************************************/

NMDevice *
nm_device_wifi_new (const char *udi,
                    const char *iface,
                    const char *driver)
{
	g_return_val_if_fail (udi != NULL, NULL);
	g_return_val_if_fail (iface != NULL, NULL);
	g_return_val_if_fail (driver != NULL, NULL);

	return (NMDevice *) g_object_new (NM_TYPE_DEVICE_WIFI,
	                                  NM_DEVICE_INTERFACE_UDI, udi,
	                                  NM_DEVICE_INTERFACE_IFACE, iface,
	                                  NM_DEVICE_INTERFACE_DRIVER, driver,
	                                  NM_DEVICE_INTERFACE_TYPE_DESC, "802.11 WiFi",
	                                  NM_DEVICE_INTERFACE_DEVICE_TYPE, NM_DEVICE_TYPE_WIFI,
	                                  NM_DEVICE_INTERFACE_RFKILL_TYPE, RFKILL_TYPE_WLAN,
	                                  NULL);
}

static void
device_interface_init (NMDeviceInterface *iface_class)
{
    iface_class->set_enabled = real_set_enabled;
}

static void
nm_device_wifi_init (NMDeviceWifi * self)
{
	g_signal_connect (self, "state-changed", G_CALLBACK (device_state_changed), NULL);
}

static void
dispose (GObject *object)
{
	NMDeviceWifi *self = NM_DEVICE_WIFI (object);
	NMDeviceWifiPrivate *priv = NM_DEVICE_WIFI_GET_PRIVATE (self);

	if (priv->disposed) {
		G_OBJECT_CLASS (nm_device_wifi_parent_class)->dispose (object);
		return;
	}

	priv->disposed = TRUE;

	if (priv->periodic_source_id) {
		g_source_remove (priv->periodic_source_id);
		priv->periodic_source_id = 0;
	}

	cleanup_association_attempt (self, TRUE);
	supplicant_interface_release (self);

	if (priv->supplicant.mgr) {
		g_object_unref (priv->supplicant.mgr);
		priv->supplicant.mgr = NULL;
	}

	if (priv->ssid) {
		g_byte_array_free (priv->ssid, TRUE);
		priv->ssid = NULL;
	}

	set_current_ap (self, NULL);
	remove_all_aps (self);

	g_free (priv->ipw_rfkill_path);
	if (priv->ipw_rfkill_id) {
		g_source_remove (priv->ipw_rfkill_id);
		priv->ipw_rfkill_id = 0;
	}

	G_OBJECT_CLASS (nm_device_wifi_parent_class)->dispose (object);
}

static void
get_property (GObject *object, guint prop_id,
              GValue *value, GParamSpec *pspec)
{
	NMDeviceWifi *device = NM_DEVICE_WIFI (object);
	NMDeviceWifiPrivate *priv = NM_DEVICE_WIFI_GET_PRIVATE (device);

	switch (prop_id) {
	case PROP_HW_ADDRESS:
		g_value_take_string (value, nm_ether_ntop ((struct ether_addr *) &priv->hw_addr));
		break;
	case PROP_PERM_HW_ADDRESS:
		g_value_take_string (value, nm_ether_ntop ((struct ether_addr *) &priv->perm_hw_addr));
		break;
	case PROP_MODE:
		g_value_set_uint (value, nm_device_wifi_get_mode (device));
		break;
	case PROP_BITRATE:
		g_value_set_uint (value, priv->rate);
		break;
	case PROP_CAPABILITIES:
		g_value_set_uint (value, priv->capabilities);
		break;
	case PROP_ACTIVE_ACCESS_POINT:
		if (priv->current_ap)
			g_value_set_boxed (value, nm_ap_get_dbus_path (priv->current_ap));
		else
			g_value_set_boxed (value, "/");
		break;
	case PROP_SCANNING:
		g_value_set_boolean (value, nm_supplicant_interface_get_scanning (priv->supplicant.iface));
		break;
	case PROP_IPW_RFKILL_STATE:
		g_value_set_uint (value, nm_device_wifi_get_ipw_rfkill_state (device));
		break;
	default:
		G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
		break;
	}
}

static void
set_property (GObject *object, guint prop_id,
			  const GValue *value, GParamSpec *pspec)
{
	NMDeviceWifiPrivate *priv = NM_DEVICE_WIFI_GET_PRIVATE (object);

	switch (prop_id) {
	case PROP_IPW_RFKILL_STATE:
		/* construct only */
		priv->ipw_rfkill_state = g_value_get_uint (value);
		break;
	default:
		G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
		break;
	}
}


static void
nm_device_wifi_class_init (NMDeviceWifiClass *klass)
{
	GObjectClass *object_class = G_OBJECT_CLASS (klass);
	NMDeviceClass *parent_class = NM_DEVICE_CLASS (klass);

	g_type_class_add_private (object_class, sizeof (NMDeviceWifiPrivate));

	object_class->constructor = constructor;
	object_class->get_property = get_property;
	object_class->set_property = set_property;
	object_class->dispose = dispose;

	parent_class->get_type_capabilities = real_get_type_capabilities;
	parent_class->get_generic_capabilities = real_get_generic_capabilities;
	parent_class->hw_is_up = real_hw_is_up;
	parent_class->hw_bring_up = real_hw_bring_up;
	parent_class->hw_take_down = real_hw_take_down;
	parent_class->is_up = real_is_up;
	parent_class->bring_up = real_bring_up;
	parent_class->take_down = real_take_down;
	parent_class->update_hw_address = real_update_hw_address;
	parent_class->update_permanent_hw_address = real_update_permanent_hw_address;
	parent_class->update_initial_hw_address = real_update_initial_hw_address;
	parent_class->get_best_auto_connection = real_get_best_auto_connection;
	parent_class->is_available = real_is_available;
	parent_class->check_connection_compatible = real_check_connection_compatible;
	parent_class->complete_connection = real_complete_connection;

	parent_class->act_stage1_prepare = real_act_stage1_prepare;
	parent_class->act_stage2_config = real_act_stage2_config;
	parent_class->act_stage4_get_ip4_config = real_act_stage4_get_ip4_config;
	parent_class->act_stage4_ip4_config_timeout = real_act_stage4_ip4_config_timeout;
	parent_class->act_stage4_ip6_config_timeout = real_act_stage4_ip6_config_timeout;
	parent_class->deactivate = real_deactivate;
	parent_class->can_interrupt_activation = real_can_interrupt_activation;
	parent_class->spec_match_list = spec_match_list;

	klass->scanning_allowed = scanning_allowed;

	/* Properties */
	g_object_class_install_property (object_class, PROP_HW_ADDRESS,
		g_param_spec_string (NM_DEVICE_WIFI_HW_ADDRESS,
		                     "Active MAC Address",
		                     "Currently set hardware MAC address",
		                     NULL,
		                     G_PARAM_READABLE));

	g_object_class_install_property (object_class, PROP_PERM_HW_ADDRESS,
		g_param_spec_string (NM_DEVICE_WIFI_PERMANENT_HW_ADDRESS,
		                     "Permanent MAC Address",
		                     "Permanent hardware MAC address",
		                     NULL,
		                     G_PARAM_READABLE));

	g_object_class_install_property (object_class, PROP_MODE,
		g_param_spec_uint (NM_DEVICE_WIFI_MODE,
		                   "Mode",
		                   "Mode",
		                   NM_802_11_MODE_UNKNOWN,
		                   NM_802_11_MODE_INFRA,
		                   NM_802_11_MODE_INFRA,
		                   G_PARAM_READABLE));

	g_object_class_install_property (object_class, PROP_BITRATE,
		g_param_spec_uint (NM_DEVICE_WIFI_BITRATE,
		                   "Bitrate",
		                   "Bitrate",
		                   0, G_MAXUINT32, 0,
		                   G_PARAM_READABLE));

	g_object_class_install_property (object_class, PROP_ACTIVE_ACCESS_POINT,
		g_param_spec_boxed (NM_DEVICE_WIFI_ACTIVE_ACCESS_POINT,
		                    "Active access point",
		                    "Currently active access point",
		                    DBUS_TYPE_G_OBJECT_PATH,
		                    G_PARAM_READABLE));

	g_object_class_install_property (object_class, PROP_CAPABILITIES,
		g_param_spec_uint (NM_DEVICE_WIFI_CAPABILITIES,
		                   "Wireless Capabilities",
		                   "Wireless Capabilities",
		                   0, G_MAXUINT32, NM_WIFI_DEVICE_CAP_NONE,
		                   G_PARAM_READABLE));

	g_object_class_install_property (object_class, PROP_SCANNING,
		g_param_spec_boolean (NM_DEVICE_WIFI_SCANNING,
		                   "Scanning",
		                   "Scanning",
		                   FALSE,
		                   G_PARAM_READABLE | NM_PROPERTY_PARAM_NO_EXPORT));

	g_object_class_install_property (object_class, PROP_IPW_RFKILL_STATE,
		g_param_spec_uint (NM_DEVICE_WIFI_IPW_RFKILL_STATE,
		                   "IpwRfkillState",
		                   "ipw rf-kill state",
		                   RFKILL_UNBLOCKED, RFKILL_HARD_BLOCKED, RFKILL_UNBLOCKED,
		                   G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY | NM_PROPERTY_PARAM_NO_EXPORT));

	/* Signals */
	signals[ACCESS_POINT_ADDED] =
		g_signal_new ("access-point-added",
		              G_OBJECT_CLASS_TYPE (object_class),
		              G_SIGNAL_RUN_FIRST,
		              G_STRUCT_OFFSET (NMDeviceWifiClass, access_point_added),
		              NULL, NULL,
		              g_cclosure_marshal_VOID__OBJECT,
		              G_TYPE_NONE, 1,
		              G_TYPE_OBJECT);

	signals[ACCESS_POINT_REMOVED] =
		g_signal_new ("access-point-removed",
		              G_OBJECT_CLASS_TYPE (object_class),
		              G_SIGNAL_RUN_FIRST,
		              G_STRUCT_OFFSET (NMDeviceWifiClass, access_point_removed),
		              NULL, NULL,
		              g_cclosure_marshal_VOID__OBJECT,
		              G_TYPE_NONE, 1,
		              G_TYPE_OBJECT);

	signals[HIDDEN_AP_FOUND] =
		g_signal_new ("hidden-ap-found",
		              G_OBJECT_CLASS_TYPE (object_class),
		              G_SIGNAL_RUN_FIRST,
		              G_STRUCT_OFFSET (NMDeviceWifiClass, hidden_ap_found),
		              NULL, NULL,
		              g_cclosure_marshal_VOID__OBJECT,
		              G_TYPE_NONE, 1,
		              G_TYPE_OBJECT);

	signals[PROPERTIES_CHANGED] =
		nm_properties_changed_signal_new (object_class,
		                                  G_STRUCT_OFFSET (NMDeviceWifiClass, properties_changed));

	signals[SCANNING_ALLOWED] =
		g_signal_new ("scanning-allowed",
		              G_OBJECT_CLASS_TYPE (object_class),
		              G_SIGNAL_RUN_LAST,
		              G_STRUCT_OFFSET (NMDeviceWifiClass, scanning_allowed),
		              scanning_allowed_accumulator, NULL,
		              _nm_marshal_BOOLEAN__VOID,
		              G_TYPE_BOOLEAN, 0);

	dbus_g_object_type_install_info (G_TYPE_FROM_CLASS (klass), &dbus_glib_nm_device_wifi_object_info);

	dbus_g_error_domain_register (NM_WIFI_ERROR, NULL, NM_TYPE_WIFI_ERROR);
}