summaryrefslogtreecommitdiff
path: root/src/NetworkManagerDevice.c
blob: 2a4bdbfdd96d759087f5ede317b9480d13f4bbaf (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
/* NetworkManager -- Network link manager
 *
 * Dan Williams <dcbw@redhat.com>
 *
 * 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 *
 * (C) Copyright 2004 Red Hat, Inc.
 */

#include <errno.h>
#include <glib.h>
#include <dbus/dbus-glib.h>
#include <libhal.h>
#include <iwlib.h>
#include <signal.h>
#include <string.h>

#include "NetworkManager.h"
#include "NetworkManagerMain.h"
#include "NetworkManagerDevice.h"
#include "NetworkManagerDevicePrivate.h"
#include "NetworkManagerUtils.h"
#include "NetworkManagerDbus.h"
#include "NetworkManagerWireless.h"
#include "NetworkManagerPolicy.h"
#include "NetworkManagerAPList.h"
#include "NetworkManagerSystem.h"
#include "NetworkManagerDHCP.h"

#include "nm-utils.h"

/* Local static prototypes */
static gpointer nm_device_worker (gpointer user_data);
static gboolean nm_device_activate (gpointer user_data);
static gboolean nm_device_activation_configure_ip (NMDevice *dev, gboolean do_only_autoip);
static gboolean nm_device_wireless_scan (gpointer user_data);
static gboolean supports_mii_carrier_detect (NMDevice *dev);
static gboolean supports_ethtool_carrier_detect (NMDevice *dev);
static gboolean nm_device_bring_up_wait (NMDevice *dev, gboolean cancelable);
static gboolean nm_device_activation_handle_cancel (NMDevice *dev);

typedef struct
{
	NMDevice					*dev;
	struct wireless_scan_head	 scan_head;
} NMWirelessScanResults;

typedef struct
{
	NMDevice		*dev;
	gboolean		 reschedule;
} NMWirelessScanCB;

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


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

/*
 * nm_device_test_wireless_extensions
 *
 * Test whether a given device is a wireless one or not.
 *
 */
static gboolean nm_device_test_wireless_extensions (NMDevice *dev)
{
	int		 err = -1;
	char		 ioctl_buf[64];
	NMSock	*sk;

	g_return_val_if_fail (dev != NULL, FALSE);

	/* We obviously cannot probe test devices (since they don't
	 * actually exist in hardware).
	 */
	if (dev->test_device)
		return (FALSE);

	ioctl_buf[63] = 0;
	strncpy (ioctl_buf, nm_device_get_iface(dev), 63);

	if ((sk = nm_dev_sock_open (dev, DEV_WIRELESS, __FUNCTION__, NULL)))
	{
		err = ioctl (nm_dev_sock_get_fd (sk), SIOCGIWNAME, ioctl_buf);
		nm_dev_sock_close (sk);
	}
	return (err == 0);
}


/*
 * nm_device_supports_wireless_scan
 *
 * Test whether a given device is a wireless one or not.
 *
 */
static gboolean nm_device_supports_wireless_scan (NMDevice *dev)
{
	NMSock			*sk;
	int				 err;
	gboolean			 can_scan = TRUE;
	wireless_scan_head	 scan_data;
	
	g_return_val_if_fail (dev != NULL, FALSE);
	g_return_val_if_fail (dev->type == DEVICE_TYPE_WIRELESS_ETHERNET, FALSE);

	/* A test wireless device can always scan (we generate fake scan data for it) */
	if (dev->test_device)
		return (TRUE);

	if ((sk = nm_dev_sock_open (dev, DEV_WIRELESS, __FUNCTION__, NULL)))
	{
		err = iw_scan (nm_dev_sock_get_fd (sk), (char *)nm_device_get_iface (dev), WIRELESS_EXT, &scan_data);
		nm_dispose_scan_results (scan_data.result);
		if ((err == -1) && (errno == EOPNOTSUPP))
			can_scan = FALSE;
		nm_dev_sock_close (sk);
	}
	return (can_scan);
}


/*
 * nm_get_device_by_udi
 *
 * Search through the device list for a device with a given UDI.
 *
 * NOTE: the caller MUST hold the device list mutex already to make
 * this routine thread-safe.
 *
 */
NMDevice *nm_get_device_by_udi (NMData *data, const char *udi)
{
	NMDevice	*dev = NULL;
	GSList	*elt;
	
	g_return_val_if_fail (data != NULL, NULL);
	g_return_val_if_fail (udi  != NULL, NULL);

	for (elt = data->dev_list; elt; elt = g_slist_next (elt))
	{
		dev = (NMDevice *)(elt->data);
		if (dev)
		{
			if (nm_null_safe_strcmp (nm_device_get_udi (dev), udi) == 0)
				break;
		}
	}

	return (dev);
}


/*
 * nm_get_device_by_iface
 *
 * Search through the device list for a device with a given iface.
 *
 * NOTE: the caller MUST hold the device list mutex already to make
 * this routine thread-safe.
 *
 */
NMDevice *nm_get_device_by_iface (NMData *data, const char *iface)
{
	NMDevice	*iter_dev = NULL;
	NMDevice	*found_dev = NULL;
	GSList	*elt;
	
	g_return_val_if_fail (data  != NULL, NULL);
	g_return_val_if_fail (iface != NULL, NULL);

	for (elt = data->dev_list; elt; elt = g_slist_next (elt))
	{
		iter_dev = (NMDevice *)(elt->data);
		if (iter_dev)
		{
			if (nm_null_safe_strcmp (nm_device_get_iface (iter_dev), iface) == 0)
			{
				found_dev = iter_dev;
				break;
			}
		}
	}

	return (found_dev);
}


/*****************************************************************************/
/* NMDevice object routines                                                  */
/*****************************************************************************/


/*
 * nm_device_copy_allowed_to_dev_list
 *
 * For devices that don't support wireless scanning, copy
 * the allowed AP list to the device's ap list.
 *
 */
void nm_device_copy_allowed_to_dev_list (NMDevice *dev, NMAccessPointList *allowed_list)
{
	NMAPListIter		*iter;
	NMAccessPoint		*src_ap;
	NMAccessPointList	*dev_list;

	g_return_if_fail (dev != NULL);

	if (allowed_list == NULL)
		return;

	nm_device_ap_list_clear (dev);
	dev->options.wireless.ap_list = nm_ap_list_new (NETWORK_TYPE_ALLOWED);

	if (!(iter = nm_ap_list_iter_new (allowed_list)))
		return;

	dev_list = nm_device_ap_list_get (dev);
	while ((src_ap = nm_ap_list_iter_next (iter)))
	{
		NMAccessPoint	*dst_ap = nm_ap_new_from_ap (src_ap);

		/* Assume that if the allowed list AP has a saved encryption
		 * key that the AP is encrypted.
		 */
		if (    (nm_ap_get_auth_method (src_ap) == NM_DEVICE_AUTH_METHOD_OPEN_SYSTEM)
			|| (nm_ap_get_auth_method (src_ap) == NM_DEVICE_AUTH_METHOD_SHARED_KEY))
			nm_ap_set_encrypted (dst_ap, TRUE);

		nm_ap_list_append_ap (dev_list, dst_ap);
		nm_ap_unref (dst_ap);
	}
	nm_ap_list_iter_free (iter);
}


/*
 * nm_device_new
 *
 * Creates and initializes the structure representation of an NM device.  For test
 * devices, a device type other than DEVICE_TYPE_DONT_KNOW must be specified, this
 * argument is ignored for real hardware devices since they are auto-probed.
 *
 */
NMDevice *nm_device_new (const char *iface, const char *udi, gboolean test_dev, NMDeviceType test_dev_type, NMData *app_data)
{
	NMDevice	*dev;
	GError	*error = NULL;
	nm_completion_args args;

	g_return_val_if_fail (iface != NULL, NULL);
	g_return_val_if_fail (strlen (iface) > 0, NULL);
	g_return_val_if_fail (app_data != NULL, NULL);

	/* Test devices must have a valid type specified */
	if (test_dev && !(test_dev_type != DEVICE_TYPE_DONT_KNOW))
		return (NULL);

	/* Another check to make sure we don't create a test device unless
	 * test devices were enabled on the command line.
	 */
	if (!app_data->enable_test_devices && test_dev)
	{
		nm_warning ("attempt to create a test device, but test devices were not enabled "
			    "on the command line.  Will not create the device.");
		return (NULL);
	}

	dev = g_malloc0 (sizeof (NMDevice));
	if (!dev)
	{
		nm_warning ("could not allocate a new device...  Not enough memory?");
		return (NULL);
	}

	dev->refcount = 2; /* 1 for starters, and another 1 for the worker thread */
	dev->app_data = app_data;
	dev->iface = g_strdup (iface);
	dev->test_device = test_dev;
	nm_device_set_udi (dev, udi);

	/* Real hardware devices are probed for their type, test devices must have
	 * their type specified.
	 */
	if (test_dev)
		dev->type = test_dev_type;
	else
		dev->type = nm_device_test_wireless_extensions (dev) ?
						DEVICE_TYPE_WIRELESS_ETHERNET : DEVICE_TYPE_WIRED_ETHERNET;

	/* Device thread's main loop */
	dev->context = g_main_context_new ();
	dev->loop = g_main_loop_new (dev->context, FALSE);

	if (!dev->context || !dev->loop)
		goto err;

	/* Have to bring the device up before checking link status and other stuff */
	nm_device_bring_up_wait (dev, 0);

	/* Initialize wireless-specific options */
	if (nm_device_is_wireless (dev))
	{
		NMSock				*sk;
		NMDeviceWirelessOptions	*opts = &(dev->options.wireless);

		nm_device_set_mode (dev, NETWORK_MODE_INFRA);

		opts->scan_interval = 20;

		opts->scan_mutex = g_mutex_new ();
		opts->best_ap_mutex = g_mutex_new ();
		opts->ap_list = nm_ap_list_new (NETWORK_TYPE_DEVICE);
		if (!opts->scan_mutex || !opts->best_ap_mutex || !opts->ap_list)
			goto err;

		nm_register_mutex_desc (opts->scan_mutex, "Scan Mutex");
		nm_register_mutex_desc (opts->best_ap_mutex, "Best AP Mutex");

		opts->supports_wireless_scan = nm_device_supports_wireless_scan (dev);

		/* Non-scanning devices show the entire allowed AP list as their
		 * available networks.
		 */
		if (opts->supports_wireless_scan == FALSE)
			nm_device_copy_allowed_to_dev_list (dev, app_data->allowed_ap_list);

		if ((sk = nm_dev_sock_open (dev, DEV_WIRELESS, __FUNCTION__, NULL)))
		{
			iwrange	range;
			if (iw_get_range_info (nm_dev_sock_get_fd (sk), nm_device_get_iface (dev), &range) >= 0)
			{
				int i;

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

				opts->avg_qual.qual = range.avg_qual.qual;
				opts->avg_qual.level = range.avg_qual.level;
				opts->avg_qual.noise = range.avg_qual.noise;
				opts->avg_qual.updated = range.avg_qual.updated;

				opts->num_freqs = MIN (range.num_frequency, IW_MAX_FREQUENCIES);
				for (i = 0; i < opts->num_freqs; i++)
					opts->freqs[i] = iw_freq2float (&(range.freq[i]));
			}
			nm_dev_sock_close (sk);
		}
	}
	else if (nm_device_is_wired (dev))
	{
		if (supports_ethtool_carrier_detect (dev) || supports_mii_carrier_detect (dev))
			dev->options.wired.has_carrier_detect = TRUE;
	}

	/* Must be called after carrier detect or wireless scan detect. */
	dev->driver_support_level = nm_get_driver_support_level (dev->app_data->hal_ctx, dev);

	if (nm_device_get_driver_support_level (dev) != NM_DRIVER_UNSUPPORTED)
	{
		if (nm_device_is_wireless (dev))
			nm_device_update_link_state (dev);

		nm_device_update_ip4_address (dev);
		nm_device_update_hw_address (dev);

		/* Grab IP config data for this device from the system configuration files */
		nm_system_device_update_config_info (dev);
	}

	dev->worker = g_thread_create (nm_device_worker, dev, TRUE, &error);
	if (!dev->worker)
	{
		nm_error ("could not create device worker thread. (glib said: '%s')", error->message);
		g_error_free (error);
		goto err;
	}

	/* Block until our device thread has actually had a chance to start. */
	args[0] = &dev->worker_started;
	args[1] = "nm_device_new(): waiting for device's worker thread to start";
	args[2] = (void *)LOG_INFO;
	args[3] = 0;
	nm_wait_for_completion (NM_COMPLETION_TRIES_INFINITY,
			G_USEC_PER_SEC / 20, nm_completion_boolean_test, NULL, args);

	nm_info ("nm_device_new(): device's worker thread started, continuing.");

	return (dev);

err:
	/* Initial refcount is 2 */
	nm_device_unref (dev);
	nm_device_unref (dev);
	return NULL;
}


/*
 * Refcounting functions
 */
void nm_device_ref (NMDevice *dev)
{
	g_return_if_fail (dev != NULL);

	dev->refcount++;
}

/*
 * nm_device_unref
 *
 * Decreases the refcount on a device by 1, and if the refcount reaches 0,
 * deallocates memory used by the device.
 *
 * Returns:	FALSE if device was not deallocated
 *			TRUE if device was deallocated
 */
gboolean nm_device_unref (NMDevice *dev)
{
	gboolean	deleted = FALSE;

	g_return_val_if_fail (dev != NULL, TRUE);

	dev->refcount--;
	if (dev->refcount <= 0)
	{
		nm_device_worker_thread_stop (dev);
		nm_device_bring_down (dev);

		if (nm_device_is_wireless (dev))
		{
			nm_device_ap_list_clear (dev);

			g_mutex_free (dev->options.wireless.scan_mutex);
			if (dev->options.wireless.ap_list)
				nm_ap_list_unref (dev->options.wireless.ap_list);
			if (dev->options.wireless.best_ap)
				nm_ap_unref (dev->options.wireless.best_ap);
			g_mutex_free (dev->options.wireless.best_ap_mutex);
		}

		/* Get rid of DHCP state data */
		if (dev->dhcp_iface)
		{
			dhcp_interface_free (dev->dhcp_iface);
			dev->dhcp_iface = NULL;
		}

		g_free (dev->udi);
		g_free (dev->iface);
		memset (dev, 0, sizeof (NMDevice));
		g_free (dev);
		deleted = TRUE;
	}

	return deleted;
}


/*
 * nm_device_worker
 *
 * Main thread of the device.
 *
 */
static gpointer nm_device_worker (gpointer user_data)
{
	NMDevice *dev = (NMDevice *)user_data;

	if (!dev)
	{
		nm_error ("received NULL device object, NetworkManager cannot continue.");
		exit (1);
	}

	/* Start the scanning timeout for devices that can do scanning */
	if (nm_device_is_wireless (dev) && nm_device_get_supports_wireless_scan (dev))
	{
		GSource			*source = g_idle_source_new ();
		guint			 source_id = 0;
		NMWirelessScanCB	*scan_cb;

		scan_cb = g_malloc0 (sizeof (NMWirelessScanCB));
		scan_cb->dev = dev;
		scan_cb->reschedule = TRUE;

		g_source_set_callback (source, nm_device_wireless_scan, scan_cb, NULL);
		source_id = g_source_attach (source, dev->context);
		g_source_unref (source);
	}

	dev->worker_started = TRUE;
	g_main_loop_run (dev->loop);

	/* Remove any DHCP timeouts that might have been running */
	if (nm_device_config_get_use_dhcp (dev))
		nm_device_dhcp_remove_timeouts (dev);

	g_main_loop_unref (dev->loop);
	g_main_context_unref (dev->context);

	dev->loop = NULL;
	dev->context = NULL;

	nm_device_unref (dev);

	return NULL;
}


void nm_device_worker_thread_stop (NMDevice *dev)
{
	g_return_if_fail (dev != NULL);

	if (dev->loop)
		g_main_loop_quit (dev->loop);
	g_thread_join(dev->worker);
	dev->worker = NULL;
}


/*
 * nm_device_get_app_data
 *
 */
NMData *nm_device_get_app_data (const NMDevice *dev)
{
	g_return_val_if_fail (dev != NULL, FALSE);

	return (dev->app_data);
}


/*
 * Get/Set for "removed" flag
 */
gboolean nm_device_get_removed (const NMDevice *dev)
{
	g_return_val_if_fail (dev != NULL, TRUE);

	return (dev->removed);
}

void nm_device_set_removed (NMDevice *dev, const gboolean removed)
{
	g_return_if_fail (dev != NULL);

	dev->removed = removed;
}


/*
 * Return the amount of time we should wait for the device
 * to get a link, based on the # of frequencies it has to
 * scan.
 */
gint nm_device_get_association_pause_value (NMDevice *dev)
{
	g_return_val_if_fail (dev != NULL, -1);
	g_return_val_if_fail (nm_device_is_wireless (dev), -1);

	/* If the card supports more than 14 channels, we should probably wait
	 * around 10s so it can scan them all. After we set the ESSID on the card, the card
	 * has to scan all channels to find our requested AP (which can take a long time
	 * if it is an A/B/G chipset like the Atheros 5212, for example).
	 */
	if (dev->options.wireless.num_freqs > 14)
		return 8;
	else
		return 5;
}


/*
 * Get/set functions for UDI
 */
char * nm_device_get_udi (NMDevice *dev)
{
	g_return_val_if_fail (dev != NULL, NULL);

	return (dev->udi);
}

void nm_device_set_udi (NMDevice *dev, const char *udi)
{
	g_return_if_fail (dev != NULL);
	g_return_if_fail (udi != NULL);

	if (dev->udi)
		g_free (dev->udi);

	dev->udi = g_strdup (udi);
}


/*
 * Get/set functions for iface
 */
const char * nm_device_get_iface (NMDevice *dev)
{
	g_return_val_if_fail (dev != NULL, NULL);

	return (dev->iface);
}


/*
 * Get/set functions for type
 */
guint nm_device_get_type (NMDevice *dev)
{
	g_return_val_if_fail (dev != NULL, DEVICE_TYPE_DONT_KNOW);

	return (dev->type);
}

gboolean nm_device_is_wireless (NMDevice *dev)
{
	g_return_val_if_fail (dev != NULL, FALSE);

	return (dev->type == DEVICE_TYPE_WIRELESS_ETHERNET);
}

gboolean nm_device_is_wired (NMDevice *dev)
{
	g_return_val_if_fail (dev != NULL, FALSE);

	return (dev->type == DEVICE_TYPE_WIRED_ETHERNET);
}


/*
 * Accessor for driver support level
 */
NMDriverSupportLevel nm_device_get_driver_support_level (NMDevice *dev)
{
	g_return_val_if_fail (dev != NULL, NM_DRIVER_UNSUPPORTED);

	return (dev->driver_support_level);
}


/*
 * Get/set functions for link_active
 */
gboolean nm_device_has_active_link (NMDevice *dev)
{
	g_return_val_if_fail (dev != NULL, FALSE);

	return (dev->link_active);
}

void nm_device_set_link_active (NMDevice *dev, const gboolean link_active)
{
	g_return_if_fail (dev != NULL);

	if (dev->link_active != link_active)
	{
		dev->link_active = link_active;

		nm_dbus_schedule_device_status_change (dev, DEVICE_STATUS_CHANGE);
		nm_policy_schedule_state_update (dev->app_data);
	}
}


/*
 * Get/set functions for now_scanning
 */
gboolean nm_device_get_now_scanning (NMDevice *dev)
{
	g_return_val_if_fail (dev != NULL, FALSE);
	g_return_val_if_fail (nm_device_is_wireless (dev), FALSE);

	return (dev->options.wireless.now_scanning);
}

void nm_device_set_now_scanning (NMDevice *dev, const gboolean now_scanning)
{
	gboolean	old_val;

	g_return_if_fail (dev != NULL);
	g_return_if_fail (nm_device_is_wireless (dev));

	old_val = nm_device_get_now_scanning (dev);
	dev->options.wireless.now_scanning = now_scanning;
	if (old_val != now_scanning)
		nm_dbus_schedule_device_status_change (dev, DEVICE_STATUS_CHANGE);
}


/*
 * Get function for supports_wireless_scan
 */
gboolean nm_device_get_supports_wireless_scan (NMDevice *dev)
{
	g_return_val_if_fail (dev != NULL, FALSE);

	if (!nm_device_is_wireless (dev))
		return (FALSE);

	return (dev->options.wireless.supports_wireless_scan);
}


/*
 * nm_device_get_supports_carrier_detect
 */
gboolean nm_device_get_supports_carrier_detect (NMDevice *dev)
{
	g_return_val_if_fail (dev != NULL, FALSE);

	if (!nm_device_is_wired (dev))
		return (FALSE);

	return (dev->options.wired.has_carrier_detect);
}

/*
 * nm_device_wireless_is_associated
 *
 * Figure out whether or not we're associated to an access point
 */
static gboolean nm_device_wireless_is_associated (NMDevice *dev)
{
	struct iwreq	 wrq;
	NMSock		*sk;
	gboolean		 associated = FALSE;

	g_return_val_if_fail (dev != NULL, FALSE);
	g_return_val_if_fail (dev->app_data != NULL, FALSE);

	/* Test devices have their link state set through DBUS */
	if (dev->test_device)
		return (nm_device_has_active_link (dev));

	if ((sk = nm_dev_sock_open (dev, DEV_WIRELESS, __FUNCTION__, NULL)) == NULL)
		return (FALSE);

	/* Some cards, for example ipw2x00 cards, can short-circuit the MAC
	 * address check using this check on IWNAME.  Its faster.
	 */
	if (iw_get_ext (nm_dev_sock_get_fd (sk), nm_device_get_iface (dev), SIOCGIWNAME, &wrq) >= 0)
	{
		if (!strcmp(wrq.u.name, "unassociated"))
		{
			associated = FALSE;
			goto out;
		}
	}

	if (!associated)
	{
		/*
		 * For all other wireless cards, the best indicator of a "link" at this time
		 * seems to be whether the card has a valid access point MAC address.
		 * Is there a better way?  Some cards don't work too well with this check, ie
		 * Lucent WaveLAN.
		 */
		if (iw_get_ext (nm_dev_sock_get_fd (sk), nm_device_get_iface (dev), SIOCGIWAP, &wrq) >= 0)
			if (nm_ethernet_address_is_valid ((struct ether_addr *)(&(wrq.u.ap_addr.sa_data))))
				associated = TRUE;
	}

out:
	nm_dev_sock_close (sk);

	return (associated);
}

/*
 * nm_device_probe_wireless_link_state
 *
 * Gets the link state of a wireless device
 *
 */
static gboolean nm_device_probe_wireless_link_state (NMDevice *dev)
{
	gboolean 		 link = FALSE;
	NMAccessPoint	*best_ap;

	g_return_val_if_fail (dev != NULL, FALSE);
	g_return_val_if_fail (dev->app_data != NULL, FALSE);

	/* Test devices have their link state set through DBUS */
	if (dev->test_device)
		return (nm_device_has_active_link (dev));

	if (!nm_device_wireless_is_associated (dev))
		return (FALSE);

	/* If we don't have a "best" ap, we can't logically have a valid link
	 * that we want to use.
	 */
	if ((best_ap = nm_device_get_best_ap (dev)))
	{
		if (!nm_device_need_ap_switch (dev))
			link = TRUE;
		nm_ap_unref (best_ap);
	}

	return (link);
}


/*
 * nm_device_probe_wired_link_state
 *
 * 
 *
 */
static gboolean nm_device_probe_wired_link_state (NMDevice *dev)
{
	gboolean	link = FALSE;
	gchar *contents, *carrier_path;
	gsize length;

	g_return_val_if_fail (dev != NULL, FALSE);
	g_return_val_if_fail (nm_device_is_wired (dev) == TRUE, FALSE);
	g_return_val_if_fail (dev->app_data != NULL, FALSE);

	/* Test devices have their link state set through DBUS */
	if (dev->test_device)
		return (nm_device_has_active_link (dev));

	if (dev->removed)
		return FALSE;

	carrier_path = g_strdup_printf ("/sys/class/net/%s/carrier", dev->iface);
	if (g_file_get_contents (carrier_path, &contents, &length, NULL)) {
		link = (gboolean) atoi (contents);
		g_free (contents);
	}
	g_free(carrier_path);

	/* We say that non-carrier-detect devices always have a link, because
	 * they never get auto-selected by NM.  User has to force them on us,
	 * so we just hope the user knows whether or not the cable's plugged in.
	 */
	if (dev->options.wired.has_carrier_detect != TRUE)
		link = TRUE;

	return (link);
}

/*
 * nm_device_update_link_state
 *
 * Updates the link state for a particular device.
 *
 */
void nm_device_update_link_state (NMDevice *dev)
{
	gboolean		link = FALSE;

	g_return_if_fail (dev != NULL);
	g_return_if_fail (dev->app_data != NULL);

	switch (nm_device_get_type (dev))
	{
		case DEVICE_TYPE_WIRELESS_ETHERNET:
			nm_device_set_link_active (dev, nm_device_probe_wireless_link_state (dev));
			nm_device_update_signal_strength (dev);
			break;

		case DEVICE_TYPE_WIRED_ETHERNET:
			nm_device_set_link_active (dev, nm_device_probe_wired_link_state (dev));
			break;

		default:
			break;
	}
}


/*
 * nm_device_get_essid
 *
 * If a device is wireless, return the essid that it is attempting
 * to use.
 *
 * Returns:	allocated string containing essid.  Must be freed by caller.
 *
 */
char * nm_device_get_essid (NMDevice *dev)
{
	NMSock	*sk;
	int		 err;
	
	g_return_val_if_fail (dev != NULL, NULL);
	g_return_val_if_fail (nm_device_is_wireless (dev), NULL);

	/* Test devices return the essid of their "best" access point
	 * or if there is none, the contents of the cur_essid field.
	 */
	if (dev->test_device)
	{
		NMAccessPoint	*best_ap = nm_device_get_best_ap (dev);
		char			*essid = dev->options.wireless.cur_essid;

		/* Or, if we've got a best ap, use that ESSID instead */
		if (best_ap)
		{
			essid = nm_ap_get_essid (best_ap);
			nm_ap_unref (best_ap);
		}
		return (essid);
	}
	
	if ((sk = nm_dev_sock_open (dev, DEV_WIRELESS, __FUNCTION__, NULL)))
	{
		wireless_config	info;

		err = iw_get_basic_config (nm_dev_sock_get_fd (sk), nm_device_get_iface (dev), &info);
		if (err >= 0)
		{
			if (dev->options.wireless.cur_essid)
				g_free (dev->options.wireless.cur_essid);
			dev->options.wireless.cur_essid = g_strdup (info.essid);
		}
		else
			nm_warning ("nm_device_get_essid(): error getting ESSID for device %s.  errno = %d", nm_device_get_iface (dev), errno);

		nm_dev_sock_close (sk);
	}

	return (dev->options.wireless.cur_essid);
}


/*
 * nm_device_set_essid
 *
 * If a device is wireless, set the essid that it should use.
 */
void nm_device_set_essid (NMDevice *dev, const char *essid)
{
	NMSock			*sk;
	int				 err;
	struct iwreq		 wreq;
	unsigned char		 safe_essid[IW_ESSID_MAX_SIZE + 1] = "\0";
	
	g_return_if_fail (dev != NULL);
	g_return_if_fail (nm_device_is_wireless (dev));

	/* Test devices directly set cur_essid */
	if (dev->test_device)
	{
		if (dev->options.wireless.cur_essid)
			g_free (dev->options.wireless.cur_essid);
		dev->options.wireless.cur_essid = g_strdup (essid);
		return;
	}

	/* Make sure the essid we get passed is a valid size */
	if (!essid)
		safe_essid[0] = '\0';
	else
	{
		strncpy (safe_essid, essid, IW_ESSID_MAX_SIZE);
		safe_essid[IW_ESSID_MAX_SIZE] = '\0';
	}

	if ((sk = nm_dev_sock_open (dev, DEV_WIRELESS, __FUNCTION__, NULL)))
	{
		wreq.u.essid.pointer = (caddr_t) safe_essid;
		wreq.u.essid.length	 = strlen (safe_essid) + 1;
		wreq.u.essid.flags	 = 1;	/* Enable essid on card */
	
		err = iw_set_ext (nm_dev_sock_get_fd (sk), nm_device_get_iface (dev), SIOCSIWESSID, &wreq);
		if (err == -1)
			nm_warning ("nm_device_set_essid(): error setting ESSID '%s' for device %s.  errno = %d", safe_essid, nm_device_get_iface (dev), errno);

		nm_dev_sock_close (sk);

		/* Orinoco cards seem to need extra time here to not screw
		 * up the firmware, which reboots when you set the ESSID.
		 * Unfortunately, there's no way to know when the card is back up
		 * again.  Sigh...
		 */
		sleep (2);
	}
}


/*
 * nm_device_get_frequency
 *
 * For wireless devices, get the frequency we broadcast/receive on.
 *
 */
double nm_device_get_frequency (NMDevice *dev)
{
	NMSock	*sk;
	int		 err;
	double	 freq = 0;

	g_return_val_if_fail (dev != NULL, 0);
	g_return_val_if_fail (nm_device_is_wireless (dev), 0);

	/* Test devices don't really have a frequency, they always succeed */
	if (dev->test_device)
		return 703000000;

	if ((sk = nm_dev_sock_open (dev, DEV_WIRELESS, __FUNCTION__, NULL)))
	{
		struct iwreq		wrq;

		err = iw_get_ext (nm_dev_sock_get_fd (sk), nm_device_get_iface (dev), SIOCGIWFREQ, &wrq);
		if (err >= 0)
			freq = iw_freq2float (&wrq.u.freq);
		if (err == -1)
			nm_warning ("nm_device_get_frequency(): error getting frequency for device %s.  errno = %d", nm_device_get_iface (dev), errno);

		nm_dev_sock_close (sk);
	}
	return (freq);
}


/*
 * nm_device_set_frequency
 *
 * For wireless devices, set the frequency to broadcast/receive on.
 * A frequency <= 0 means "auto".
 *
 */
void nm_device_set_frequency (NMDevice *dev, const double freq)
{
	NMSock	*sk;
	int		 err;
	
	/* HACK FOR NOW */
	if (freq <= 0)
		return;

	g_return_if_fail (dev != NULL);
	g_return_if_fail (nm_device_is_wireless (dev));

	/* Test devices don't really have a frequency, they always succeed */
	if (dev->test_device)
		return;

	if (nm_device_get_frequency (dev) == freq)
		return;

	if ((sk = nm_dev_sock_open (dev, DEV_WIRELESS, __FUNCTION__, NULL)))
	{
		struct iwreq		wrq;

		if (freq <= 0)
		{
			/* Auto */
			/* People like to make things hard for us.  Even though iwlib/iwconfig say
			 * that wrq.u.freq.m should be -1 for "auto" mode, nobody actually supports
			 * that.  Madwifi actually uses "0" to mean "auto".  So, we'll try 0 first
			 * and if that doesn't work, fall back to the iwconfig method and use -1.
			 *
			 * As a further note, it appears that Atheros/Madwifi cards can't go back to
			 * any-channel operation once you force set the channel on them.  For example,
			 * if you set a prism54 card to a specific channel, but then set the ESSID to
			 * something else later, it will scan for the ESSID and switch channels just fine.
			 * Atheros cards, however, just stay at the channel you previously set and don't
			 * budge, no matter what you do to them, until you tell them to go back to
			 * any-channel operation.
			 */
			wrq.u.freq.m = 0;
			wrq.u.freq.e = 0;
			wrq.u.freq.flags = 0;
		}
		else
		{
			/* Fixed */
			wrq.u.freq.flags = IW_FREQ_FIXED;
			iw_float2freq (freq, &wrq.u.freq);
		}
		err = iw_set_ext (nm_dev_sock_get_fd (sk), nm_device_get_iface (dev), SIOCSIWFREQ, &wrq);
		if (err == -1)
		{
			gboolean	success = FALSE;
			if ((freq <= 0) && ((errno == EINVAL) || (errno == EOPNOTSUPP)))
			{
				/* Ok, try "auto" the iwconfig way if the Atheros way didn't work */
				wrq.u.freq.m = -1;
				wrq.u.freq.e = 0;
				wrq.u.freq.flags = 0;
				if (iw_set_ext (nm_dev_sock_get_fd (sk), nm_device_get_iface (dev), SIOCSIWFREQ, &wrq) != -1)
					success = TRUE;
			}
		}

		nm_dev_sock_close (sk);
	}
}


/*
 * nm_device_get_bitrate
 *
 * For wireless devices, get the bitrate to broadcast/receive at.
 * Returned value is rate in KHz.
 *
 */
int nm_device_get_bitrate (NMDevice *dev)
{
	NMSock		*sk;
	int			 err = -1;
	struct iwreq	 wrq;
	
	g_return_val_if_fail (dev != NULL, 0);
	g_return_val_if_fail (nm_device_is_wireless (dev), 0);

	/* Test devices don't really have a bitrate, they always succeed */
	if (dev->test_device)
		return 11;

	if ((sk = nm_dev_sock_open (dev, DEV_WIRELESS, __FUNCTION__, NULL)))
	{
		err = iw_get_ext (nm_dev_sock_get_fd (sk), nm_device_get_iface (dev), SIOCGIWRATE, &wrq);
		nm_dev_sock_close (sk);
	}

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


/*
 * nm_device_set_bitrate
 *
 * For wireless devices, set the bitrate to broadcast/receive at.
 * Rate argument should be in Mbps (mega-bits per second), or 0 for automatic.
 *
 */
void nm_device_set_bitrate (NMDevice *dev, const int Mbps)
{
	NMSock	*sk;
	
	g_return_if_fail (dev != NULL);
	g_return_if_fail (nm_device_is_wireless (dev));

	/* Test devices don't really have a bitrate, they always succeed */
	if (dev->test_device)
		return;

	if (nm_device_get_bitrate (dev) == Mbps)
		return;

	if ((sk = nm_dev_sock_open (dev, DEV_WIRELESS, __FUNCTION__, NULL)))
	{
		struct iwreq		wrq;

		if (Mbps != 0)
		{
			wrq.u.bitrate.value = Mbps * 1000;
			wrq.u.bitrate.fixed = 1;
		}
		else
		{
			/* Auto bitrate */
			wrq.u.bitrate.value = -1;
			wrq.u.bitrate.fixed = 0;
		}
		/* Silently fail as not all drivers support setting bitrate yet (ipw2x00 for example) */
		iw_set_ext (nm_dev_sock_get_fd (sk), nm_device_get_iface (dev), SIOCSIWRATE, &wrq);

		nm_dev_sock_close (sk);
	}
}


/*
 * nm_device_get_ap_address
 *
 * If a device is wireless, get the access point's ethernet address
 * that the card is associated with.
 */
void nm_device_get_ap_address (NMDevice *dev, struct ether_addr *addr)
{
	NMSock		*sk;
	struct iwreq	 wrq;

	g_return_if_fail (dev != NULL);
	g_return_if_fail (addr != NULL);
	g_return_if_fail (nm_device_is_wireless (dev));

	/* Test devices return an invalid address when there's no link,
	 * and a made-up address when there is a link.
	 */
	if (dev->test_device)
	{
		struct ether_addr	good_addr = { {0x70, 0x37, 0x03, 0x70, 0x37, 0x03} };
		struct ether_addr	bad_addr = { {0x00, 0x00, 0x00, 0x00, 0x00, 0x00} };
		gboolean			link = nm_device_has_active_link (dev);

		memcpy ((link ? &good_addr : &bad_addr), &(wrq.u.ap_addr.sa_data), sizeof (struct ether_addr));
		return;
	}

	if ((sk = nm_dev_sock_open (dev, DEV_WIRELESS, __FUNCTION__, NULL)))
	{
		if (iw_get_ext (nm_dev_sock_get_fd (sk), nm_device_get_iface (dev), SIOCGIWAP, &wrq) >= 0)
			memcpy (addr, &(wrq.u.ap_addr.sa_data), sizeof (struct ether_addr));
		else
			memset (addr, 0, sizeof (struct ether_addr));
		nm_dev_sock_close (sk);
	}
}


/*
 * nm_device_set_enc_key
 *
 * If a device is wireless, set the encryption key that it should use.
 *
 * key:	encryption key to use, or NULL or "" to disable encryption.
 *		NOTE that at this time, the key must be the raw HEX key, not
 *		a passphrase.
 */
void nm_device_set_enc_key (NMDevice *dev, const char *key, NMDeviceAuthMethod auth_method)
{
	NMSock			*sk;
	int				err;
	struct iwreq		wreq;
	int				keylen;
	unsigned char		safe_key[IW_ENCODING_TOKEN_MAX + 1];
	gboolean			set_key = FALSE;
	
	g_return_if_fail (dev != NULL);
	g_return_if_fail (nm_device_is_wireless (dev));

	/* Test devices just ignore encryption keys */
	if (dev->test_device)
		return;

	/* Make sure the essid we get passed is a valid size */
	if (!key)
		safe_key[0] = '\0';
	else
	{
		strncpy (safe_key, key, IW_ENCODING_TOKEN_MAX);
		safe_key[IW_ENCODING_TOKEN_MAX] = '\0';
	}

	if ((sk = nm_dev_sock_open (dev, DEV_WIRELESS, __FUNCTION__, NULL)))
	{
		wreq.u.data.pointer = (caddr_t) NULL;
		wreq.u.data.length = 0;
		wreq.u.data.flags = IW_ENCODE_ENABLED;

		/* Unfortunately, some drivers (Cisco) don't make a distinction between
		 * Open System authentication mode and whether or not to use WEP.  You
		 * DON'T have to use WEP when using Open System, but these cards force
		 * it.  Therefore, we have to set Open System mode when using WEP.
		 */

		if (strlen (safe_key) == 0)
		{
			wreq.u.data.flags |= IW_ENCODE_DISABLED | IW_ENCODE_NOKEY;
			set_key = TRUE;
		}
		else
		{
			unsigned char		parsed_key[IW_ENCODING_TOKEN_MAX + 1];

			keylen = iw_in_key_full (nm_dev_sock_get_fd (sk), nm_device_get_iface (dev), safe_key, &parsed_key[0], &wreq.u.data.flags);
			if (keylen > 0)
			{
				switch (auth_method)
				{
					case NM_DEVICE_AUTH_METHOD_OPEN_SYSTEM:
						wreq.u.data.flags |= IW_ENCODE_OPEN;
						break;
					case NM_DEVICE_AUTH_METHOD_SHARED_KEY:
						wreq.u.data.flags |= IW_ENCODE_RESTRICTED;
						break;
					default:
						wreq.u.data.flags |= IW_ENCODE_RESTRICTED;
						break;
				}
				wreq.u.data.pointer	=  (caddr_t) &parsed_key;
				wreq.u.data.length	=  keylen;
				set_key = TRUE;
			}
		}

		if (set_key)
		{
			if (iw_set_ext (nm_dev_sock_get_fd (sk), nm_device_get_iface (dev), SIOCSIWENCODE, &wreq) == -1)
				nm_warning ("nm_device_set_enc_key(): error setting key for device %s.  errno = %d", nm_device_get_iface (dev), errno);
		}

		nm_dev_sock_close (sk);
	} else nm_warning ("nm_device_set_enc_key(): could not get wireless control socket.");
}


/*
 * nm_device_get_signal_strength
 *
 * Get the current signal strength of a wireless device.  This only works when
 * the card is associated with an access point, so will only work for the
 * active device.
 *
 * Returns:	-1 on error
 *			0 - 100  strength percentage of the connection to the current access point
 *
 */
gint8 nm_device_get_signal_strength (NMDevice *dev)
{
	g_return_val_if_fail (dev != NULL, -1);
	g_return_val_if_fail (nm_device_is_wireless (dev), -1);

	return (dev->options.wireless.strength);
}


/*
 * nm_device_update_signal_strength
 *
 * Update the device's idea of the strength of its connection to the
 * current access point.
 *
 */
void nm_device_update_signal_strength (NMDevice *dev)
{
	gboolean	has_range = FALSE;
	NMSock	*sk;
	iwrange	range;
	iwstats	stats;
	int		percent = -1;

	g_return_if_fail (dev != NULL);
	g_return_if_fail (nm_device_is_wireless (dev));
	g_return_if_fail (dev->app_data != NULL);

	/* Grab the scan lock since our strength is meaningless during a scan. */
	if (!nm_try_acquire_mutex (dev->options.wireless.scan_mutex, __FUNCTION__))
		return;

	/* If we aren't the active device, we don't really have a signal strength
	 * that would mean anything.
	 */
	if (dev != dev->app_data->active_device)
	{
		dev->options.wireless.strength = -1;
		goto out;
	}

	/* Fake a value for test devices */
	if (dev->test_device)
	{
		dev->options.wireless.strength = 75;
		goto out;
	}

	if ((sk = nm_dev_sock_open (dev, DEV_WIRELESS, __FUNCTION__, NULL)))
	{
		has_range = (iw_get_range_info (nm_dev_sock_get_fd (sk), nm_device_get_iface (dev), &range) >= 0);
		if (iw_get_stats (nm_dev_sock_get_fd (sk), nm_device_get_iface (dev), &stats, &range, has_range) == 0)
		{
			percent = nm_wireless_qual_to_percent (&stats.qual, (const iwqual *)(&dev->options.wireless.max_qual),
					(const iwqual *)(&dev->options.wireless.avg_qual));
		}
		nm_dev_sock_close (sk);
	}

	/* Try to smooth out the strength.  Atmel cards, for example, will give no strength
	 * one second and normal strength the next.
	 */
	if ((percent == -1) && (++dev->options.wireless.invalid_strength_counter <= 3))
		percent = dev->options.wireless.strength;
	else
		dev->options.wireless.invalid_strength_counter = 0;

	dev->options.wireless.strength = percent;

out:
	nm_unlock_mutex (dev->options.wireless.scan_mutex, __FUNCTION__);
}


/*
 * nm_device_get_ip4_address
 *
 * Get a device's IPv4 address
 *
 */
guint32 nm_device_get_ip4_address(NMDevice *dev)
{
	g_return_val_if_fail (dev != NULL, 0);

	return (dev->ip4_address);
}

void nm_device_update_ip4_address (NMDevice *dev)
{
	guint32		new_address;
	struct ifreq	req;
	NMSock		*sk;
	int			err;
	
	g_return_if_fail (dev  != NULL);
	g_return_if_fail (dev->app_data != NULL);
	g_return_if_fail (nm_device_get_iface (dev) != NULL);

	/* Test devices get a nice, bogus IP address */
	if (dev->test_device)
	{
		dev->ip4_address = 0x07030703;
		return;
	}

	if ((sk = nm_dev_sock_open (dev, DEV_GENERAL, __FUNCTION__, NULL)) == NULL)
		return;
	
	memset (&req, 0, sizeof (struct ifreq));
	strncpy ((char *)(&req.ifr_name), nm_device_get_iface (dev), strlen (nm_device_get_iface (dev)));
	err = ioctl (nm_dev_sock_get_fd (sk), SIOCGIFADDR, &req);
	nm_dev_sock_close (sk);
	if (err != 0)
		return;

	new_address = ((struct sockaddr_in *)(&req.ifr_addr))->sin_addr.s_addr;

	/* If the new address is different, send an IP4AddressChanged signal on the bus */
	if (new_address != nm_device_get_ip4_address (dev))
	{
		nm_dbus_signal_device_ip4_address_change (dev->app_data->dbus_connection, dev);
		dev->ip4_address = new_address;
	}
}


/*
 * nm_device_get_ip6_address
 *
 * Get a device's IPv6 address
 *
 */
void nm_device_get_ip6_address(NMDevice *dev)
{
	/* FIXME
	 * Implement
	 */
}


/*
 * nm_device_get_hw_address
 *
 * Get a device's hardware address
 *
 */
void nm_device_get_hw_address(NMDevice *dev, unsigned char *eth_addr)
{
	g_return_if_fail (eth_addr != NULL);
	g_return_if_fail (dev != NULL);

	memcpy (eth_addr, dev->hw_addr, ETH_ALEN);
}

void nm_device_update_hw_address (NMDevice *dev)
{
	struct ifreq	req;
	NMSock		*sk;
	int			err;

	g_return_if_fail (dev  != NULL);
	g_return_if_fail (dev->app_data != NULL);
	g_return_if_fail (nm_device_get_iface (dev) != NULL);

	/* Test devices get a nice, bogus IP address */
	if (dev->test_device)
	{
		memset (dev->hw_addr, 0, ETH_ALEN);
		return;
	}

	if ((sk = nm_dev_sock_open (dev, DEV_GENERAL, __FUNCTION__, NULL)) == NULL)
		return;
	
	memset (&req, 0, sizeof (struct ifreq));
	strncpy ((char *)(&req.ifr_name), nm_device_get_iface (dev), strlen (nm_device_get_iface (dev)));
	err = ioctl (nm_dev_sock_get_fd (sk), SIOCGIFHWADDR, &req);
	nm_dev_sock_close (sk);
	if (err != 0)
		return;

     memcpy (dev->hw_addr, req.ifr_hwaddr.sa_data, ETH_ALEN);
}


/*
 * nm_device_set_up_down
 *
 * Set the up flag on the device on or off
 *
 */
static void nm_device_set_up_down (NMDevice *dev, gboolean up)
{
	struct ifreq	ifr;
	NMSock		*sk;
	guint32		flags = up ? IFF_UP : ~IFF_UP;

	g_return_if_fail (dev != NULL);

	/* Test devices do whatever we tell them to do */
	if (dev->test_device)
	{
		dev->test_device_up = up;
		return;
	}

	if ((sk = nm_dev_sock_open (dev, DEV_GENERAL, __FUNCTION__, NULL)) == NULL)
		return;

	/* Get flags already there */
	strcpy (ifr.ifr_name, nm_device_get_iface (dev));
	if (ioctl (nm_dev_sock_get_fd (sk), SIOCGIFFLAGS, &ifr) != -1)
	{
		/* If the interface doesn't have those flags already,
		 * set them on it.
		 */
		if ((ifr.ifr_flags^flags) & IFF_UP)
		{
			ifr.ifr_flags &= ~IFF_UP;
			ifr.ifr_flags |= IFF_UP & flags;
			if (ioctl (nm_dev_sock_get_fd (sk), SIOCSIFFLAGS, &ifr) == -1)
				nm_warning ("nm_device_set_up_down() could not bring device %s %s.  errno = %d", nm_device_get_iface (dev), (up ? "up" : "down"), errno );
		}
		/* Make sure we have a valid MAC address, some cards reload firmware when they
		 * are brought up.
		 */
		if (!nm_ethernet_address_is_valid((struct ether_addr *)dev->hw_addr))
			nm_device_update_hw_address(dev);
	}
	else
		nm_warning ("nm_device_set_up_down() could not get flags for device %s.  errno = %d", nm_device_get_iface (dev), errno );

	nm_dev_sock_close (sk);
}


/*
 * Interface state functions: bring up, down, check
 *
 */
gboolean nm_device_is_up (NMDevice *dev)
{
	NMSock		*sk;
	struct ifreq	ifr;
	int			err;

	g_return_val_if_fail (dev != NULL, FALSE);

	if (dev->test_device)
		return (dev->test_device_up);

	if ((sk = nm_dev_sock_open (dev, DEV_GENERAL, __FUNCTION__, NULL)) == NULL)
		return (FALSE);

	/* Get device's flags */
	strcpy (ifr.ifr_name, nm_device_get_iface (dev));
	err = ioctl (nm_dev_sock_get_fd (sk), SIOCGIFFLAGS, &ifr);
	nm_dev_sock_close (sk);
	if (!err)
		return (!((ifr.ifr_flags^IFF_UP) & IFF_UP));

	nm_warning ("nm_device_is_up() could not get flags for device %s.  errno = %d", nm_device_get_iface (dev), errno );
	return (FALSE);
}

/* I really wish nm_v_wait_for_completion_or_timeout could translate these
 * to first class args instead of a all this void * arg stuff, so these
 * helpers could be nice and _tiny_. */
gboolean nm_completion_device_is_up_test(int tries, nm_completion_args args)
{
	NMDevice *dev = args[0];
	gboolean *err = args[1];
	gboolean cancelable = (gboolean)args[2];

	g_return_val_if_fail(dev != NULL, TRUE);
	g_return_val_if_fail(err != NULL, TRUE);

	*err = FALSE;
	if (cancelable && nm_device_activation_handle_cancel(dev)) {
		*err = TRUE;
		return TRUE;
	}
	if (nm_device_is_up (dev))
		return TRUE;
	return FALSE;
}

void nm_device_bring_up (NMDevice *dev)
{
	g_return_if_fail (dev != NULL);

	nm_device_set_up_down (dev, TRUE);
}

gboolean nm_device_bring_up_wait (NMDevice *dev, gboolean cancelable)
{
	gboolean err = FALSE;
	nm_completion_args args;

	g_return_val_if_fail (dev != NULL, TRUE);

	nm_device_bring_up (dev);

	args[0] = dev;
	args[1] = &err;
	args[2] = (void *)cancelable;
	nm_wait_for_completion(400, G_USEC_PER_SEC / 200, NULL,
			nm_completion_device_is_up_test, args);
	if (err)
		nm_info ("failed to bring device up");
	return err;
}

void nm_device_bring_down (NMDevice *dev)
{
	g_return_if_fail (dev != NULL);

	nm_device_set_up_down (dev, FALSE);
}

gboolean nm_completion_device_is_down_test(int tries, nm_completion_args args)
{
	NMDevice *dev = args[0];
	gboolean *err = args[1];
	gboolean cancelable = (gboolean)args[2];

	g_return_val_if_fail(dev != NULL, TRUE);
	g_return_val_if_fail(err != NULL, TRUE);

	*err = FALSE;
	if (cancelable && nm_device_activation_handle_cancel(dev)) {
		*err = TRUE;
		return TRUE;
	}
	if (!nm_device_is_up (dev))
		return TRUE;
	return FALSE;
}

gboolean nm_device_bring_down_wait (NMDevice *dev, gboolean cancelable)
{
	gboolean err = FALSE;
	nm_completion_args args;

	g_return_val_if_fail (dev != NULL, TRUE);

	nm_device_bring_down (dev);

	args[0] = dev;
	args[1] = &err;
	args[2] = (void *)cancelable;
	nm_wait_for_completion(400, G_USEC_PER_SEC / 200, NULL,
			nm_completion_device_is_down_test, args);
	if (err)
		nm_info ("failed to bring device down");
	return err;
}


/*
 * nm_device_get_mode
 *
 * Get managed/infrastructure/adhoc mode on a device (currently wireless only)
 *
 */
NMNetworkMode nm_device_get_mode (NMDevice *dev)
{
	NMSock		*sk;
	NMNetworkMode	mode = NETWORK_MODE_UNKNOWN;

	g_return_val_if_fail (dev != NULL, NETWORK_MODE_UNKNOWN);
	g_return_val_if_fail (nm_device_is_wireless (dev), NETWORK_MODE_UNKNOWN);

	/* Force the card into Managed/Infrastructure mode */
	if ((sk = nm_dev_sock_open (dev, DEV_WIRELESS, __FUNCTION__, NULL)))
	{
		struct iwreq	wrq;
		int			err;

		if (iw_get_ext (nm_dev_sock_get_fd (sk), nm_device_get_iface (dev), SIOCGIWMODE, &wrq) == 0)
		{
			switch (wrq.u.mode)
			{
				case IW_MODE_INFRA:
					mode = NETWORK_MODE_INFRA;
					break;
				case IW_MODE_ADHOC:
					mode = NETWORK_MODE_ADHOC;
					break;
				default:
					break;
			}
		}
		else
			nm_warning ("nm_device_get_mode (%s): error getting card mode.  errno = %d", nm_device_get_iface (dev), errno);				
		nm_dev_sock_close (sk);
	}

	return (mode);
}


/*
 * nm_device_set_mode
 *
 * Set managed/infrastructure/adhoc mode on a device (currently wireless only)
 *
 */
gboolean nm_device_set_mode (NMDevice *dev, const NMNetworkMode mode)
{
	NMSock		*sk;
	gboolean		 success = FALSE;

	g_return_val_if_fail (dev != NULL, FALSE);
	g_return_val_if_fail (nm_device_is_wireless (dev), FALSE);
	g_return_val_if_fail ((mode == NETWORK_MODE_INFRA) || (mode == NETWORK_MODE_ADHOC), FALSE);

	if (nm_device_get_mode (dev) == mode)
		return TRUE;

	/* Force the card into Managed/Infrastructure mode */
	if ((sk = nm_dev_sock_open (dev, DEV_WIRELESS, __FUNCTION__, NULL)))
	{
		struct iwreq	wreq;
		int			err;
		gboolean		mode_good = FALSE;

		switch (mode)
		{
			case NETWORK_MODE_INFRA:
				wreq.u.mode = IW_MODE_INFRA;
				mode_good = TRUE;
				break;
			case NETWORK_MODE_ADHOC:
				wreq.u.mode = IW_MODE_ADHOC;
				mode_good = TRUE;
				break;
			default:
				mode_good = FALSE;
				break;
		}
		if (mode_good)
		{
			if (iw_set_ext (nm_dev_sock_get_fd (sk), nm_device_get_iface (dev), SIOCSIWMODE, &wreq) == 0)
				success = TRUE;
			else
				nm_warning ("nm_device_set_mode (%s): error setting card to %s mode.  errno = %d",
					nm_device_get_iface (dev),
					mode == NETWORK_MODE_INFRA ? "Infrastructure" : (mode == NETWORK_MODE_ADHOC ? "adhoc" : "unknown"),
					errno);
		}
		nm_dev_sock_close (sk);
	}

	return (success);
}


/*
 * nm_device_activation_schedule_finish
 *
 * Schedule an idle routine in the main thread to finish the activation.
 *
 */
void nm_device_activation_schedule_finish (NMDevice *dev, NMAccessPoint *failed_ap, DeviceStatus activation_result)
{
	GSource			*source = NULL;
	NMActivationResult	*result = NULL;

	g_return_if_fail (dev != NULL);
	g_return_if_fail (dev->app_data != NULL);

	result = g_malloc0 (sizeof (NMActivationResult));
	nm_device_ref (dev);	/* Ref device for idle handler */
	result->dev = dev;
	result->failed_ap = failed_ap;
	result->result = activation_result;

	source = g_idle_source_new ();
	g_source_set_callback (source, nm_policy_activation_finish, (gpointer)result, NULL);
	g_source_attach (source, dev->app_data->main_context);
	g_source_unref (source);
}


/*
 * nm_device_activation_schedule_start
 *
 * Tell the device thread to begin activation.
 *
 * Returns:	TRUE on success activation beginning
 *			FALSE on error beginning activation (bad params, couldn't create thread)
 *
 */
gboolean nm_device_activation_schedule_start (NMDevice *dev)
{
	NMData	*data = NULL;
	GSource	*source = NULL;

	g_return_val_if_fail (dev != NULL, FALSE);
	g_return_val_if_fail (!dev->activating, TRUE);	/* Return if activation has already begun */

	data = dev->app_data;
	g_return_val_if_fail (data != NULL, FALSE);

	/* Reset communication flags between worker and main thread */
	dev->activating = TRUE;
	dev->quit_activation = FALSE;
	if (nm_device_is_wireless (dev))
	{
		nm_device_set_now_scanning (dev, TRUE);
		dev->options.wireless.user_key_received = FALSE;
	}

	if (nm_device_get_driver_support_level (dev) == NM_DRIVER_UNSUPPORTED)
	{
		dev->activating = FALSE;
		return (FALSE);
	}

	source = g_idle_source_new ();
	g_source_set_callback (source, nm_device_activate, dev, NULL);
	g_source_attach (source, dev->context);
	g_source_unref (source);

	nm_dbus_signal_device_status_change (data->dbus_connection, dev, DEVICE_ACTIVATING);

	return (TRUE);
}


/*
 * nm_device_activation_handle_cancel
 *
 * Check whether we should stop activation, and if so clean up flags
 * and other random things.
 *
 */
static gboolean nm_device_activation_handle_cancel (NMDevice *dev)
{
	g_return_val_if_fail (dev != NULL, TRUE);

	/* If we were told to quit activation, stop the thread and return */
	if (dev->quit_activation)
	{
		nm_debug ("activation of device '%s' canceled.", nm_device_get_iface (dev));
		if (nm_device_is_wireless (dev))
			nm_device_set_now_scanning (dev, FALSE);
		return (TRUE);
	}

	return (FALSE);
}


static gboolean nm_dwwfl_test (int tries, nm_completion_args args)
{
	NMDevice *dev = args[0];
	guint *assoc_count = args[1];
	double *last_freq = args[2];
	char *essid = args[3];
	int required = (int)args[4];

	double cur_freq = nm_device_get_frequency (dev);
	gboolean assoc = nm_device_wireless_is_associated (dev);
	const char * cur_essid = nm_device_get_essid (dev);

	/* If we've been cancelled, return that we should stop */
	if (nm_device_activation_should_cancel (dev))
		return TRUE;

	/* If we're on the same frequency and essid, and we're associated,
	 * increment the count for how many iterations we've been associated;
	 * otherwise start over. */
	/* XXX floating point comparison this way is dangerous, IIRC */
	if ((cur_freq == *last_freq) && assoc && !strcmp (essid, cur_essid))
	{
		(*assoc_count)++;
	}
	else
	{
		*assoc_count = 0;
		*last_freq = cur_freq;
	}

	/* If we're told to cancel, return that we're finished.
	 * If we've the frequency has been stable for more than the required
	 * interval, return that we're finished.
	 * Otherwise, we're not finished. */
	if (nm_device_activation_should_cancel (dev) || *assoc_count >= required)
		return TRUE;

	return FALSE;
}


/*
 * nm_device_wireless_wait_for_link
 *
 * Try to be clever about when the wireless card really has associated with the access point.
 * Return TRUE when we think that it has, and FALSE when we thing it has not associated.
 *
 */
static gboolean nm_device_wireless_wait_for_link (NMDevice *dev, const char *essid)
{
	guint		assoc = 0;
	double		last_freq = 0;
	guint		assoc_count = 0;
	struct timeval	timeout = { .tv_sec = 0, .tv_usec = 0 };
	nm_completion_args args;

	/* we want to sleep for a very short amount of time, to minimize
	 * hysteresis on the boundaries of our required time.  But we
	 * also want the maximum to be based on what the card */
	const guint	delay = 30;
	const guint	required_tries = 10;
	const guint	min_delay = 2 * (required_tries / delay);

	g_return_val_if_fail (dev != NULL, FALSE);
	g_return_val_if_fail (time > 0, FALSE);

	/* for cards which don't scan many frequencies, this will return 
	 * 5 seconds, which we'll bump up to 6 seconds below.  Oh well. */
	timeout.tv_sec = (time_t)nm_device_get_association_pause_value (dev);

	/* Refuse to to have a timeout that's _less_ than twice the total time
	 * required before calling a link valid */
	if (timeout.tv_sec < min_delay)
		timeout.tv_sec = min_delay;

	/* We more or less keep asking the driver for the frequency the
	 * card is listening on until it connects to an AP.  Once it's 
	 * associated, the driver stops scanning.  To detect that, we look
	 * for the essid and frequency to remain constant for 3 seconds.
	 * When it remains constant, we assume it's a real link. */
	args[0] = dev;
	args[1] = &assoc;
	args[2] = &last_freq;
	args[3] = (void *)essid;
	args[4] = (void *)(required_tries * 2);
	nm_wait_for_timeout (&timeout, G_USEC_PER_SEC / delay,
			    nm_dwwfl_test, nm_dwwfl_test, args);

	/* If we've had a reasonable association count, we say we have a link */
	if (assoc > required_tries)
		return TRUE;
	return FALSE;
}


static gboolean nm_device_link_test(int tries, nm_completion_args args)
{
	NMDevice *dev = args[0];
	gboolean *err = args[1];

	g_return_val_if_fail(dev != NULL, TRUE);
	g_return_val_if_fail(err != NULL, TRUE);

	if (nm_device_wireless_is_associated (dev) && nm_device_get_essid (dev))
	{
		*err = FALSE;
		return TRUE;
	}
	*err = TRUE;
	return FALSE;
}
 
static gboolean nm_device_is_up_and_associated_wait (NMDevice *dev, int timeout, int interval)
{
	gboolean err;
	const gint delay = (G_USEC_PER_SEC * nm_device_get_association_pause_value (dev)) / interval;
	const gint max_cycles = timeout * interval;
	nm_completion_args args;

	g_return_val_if_fail (dev != NULL, TRUE);

	args[0] = dev;
	args[1] = &err;
	nm_wait_for_completion (max_cycles, delay, NULL, nm_device_link_test, args);
	return !err;
}


/*
 * nm_device_set_wireless_config
 *
 * Bring up a wireless card with the essid and wep key of its "best" ap
 *
 * Returns:	TRUE on successful activation
 *			FALSE on unsuccessful activation (ie no best AP)
 *
 */
static gboolean nm_device_set_wireless_config (NMDevice *dev, NMAccessPoint *ap)
{
	NMDeviceAuthMethod	 auth;
	const char		*essid = NULL;

	g_return_val_if_fail (dev  != NULL, FALSE);
	g_return_val_if_fail (nm_device_is_wireless (dev), FALSE);
	g_return_val_if_fail (ap != NULL, FALSE);
	g_return_val_if_fail (nm_ap_get_essid (ap) != NULL, FALSE);
	g_return_val_if_fail (nm_ap_get_auth_method (ap) != NM_DEVICE_AUTH_METHOD_UNKNOWN, FALSE);

	/* Force the card into Managed/Infrastructure mode */
	nm_device_bring_down_wait (dev, 0);
	nm_device_bring_up_wait (dev, 0);

	nm_device_set_mode (dev, NETWORK_MODE_INFRA);

	essid = nm_ap_get_essid (ap);
	auth = nm_ap_get_auth_method (ap);

	nm_device_set_mode (dev, nm_ap_get_mode (ap));
	nm_device_set_bitrate (dev, 0);

	if (nm_ap_get_user_created (ap) || (nm_ap_get_freq (ap) && (nm_ap_get_mode (ap) == NETWORK_MODE_ADHOC)))
		nm_device_set_frequency (dev, nm_ap_get_freq (ap));
	else
		nm_device_set_frequency (dev, 0);	/* auto */

	if (nm_ap_get_encrypted (ap) && nm_ap_is_enc_key_valid (ap))
	{
		char				*hashed_key = nm_ap_get_enc_key_hashed (ap);

		if (auth == NM_DEVICE_AUTH_METHOD_NONE)
		{
			nm_ap_set_auth_method (ap, NM_DEVICE_AUTH_METHOD_OPEN_SYSTEM);
			nm_warning ("Activation (%s/wireless): AP '%s' said it was encrypted, but had "
					"'none' for authentication method.  Using Open System authentication method.",
					nm_device_get_iface (dev), nm_ap_get_essid (ap));
		}
		nm_device_set_enc_key (dev, hashed_key, auth);
		g_free (hashed_key);
	}
	else
		nm_device_set_enc_key (dev, NULL, NM_DEVICE_AUTH_METHOD_NONE);

	nm_device_set_essid (dev, essid);

	nm_info ("Activation (%s/wireless): using essid '%s', with %s authentication.",
			nm_device_get_iface (dev), essid, (auth == NM_DEVICE_AUTH_METHOD_NONE) ? "no" :
				((auth == NM_DEVICE_AUTH_METHOD_OPEN_SYSTEM) ? "Open System" :
				((auth == NM_DEVICE_AUTH_METHOD_SHARED_KEY) ? "Shared Key" : "unknown")));

	/* Bring the device up and pause to allow card to associate.  After we set the ESSID
	 * on the card, the card has to scan all channels to find our requested AP (which can
	 * take a long time if it is an A/B/G chipset like the Atheros 5212, for example).
	 */
	nm_device_is_up_and_associated_wait (dev, 2, 100);

	/* Some cards don't really work well in ad-hoc mode unless you explicitly set the bitrate
	 * on them. (Netgear WG511T/Atheros 5212 with madwifi drivers).  Until we can get rate information
	 * from scanned access points out of iwlib, clamp bitrate for these cards at 11Mbps.
	 */
	if ((nm_ap_get_mode (ap) == NETWORK_MODE_ADHOC) && (nm_device_get_bitrate (dev) <= 0))
		nm_device_set_bitrate (dev, 11000);	/* In Kbps */

	return (TRUE);
}


/*
 * nm_device_activate_wireless_adhoc
 *
 * Create an ad-hoc network (rather than associating with one).
 *
 */
static gboolean nm_device_activate_wireless_adhoc (NMDevice *dev, NMAccessPoint *ap)
{
	gboolean			 success = FALSE;
	NMDeviceAuthMethod	 auth = NM_DEVICE_AUTH_METHOD_NONE;
	NMAPListIter		*iter;
	NMAccessPoint		*tmp_ap;
	double			 card_freqs[IW_MAX_FREQUENCIES];
	int				 num_freqs = 0, i;
	double			 freq_to_use = 0;
	iwrange			 range;
	NMSock			*sk;
	int				 err;

	g_return_val_if_fail (dev != NULL, FALSE);
	g_return_val_if_fail (ap != NULL, FALSE);

	if (nm_ap_get_encrypted (ap))
		auth = NM_DEVICE_AUTH_METHOD_SHARED_KEY;

	/* Build our local list of frequencies to whittle down until we find a free one */
	memset (&card_freqs, 0, sizeof (card_freqs));
	num_freqs = MIN (dev->options.wireless.num_freqs, IW_MAX_FREQUENCIES);
	for (i = 0; i < num_freqs; i++)
		card_freqs[i] = dev->options.wireless.freqs[i];

	/* We need to find a clear wireless channel to use.  We will
	 * only use 802.11b channels for now.
	 */
	iter = nm_ap_list_iter_new (nm_device_ap_list_get (dev));
	while ((tmp_ap = nm_ap_list_iter_next (iter)))
	{
		double ap_freq = nm_ap_get_freq (tmp_ap);
		for (i = 0; i < num_freqs && ap_freq; i++)
		{
			if (card_freqs[i] == ap_freq)
				card_freqs[i] = 0;
		}
	}
	nm_ap_list_iter_free (iter);

	if ((sk = nm_dev_sock_open (dev, DEV_WIRELESS, __FUNCTION__, NULL)) == NULL)
		return FALSE;

	err = iw_get_range_info (nm_dev_sock_get_fd (sk), nm_device_get_iface (dev), &range);
	nm_dev_sock_close (sk);
	if (err < 0)
		return FALSE;

	/* Ok, find the first non-zero freq in our table and use it.
	 * For now we only try to use a channel in the 802.11b channel
	 * space so that most everyone can see it.
	 */
	for (i = 0; i < num_freqs; i++)
	{
		int channel = iw_freq_to_channel (card_freqs[i], &range);
		if (card_freqs[i] && (channel > 0) && (channel < 15))
		{
			freq_to_use = card_freqs[i];
			break;
		}
	}

	/* Hmm, no free channels in 802.11b space.  Pick one more or less randomly */
	if (!freq_to_use)
	{
		double pfreq;
		int	channel = (int)(random () % 14);
		int	err;

		err = iw_channel_to_freq (channel, &pfreq, &range);
		if (err == channel)
			freq_to_use = pfreq;
	}

	if (freq_to_use)
	{
		nm_ap_set_freq (ap, freq_to_use);
	
		nm_info ("Will create network '%s' with frequency %f.", nm_ap_get_essid (ap), nm_ap_get_freq (ap));
		if ((success = nm_device_set_wireless_config (dev, ap)))
			success = nm_device_activation_configure_ip (dev, TRUE);
	}

	return (success);
}


static gboolean AP_NEED_KEY (NMDevice *dev, NMAccessPoint *ap)
{
	char		*essid;
	gboolean	 need_key = FALSE;

	g_return_val_if_fail (ap != NULL, FALSE);

	essid = nm_ap_get_essid (ap);

	if (!nm_ap_get_encrypted (ap))
	{
		nm_info ("Activation (%s/wireless): access point '%s' is "
			 "unencrypted, no key needed.", 
			 nm_device_get_iface (dev), essid ? essid : "(null)");
	}
	else
	{
		if (nm_ap_is_enc_key_valid (ap))
		{
			nm_info ("Activation (%s/wireless): access point '%s' "
				 "is encrypted, and a key exists.  No new key needed.",
			  	 nm_device_get_iface (dev), essid ? essid : "(null)");
		}
		else
		{
			nm_info ("Activation (%s/wireless): access point '%s' "
				 "is encrypted, but NO valid key exists.  New key needed.",
				 nm_device_get_iface (dev), 
				 essid ? essid : "(null)");
			need_key = TRUE;
		}
	}

	return (need_key);
}


/*
 * get_initial_auth_method
 *
 * Update the auth method of the AP from the last-known-good one saved in the allowed list
 * (which is found from NMI) and ensure that its valid with the encryption status of the AP.
 *
 */
static NMDeviceAuthMethod get_initial_auth_method (NMAccessPoint *ap, NMAccessPointList *allowed_list)
{
	g_return_val_if_fail (ap != NULL, NM_DEVICE_AUTH_METHOD_OPEN_SYSTEM);

	if (nm_ap_get_encrypted (ap))
	{
		NMDeviceAuthMethod	 auth = nm_ap_get_auth_method (ap);
		NMAccessPoint		*allowed_ap = nm_ap_list_get_ap_by_essid (allowed_list, nm_ap_get_essid (ap));
		
		/* Prefer default auth method if we found one for this AP in our allowed list. */
		if (allowed_ap)
			auth = nm_ap_get_auth_method (allowed_ap);

		if (    (auth == NM_DEVICE_AUTH_METHOD_OPEN_SYSTEM)
			|| (auth == NM_DEVICE_AUTH_METHOD_SHARED_KEY))
			return (auth);
		else
			return (NM_DEVICE_AUTH_METHOD_OPEN_SYSTEM);
	}

	return (NM_DEVICE_AUTH_METHOD_NONE);
}


void invalidate_ap (NMDevice *dev, NMAccessPoint *ap)
{
	g_return_if_fail (dev != NULL);
	g_return_if_fail (dev->app_data != NULL);
	g_return_if_fail (ap != NULL);

	/* If its an AP the user forced, notify the user it failed. */
	/* FIXME: we dont' set ap's that are in our scan list as "artificial",
	 * so we won't be able to signal the user when a connection to on of them
	 * failed.
	 */
	if (nm_ap_get_artificial (ap))
		nm_dbus_schedule_network_not_found_signal (dev->app_data, nm_ap_get_essid (ap));	

	nm_ap_set_invalid (ap, TRUE);
	nm_ap_list_append_ap (dev->app_data->invalid_ap_list, ap);
	nm_ap_unref (ap);
	nm_device_update_best_ap (dev);
}


/* this gets called without the scan mutex held */
static gboolean nm_wa_test (int tries, nm_completion_args args)
{
	NMDevice *dev = args[0];
	NMAccessPoint **best_ap = args[1];
	gboolean *err = args[2];

	g_return_val_if_fail(dev != NULL, TRUE);
	g_return_val_if_fail(best_ap != NULL, TRUE);
	g_return_val_if_fail(err != NULL, TRUE);

	*err = TRUE;
	if (nm_device_activation_handle_cancel(dev))
		return TRUE;

	if (tries % 100 == 0)
		nm_info ("Activation (%s/wireless): waiting for access point. (attempt %d)", nm_device_get_iface(dev), tries);

	*best_ap = nm_device_get_best_ap(dev);
	if (*best_ap)
	{
		/* Set ESSID early so that when we send out the
		 * DeviceStatusChanged signal below, we are able to 
		 * respond correctly to queries for "getActiveNetwork"
		 * against our device.  nm_device_get_path_for_ap() uses 
		 * the /card's/ AP, not the best_ap. */
		nm_device_set_essid (dev, nm_ap_get_essid (*best_ap));
		nm_device_set_now_scanning (dev, FALSE);
		*err = FALSE;
		return TRUE;
	}
	else
	{
		/* Since scanning runs in the device thread, we block scans
		 * during device activation.  So we need to run a scan periodically
		 * during activation too.
		 */
		GTimeVal			 cur_time;

		/* If the last scan was done more than 15s before, do another one. */
		g_get_current_time (&cur_time);
		if (cur_time.tv_sec >= dev->options.wireless.last_scan + 15)
		{
			NMWirelessScanCB	*scan_cb = g_malloc0 (sizeof (NMWirelessScanCB));

			scan_cb->dev = dev;
			scan_cb->reschedule = FALSE;
			nm_device_wireless_scan (scan_cb);
		}
	}

	return FALSE;
}


static gboolean nm_dukr_test (int tries, nm_completion_args args)
{
	NMDevice	*dev = args[0];
	gboolean	*err = args[1];

	g_return_val_if_fail (dev != NULL, TRUE);
	g_return_val_if_fail (err != NULL, TRUE);

	*err = TRUE;

	if (nm_device_activation_handle_cancel (dev))
		return TRUE;
	if (dev->options.wireless.user_key_received)
	{
		*err = FALSE;
		return TRUE;
	}
	return FALSE;
}


/*
 * nm_device_activate_wireless
 *
 * Activate a wireless ethernet device.  Locking could be confusing here, pay attention to it.
 * We grab the scan mutex because scanning requires us to set certain state on the card,
 * like mode, which could screw up device activation link state checks.
 *
 */
static gboolean nm_device_activate_wireless (NMDevice *dev)
{
	NMAccessPoint		*best_ap = NULL;
	gboolean			 success = FALSE;
	guint8			 attempt = 1;
	char				 last_essid [50] = "\0";
	gboolean			 need_key = FALSE;
	gboolean			 found_ap = FALSE;
	gboolean			 err = FALSE;
	nm_completion_args	 args;

	g_return_val_if_fail (dev != NULL, FALSE);
	g_return_val_if_fail (dev->app_data != NULL, FALSE);

	/* Grab the scan mutex, we don't want the scan thread to mess up our settings
	 * during activation and link detection.
	 */
	nm_lock_mutex (dev->options.wireless.scan_mutex, __FUNCTION__);

	nm_device_bring_up_wait (dev, 1);

get_ap:
	/* If we were told to quit activation, stop the thread and return */
	if (nm_device_activation_handle_cancel (dev))
		goto out;

	/* Get a valid "best" access point we should connect to.  We don't hold the scan
	 * lock here because this might take a while.
	 */
	nm_unlock_mutex (dev->options.wireless.scan_mutex, __FUNCTION__);

	/* Get a valid "best" access point we should connect to. */
	nm_device_set_now_scanning (dev, TRUE);

	/* Get an access point to connect to */
	args[0] = dev;
	args[1] = &best_ap;
	args[2] = &err;
	nm_wait_for_completion (NM_COMPLETION_TRIES_INFINITY, G_USEC_PER_SEC / 50,
			nm_wa_test, NULL, args);
	if (err)
	{
		/* Wierd as it may seem, we lock here to balance the unlock in "out:" */
		nm_lock_mutex (dev->options.wireless.scan_mutex, __FUNCTION__);
		goto out;
	}
	nm_info ("Activation (%s/wireless): found access point '%s' to use.", nm_device_get_iface (dev), nm_ap_get_essid (best_ap));

	/* We grab the scan mutex so that scanning cannot screw up our link detection, since
	 * a scan can change most any attribute on the card for a period of time.
	 */
	nm_device_set_now_scanning (dev, FALSE);
	nm_lock_mutex (dev->options.wireless.scan_mutex, __FUNCTION__);

	if (nm_ap_get_artificial (best_ap))
	{
		/* Some Cisco cards (340/350 PCMCIA) don't return non-broadcasting APs
		 * in their scan results, so we can't know beforehand whether or not the
		 * AP was encrypted.  We have to update their encryption status on the fly.
		 */
		if (nm_ap_get_encrypted (best_ap) || nm_ap_is_enc_key_valid (best_ap))
		{
			nm_ap_set_encrypted (best_ap, TRUE);
			nm_ap_set_auth_method (best_ap, NM_DEVICE_AUTH_METHOD_OPEN_SYSTEM);
		}
	}

	need_key = AP_NEED_KEY (dev, best_ap);

need_key:
	if (nm_device_activation_handle_cancel (dev))
		goto out;
	if (need_key)
	{
		char	*essid = nm_ap_get_essid (best_ap);
		if (strcmp (essid, last_essid) != 0)
			attempt = 1;
		strncpy (&last_essid[0], essid, 49);

		/* Don't hold the mutex while waiting for a key */
		nm_unlock_mutex (dev->options.wireless.scan_mutex, __FUNCTION__);

		/* Get a wireless key */
		dev->options.wireless.user_key_received = FALSE;
		nm_dbus_get_user_key_for_network (dev->app_data->dbus_connection, dev, best_ap, attempt);
		attempt++;
		need_key = FALSE;

		/* Wait for the key to come back */
		nm_debug ("Activation (%s/wireless): asking for user key.", nm_device_get_iface (dev));

		args[0] = dev;
		args[1] = &err;
		nm_wait_for_completion (NM_COMPLETION_TRIES_INFINITY,
				G_USEC_PER_SEC / 20, nm_dukr_test, nm_dukr_test, args);
		nm_debug ("Activation (%s/wireless): user key received.", nm_device_get_iface (dev));

		/* Done waiting, grab lock again */
		nm_lock_mutex (dev->options.wireless.scan_mutex, __FUNCTION__);

		/* User may have cancelled the key request, so we need to update our best AP again. */
		nm_ap_unref (best_ap);

		goto get_ap;
	}

	if (nm_ap_get_mode (best_ap) == NETWORK_MODE_ADHOC)
	{
		/* Only do auto-ip on Ad-Hoc connections for now.  We technically
		 * could do DHCP on them though.
		 */
		nm_device_set_wireless_config (dev, best_ap);
		success = nm_device_activation_configure_ip (dev, FALSE);
		goto connect_done;
	}

try_connect:
	/* Initial authentication method */
	nm_ap_set_auth_method (best_ap, get_initial_auth_method (best_ap, dev->app_data->allowed_ap_list));

	while (success == FALSE)
	{
		NMAccessPoint	*tmp_ap = NULL;
		gboolean		 link = FALSE;

		/* If we were told to quit activation, stop the thread and return */
		if (nm_device_activation_handle_cancel (dev))
			goto out;

		nm_device_set_wireless_config (dev, best_ap);

		link = nm_device_wireless_wait_for_link (dev, nm_ap_get_essid (best_ap));

		/* If we were told to quit activation, stop the thread and return */
		if (nm_device_activation_handle_cancel (dev))
			goto out;

		if (!link)
		{
			if (nm_ap_get_auth_method (best_ap) == NM_DEVICE_AUTH_METHOD_OPEN_SYSTEM)
			{
				nm_debug ("Activation (%s/wireless): no hardware link to '%s' in Open System mode, trying Shared Key.",
						nm_device_get_iface (dev), nm_ap_get_essid (best_ap) ? nm_ap_get_essid (best_ap) : "(none)");
				/* Back down to Shared Key mode */
				nm_ap_set_auth_method (best_ap, NM_DEVICE_AUTH_METHOD_SHARED_KEY);
				continue;
			}
			else if (nm_ap_get_auth_method (best_ap) == NM_DEVICE_AUTH_METHOD_SHARED_KEY)
			{
				/* Must be in Open System mode and it still didn't work, so
				 * we'll invalidate the current "best" ap and get another one */
				nm_debug ("Activation (%s/wireless): no hardware link to '%s' in Shared Key mode, trying another access point.",
						nm_device_get_iface (dev), nm_ap_get_essid (best_ap) ? nm_ap_get_essid (best_ap) : "(none)");
			}
			else
			{
				nm_debug ("Activation (%s/wireless): no hardware link to '%s' in non-encrypted mode.",
						nm_device_get_iface (dev), nm_ap_get_essid (best_ap) ? nm_ap_get_essid (best_ap) : "(none)");
			}

			/* Don't try other APs for non-scanning devices.
			 * User must pick a new one manually.
			 */
			if (!nm_device_get_supports_wireless_scan (dev))
				goto out;

			/* All applicable modes failed, invalidate current best_ap and get a new one */
			invalidate_ap (dev, best_ap);
			goto get_ap;
		}

		/* For those broken cards that report successful hardware link even when WEP key is wrong,
		 * and also for Open System mode (where you cannot know WEP key is wrong ever), we try to
		 * do DHCP and if that fails, fall back to next auth mode and try again.
		 */
		success = FALSE;
		if ((success = nm_device_activation_configure_ip (dev, FALSE)))
		{
			if (nm_device_activation_handle_cancel (dev))
			{
				success = FALSE;
				goto out;
			}

			/* Cache the last known good auth method in both NetworkManagerInfo and our allowed AP list */
			nm_dbus_update_network_auth_method (dev->app_data->dbus_connection, nm_ap_get_essid (best_ap), nm_ap_get_auth_method (best_ap));
			if ((tmp_ap = nm_ap_list_get_ap_by_essid (dev->app_data->allowed_ap_list, nm_ap_get_essid (best_ap))))
				nm_ap_set_auth_method (tmp_ap, nm_ap_get_auth_method (best_ap));
		}
		else
		{
			if (nm_device_activation_handle_cancel (dev))
				goto out;

			if ((nm_ap_get_auth_method (best_ap) == NM_DEVICE_AUTH_METHOD_OPEN_SYSTEM) && !adhoc)
			{
				/* Back down to Shared Key mode */
				nm_debug ("Activation (%s/wireless): could not get IP configuration info for '%s' in Open System mode, trying Shared Key.",
						nm_device_get_iface (dev), nm_ap_get_essid (best_ap) ? nm_ap_get_essid (best_ap) : "(none)");
				nm_ap_set_auth_method (best_ap, NM_DEVICE_AUTH_METHOD_SHARED_KEY);
				continue;
			}
			else if ((nm_ap_get_auth_method (best_ap) == NM_DEVICE_AUTH_METHOD_SHARED_KEY) && !adhoc)
			{
				/* Shared Key mode failed, we must have bad WEP key */
				nm_debug ("Activation (%s/wireless): could not get IP configuration info for '%s' in Shared Key mode, asking for new key.",
						nm_device_get_iface (dev), nm_ap_get_essid (best_ap) ? nm_ap_get_essid (best_ap) : "(none)");
				need_key = TRUE;
				goto need_key;
			}
			else
			{
				/* Don't try other APs for non-scanning devices.
				 * User must pick a new one manually.
				 */
				if (!nm_device_get_supports_wireless_scan (dev))
					goto out;

				/* All applicable modes failed, invalidate current best_ap and get a new one */
				invalidate_ap (dev, best_ap);
				goto get_ap;
			}
		}
	}

connect_done:
	/* If we were told to quit activation, stop the thread and return */
	if (nm_device_activation_handle_cancel (dev))
	{
		success = FALSE;
		goto out;
	}

	if (success)
	{
		nm_info ("Activation (%s/wireless): Success!  Connected to access point '%s' and got an IP address.",
				nm_device_get_iface (dev), nm_ap_get_essid (best_ap) ? nm_ap_get_essid (best_ap) : "(none)");
		nm_ap_unref (best_ap);
	}

out:
	nm_device_set_now_scanning (dev, FALSE);
	nm_unlock_mutex (dev->options.wireless.scan_mutex, __FUNCTION__);
	return (success);
}


/*
 * nm_device_activation_configure_ip
 *
 * Perform any IP-based configuration on a device, like running DHCP
 * or manually setting up the IP address, gateway, and default route.
 *
 */
static gboolean nm_device_activation_configure_ip (NMDevice *dev, gboolean do_only_autoip)
{
	gboolean success = FALSE;

	g_return_val_if_fail (dev != NULL, FALSE);

	nm_system_delete_default_route ();
	if (do_only_autoip)
	{
		success = nm_device_do_autoip (dev);
	}
	else if (nm_device_config_get_use_dhcp (dev))
	{
		int		err;

		err = nm_device_dhcp_request (dev);
		if (err == RET_DHCP_BOUND)
			success = TRUE;
		else
		{
			/* Interfaces cannot be down if they are the active interface,
			 * otherwise we cannot use them for scanning or link detection.
			 */
			if (nm_device_is_wireless (dev))
			{
				nm_device_set_essid (dev, "");
				nm_device_set_enc_key (dev, NULL, NM_DEVICE_AUTH_METHOD_NONE);
			}

			if (!nm_device_is_up (dev))
				nm_device_bring_up (dev);
		}
	}
	else
	{
		/* Manually set up the device */
		nm_system_device_clear_ip4_nameservers (dev);
		nm_system_device_clear_domain_searches (dev);
		success = nm_system_device_setup_static_ip4_config (dev);
		nm_device_update_ip4_address (dev);
	}

	if (success)
	{
		nm_system_device_add_ip6_link_address (dev);
		nm_system_flush_arp_cache ();
		nm_system_restart_mdns_responder ();
	}

	return (success);
}


/*
 * nm_device_activate
 *
 * Activate a device, done from the device's worker thread.
 *
 */
static gboolean nm_device_activate (gpointer user_data)
{
	NMDevice			*dev = (NMDevice *)user_data;
	gboolean			 success = FALSE;
	gboolean			 finished = FALSE;
	NMAccessPoint		*failed_best_ap = NULL;

	g_return_val_if_fail (dev  != NULL, FALSE);
	g_return_val_if_fail (dev->app_data != NULL, FALSE);

	nm_info ("Activation (%s) started...", nm_device_get_iface (dev));

	/* Bring the device up */
	if (!nm_device_is_up (dev));
		nm_device_bring_up (dev);

	if (nm_device_is_wireless (dev))
	{
		gboolean		create_network = FALSE;
		NMAccessPoint *best_ap = nm_device_get_best_ap (dev);

		if (best_ap)
		{
			if (nm_ap_get_user_created (best_ap))
			{
				create_network = TRUE;
				nm_info ("Creating wireless network '%s'.", nm_ap_get_essid (best_ap));
				success = nm_device_activate_wireless_adhoc (dev, best_ap);
				nm_info ("Wireless network creation for '%s' was %s.", nm_ap_get_essid (best_ap), success ? "successful" : "unsuccessful");
			}
			nm_ap_unref (best_ap);
		}

		if (!create_network)
			success = nm_device_activate_wireless (dev);
	}
	else if (nm_device_is_wired (dev))
		success = nm_device_activation_configure_ip (dev, FALSE);

	/* If we were told to quit activation, stop the thread and return */
	if (nm_device_activation_handle_cancel (dev))
		goto out;

	if (success)
		nm_info ("Activation (%s) IP configuration/DHCP successful!", nm_device_get_iface (dev));
	else
		nm_info ("Activation (%s) IP configuration/DHCP unsuccessful!  Ending activation...",
			  nm_device_get_iface (dev));

	finished = TRUE;

out:
	nm_info ("Activation (%s) ended.", nm_device_get_iface (dev));
	if (finished)
	{
		if (nm_device_is_wireless (dev) && !success)
			failed_best_ap = nm_device_get_best_ap (dev);
	}
	dev->activating = FALSE;
	dev->quit_activation = FALSE;
	if (finished)
		nm_device_activation_schedule_finish (dev, failed_best_ap, success ? DEVICE_NOW_ACTIVE : DEVICE_ACTIVATION_FAILED);

	return FALSE;
}


/*
 * nm_device_is_activating
 *
 * Return whether or not the device is currently activating itself.
 *
 */
gboolean nm_device_is_activating (NMDevice *dev)
{
	g_return_val_if_fail (dev != NULL, FALSE);

	return (dev->activating);
}


/*
 * nm_device_activation_should_cancel
 *
 * Return whether or not we've been told to cancel activation
 *
 */
gboolean nm_device_activation_should_cancel (NMDevice *dev)
{
	g_return_val_if_fail (dev != NULL, FALSE);

	return (dev->quit_activation);
}


static gboolean nm_ac_test (int tries, nm_completion_args args)
{
	NMDevice *dev = args[0];

	g_return_val_if_fail (dev != NULL, TRUE);

	if (tries == 0 && nm_device_get_dhcp_iface (dev))
		nm_device_dhcp_cease (dev);
	
	if (nm_device_is_activating(dev))
	{
		/* Nice race here between quit activation and dhcp.  We may
		 * not have started DHCP when we're told to quit activation,
		 * so we need to keep signalling dhcp to quit, which it will 
		 * pick up whenever it starts.
		 *
		 * This should really be taken care of a better way.
		 */
		if (nm_device_get_dhcp_iface (dev))
			nm_device_dhcp_cease (dev);
		if (tries % 20 == 0)
			nm_debug ("Activation (%s/wireless): waiting on dhcp to cease or device to finish activation", nm_device_get_iface(dev));
		return FALSE;
	}

	return TRUE;
}


/*
 * nm_device_activation_cancel
 *
 * Signal activation worker that it should stop and die.
 *
 */
void nm_device_activation_cancel (NMDevice *dev)
{
	nm_completion_args args;

	g_return_if_fail (dev != NULL);

	if (nm_device_is_activating (dev))
	{
		nm_debug ("Activation (%s/wireless): cancelling...", nm_device_get_iface (dev));
		dev->quit_activation = TRUE;

		/* Spin until cancelled.  Possible race conditions or deadlocks here.
		 * The other problem with waiting here is that we hold up dbus traffic
		 * that we should respond to.
		 */
		args[0] = dev;
		nm_wait_for_completion(NM_COMPLETION_TRIES_INFINITY,
				G_USEC_PER_SEC / 20, nm_ac_test, NULL, args);
		nm_debug ("Activation (%s/wireless): cancelled.", nm_device_get_iface(dev));
	}
}


/*
 * nm_device_deactivate
 *
 * Remove a device's routing table entries and IP address.
 *
 */
gboolean nm_device_deactivate (NMDevice *dev, gboolean just_added)
{
	g_return_val_if_fail (dev  != NULL, FALSE);
	g_return_val_if_fail (dev->app_data != NULL, FALSE);

	nm_device_activation_cancel (dev);

	if (nm_device_get_driver_support_level (dev) == NM_DRIVER_UNSUPPORTED)
		return (TRUE);

	/* Remove any DHCP timeouts that might have been running */
	if (nm_device_config_get_use_dhcp (dev))
		nm_device_dhcp_remove_timeouts (dev);

	/* Take out any entries in the routing table and any IP address the device had. */
	nm_system_device_flush_routes (dev);
	nm_system_device_flush_addresses (dev);
	nm_device_update_ip4_address (dev);

	if (!just_added && (dev == dev->app_data->active_device))
		nm_dbus_signal_device_status_change (dev->app_data->dbus_connection, dev, DEVICE_NO_LONGER_ACTIVE);

	/* Clean up stuff, don't leave the card associated */
	if (nm_device_is_wireless (dev))
	{
		nm_device_set_essid (dev, "");
		nm_device_set_enc_key (dev, NULL, NM_DEVICE_AUTH_METHOD_NONE);
		nm_device_set_mode (dev, NETWORK_MODE_INFRA);
		dev->options.wireless.scan_interval = 20;
	}

	return (TRUE);
}


/*
 * nm_device_set_user_key_for_network
 *
 * Called upon receipt of a NetworkManagerInfo reply with a
 * user-supplied key.
 *
 */
void nm_device_set_user_key_for_network (NMDevice *dev, NMAccessPointList *invalid_list,
									unsigned char *network, unsigned char *key,
									NMEncKeyType enc_type)
{
	NMAccessPoint	*best_ap;
	const char 	*cancel_message = "***canceled***";

	g_return_if_fail (dev != NULL);
	g_return_if_fail (nm_device_is_wireless (dev));
	g_return_if_fail (network != NULL);
	g_return_if_fail (key != NULL);

	/* If the user canceled, mark the ap as invalid */
	if (strncmp (key, cancel_message, strlen (cancel_message)) == 0)
	{
		NMAccessPoint	*ap;

		if ((ap = nm_device_ap_list_get_ap_by_essid (dev, network)))
		{
			NMAccessPoint	*invalid_ap = nm_ap_new_from_ap (ap);
			if (invalid_list)
				nm_ap_list_append_ap (invalid_list, invalid_ap);
		}

		nm_device_update_best_ap (dev);
	}
	else if ((best_ap = nm_device_get_best_ap (dev)))
	{
		/* Make sure the "best" ap matches the essid we asked for the key of,
		 * then set the new key on the access point.
		 */
		if (nm_null_safe_strcmp (network, nm_ap_get_essid (best_ap)) == 0)
			nm_ap_set_enc_key_source (best_ap, key, enc_type);

		nm_ap_unref (best_ap);
	}
	dev->options.wireless.user_key_received = TRUE;
}


/*
 * nm_device_ap_list_add_ap
 *
 * Add an access point to the devices internal AP list.
 *
 */
static void nm_device_ap_list_add_ap (NMDevice *dev, NMAccessPoint *ap)
{
	g_return_if_fail (dev != NULL);
	g_return_if_fail (ap  != NULL);
	g_return_if_fail (nm_device_is_wireless (dev));

	nm_ap_list_append_ap (dev->options.wireless.ap_list, ap);
	/* Transfer ownership of ap to the list by unrefing it here */
	nm_ap_unref (ap);
}


/*
 * nm_device_ap_list_clear
 *
 * Clears out the device's internal list of available access points.
 *
 */
void	nm_device_ap_list_clear (NMDevice *dev)
{
	g_return_if_fail (dev != NULL);
	g_return_if_fail (nm_device_is_wireless (dev));

	if (!dev->options.wireless.ap_list)
		return;

	nm_ap_list_unref (dev->options.wireless.ap_list);
	dev->options.wireless.ap_list = NULL;
}


/*
 * nm_device_ap_list_get_ap_by_essid
 *
 * Get the access point for a specific essid
 *
 */
NMAccessPoint *nm_device_ap_list_get_ap_by_essid (NMDevice *dev, const char *essid)
{
	NMAccessPoint	*ret_ap = NULL;

	g_return_val_if_fail (dev != NULL, NULL);
	g_return_val_if_fail (nm_device_is_wireless (dev), NULL);
	g_return_val_if_fail (essid != NULL, NULL);

	if (!dev->options.wireless.ap_list)
		return (NULL);

	ret_ap = nm_ap_list_get_ap_by_essid (dev->options.wireless.ap_list, essid);

	return (ret_ap);
}


/*
 * nm_device_ap_list_get_ap_by_address
 *
 * Get the access point for a specific MAC address
 *
 */
NMAccessPoint *nm_device_ap_list_get_ap_by_address (NMDevice *dev, const struct ether_addr *addr)
{
	NMAccessPoint	*ret_ap = NULL;

	g_return_val_if_fail (dev != NULL, NULL);
	g_return_val_if_fail (nm_device_is_wireless (dev), NULL);
	g_return_val_if_fail (addr != NULL, NULL);

	if (!dev->options.wireless.ap_list)
		return (NULL);

	ret_ap = nm_ap_list_get_ap_by_address (dev->options.wireless.ap_list, addr);

	return (ret_ap);
}


/*
 * nm_device_ap_list_get
 *
 * Return a pointer to the AP list
 *
 */
NMAccessPointList *nm_device_ap_list_get (NMDevice *dev)
{
	g_return_val_if_fail (dev != NULL, NULL);
	g_return_val_if_fail (nm_device_is_wireless (dev), NULL);

	return (dev->options.wireless.ap_list);
}

/*
 * Get/Set functions for "best" access point
 *
 * Caller MUST unref returned access point when done with it.
 *
 */
NMAccessPoint *nm_device_get_best_ap (NMDevice *dev)
{
	NMAccessPoint	*best_ap;

	g_return_val_if_fail (dev != NULL, NULL);
	g_return_val_if_fail (nm_device_is_wireless (dev), NULL);

	nm_lock_mutex (dev->options.wireless.best_ap_mutex, __FUNCTION__);
	best_ap = dev->options.wireless.best_ap;
	/* Callers get a reffed AP */
	if (best_ap) nm_ap_ref (best_ap);
	nm_unlock_mutex (dev->options.wireless.best_ap_mutex, __FUNCTION__);
	
	return (best_ap);
}

void nm_device_set_best_ap (NMDevice *dev, NMAccessPoint *ap)
{
	g_return_if_fail (dev != NULL);
	g_return_if_fail (nm_device_is_wireless (dev));

	nm_lock_mutex (dev->options.wireless.best_ap_mutex, __FUNCTION__);

	if (dev->options.wireless.best_ap)
		nm_ap_unref (dev->options.wireless.best_ap);

	if (ap)
		nm_ap_ref (ap);

	dev->options.wireless.best_ap = ap;
	nm_device_unfreeze_best_ap (dev);
	nm_unlock_mutex (dev->options.wireless.best_ap_mutex, __FUNCTION__);
}


/*
 * Freeze/unfreeze best ap
 *
 * If the user explicitly picks a network to associate with, we don't
 * change the active network until it goes out of range.
 *
 */
void nm_device_freeze_best_ap (NMDevice *dev)
{
	g_return_if_fail (dev != NULL);
	g_return_if_fail (nm_device_is_wireless (dev));

	dev->options.wireless.freeze_best_ap = TRUE;
}

void nm_device_unfreeze_best_ap (NMDevice *dev)
{
	g_return_if_fail (dev != NULL);
	g_return_if_fail (nm_device_is_wireless (dev));

	dev->options.wireless.freeze_best_ap = FALSE;
}

gboolean nm_device_is_best_ap_frozen (NMDevice *dev)
{
	g_return_val_if_fail (dev != NULL, FALSE);
	g_return_val_if_fail (nm_device_is_wireless (dev), FALSE);

	return (dev->options.wireless.freeze_best_ap);
}


/*
 * Accessor for dhcp_interface
 *
 */
struct dhcp_interface *nm_device_get_dhcp_iface (NMDevice *dev)
{
	g_return_val_if_fail (dev != NULL, FALSE);

	return (dev->dhcp_iface);
}

void nm_device_set_dhcp_iface (NMDevice *dev, struct dhcp_interface *dhcp_iface)
{
	g_return_if_fail (dev != NULL);

	/* NOTE: this function should only be used from the activation worker thread
	 * which will take care of shutting down any active DHCP threads and cleaning
	 * up the dev->dhcp_iface structure.
	 */

	dev->dhcp_iface = dhcp_iface;
}


/*
 * nm_device_get_path_for_ap
 *
 * Return the object path for an access point.
 *
 * NOTE: assumes the access point is actually in the device's access point list.
 *
 */
char * nm_device_get_path_for_ap (NMDevice *dev, NMAccessPoint *ap)
{
	g_return_val_if_fail (dev != NULL, NULL);
	g_return_val_if_fail (ap  != NULL, NULL);

	if (nm_ap_get_essid (ap))
	{
		char *path, *escaped_path;

		path = g_strdup_printf ("%s/%s/Networks/%s", NM_DBUS_PATH_DEVICES, nm_device_get_iface (dev), nm_ap_get_essid (ap));
		escaped_path = nm_dbus_escape_object_path (path);
		g_free (path);

		return (escaped_path);
	} else
		return (NULL);
}


/*
 * nm_device_need_ap_switch
 *
 * Returns TRUE if the essid of the card does not match the essid
 * of the "best" access point it should be associating with.
 *
 */
gboolean nm_device_need_ap_switch (NMDevice *dev)
{
	NMAccessPoint	*ap;
	gboolean		 need_switch = FALSE;

	g_return_val_if_fail (dev != NULL, FALSE);
	g_return_val_if_fail (nm_device_is_wireless (dev), FALSE);


	/* Since the card's ESSID may change during a scan, we can't really
	 * rely on checking the ESSID during that time.
	 */
	if (!nm_try_acquire_mutex (dev->options.wireless.scan_mutex, __FUNCTION__))
		return FALSE;

	ap = nm_device_get_best_ap (dev);
	if (nm_null_safe_strcmp (nm_device_get_essid (dev), (ap ? nm_ap_get_essid (ap) : NULL)) != 0)
		need_switch = TRUE;

	if (ap)
		nm_ap_unref (ap);
	nm_unlock_mutex (dev->options.wireless.scan_mutex, __FUNCTION__);

	return (need_switch);
}


/*
 * nm_device_update_best_ap
 *
 * Recalculate the "best" access point we should be associating with.  This
 * function may disrupt the current connection, so it should be called only
 * when necessary, ie when the current access point is no longer in range
 * or is for some other reason invalid and should no longer be used.
 *
 */
void nm_device_update_best_ap (NMDevice *dev)
{
	NMAccessPointList	*ap_list;
	NMAPListIter		*iter;
	NMAccessPoint		*scan_ap = NULL;
	NMAccessPoint		*best_ap = NULL;
	NMAccessPoint		*trusted_best_ap = NULL;
	NMAccessPoint		*untrusted_best_ap = NULL;
	GTimeVal			 trusted_latest_timestamp = {0, 0};
	GTimeVal			 untrusted_latest_timestamp = {0, 0};

	g_return_if_fail (dev != NULL);
	g_return_if_fail (dev->app_data != NULL);
	g_return_if_fail (nm_device_is_wireless (dev));

	/* Devices that can't scan don't do anything automatic.
	 * The user must choose the access point from the menu.
	 */
	if (!nm_device_get_supports_wireless_scan (dev))
	{
		/* If we lost a link to the AP, clear it out.
		 *
		 * FIXME: take samples over 5 seconds or so of the
		 * whether or not the link is active and only blow away
		 * the best_ap if its been down for 5 seconds or more.
		 */
		if (!nm_device_has_active_link (dev))
			nm_device_set_best_ap (dev, NULL);
		return;
	}

	if (!(ap_list = nm_device_ap_list_get (dev)))
		return;

	/* Iterate over the device's ap list to make sure the current
	 * "best" ap is still in the device's ap list (so that if its
	 * not, we can "unfreeze" the best ap if its been frozen already).
	 * If it is, we don't change the best ap here.
	 */
	if (nm_device_is_best_ap_frozen (dev))
	{
		best_ap = nm_device_get_best_ap (dev);

		/* If its in the device's ap list still, don't change the
		 * best ap, since its frozen.
		 */
		nm_lock_mutex (dev->options.wireless.best_ap_mutex, __FUNCTION__);
		if (best_ap)
		{
			char *essid = nm_ap_get_essid (best_ap);
			/* Two reasons to keep the current best_ap:
			 * 1) Its still valid and we see it in our scan data
			 * 2) Its an ad-hoc network that we've created (and therefore its not in our scan data)
			 */
			if (    (    !nm_ap_list_get_ap_by_essid (dev->app_data->invalid_ap_list, essid)
					&& nm_device_ap_list_get_ap_by_essid (dev, essid))
				|| nm_ap_get_user_created (best_ap))
			{
				nm_ap_unref (best_ap);
				nm_unlock_mutex (dev->options.wireless.best_ap_mutex, __FUNCTION__);
				return;
			}
			nm_ap_unref (best_ap);
		}

		/* Otherwise, its gone away and we don't care about it anymore */
		nm_device_unfreeze_best_ap (dev);
		nm_unlock_mutex (dev->options.wireless.best_ap_mutex, __FUNCTION__);
	}

	if (!(iter = nm_ap_list_iter_new (ap_list)))
		return;
	while ((scan_ap = nm_ap_list_iter_next (iter)))
	{
		NMAccessPoint	*tmp_ap;
		char			*ap_essid = nm_ap_get_essid (scan_ap);

		/* Access points in the "invalid" list cannot be used */
		if (nm_ap_list_get_ap_by_essid (dev->app_data->invalid_ap_list, ap_essid))
			continue;

		if ((tmp_ap = nm_ap_list_get_ap_by_essid (dev->app_data->allowed_ap_list, ap_essid)))
		{
			const GTimeVal *curtime = nm_ap_get_timestamp (tmp_ap);

			if (nm_ap_get_trusted (tmp_ap) && (curtime->tv_sec > trusted_latest_timestamp.tv_sec))
			{
				trusted_latest_timestamp = *nm_ap_get_timestamp (tmp_ap);
				trusted_best_ap = scan_ap;
				/* Merge access point data (mainly to get updated WEP key) */
				nm_ap_set_enc_key_source (trusted_best_ap, nm_ap_get_enc_key_source (tmp_ap), nm_ap_get_enc_type (tmp_ap));
			}
			else if (!nm_ap_get_trusted (tmp_ap) && (curtime->tv_sec > untrusted_latest_timestamp.tv_sec))
			{
				untrusted_latest_timestamp = *nm_ap_get_timestamp (tmp_ap);
				untrusted_best_ap = scan_ap;
				/* Merge access point data (mainly to get updated WEP key) */
				nm_ap_set_enc_key_source (untrusted_best_ap, nm_ap_get_enc_key_source (tmp_ap), nm_ap_get_enc_type (tmp_ap));
			}
		}
	}
	best_ap = trusted_best_ap ? trusted_best_ap : untrusted_best_ap;
	nm_ap_list_iter_free (iter);

	nm_device_set_best_ap (dev, best_ap);
}


typedef struct NMDeviceForceData
{
	NMDevice		*dev;
	const char	*net;
	const char	*key;
	NMEncKeyType	 key_type;
} NMDeviceForceData;


static gboolean nm_device_wireless_force_use (NMDevice *dev, const char *essid, const char *key, NMEncKeyType key_type)
{
	gboolean			 encrypted = FALSE;
	NMAccessPoint		*ap = NULL;
	NMAccessPoint		*tmp_ap = NULL;

	g_return_val_if_fail (dev != NULL, FALSE);
	g_return_val_if_fail (dev->app_data != NULL, FALSE);

	if (!essid)
		return FALSE;

	nm_debug ("Forcing AP '%s'", essid);

	if (    key
		&& strlen (key)
		&& (key_type != NM_ENC_TYPE_UNKNOWN)
		&& (key_type != NM_ENC_TYPE_NONE))
		encrypted = TRUE;

	/* Find the AP in our card's scan list first.
	 * If its not there, create an entirely new AP.
	 */
	if (!(ap = nm_ap_list_get_ap_by_essid (nm_device_ap_list_get (dev), essid)))
	{
		/* Okay, the card didn't see it in the scan, Cisco cards sometimes do this.
		 * So we make a "fake" access point and add it to the scan list.
		 */
		ap = nm_ap_new ();
		nm_ap_set_essid (ap, essid);
		nm_ap_set_encrypted (ap, encrypted);		
		if (encrypted)
			nm_ap_set_auth_method (ap, NM_DEVICE_AUTH_METHOD_OPEN_SYSTEM);
		else
			nm_ap_set_auth_method (ap, NM_DEVICE_AUTH_METHOD_NONE);
		nm_ap_set_artificial (ap, TRUE);
		nm_ap_list_append_ap (nm_device_ap_list_get (dev), ap);
		nm_ap_unref (ap);
	}
	else
	{
		/* If the AP is in the ignore list, we have to remove it since
		 * the User Knows What's Best.
		 */
		nm_ap_list_remove_ap_by_essid (dev->app_data->invalid_ap_list, nm_ap_get_essid (ap));
	}

	/* Now that this AP has an essid, copy over encryption keys and whatnot */
	if ((tmp_ap = nm_ap_list_get_ap_by_essid (dev->app_data->allowed_ap_list, nm_ap_get_essid (ap))))
	{
		nm_ap_set_enc_key_source (ap, nm_ap_get_enc_key_source (tmp_ap), nm_ap_get_enc_type (tmp_ap));
		nm_ap_set_auth_method (ap, nm_ap_get_auth_method (tmp_ap));
		nm_ap_set_invalid (ap, nm_ap_get_invalid (tmp_ap));
		nm_ap_set_timestamp (ap, nm_ap_get_timestamp (tmp_ap));
	}

	/* Use the encryption key and type the user sent us if its valid */
	if (encrypted)
		nm_ap_set_enc_key_source (ap, key, key_type);

	nm_device_set_best_ap (dev, ap);
	nm_device_freeze_best_ap (dev);

	return TRUE;
}


gboolean nm_device_wired_force_use (NMDevice *dev)
{
	g_return_val_if_fail (dev != NULL, FALSE);
	g_return_val_if_fail (dev->app_data != NULL, FALSE);

	return TRUE;
}


gboolean nm_device_force_use (gpointer user_data)
{
	NMDeviceForceData	*cb_data = (NMDeviceForceData *)user_data;
	NMData			*app_data = NULL;
	gboolean			 success = FALSE;

	g_return_val_if_fail (cb_data != NULL, FALSE);

	if (!cb_data->dev || !cb_data->dev->app_data)
		goto out;
	
	app_data = cb_data->dev->app_data;
	if (nm_device_is_wireless (cb_data->dev))
		success = nm_device_wireless_force_use (cb_data->dev, cb_data->net, cb_data->key, cb_data->key_type);
	else if (nm_device_is_wired (cb_data->dev))
		success = nm_device_wired_force_use (cb_data->dev);

	if (success)
		nm_policy_schedule_device_switch (cb_data->dev, cb_data->dev->app_data);
	
out:
	/* Function that scheduled us must ref the device */
	if (cb_data->dev)
		nm_device_unref (cb_data->dev);
	if (app_data)
		app_data->forcing_device = FALSE;

	g_free (cb_data);
	return FALSE;
}


void nm_device_schedule_force_use (NMDevice *dev, const char *network, const char *key, NMEncKeyType key_type)
{
	NMDeviceForceData	*cb_data;
	GSource			*source;

	g_return_if_fail (dev != NULL);
	g_return_if_fail (dev->app_data != NULL);
	g_return_if_fail (dev->app_data->main_context != NULL);

	cb_data = g_malloc0 (sizeof (NMDeviceForceData));
	cb_data->dev = dev;
	cb_data->net = network ? g_strdup (network) : NULL;
	cb_data->key = key ? g_strdup (key) : NULL;
	cb_data->key_type = key_type;

	source = g_idle_source_new ();
	g_source_set_callback (source, nm_device_force_use, cb_data, NULL);
	g_source_attach (source, dev->context);
	g_source_unref (source);
}


/*
 * nm_device_fake_ap_list
 *
 * Fake the access point list, used for test devices.
 *
 */
static void nm_device_fake_ap_list (NMDevice *dev)
{
	#define NUM_FAKE_APS	4

	int				 i;
	NMAccessPointList	*old_ap_list = nm_device_ap_list_get (dev);

	char				*fake_essids[NUM_FAKE_APS] = { "green", "bay", "packers", "rule" };
	struct ether_addr	 fake_addrs[NUM_FAKE_APS] =  {{{0x70, 0x37, 0x03, 0x70, 0x37, 0x03}},
											{{0x12, 0x34, 0x56, 0x78, 0x90, 0xab}},
											{{0xcd, 0xef, 0x12, 0x34, 0x56, 0x78}},
											{{0x90, 0xab, 0xcd, 0xef, 0x12, 0x34}} };
	guint8			 fake_qualities[NUM_FAKE_APS] = { 150, 26, 200, 100 };
	double			 fake_freqs[NUM_FAKE_APS] = { 3.1416, 4.1416, 5.1415, 6.1415 };
	gboolean			 fake_enc[NUM_FAKE_APS] = { FALSE, TRUE, FALSE, TRUE };

	g_return_if_fail (dev != NULL);
	g_return_if_fail (dev->app_data != NULL);

	dev->options.wireless.ap_list = nm_ap_list_new (NETWORK_TYPE_DEVICE);

	for (i = 0; i < NUM_FAKE_APS; i++)
	{
		NMAccessPoint		*nm_ap  = nm_ap_new ();
		NMAccessPoint		*list_ap;

		/* Copy over info from scan to local structure */
		nm_ap_set_essid (nm_ap, fake_essids[i]);

		if (fake_enc[i])
			nm_ap_set_encrypted (nm_ap, FALSE);
		else
			nm_ap_set_encrypted (nm_ap, TRUE);

		nm_ap_set_address (nm_ap, (const struct ether_addr *)(&fake_addrs[i]));
		nm_ap_set_strength (nm_ap, fake_qualities[i]);
		nm_ap_set_freq (nm_ap, fake_freqs[i]);

		/* Merge settings from wireless networks, mainly keys */
		if ((list_ap = nm_ap_list_get_ap_by_essid (dev->app_data->allowed_ap_list, nm_ap_get_essid (nm_ap))))
		{
			nm_ap_set_timestamp (nm_ap, nm_ap_get_timestamp (list_ap));
			nm_ap_set_enc_key_source (nm_ap, nm_ap_get_enc_key_source (list_ap), nm_ap_get_enc_type (list_ap));
		}

		/* Add the AP to the device's AP list */
		nm_device_ap_list_add_ap (dev, nm_ap);
	}

	if (dev == dev->app_data->active_device)
		nm_ap_list_diff (dev->app_data, dev, old_ap_list, nm_device_ap_list_get (dev));
	if (old_ap_list)
		nm_ap_list_unref (old_ap_list);
}


/*
 * nm_device_wireless_schedule_scan
 *
 * Schedule a wireless scan in the /device's/ thread.
 *
 */
static void nm_device_wireless_schedule_scan (NMDevice *dev)
{
	GSource			*wscan_source;
	guint			 wscan_source_id;
	NMWirelessScanCB	*scan_cb;

	g_return_if_fail (dev != NULL);
	g_return_if_fail (nm_device_is_wireless (dev));

	scan_cb = g_malloc0 (sizeof (NMWirelessScanCB));
	scan_cb->dev = dev;
	scan_cb->reschedule = TRUE;

	wscan_source = g_timeout_source_new (dev->options.wireless.scan_interval * 1000);
	g_source_set_callback (wscan_source, nm_device_wireless_scan, scan_cb, NULL);
	wscan_source_id = g_source_attach (wscan_source, dev->context);
	g_source_unref (wscan_source);
}


/*
 * nm_device_wireless_process_scan_results
 *
 * Process results of an iwscan() into our own AP lists.  We're an idle function,
 * but we never reschedule ourselves.
 *
 */
static gboolean nm_device_wireless_process_scan_results (gpointer user_data)
{
	NMWirelessScanResults	*results = (NMWirelessScanResults *)user_data;
	NMDevice				*dev;
	wireless_scan			*tmp_ap;
	gboolean				 have_blank_essids = FALSE;
	NMAPListIter			*iter;
	GTimeVal				 cur_time;
	gboolean				 list_changed = FALSE;

	g_return_val_if_fail (results != NULL, FALSE);	

	dev = results->dev;
	if (!dev || !results->scan_head.result)
		return FALSE;

	g_get_current_time (&cur_time);

	/* Translate iwlib scan results to NM access point list */
	for (tmp_ap = results->scan_head.result; tmp_ap; tmp_ap = tmp_ap->next)
	{
		/* We need at least an ESSID or a MAC address for each access point */
		if (tmp_ap->b.has_essid || tmp_ap->has_ap_addr)
		{
			NMAccessPoint		*nm_ap  = nm_ap_new ();
			int				 percent;
			gboolean			 new = FALSE;
			gboolean			 strength_changed = FALSE;
			gboolean			 success = FALSE;

			/* Copy over info from scan to local structure */

			/* ipw2x00 drivers fill in an essid of "<hidden>" if they think the access point
			 * is hiding its MAC address.  Sigh.
			 */
			if (    !tmp_ap->b.has_essid
				|| (tmp_ap->b.essid && !strlen (tmp_ap->b.essid))
				|| (tmp_ap->b.essid && !strcmp (tmp_ap->b.essid, "<hidden>")))	/* Stupid ipw drivers use <hidden> */
				nm_ap_set_essid (nm_ap, NULL);
			else
				nm_ap_set_essid (nm_ap, tmp_ap->b.essid);

			if (tmp_ap->b.has_key && (tmp_ap->b.key_flags & IW_ENCODE_DISABLED))
			{
				nm_ap_set_encrypted (nm_ap, FALSE);
				nm_ap_set_auth_method (nm_ap, NM_DEVICE_AUTH_METHOD_NONE);
			}
			else
			{
				nm_ap_set_encrypted (nm_ap, TRUE);
				nm_ap_set_auth_method (nm_ap, NM_DEVICE_AUTH_METHOD_OPEN_SYSTEM);
			}

			if (tmp_ap->has_ap_addr)
				nm_ap_set_address (nm_ap, (const struct ether_addr *)(tmp_ap->ap_addr.sa_data));

			if (tmp_ap->b.has_mode)
			{
				NMNetworkMode mode = NETWORK_MODE_INFRA;
				switch (tmp_ap->b.mode)
				{
					case IW_MODE_INFRA:
						mode = NETWORK_MODE_INFRA;
						break;
					case IW_MODE_ADHOC:
						mode = NETWORK_MODE_ADHOC;
						break;
					default:
						mode = NETWORK_MODE_INFRA;
						break;
				}
				nm_ap_set_mode (nm_ap, mode);
			}
			else
				nm_ap_set_mode (nm_ap, NETWORK_MODE_INFRA);

			percent = nm_wireless_qual_to_percent (&(tmp_ap->stats.qual),
							(const iwqual *)(&dev->options.wireless.max_qual),
							(const iwqual *)(&dev->options.wireless.avg_qual));
			nm_ap_set_strength (nm_ap, percent);

			if (tmp_ap->b.has_freq)
				nm_ap_set_freq (nm_ap, tmp_ap->b.freq);

			nm_ap_set_last_seen (nm_ap, &cur_time);

			/* If the AP is not broadcasting its ESSID, try to fill it in here from our
			 * allowed list where we cache known MAC->ESSID associations.
			 */
			if (!nm_ap_get_essid (nm_ap))
				nm_ap_list_copy_one_essid_by_address (nm_ap, dev->app_data->allowed_ap_list);

			/* Add the AP to the device's AP list */
			success = nm_ap_list_merge_scanned_ap (nm_device_ap_list_get (dev), nm_ap, &new, &strength_changed);
			if (success)
			{
				/* Handle dbus signals that we need to broadcast when the AP is added to the list or changes
				 * strength.
				 */
				if (new)
				{
					nm_dbus_signal_wireless_network_change	(dev->app_data->dbus_connection, dev, nm_ap,
								NETWORK_STATUS_APPEARED, -1);
					list_changed = TRUE;
				}
				else if (strength_changed)
				{
					nm_dbus_signal_wireless_network_change	(dev->app_data->dbus_connection, dev, nm_ap,
								NETWORK_STATUS_STRENGTH_CHANGED, nm_ap_get_strength (nm_ap));
				}
			}
			nm_ap_unref (nm_ap);
		}
	}	

	/* Once we have the list, copy in any relevant information from our Allowed list. */
	nm_ap_list_copy_properties (nm_device_ap_list_get (dev), dev->app_data->allowed_ap_list);

	/* Walk the access point list and remove any access points older than 120s */
	g_get_current_time (&cur_time);
	if (nm_device_ap_list_get (dev) && (iter = nm_ap_list_iter_new (nm_device_ap_list_get (dev))))
	{
		NMAccessPoint	*outdated_ap;
		GSList		*outdated_list = NULL;
		GSList		*elt;
		NMAccessPoint	*best_ap = nm_device_get_best_ap (dev);

		while ((outdated_ap = nm_ap_list_iter_next (iter)))
		{
			const GTimeVal	*ap_time = nm_ap_get_last_seen (outdated_ap);
			gboolean		 keep_around = FALSE;

			/* Don't ever get prune the AP we're currently associated with */
			if (	    nm_ap_get_essid (outdated_ap)
				&&  (best_ap && (nm_null_safe_strcmp (nm_ap_get_essid (best_ap), nm_ap_get_essid (outdated_ap))) == 0))
				keep_around = TRUE;

			if (!keep_around && (ap_time->tv_sec + 120 < cur_time.tv_sec))
				outdated_list = g_slist_append (outdated_list, outdated_ap);
		}
		nm_ap_list_iter_free (iter);

		/* nm_device_get_best_ap() refs the ap */
		if (best_ap)
			nm_ap_unref (best_ap);

		/* Ok, now remove outdated ones.  We have to do it after the lock
		 * because nm_ap_list_remove_ap() locks the list too.
		 */
		for (elt = outdated_list; elt; elt = g_slist_next (elt))
		{
			if ((outdated_ap = (NMAccessPoint *)(elt->data)))
			{
				nm_dbus_signal_wireless_network_change	(dev->app_data->dbus_connection, dev, outdated_ap, NETWORK_STATUS_DISAPPEARED, -1);
				nm_ap_list_remove_ap (nm_device_ap_list_get (dev), outdated_ap);
				list_changed = TRUE;
			}
		}
		g_slist_free (outdated_list);
	}

	/* If the list changed, decrease our wireless scanning interval */
	if (list_changed)
		dev->options.wireless.scan_interval = 20;
	else
		dev->options.wireless.scan_interval = MIN (60, dev->options.wireless.scan_interval + 10);

	return FALSE;
}


static gboolean nm_completion_scan_has_results (int tries, 
		nm_completion_args args)
{
	NMDevice				*dev = args[0];
	gboolean				*err = args[1];
	NMSock				*sk = args[2];
	NMWirelessScanResults	*scan_results = args[3];
	int					 rc;

	g_return_val_if_fail (dev != NULL, TRUE);
	g_return_val_if_fail (err != NULL, TRUE);
	g_return_val_if_fail (scan_results != NULL, TRUE);

	rc = iw_scan (nm_dev_sock_get_fd (sk), (char *)nm_device_get_iface (dev), WIRELESS_EXT, &(scan_results->scan_head));
	*err = FALSE;
	if (rc == -1 && errno == ETIME)
	{
		/* Scans take time.  iw_scan's timeout is 15 seconds, so if the card hasn't returned
		 * scan results after two consecutive runs of iw_scan(), the card sucks.
		 */
		if (tries >= 1)
		{
			nm_warning ("Warning: the wireless card (%s) requires too much time for scans.  Its driver needs to be fixed.", nm_device_get_iface (dev));
			scan_results->scan_head.result = NULL;
			*err = TRUE;
			return TRUE;
		}
		else
		{
			/* Give the card one more chance to return scan results */
			scan_results->scan_head.result = NULL;
			return FALSE;
		}
	}
	if ((rc == -1 && errno == ENODATA) || (rc == 0 && scan_results->scan_head.result == NULL))
	{
		/* Card hasn't had time yet to compile full access point list.
		 * Give it some more time and scan again.  If that doesn't
		 * work, we eventually give up.  */
		scan_results->scan_head.result = NULL;
		return FALSE;
	}
	else if (rc == -1)
	{
		scan_results->scan_head.result = NULL;
		return TRUE;
	}
	return TRUE;
}


/*
 * nm_device_wireless_scan
 *
 * Get a list of access points this device can see.
 *
 */
static gboolean nm_device_wireless_scan (gpointer user_data)
{
	NMWirelessScanCB		*scan_cb = (NMWirelessScanCB *)(user_data);
	NMDevice 				*dev = NULL;
	NMWirelessScanResults	*scan_results = NULL;

	g_return_val_if_fail (scan_cb != NULL, FALSE);

	dev = scan_cb->dev;
	if (!dev || !dev->app_data)
	{
		g_free (scan_cb);
		return FALSE;
	}

	/* Reschedule if scanning is off, or if scanning is AUTO and we are
	 * associated to an access point.
	 */
	if (    (dev->app_data->scanning_method == NM_SCAN_METHOD_NEVER)
		|| (    (dev->app_data->scanning_method == NM_SCAN_METHOD_WHEN_UNASSOCIATED)
			&& (dev->app_data->active_device == dev)
			&& nm_device_is_activating(dev)))
	{
		dev->options.wireless.scan_interval = 10;
		goto reschedule;
	}

	/* Reschedule ourselves if all wireless is disabled, we're asleep,
	 * or we are currently activating.
	 */
	if (    (dev->app_data->wireless_enabled == FALSE)
		|| (dev->app_data->asleep == TRUE))
	{
		dev->options.wireless.scan_interval = 10;
		goto reschedule;
	}

	/* Test devices get a fake ap list */
	if (dev->test_device)
	{
		nm_device_fake_ap_list (dev);
		dev->options.wireless.scan_interval = 20;
		goto reschedule;
	}

	/* Grab the scan mutex */
	if (nm_try_acquire_mutex (dev->options.wireless.scan_mutex, __FUNCTION__))
	{
		NMSock	*sk;
		gboolean	 devup_err;

		/* Device must be up before we can scan */
		devup_err = nm_device_bring_up_wait(dev, 1);
		if (devup_err)
		{
			nm_unlock_mutex (dev->options.wireless.scan_mutex, __FUNCTION__);
			goto reschedule;
		}

		if ((sk = nm_dev_sock_open (dev, DEV_WIRELESS, __FUNCTION__, NULL)))
		{
			int			err;
			NMNetworkMode	orig_mode = NETWORK_MODE_INFRA;
			double		orig_freq = 0;
			int			orig_rate = 0;
			const int		max_wait = G_USEC_PER_SEC * nm_device_get_association_pause_value (dev) /2;
			nm_completion_args args;

			orig_mode = nm_device_get_mode (dev);
			if (orig_mode == NETWORK_MODE_ADHOC)
			{
				orig_freq = nm_device_get_frequency (dev);
				orig_rate = nm_device_get_bitrate (dev);
			}

			/* Must be in infrastructure mode during scan, otherwise we don't get a full
			 * list of scan results.  Scanning doesn't work well in Ad-Hoc mode :( 
			 */
			nm_device_set_mode (dev, NETWORK_MODE_INFRA);
			nm_device_set_frequency (dev, 0);

			scan_results = g_malloc0 (sizeof (NMWirelessScanResults));

			args[0] = dev;
			args[1] = &err;
			args[2] = sk;
			args[3] = scan_results;
			nm_wait_for_completion(max_wait, max_wait/20,
				nm_completion_scan_has_results, NULL, args);

			nm_device_set_mode (dev, orig_mode);
			/* Only set frequency if ad-hoc mode */
			if (orig_mode == NETWORK_MODE_ADHOC)
			{
				nm_device_set_frequency (dev, orig_freq);
				nm_device_set_bitrate (dev, orig_rate);
			}

			nm_dev_sock_close (sk);

			if (!scan_results->scan_head.result)
			{
				g_free (scan_results);
				scan_results = NULL;
			}
		}
		nm_unlock_mutex (dev->options.wireless.scan_mutex, __FUNCTION__);
	}

	/* We run the scan processing function from the main thread, since it must deliver
	 * messages over DBUS.  Plus, that way the main thread is the only thread that has
	 * to modify the device's access point list.
	 */
	if ((scan_results != NULL) && (scan_results->scan_head.result != NULL))
	{
		guint	 scan_process_source_id = 0;
		GSource	*scan_process_source = g_idle_source_new ();
		GTimeVal	 cur_time;

		scan_results->dev = dev;
		g_source_set_callback (scan_process_source, nm_device_wireless_process_scan_results, scan_results, NULL);
		scan_process_source_id = g_source_attach (scan_process_source, dev->app_data->main_context);
		g_source_unref (scan_process_source);

		g_get_current_time (&cur_time);
		dev->options.wireless.last_scan = cur_time.tv_sec;
	}

reschedule:
	/* Make sure we reschedule ourselves so we keep scanning */
	if (scan_cb->reschedule)
		nm_device_wireless_schedule_scan (dev);

	g_free (scan_cb);
	return FALSE;
}


/* System config data accessors */

gboolean nm_device_config_get_use_dhcp (NMDevice *dev)
{
	g_return_val_if_fail (dev != NULL, 0);

	return (dev->config_info.use_dhcp);
}

void nm_device_config_set_use_dhcp (NMDevice *dev, gboolean use_dhcp)
{
	g_return_if_fail (dev != NULL);

	dev->config_info.use_dhcp = use_dhcp;
}

guint32 nm_device_config_get_ip4_address (NMDevice *dev)
{
	g_return_val_if_fail (dev != NULL, 0);

	return (dev->config_info.ip4_address);
}

void nm_device_config_set_ip4_address (NMDevice *dev, guint32 addr)
{
	g_return_if_fail (dev != NULL);

	dev->config_info.ip4_address = addr;
}

guint32 nm_device_config_get_ip4_gateway (NMDevice *dev)
{
	g_return_val_if_fail (dev != NULL, 0);

	return (dev->config_info.ip4_gateway);
}

void nm_device_config_set_ip4_gateway (NMDevice *dev, guint32 gateway)
{
	g_return_if_fail (dev != NULL);

	dev->config_info.ip4_gateway = gateway;
}

guint32 nm_device_config_get_ip4_netmask (NMDevice *dev)
{
	g_return_val_if_fail (dev != NULL, 0);

	return (dev->config_info.ip4_netmask);
}

void nm_device_config_set_ip4_netmask (NMDevice *dev, guint32 netmask)
{
	g_return_if_fail (dev != NULL);

	dev->config_info.ip4_netmask = netmask;
}
guint32 nm_device_config_get_ip4_broadcast (NMDevice *dev)
{
	g_return_val_if_fail (dev != NULL, 0);

	return (dev->config_info.ip4_broadcast);
}

void nm_device_config_set_ip4_broadcast (NMDevice *dev, guint32 broadcast)
{
	g_return_if_fail (dev != NULL);

	dev->config_info.ip4_broadcast = broadcast;
}


/* Define types for stupid headers */
typedef u_int8_t u8;
typedef u_int16_t u16;
typedef u_int32_t u32;
typedef u_int64_t u64;


/**************************************/
/*    Ethtool capability detection    */
/**************************************/
#include <linux/sockios.h>
#include <linux/ethtool.h>

static gboolean supports_ethtool_carrier_detect (NMDevice *dev)
{
	NMSock			*sk;
	struct ifreq		ifr;
	gboolean			supports_ethtool = FALSE;
	struct ethtool_cmd	edata;

	g_return_val_if_fail (dev != NULL, FALSE);

	if ((sk = nm_dev_sock_open (dev, DEV_GENERAL, __FUNCTION__, NULL)) == NULL)
	{
		nm_warning ("cannot open socket on interface %s for ethtool detect; errno=%d", nm_device_get_iface (dev), errno);
		return (FALSE);
	}

	strncpy (ifr.ifr_name, nm_device_get_iface (dev), sizeof(ifr.ifr_name)-1);
	edata.cmd = ETHTOOL_GLINK;
	ifr.ifr_data = (char *) &edata;
	if (ioctl (nm_dev_sock_get_fd (sk), SIOCETHTOOL, &ifr) == -1)
		goto out;

	supports_ethtool = TRUE;

out:
	nm_dev_sock_close (sk);
	return (supports_ethtool);
}



/**************************************/
/*    MII capability detection        */
/**************************************/
#include <linux/mii.h>

static int mdio_read (NMSock *sk, struct ifreq *ifr, int location)
{
	struct mii_ioctl_data *mii;

	g_return_val_if_fail (sk != NULL, -1);
	g_return_val_if_fail (ifr != NULL, -1);

	mii = (struct mii_ioctl_data *) &(ifr->ifr_data);
	mii->reg_num = location;

	if (ioctl (nm_dev_sock_get_fd (sk), SIOCGMIIREG, ifr) < 0)
		return -1;

	return (mii->val_out);
}

static gboolean supports_mii_carrier_detect (NMDevice *dev)
{
	NMSock		*sk;
	struct ifreq	ifr;
	int			bmsr;
	gboolean		supports_mii = FALSE;

	g_return_val_if_fail (dev != NULL, FALSE);

	if ((sk = nm_dev_sock_open (dev, DEV_GENERAL, __FUNCTION__, NULL)) == NULL)
	{
		nm_warning ("cannot open socket on interface %s for MII detect; errno=%d", nm_device_get_iface (dev), errno);
		return (FALSE);
	}

	strncpy (ifr.ifr_name, nm_device_get_iface (dev), sizeof(ifr.ifr_name)-1);
	if (ioctl (nm_dev_sock_get_fd (sk), SIOCGMIIPHY, &ifr) < 0)
		goto out;

	/* If we can read the BMSR register, we assume that the card supports MII link detection */
	bmsr = mdio_read (sk, &ifr, MII_BMSR);
	supports_mii = (bmsr != -1) ? TRUE : FALSE;

out:
	nm_dev_sock_close (sk);
	return (supports_mii);	
}

/****************************************/
/* End Code ripped from HAL             */
/****************************************/


/****************************************/
/* Test device routes                   */
/****************************************/

/*
 * nm_device_is_test_device
 *
 */
gboolean nm_device_is_test_device (NMDevice *dev)
{
	g_return_val_if_fail (dev != NULL, FALSE);

	return (dev->test_device);
}