summaryrefslogtreecommitdiff
path: root/clients/cli/devices.c
blob: 39bfcfa1d88519ae58884a4b13468e493a15b3c7 (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
/* nmcli - command-line tool to control NetworkManager
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Copyright 2010 - 2014 Red Hat, Inc.
 */

#include "nm-default.h"

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <readline/readline.h>

#include "nm-secret-agent-simple.h"
#include "polkit-agent.h"
#include "utils.h"
#include "common.h"
#include "devices.h"
#include "connections.h"

/* define some prompts */
#define PROMPT_INTERFACE  _("Interface: ")
#define PROMPT_INTERFACES _("Interface(s): ")

/* Available fields for 'device status' */
static NmcOutputField nmc_fields_dev_status[] = {
	{"DEVICE",     N_("DEVICE")},      /* 0 */
	{"TYPE",       N_("TYPE")},        /* 1 */
	{"STATE",      N_("STATE")},       /* 2 */
	{"DBUS-PATH",  N_("DBUS-PATH")},   /* 3 */
	{"CONNECTION", N_("CONNECTION")},  /* 4 */
	{"CON-UUID",   N_("CON-UUID")},    /* 5 */
	{"CON-PATH",   N_("CON-PATH")},    /* 6 */
	{NULL, NULL}
};
#define NMC_FIELDS_DEV_STATUS_ALL     "DEVICE,TYPE,STATE,DBUS-PATH,CONNECTION,CON-UUID,CON-PATH"
#define NMC_FIELDS_DEV_STATUS_COMMON  "DEVICE,TYPE,STATE,CONNECTION"


/* Available fields for 'device show' - GENERAL part */
static NmcOutputField nmc_fields_dev_show_general[] = {
	{"NAME",              N_("NAME")},               /* 0 */
	{"DEVICE",            N_("DEVICE")},             /* 1 */
	{"TYPE",              N_("TYPE")},               /* 2 */
	{"NM-TYPE",           N_("NM-TYPE")},            /* 3 */
	{"VENDOR",            N_("VENDOR")},             /* 4 */
	{"PRODUCT",           N_("PRODUCT")},            /* 5 */
	{"DRIVER",            N_("DRIVER")},             /* 6 */
	{"DRIVER-VERSION",    N_("DRIVER-VERSION")},     /* 7 */
	{"FIRMWARE-VERSION",  N_("FIRMWARE-VERSION")},   /* 8 */
	{"HWADDR",            N_("HWADDR")},             /* 9 */
	{"MTU",               N_("MTU")},                /* 10 */
	{"STATE",             N_("STATE")},              /* 11 */
	{"REASON",            N_("REASON")},             /* 12 */
	{"UDI",               N_("UDI")},                /* 13 */
	{"IP-IFACE",          N_("IP-IFACE")},           /* 14 */
	{"IS-SOFTWARE",       N_("IS-SOFTWARE")},        /* 15 */
	{"NM-MANAGED",        N_("NM-MANAGED")},         /* 16 */
	{"AUTOCONNECT",       N_("AUTOCONNECT")},        /* 17 */
	{"FIRMWARE-MISSING",  N_("FIRMWARE-MISSING")},   /* 18 */
	{"NM-PLUGIN-MISSING", N_("NM-PLUGIN-MISSING")},  /* 19 */
	{"PHYS-PORT-ID",      N_("PHYS-PORT-ID")},       /* 20 */
	{"CONNECTION",        N_("CONNECTION")},         /* 21 */
	{"CON-UUID",          N_("CON-UUID")},           /* 22 */
	{"CON-PATH",          N_("CON-PATH")},           /* 23 */
	{"METERED",           N_("METERED")},            /* 24 */
	{NULL, NULL}
};
#define NMC_FIELDS_DEV_SHOW_GENERAL_ALL     "NAME,DEVICE,TYPE,NM-TYPE,VENDOR,PRODUCT,DRIVER,DRIVER-VERSION,FIRMWARE-VERSION,HWADDR,MTU,"\
                                            "STATE,REASON,UDI,IP-IFACE,IS-SOFTWARE,NM-MANAGED,AUTOCONNECT,FIRMWARE-MISSING,NM-PLUGIN-MISSING,"\
                                            "PHYS-PORT-ID,CONNECTION,CON-UUID,CON-PATH,METERED"
#define NMC_FIELDS_DEV_SHOW_GENERAL_COMMON  "NAME,DEVICE,TYPE,VENDOR,PRODUCT,DRIVER,HWADDR,STATE"

/* Available fields for 'device show' - CONNECTIONS part */
static NmcOutputField nmc_fields_dev_show_connections[] = {
	{"NAME",                       N_("NAME")},                        /* 0 */
	{"AVAILABLE-CONNECTION-PATHS", N_("AVAILABLE-CONNECTION-PATHS")},  /* 1 */
	{"AVAILABLE-CONNECTIONS",      N_("AVAILABLE-CONNECTIONS")},       /* 2 */
	{NULL, NULL}
};
#define NMC_FIELDS_DEV_SHOW_CONNECTIONS_ALL     "AVAILABLE-CONNECTION-PATHS,AVAILABLE-CONNECTIONS"
#define NMC_FIELDS_DEV_SHOW_CONNECTIONS_COMMON  "AVAILABLE-CONNECTION-PATHS,AVAILABLE-CONNECTIONS"

/* Available fields for 'device show' - CAPABILITIES part */
static NmcOutputField nmc_fields_dev_show_cap[] = {
	{"NAME",            N_("NAME")},            /* 0 */
	{"CARRIER-DETECT",  N_("CARRIER-DETECT")},  /* 1 */
	{"SPEED",           N_("SPEED")},           /* 2 */
	{"IS-SOFTWARE",     N_("IS-SOFTWARE")},     /* 3 */
	{NULL, NULL}
};
#define NMC_FIELDS_DEV_SHOW_CAP_ALL     "NAME,CARRIER-DETECT,SPEED,IS-SOFTWARE"
#define NMC_FIELDS_DEV_SHOW_CAP_COMMON  "NAME,CARRIER-DETECT,SPEED,IS-SOFTWARE"

/* Available fields for 'device show' - wired properties part */
static NmcOutputField nmc_fields_dev_show_wired_prop[] = {
	{"NAME",             N_("NAME")},              /* 0 */
	{"CARRIER",          N_("CARRIER")},           /* 1 */
	{"S390-SUBCHANNELS", N_("S390-SUBCHANNELS")},  /* 2 */
	{NULL, NULL}
};
#define NMC_FIELDS_DEV_SHOW_WIRED_PROP_ALL     "NAME,CARRIER,S390-SUBCHANNELS"
#define NMC_FIELDS_DEV_SHOW_WIRED_PROP_COMMON  "NAME,CARRIER,S390-SUBCHANNELS"

/* Available fields for 'device show' - wireless properties part */
static NmcOutputField nmc_fields_dev_show_wifi_prop[] = {
	{"NAME",       N_("NAME")},   /* 0 */
	{"WEP",        N_("WEP")},    /* 1 */
	{"WPA",        N_("WPA")},    /* 2 */
	{"WPA2",       N_("WPA2")},   /* 3 */
	{"TKIP",       N_("TKIP")},   /* 4 */
	{"CCMP",       N_("CCMP")},   /* 5 */
	{"AP",         N_("AP")},     /* 6 */
	{"ADHOC",      N_("ADHOC")},  /* 7 */
	{"2GHZ",       N_("2GHZ")},   /* 8 */
	{"5GHZ",       N_("5GHZ")},   /* 9 */
	{NULL, NULL}
};
#define NMC_FIELDS_DEV_SHOW_WIFI_PROP_ALL     "NAME,WEP,WPA,WPA2,TKIP,CCMP,AP,ADHOC,2GHZ,5GHZ"
#define NMC_FIELDS_DEV_SHOW_WIFI_PROP_COMMON  "NAME,WEP,WPA,WPA2,TKIP,CCMP,AP,ADHOC"

/* Available fields for 'device show' - wimax properties part */
static NmcOutputField nmc_fields_dev_show_wimax_prop[] = {
	{"NAME",       N_("NAME")},      /* 0 */
	{"CTR-FREQ",   N_("CTR-FREQ")},  /* 1 */
	{"RSSI",       N_("RSSI")},      /* 2 */
	{"CINR",       N_("CINR")},      /* 3 */
	{"TX-POW",     N_("TX-POW")},    /* 4 */
	{"BSID",       N_("BSID")},      /* 5 */
	{NULL, NULL}
};
#define NMC_FIELDS_DEV_SHOW_WIMAX_PROP_ALL     "NAME,CTR-FREQ,RSSI,CINR,TX-POW,BSID"
#define NMC_FIELDS_DEV_SHOW_WIMAX_PROP_COMMON  "NAME,CTR-FREQ,RSSI,CINR,TX-POW,BSID"

/* Available fields for 'device wifi list' */
static NmcOutputField nmc_fields_dev_wifi_list[] = {
	{"NAME",       N_("NAME")},       /* 0 */
	{"SSID",       N_("SSID")},       /* 1 */
	{"SSID-HEX",   N_("SSID-HEX")},   /* 2 */
	{"BSSID",      N_("BSSID")},      /* 3 */
	{"MODE",       N_("MODE")},       /* 4 */
	{"CHAN",       N_("CHAN")},       /* 5 */
	{"FREQ",       N_("FREQ")},       /* 6 */
	{"RATE",       N_("RATE")},       /* 7 */
	{"SIGNAL",     N_("SIGNAL")},     /* 8 */
	{"BARS",       N_("BARS")},       /* 9 */
	{"SECURITY",   N_("SECURITY")},   /* 10 */
	{"WPA-FLAGS",  N_("WPA-FLAGS")},  /* 11 */
	{"RSN-FLAGS",  N_("RSN-FLAGS")},  /* 12 */
	{"DEVICE",     N_("DEVICE")},     /* 13 */
	{"ACTIVE",     N_("ACTIVE")},     /* 14 */
	{"IN-USE",     N_("*")},          /* 15 */
	{"DBUS-PATH",  N_("DBUS-PATH")},  /* 16 */
	{NULL, NULL}
};
#define NMC_FIELDS_DEV_WIFI_LIST_ALL           "SSID,SSID-HEX,BSSID,MODE,CHAN,FREQ,RATE,SIGNAL,BARS,SECURITY,"\
                                               "WPA-FLAGS,RSN-FLAGS,DEVICE,ACTIVE,IN-USE,DBUS-PATH"
#define NMC_FIELDS_DEV_WIFI_LIST_COMMON        "IN-USE,SSID,MODE,CHAN,RATE,SIGNAL,BARS,SECURITY"
#define NMC_FIELDS_DEV_WIFI_LIST_FOR_DEV_LIST  "NAME,"NMC_FIELDS_DEV_WIFI_LIST_COMMON

/* Available fields for 'device wimax list' */
static NmcOutputField nmc_fields_dev_wimax_list[] = {
	{"NAME",       N_("NAME")},       /* 0 */
	{"NSP",        N_("NSP")},        /* 1 */
	{"SIGNAL",     N_("SIGNAL")},     /* 2 */
	{"TYPE",       N_("TYPE")},       /* 3 */
	{"DEVICE",     N_("DEVICE")},     /* 4 */
	{"ACTIVE",     N_("ACTIVE")},     /* 5 */
	{"DBUS-PATH",  N_("DBUS-PATH")},  /* 6 */
	{NULL, NULL}
};
#define NMC_FIELDS_DEV_WIMAX_LIST_ALL           "NSP,SIGNAL,TYPE,DEVICE,ACTIVE,DBUS-PATH"
#define NMC_FIELDS_DEV_WIMAX_LIST_COMMON        "NSP,SIGNAL,TYPE,DEVICE,ACTIVE"
#define NMC_FIELDS_DEV_WIMAX_LIST_FOR_DEV_LIST  "NAME,"NMC_FIELDS_DEV_WIMAX_LIST_COMMON

/* Available fields for 'device show' - BOND, BRIDGE part */
static NmcOutputField nmc_fields_dev_show_master_prop[] = {
	{"NAME",       N_("NAME")},    /* 0 */
	{"SLAVES",     N_("SLAVES")},  /* 1 */
	{NULL, NULL}
};
#define NMC_FIELDS_DEV_SHOW_MASTER_PROP_ALL     "NAME,SLAVES"
#define NMC_FIELDS_DEV_SHOW_MASTER_PROP_COMMON  "NAME,SLAVES"

/* Available fields for 'device show' - TEAM part */
static NmcOutputField nmc_fields_dev_show_team_prop[] = {
	{"NAME",       N_("NAME")},    /* 0 */
	{"SLAVES",     N_("SLAVES")},  /* 1 */
	{"CONFIG",     N_("CONFIG")},  /* 2 */
	{NULL, NULL}
};
#define NMC_FIELDS_DEV_SHOW_TEAM_PROP_ALL     "NAME,SLAVES,CONFIG"
#define NMC_FIELDS_DEV_SHOW_TEAM_PROP_COMMON  "NAME,SLAVES,CONFIG"

/* Available fields for 'device show' - VLAN part */
static NmcOutputField nmc_fields_dev_show_vlan_prop[] = {
	{"NAME",           N_("NAME")},    /* 0 */
	{"PARENT",         N_("PARENT")},  /* 1 */
	{"ID",             N_("ID")},      /* 2 */
	{NULL, NULL}
};
#define NMC_FIELDS_DEV_SHOW_VLAN_PROP_ALL     "NAME,PARENT,ID"
#define NMC_FIELDS_DEV_SHOW_VLAN_PROP_COMMON  "NAME,PARENT,ID"

/* Available fields for 'device show' - BLUETOOTH part */
static NmcOutputField nmc_fields_dev_show_bluetooth[] = {
	{"NAME",           N_("NAME")},          /* 0 */
	{"CAPABILITIES",   N_("CAPABILITIES")},  /* 1 */
	{NULL, NULL}
};
#define NMC_FIELDS_DEV_SHOW_BLUETOOTH_ALL     "NAME,CAPABILITIES"
#define NMC_FIELDS_DEV_SHOW_BLUETOOTH_COMMON  "NAME,CAPABILITIES"

/* defined in common.c */
extern NmcOutputField nmc_fields_ip4_config[];
extern NmcOutputField nmc_fields_ip6_config[];
extern NmcOutputField nmc_fields_dhcp4_config[];
extern NmcOutputField nmc_fields_dhcp6_config[];

/* Available sections for 'device show' */
static NmcOutputField nmc_fields_dev_show_sections[] = {
	{"GENERAL",           N_("GENERAL"),           0, nmc_fields_dev_show_general + 1     },  /* 0 */
	{"CAPABILITIES",      N_("CAPABILITIES"),      0, nmc_fields_dev_show_cap + 1         },  /* 1 */
	{"WIFI-PROPERTIES",   N_("WIFI-PROPERTIES"),   0, nmc_fields_dev_show_wifi_prop + 1   },  /* 2 */
	{"AP",                N_("AP"),                0, nmc_fields_dev_wifi_list + 1        },  /* 3 */
	{"WIRED-PROPERTIES",  N_("WIRED-PROPERTIES"),  0, nmc_fields_dev_show_wired_prop + 1  },  /* 4 */
	{"WIMAX-PROPERTIES",  N_("WIMAX-PROPERTIES"),  0, nmc_fields_dev_show_wimax_prop + 1  },  /* 5 */
	{"NSP",               N_("NSP"),               0, nmc_fields_dev_wimax_list + 1       },  /* 6 */
	{"IP4",               N_("IP4"),               0, nmc_fields_ip4_config + 1           },  /* 7 */
	{"DHCP4",             N_("DHCP4"),             0, nmc_fields_dhcp4_config + 1         },  /* 8 */
	{"IP6",               N_("IP6"),               0, nmc_fields_ip6_config + 1           },  /* 9 */
	{"DHCP6",             N_("DHCP6"),             0, nmc_fields_dhcp6_config + 1         },  /* 10 */
	{"BOND",              N_("BOND"),              0, nmc_fields_dev_show_master_prop + 1 },  /* 11 */
	{"TEAM",              N_("TEAM"),              0, nmc_fields_dev_show_team_prop + 1   },  /* 12 */
	{"BRIDGE",            N_("BRIDGE"),            0, nmc_fields_dev_show_master_prop + 1 },  /* 13 */
	{"VLAN",              N_("VLAN"),              0, nmc_fields_dev_show_vlan_prop  + 1  },  /* 14 */
	{"BLUETOOTH",         N_("BLUETOOTH"),         0, nmc_fields_dev_show_bluetooth + 1   },  /* 15 */
	{"CONNECTIONS",       N_("CONNECTIONS"),       0, nmc_fields_dev_show_connections + 1 },  /* 16 */
	{NULL,                NULL,                    0, NULL                                }
};
#define NMC_FIELDS_DEV_SHOW_SECTIONS_ALL     "GENERAL,CAPABILITIES,BOND,TEAM,BRIDGE,VLAN,WIFI-PROPERTIES,AP,WIRED-PROPERTIES,"\
                                             "BLUETOOTH,CONNECTIONS,IP4,DHCP4,IP6,DHCP6"
#define NMC_FIELDS_DEV_SHOW_SECTIONS_COMMON  "GENERAL.DEVICE,GENERAL.TYPE,GENERAL.HWADDR,GENERAL.MTU,GENERAL.STATE,"\
                                             "GENERAL.CONNECTION,GENERAL.CON-PATH,WIRED-PROPERTIES,IP4,IP6"

/* Available fields for 'device lldp' */
static NmcOutputField nmc_fields_dev_lldp_list[] = {
	{"NAME",                    N_("NAME")},                     /* 0 */
	{"DEVICE",                  N_("DEVICE")},                   /* 1 */
	{"CHASSIS-ID",              N_("CHASSIS-ID")},               /* 2 */
	{"PORT-ID",                 N_("PORT-ID")},                  /* 3 */
	{"PORT-DESCRIPTION",        N_("PORT-DESCRIPTION")},         /* 4 */
	{"SYSTEM-NAME",             N_("SYSTEM-NAME")},              /* 5 */
	{"SYSTEM-DESCRIPTION",      N_("SYSTEM-DESCRIPTION")},       /* 6 */
	{"SYSTEM-CAPABILITIES",     N_("SYSTEM-CAPABILITIES")},      /* 7 */
	{"IEEE-802-1-PVID",         N_("IEEE-802-1-PVID")},          /* 8 */
	{"IEEE-802-1-PPVID",        N_("IEEE-802-1-PPVID")},         /* 9 */
	{"IEEE-802-1-PPVID-FLAGS",  N_("IEEE-802-1-PPVID-FLAGS")},   /* 10 */
	{"IEEE-802-1-VID",          N_("IEEE-802-1-VID")},           /* 11 */
	{"IEEE-802-1-VLAN-NAME",    N_("IEEE-802-1-VLAN-NAME")},     /* 12 */
	{"DESTINATION",             N_("DESTINATION")},              /* 13 */
	{"CHASSIS-ID-TYPE",         N_("CHASSIS-ID-TYPE")},          /* 14 */
	{"PORT-ID-TYPE",            N_("PORT-ID-TYPE")},             /* 15 */
	{NULL, NULL}
};
#define NMC_FIELDS_DEV_LLDP_LIST_ALL     "DEVICE,CHASSIS-ID,PORT-ID,PORT-DESCRIPTION,SYSTEM-NAME,SYSTEM-DESCRIPTION," \
                                         "SYSTEM-CAPABILITIES,IEEE-802-1-PVID,IEEE-802-1-PPVID,IEEE-802-1-PPVID-FLAGS," \
                                         "IEEE-802-1-VID,IEEE-802-1-VLAN-NAME,DESTINATION,CHASSIS-ID-TYPE,PORT-ID-TYPE"
#define NMC_FIELDS_DEV_LLDP_LIST_COMMON  "DEVICE,CHASSIS-ID,PORT-ID,PORT-DESCRIPTION,SYSTEM-NAME,SYSTEM-DESCRIPTION," \
                                         "SYSTEM-CAPABILITIES"

/* glib main loop variable - defined in nmcli.c */
extern GMainLoop *loop;

static guint progress_id = 0;  /* ID of event source for displaying progress */

static void
usage (void)
{
	g_printerr (_("Usage: nmcli device { COMMAND | help }\n\n"
	              "COMMAND := { status | show | set | connect | reapply | modify | disconnect | delete | monitor | wifi | lldp }\n\n"
	              "  status\n\n"
	              "  show [<ifname>]\n\n"
	              "  set [ifname] <ifname> [autoconnect yes|no] [managed yes|no]\n\n"
	              "  connect <ifname>\n\n"
	              "  reapply <ifname>\n\n"
	              "  modify <ifname> ([+|-]<setting>.<property> <value>)+\n\n"
	              "  disconnect <ifname> ...\n\n"
	              "  delete <ifname> ...\n\n"
	              "  monitor <ifname> ...\n\n"
	              "  wifi [list [ifname <ifname>] [bssid <BSSID>]]\n\n"
	              "  wifi connect <(B)SSID> [password <password>] [wep-key-type key|phrase] [ifname <ifname>]\n"
	              "                         [bssid <BSSID>] [name <name>] [private yes|no] [hidden yes|no]\n\n"
	              "  wifi hotspot [ifname <ifname>] [con-name <name>] [ssid <SSID>] [band a|bg] [channel <channel>] [password <password>]\n\n"
	              "  wifi rescan [ifname <ifname>] [[ssid <SSID to scan>] ...]\n\n"
	              "  lldp [list [ifname <ifname>]]\n\n"
	              ));
}

static void
usage_device_status (void)
{
	g_printerr (_("Usage: nmcli device status { help }\n"
	              "\n"
	              "Show status for all devices.\n"
	              "By default, the following columns are shown:\n"
	              " DEVICE     - interface name\n"
	              " TYPE       - device type\n"
	              " STATE      - device state\n"
	              " CONNECTION - connection activated on device (if any)\n"
	              "Displayed columns can be changed using '--fields' global option. 'status' is\n"
	              "the default command, which means 'nmcli device' calls 'nmcli device status'.\n\n"));
}

static void
usage_device_show (void)
{
	g_printerr (_("Usage: nmcli device show { ARGUMENTS | help }\n"
	              "\n"
	              "ARGUMENTS := [<ifname>]\n"
	              "\n"
	              "Show details of device(s).\n"
	              "The command lists details for all devices, or for a given device.\n\n"));
}

static void
usage_device_connect (void)
{
	g_printerr (_("Usage: nmcli device connect { ARGUMENTS | help }\n"
	              "\n"
	              "ARGUMENTS := <ifname>\n"
	              "\n"
	              "Connect the device.\n"
	              "NetworkManager will try to find a suitable connection that will be activated.\n"
	              "It will also consider connections that are not set to auto-connect.\n\n"));
}

static void
usage_device_reapply (void)
{
	g_printerr (_("Usage: nmcli device reapply { ARGUMENTS | help }\n"
	              "\n"
	              "ARGUMENTS := <ifname>\n"
	              "\n"
	              "Attempts to update device with changes to the currently active connection\n"
                      "made since it was last applied.\n\n"));
}

static void
usage_device_modify (void)
{
	g_printerr (_("Usage: nmcli device modify { ARGUMENTS | --help }\n"
	              "\n"
	              "ARGUMENTS := <ifname> ([+|-]<setting>.<property> <value>)+\n"
	              "\n"
	              "Modify one or more properties currently active on the device without modifying\n"
	              "the connection profile. The changes have immediate effect. For multi-valued\n"
	              "properties you can use optional '+' or '-' prefix to the property name.\n"
	              "The '+' sign allows appending items instead of overwriting the whole value.\n"
	              "The '-' sign allows removing selected items instead of the whole value.\n"
	              "\n"
	              "Examples:\n"
	              "nmcli dev mod em1 ipv4.method manual ipv4.addr \"192.168.1.2/24, 10.10.1.5/8\"\n"
	              "nmcli dev mod em1 +ipv4.dns 8.8.4.4\n"
	              "nmcli dev mod em1 -ipv4.dns 1\n"
	              "nmcli dev mod em1 -ipv6.addr \"abbe::cafe/56\"\n"));
}

static void
usage_device_disconnect (void)
{
	g_printerr (_("Usage: nmcli device disconnect { ARGUMENTS | help }\n"
	              "\n"
	              "ARGUMENTS := <ifname> ...\n"
	              "\n"
	              "Disconnect devices.\n"
	              "The command disconnects the device and prevents it from auto-activating\n"
	              "further connections without user/manual intervention.\n\n"));
}

static void
usage_device_delete (void)
{
	g_printerr (_("Usage: nmcli device delete { ARGUMENTS | help }\n"
	              "\n"
	              "ARGUMENTS := <ifname> ...\n"
	              "\n"
	              "Delete the software devices.\n"
	              "The command removes the interfaces. It only works for software devices\n"
	              "(like bonds, bridges, etc.). Hardware devices cannot be deleted by the\n"
	              "command.\n\n"));
}

static void
usage_device_set (void)
{
	g_printerr (_("Usage: nmcli device set { ARGUMENTS | help }\n"
	              "\n"
	              "ARGUMENTS := DEVICE { PROPERTY [ PROPERTY ... ] }\n"
	              "DEVICE    := [ifname] <ifname> \n"
	              "PROPERTY  := { autoconnect { yes | no } |\n"
	              "             { managed { yes | no }\n"
	              "\n"
	              "Modify device properties.\n\n"));
}

static void
usage_device_monitor (void)
{
	g_printerr (_("Usage: nmcli device monitor { ARGUMENTS | help }\n"
	              "\n"
	              "ARGUMENTS := [<ifname>] ...\n"
	              "\n"
	              "Monitor device activity.\n"
	              "This command prints a line whenever the specified devices change state.\n"
	              "Monitors all devices in case no interface is specified.\n\n"));
}

static void
usage_device_wifi (void)
{
	g_printerr (_("Usage: nmcli device wifi { ARGUMENTS | help }\n"
	              "\n"
	              "Perform operation on Wi-Fi devices.\n"
	              "\n"
	              "ARGUMENTS := [list [ifname <ifname>] [bssid <BSSID>]]\n"
	              "\n"
	              "List available Wi-Fi access points. The 'ifname' and 'bssid' options can be\n"
	              "used to list APs for a particular interface, or with a specific BSSID.\n"
	              "\n"
	              "ARGUMENTS := connect <(B)SSID> [password <password>] [wep-key-type key|phrase] [ifname <ifname>]\n"
	              "                    [bssid <BSSID>] [name <name>] [private yes|no] [hidden yes|no]\n"
	              "\n"
	              "Connect to a Wi-Fi network specified by SSID or BSSID. The command creates\n"
	              "a new connection and then activates it on a device. This is a command-line\n"
	              "counterpart of clicking an SSID in a GUI client. The command always creates\n"
	              "a new connection and thus it is mainly useful for connecting to new Wi-Fi\n"
	              "networks. If a connection for the network already exists, it is better to\n"
	              "bring up the existing profile as follows: nmcli con up id <name>. Note that\n"
	              "only open, WEP and WPA-PSK networks are supported at the moment. It is also\n"
	              "assumed that IP configuration is obtained via DHCP.\n"
	              "\n"
	              "ARGUMENTS := wifi hotspot [ifname <ifname>] [con-name <name>] [ssid <SSID>]\n"
	              "                          [band a|bg] [channel <channel>] [password <password>]\n"
	              "\n"
	              "Create a Wi-Fi hotspot. Use 'connection down' or 'device disconnect'\n"
	              "to stop the hotspot.\n"
	              "Parameters of the hotspot can be influenced by the optional parameters:\n"
	              "ifname - Wi-Fi device to use\n"
	              "con-name - name of the created hotspot connection profile\n"
	              "ssid - SSID of the hotspot\n"
	              "band - Wi-Fi band to use\n"
	              "channel - Wi-Fi channel to use\n"
	              "password - password to use for the hotspot\n"
	              "\n"
	              "ARGUMENTS := rescan [ifname <ifname>] [[ssid <SSID to scan>] ...]\n"
	              "\n"
	              "Request that NetworkManager immediately re-scan for available access points.\n"
	              "NetworkManager scans Wi-Fi networks periodically, but in some cases it might\n"
	              "be useful to start scanning manually. 'ssid' allows scanning for a specific\n"
	              "SSID, which is useful for APs with hidden SSIDs. More 'ssid' parameters can be\n"
	              "given. Note that this command does not show the APs,\n"
	              "use 'nmcli device wifi list' for that.\n\n"));
}

static void
usage_device_lldp (void)
{
	g_printerr (_("Usage: nmcli device lldp { ARGUMENTS | help }\n"
	              "\n"
	              "ARGUMENTS := [list [ifname <ifname>]]\n"
	              "\n"
	              "List neighboring devices discovered through LLDP. The 'ifname' option can be\n"
	              "used to list neighbors for a particular interface.\n\n"));
}

/* quit main loop */
static void
quit (void)
{
	if (progress_id) {
		g_source_remove (progress_id);
		nmc_terminal_erase_line ();
	}

	g_main_loop_quit (loop);  /* quit main loop */
}

static int
compare_devices (const void *a, const void *b)
{
	NMDevice *da = *(NMDevice **)a;
	NMDevice *db = *(NMDevice **)b;
	int cmp;

	/* Sort by later device states first */
	cmp = nm_device_get_state (db) - nm_device_get_state (da);
	if (cmp != 0)
		return cmp;

	cmp = g_strcmp0 (nm_device_get_type_description (da),
	                 nm_device_get_type_description (db));
	if (cmp != 0)
		return cmp;

	return g_strcmp0 (nm_device_get_iface (da),
	                  nm_device_get_iface (db));
}

NMDevice **
nmc_get_devices_sorted (NMClient *client)
{
	const GPtrArray *devs;
	NMDevice **sorted;

	devs = nm_client_get_devices (client);

	sorted = g_new (NMDevice *, devs->len + 1);
	memcpy (sorted, devs->pdata, devs->len * sizeof (NMDevice *));
	sorted[devs->len] = NULL;

	qsort (sorted, devs->len, sizeof (NMDevice *), compare_devices);
	return sorted;
}

static void
complete_device (NMDevice **devices, const char *prefix)
{
	int i;

	for (i = 0; devices[i]; i++) {
		const char *iface = nm_device_get_iface (devices[i]);

		if (g_str_has_prefix (iface, prefix))
			g_print ("%s\n", iface);
	}
}

static GSList *
get_device_list (NmCli *nmc, int argc, char **argv)
{
	int arg_num = argc;
	char **arg_arr = NULL;
	char **arg_ptr = argv;
	NMDevice **devices;
	GSList *queue = NULL;
	NMDevice *device;
	int i;

	if (argc == 0) {
		if (nmc->ask) {
			char *line = nmc_readline (PROMPT_INTERFACES);
			nmc_string_to_arg_array (line, NULL, FALSE, &arg_arr, &arg_num);
			g_free (line);
			arg_ptr = arg_arr;
		}
		if (arg_num == 0) {
			g_string_printf (nmc->return_text, _("Error: No interface specified."));
			nmc->return_value = NMC_RESULT_ERROR_USER_INPUT;
			goto error;
		}
	}

	devices = nmc_get_devices_sorted (nmc->client);
	while (arg_num > 0) {
		if (arg_num == 1 && nmc->complete)
			complete_device (devices, *arg_ptr);

		device = NULL;
		for (i = 0; devices[i]; i++) {
			if (!g_strcmp0 (nm_device_get_iface (devices[i]), *arg_ptr)) {
				device = devices[i];
				break;
			}
		}

		if (device) {
			if (!g_slist_find (queue, device))
				queue = g_slist_prepend (queue, device);
			else
				g_printerr (_("Warning: argument '%s' is duplicated.\n"), *arg_ptr);
		} else {
			if (!nmc->complete)
				g_printerr (_("Error: Device '%s' not found.\n"), *arg_ptr);
			g_string_printf (nmc->return_text, _("Error: not all devices found."));
			nmc->return_value = NMC_RESULT_ERROR_NOT_FOUND;
		}

		/* Take next argument */
		next_arg (&arg_num, &arg_ptr);
	}
	g_free (devices);

error:
	g_strfreev (arg_arr);

	return queue;
}

static NMDevice *
get_device (NmCli *nmc, int *argc, char ***argv, GError **error)
{
	gs_free NMDevice **devices = NULL;
	gs_free char *ifname_ask = NULL;
	const char *ifname = NULL;
	int i;

	if (*argc == 0) {
		if (nmc->ask)
			ifname = ifname_ask = nmc_readline (PROMPT_INTERFACE);

		if (!ifname_ask) {
			g_set_error_literal (error, NMCLI_ERROR, NMC_RESULT_ERROR_USER_INPUT,
			                     _("No interface specified"));
			return NULL;
		}
	} else {
		ifname = **argv;
		next_arg (argc, argv);
	}

	devices = nmc_get_devices_sorted (nmc->client);
	for (i = 0; devices[i]; i++) {
		if (!g_strcmp0 (nm_device_get_iface (devices[i]), ifname))
			break;
	}

	if (nmc->complete && !*argc)
		complete_device (devices, ifname);

	if (devices[i] == NULL) {
		g_set_error (error, NMCLI_ERROR, NMC_RESULT_ERROR_NOT_FOUND,
		             _("Device '%s' not found"), ifname);
	}

	return devices[i];
}

static int
compare_aps (gconstpointer a, gconstpointer b, gpointer user_data)
{
	NMAccessPoint *apa = *(NMAccessPoint **)a;
	NMAccessPoint *apb = *(NMAccessPoint **)b;
	int cmp;

	cmp = nm_access_point_get_strength (apb) - nm_access_point_get_strength (apa);
	if (cmp != 0)
		return cmp;

	cmp = nm_access_point_get_frequency (apa) - nm_access_point_get_frequency (apb);
	if (cmp != 0)
		return cmp;

	return nm_access_point_get_max_bitrate (apb) - nm_access_point_get_max_bitrate (apa);
}

static GPtrArray *
sort_access_points (const GPtrArray *aps)
{
	GPtrArray *sorted;
	int i;

	g_return_val_if_fail (aps, NULL);

	sorted = g_ptr_array_sized_new (aps->len);
	for (i = 0; i < aps->len; i++)
		g_ptr_array_add (sorted, aps->pdata[i]);
	g_ptr_array_sort_with_data (sorted, compare_aps, NULL);
	return sorted;
}

static void
wifi_signal_to_color (guint8 strength, NmcTermColor *color, NmcTermFormat *color_fmt)
{
	*color = NMC_TERM_COLOR_NORMAL;
	*color_fmt = NMC_TERM_FORMAT_NORMAL;

	if (strength > 80)
		*color = NMC_TERM_COLOR_GREEN;
	else if (strength > 55)
		*color = NMC_TERM_COLOR_YELLOW;
	else if (strength > 30)
		*color = NMC_TERM_COLOR_MAGENTA;
	else if (strength > 5)
		*color = NMC_TERM_COLOR_CYAN;
	else
		*color_fmt = NMC_TERM_FORMAT_DIM;
}

static char *
ap_wpa_rsn_flags_to_string (NM80211ApSecurityFlags flags)
{
	char *flags_str[16]; /* Enough space for flags and terminating NULL */
	char *ret_str;
	int i = 0;

	if (flags & NM_802_11_AP_SEC_PAIR_WEP40)
		flags_str[i++] = g_strdup ("pair_wpe40");
	if (flags & NM_802_11_AP_SEC_PAIR_WEP104)
		flags_str[i++] = g_strdup ("pair_wpe104");
	if (flags & NM_802_11_AP_SEC_PAIR_TKIP)
		flags_str[i++] = g_strdup ("pair_tkip");
	if (flags & NM_802_11_AP_SEC_PAIR_CCMP)
		flags_str[i++] = g_strdup ("pair_ccmp");
	if (flags & NM_802_11_AP_SEC_GROUP_WEP40)
		flags_str[i++] = g_strdup ("group_wpe40");
	if (flags & NM_802_11_AP_SEC_GROUP_WEP104)
		flags_str[i++] = g_strdup ("group_wpe104");
	if (flags & NM_802_11_AP_SEC_GROUP_TKIP)
		flags_str[i++] = g_strdup ("group_tkip");
	if (flags & NM_802_11_AP_SEC_GROUP_CCMP)
		flags_str[i++] = g_strdup ("group_ccmp");
	if (flags & NM_802_11_AP_SEC_KEY_MGMT_PSK)
		flags_str[i++] = g_strdup ("psk");
	if (flags & NM_802_11_AP_SEC_KEY_MGMT_802_1X)
		flags_str[i++] = g_strdup ("802.1X");

	if (i == 0)
		flags_str[i++] = g_strdup (_("(none)"));

	flags_str[i] = NULL;

	ret_str = g_strjoinv (" ", flags_str);

	i = 0;
	while (flags_str[i])
		g_free (flags_str[i++]);

	return ret_str;
}

typedef struct {
	NmCli *nmc;
	int index;
	guint32 output_flags;
	const char* active_bssid;
	const char* device;
} APInfo;

static void
fill_output_access_point (gpointer data, gpointer user_data)
{
	NMAccessPoint *ap = NM_ACCESS_POINT (data);
	APInfo *info = (APInfo *) user_data;
	NmcOutputField *arr;
	gboolean active = FALSE;
	NM80211ApFlags flags;
	NM80211ApSecurityFlags wpa_flags, rsn_flags;
	guint32 freq, bitrate;
	guint8 strength;
	GBytes *ssid;
	const char *bssid;
	NM80211Mode mode;
	char *channel_str, *freq_str, *ssid_str = NULL, *ssid_hex_str = NULL,
	     *bitrate_str, *strength_str, *wpa_flags_str, *rsn_flags_str;
	GString *security_str;
	char *ap_name;
	const char *sig_bars;
	NmcTermColor color;
	NmcTermFormat color_fmt;

	if (info->active_bssid) {
		const char *current_bssid = nm_access_point_get_bssid (ap);
		if (current_bssid && !strcmp (current_bssid, info->active_bssid))
			active = TRUE;
	}

	/* Get AP properties */
	flags = nm_access_point_get_flags (ap);
	wpa_flags = nm_access_point_get_wpa_flags (ap);
	rsn_flags = nm_access_point_get_rsn_flags (ap);
	ssid = nm_access_point_get_ssid (ap);
	bssid = nm_access_point_get_bssid (ap);
	freq = nm_access_point_get_frequency (ap);
	mode = nm_access_point_get_mode (ap);
	bitrate = nm_access_point_get_max_bitrate (ap);
	strength = MIN (nm_access_point_get_strength (ap), 100);

	/* Convert to strings */
	if (ssid) {
		const guint8 *ssid_data;
		gsize ssid_len;

		ssid_data = g_bytes_get_data (ssid, &ssid_len);
		ssid_str = nm_utils_ssid_to_utf8 (ssid_data, ssid_len);
		ssid_hex_str = ssid_to_hex ((const char *) ssid_data, ssid_len);
	}
	channel_str = g_strdup_printf ("%u", nm_utils_wifi_freq_to_channel (freq));
	freq_str = g_strdup_printf (_("%u MHz"), freq);
	bitrate_str = g_strdup_printf (_("%u Mbit/s"), bitrate/1000);
	strength_str = g_strdup_printf ("%u", strength);
	wpa_flags_str = ap_wpa_rsn_flags_to_string (wpa_flags);
	rsn_flags_str = ap_wpa_rsn_flags_to_string (rsn_flags);
	sig_bars = nm_utils_wifi_strength_bars (strength);

	security_str = g_string_new (NULL);

	if (   (flags & NM_802_11_AP_FLAGS_PRIVACY)
	    && (wpa_flags == NM_802_11_AP_SEC_NONE)
	    && (rsn_flags == NM_802_11_AP_SEC_NONE)) {
		g_string_append (security_str, _("WEP"));
		g_string_append_c (security_str, ' ');
	}
	if (wpa_flags != NM_802_11_AP_SEC_NONE) {
		g_string_append (security_str, _("WPA1"));
		g_string_append_c (security_str, ' ');
	}
	if (rsn_flags != NM_802_11_AP_SEC_NONE) {
		g_string_append (security_str, _("WPA2"));
		g_string_append_c (security_str, ' ');
	}
	if (   (wpa_flags & NM_802_11_AP_SEC_KEY_MGMT_802_1X)
	    || (rsn_flags & NM_802_11_AP_SEC_KEY_MGMT_802_1X)) {
		g_string_append   (security_str, _("802.1X"));
		g_string_append_c (security_str, ' ');
	}

	if (security_str->len > 0)
		g_string_truncate (security_str, security_str->len-1);  /* Chop off last space */

	arr = nmc_dup_fields_array (nmc_fields_dev_wifi_list,
	                            sizeof (nmc_fields_dev_wifi_list),
	                            info->output_flags);

	ap_name = g_strdup_printf ("AP[%d]", info->index++); /* AP */
	set_val_str  (arr, 0, ap_name);
	set_val_str  (arr, 1, ssid_str);
	set_val_str  (arr, 2, ssid_hex_str);
	set_val_strc (arr, 3, bssid);
	set_val_strc (arr, 4, mode == NM_802_11_MODE_ADHOC ? _("Ad-Hoc")
	                    : mode == NM_802_11_MODE_INFRA ? _("Infra")
	                    : _("N/A"));
	set_val_str  (arr, 5, channel_str);
	set_val_str  (arr, 6, freq_str);
	set_val_str  (arr, 7, bitrate_str);
	set_val_str  (arr, 8, strength_str);
	set_val_strc (arr, 9, sig_bars);
	set_val_str  (arr, 10, security_str->str);
	set_val_str  (arr, 11, wpa_flags_str);
	set_val_str  (arr, 12, rsn_flags_str);
	set_val_strc (arr, 13, info->device);
	set_val_strc (arr, 14, active ? _("yes") : _("no"));
	set_val_strc (arr, 15, active ? "*" : " ");
	set_val_strc (arr, 16, nm_object_get_path (NM_OBJECT (ap)));

	/* Set colors */
	wifi_signal_to_color (strength, &color, &color_fmt);
	set_val_color_all (arr, color);
	set_val_color_fmt_all (arr, color_fmt);
	if (active)
		arr[15].color = NMC_TERM_COLOR_GREEN;

	g_ptr_array_add (info->nmc->output_data, arr);

	g_string_free (security_str, FALSE);
}

static char *
bluetooth_caps_to_string (NMBluetoothCapabilities caps)
{
	char *caps_str[8]; /* Enough space for caps and terminating NULL */
	char *ret_str;
	int i = 0;

	if (caps & NM_BT_CAPABILITY_DUN)
		caps_str[i++] = g_strdup ("DUN");
	if (caps & NM_BT_CAPABILITY_NAP)
		caps_str[i++] = g_strdup ("NAP");

	if (i == 0)
		caps_str[i++] = g_strdup (_("(none)"));

	caps_str[i] = NULL;

	ret_str = g_strjoinv (" ", caps_str);

	i = 0;
	while (caps_str[i])
		g_free (caps_str[i++]);

	return ret_str;
}

static const char *
construct_header_name (const char *base, const char *spec)
{
	static char header_name[128];

	if (spec == NULL)
		return base;

	g_strlcpy (header_name, base, sizeof (header_name));
	g_strlcat (header_name, " (", sizeof (header_name));
	g_strlcat (header_name, spec, sizeof (header_name));
	g_strlcat (header_name, ")", sizeof (header_name));

	return header_name;
}

static const char *
get_active_connection_id (NMDevice *device)
{
	NMActiveConnection *ac;

	ac = nm_device_get_active_connection (device);
	if (!ac)
		return NULL;

	return nm_active_connection_get_id (ac);
}

static gboolean
print_bond_bridge_info (NMDevice *device,
                        NmCli *nmc,
                        const char *group_prefix,
                        const char *one_field)
{
	const GPtrArray *slaves = NULL;
	GString *slaves_str;
	int idx;
	NmcOutputField *tmpl, *arr;
	size_t tmpl_len;

	if (NM_IS_DEVICE_BOND (device))
		slaves = nm_device_bond_get_slaves (NM_DEVICE_BOND (device));
	else if (NM_IS_DEVICE_BRIDGE (device))
		slaves = nm_device_bridge_get_slaves (NM_DEVICE_BRIDGE (device));
	else
		g_return_val_if_reached (FALSE);

	slaves_str = g_string_new (NULL);
	for (idx = 0; slaves && idx < slaves->len; idx++) {
		NMDevice *slave = g_ptr_array_index (slaves, idx);
		const char *iface = nm_device_get_iface (slave);

		if (iface) {
			g_string_append (slaves_str, iface);
			g_string_append_c (slaves_str, ' ');
		}
	}
	if (slaves_str->len > 0)
		g_string_truncate (slaves_str, slaves_str->len-1);  /* Chop off last space */

	tmpl = nmc_fields_dev_show_master_prop;
	tmpl_len = sizeof (nmc_fields_dev_show_master_prop);
	nmc->print_fields.indices = parse_output_fields (one_field ? one_field : NMC_FIELDS_DEV_SHOW_MASTER_PROP_ALL,
	                                                 tmpl, FALSE, NULL, NULL);
	arr = nmc_dup_fields_array (tmpl, tmpl_len, NMC_OF_FLAG_FIELD_NAMES);
	g_ptr_array_add (nmc->output_data, arr);

	arr = nmc_dup_fields_array (tmpl, tmpl_len, NMC_OF_FLAG_SECTION_PREFIX);
	set_val_strc (arr, 0, group_prefix);     /* i.e. BOND, TEAM, BRIDGE */
	set_val_str  (arr, 1, slaves_str->str);
	g_ptr_array_add (nmc->output_data, arr);

	print_data (nmc);  /* Print all data */

	g_string_free (slaves_str, FALSE);
	nmc_empty_output_fields (nmc);

	return TRUE;
}

static char *
sanitize_team_config (const char *config)
{
	char *ret;
	int i;

	if (!config)
		return NULL;

	ret = g_strdup (config);

	for (i = 0; i < strlen (ret); i++) {
		if (ret[i] == '\n')
			ret[i] = ' ';
	}

	return ret;
}

static gboolean
print_team_info (NMDevice *device,
                 NmCli *nmc,
                 const char *group_prefix,
                 const char *one_field)
{
	const GPtrArray *slaves = NULL;
	GString *slaves_str;
	int idx;
	NmcOutputField *tmpl, *arr;
	size_t tmpl_len;

	if (NM_IS_DEVICE_TEAM (device))
		slaves = nm_device_team_get_slaves (NM_DEVICE_TEAM (device));
	else
		g_return_val_if_reached (FALSE);

	slaves_str = g_string_new (NULL);
	for (idx = 0; slaves && idx < slaves->len; idx++) {
		NMDevice *slave = g_ptr_array_index (slaves, idx);
		const char *iface = nm_device_get_iface (slave);

		if (iface) {
			g_string_append (slaves_str, iface);
			g_string_append_c (slaves_str, ' ');
		}
	}
	if (slaves_str->len > 0)
		g_string_truncate (slaves_str, slaves_str->len-1);  /* Chop off last space */

	tmpl = nmc_fields_dev_show_team_prop;
	tmpl_len = sizeof (nmc_fields_dev_show_team_prop);
	nmc->print_fields.indices = parse_output_fields (one_field ? one_field : NMC_FIELDS_DEV_SHOW_TEAM_PROP_ALL,
	                                                 tmpl, FALSE, NULL, NULL);
	arr = nmc_dup_fields_array (tmpl, tmpl_len, NMC_OF_FLAG_FIELD_NAMES);
	g_ptr_array_add (nmc->output_data, arr);

	arr = nmc_dup_fields_array (tmpl, tmpl_len, NMC_OF_FLAG_SECTION_PREFIX);
	set_val_strc (arr, 0, group_prefix);     /* TEAM */
	set_val_str  (arr, 1, slaves_str->str);
	set_val_str (arr, 2, sanitize_team_config (nm_device_team_get_config (NM_DEVICE_TEAM (device))));
	g_ptr_array_add (nmc->output_data, arr);

	print_data (nmc);  /* Print all data */

	g_string_free (slaves_str, FALSE);
	nmc_empty_output_fields (nmc);

	return TRUE;
}

static gboolean
show_device_info (NMDevice *device, NmCli *nmc)
{
	GError *error = NULL;
	APInfo *info;
	const char *hwaddr = NULL;
	NMDeviceState state = NM_DEVICE_STATE_UNKNOWN;
	NMDeviceStateReason reason = NM_DEVICE_STATE_REASON_NONE;
	NMDeviceCapabilities caps;
	NMActiveConnection *acon;
	guint32 speed;
	char *speed_str, *state_str, *reason_str, *mtu_str;
	GArray *sections_array;
	int k;
	char *fields_str;
	char *fields_all =    NMC_FIELDS_DEV_SHOW_SECTIONS_ALL;
	char *fields_common = NMC_FIELDS_DEV_SHOW_SECTIONS_COMMON;
	NmcOutputField *tmpl, *arr;
	size_t tmpl_len;
	gboolean was_output = FALSE;
	NMIPConfig *cfg4, *cfg6;
	NMDhcpConfig *dhcp4, *dhcp6;
	const char *base_hdr = _("Device details");
	GPtrArray *fields_in_section = NULL;

	if (!nmc->required_fields || strcasecmp (nmc->required_fields, "common") == 0)
		fields_str = fields_common;
	else if (!nmc->required_fields || strcasecmp (nmc->required_fields, "all") == 0)
		fields_str = fields_all;
	else
		fields_str = nmc->required_fields;

	sections_array = parse_output_fields (fields_str, nmc_fields_dev_show_sections, TRUE, &fields_in_section, &error);
	if (error) {
		g_string_printf (nmc->return_text, _("Error: 'device show': %s"), error->message);
		g_error_free (error);
		nmc->return_value = NMC_RESULT_ERROR_USER_INPUT;
		return FALSE;
	}

	/* Main header */
	nmc->print_fields.header_name = (char *) construct_header_name (base_hdr, nm_device_get_iface (device));
	nmc->print_fields.indices = parse_output_fields (NMC_FIELDS_DEV_SHOW_GENERAL_ALL,
	                                                 nmc_fields_dev_show_general, FALSE, NULL, NULL);

	nmc_fields_dev_show_general[0].flags = NMC_OF_FLAG_MAIN_HEADER_ONLY;
	print_required_fields (nmc, nmc_fields_dev_show_general);

	/* Loop through the required sections and print them. */
	for (k = 0; k < sections_array->len; k++) {
		int section_idx = g_array_index (sections_array, int, k);
		char *section_fld = (char *) g_ptr_array_index (fields_in_section, k);

		if (nmc->print_output != NMC_PRINT_TERSE && !nmc->multiline_output && was_output)
			g_print ("\n"); /* Print empty line between groups in tabular mode */

		was_output = FALSE;

		/* Remove any previous data */
		nmc_empty_output_fields (nmc);

		state = nm_device_get_state (device);
		reason = nm_device_get_state_reason (device);

		/* section GENERAL */
		if (!strcasecmp (nmc_fields_dev_show_sections[section_idx].name, nmc_fields_dev_show_sections[0].name)) {
			tmpl = nmc_fields_dev_show_general;
			tmpl_len = sizeof (nmc_fields_dev_show_general);
			nmc->print_fields.indices = parse_output_fields (section_fld ? section_fld : NMC_FIELDS_DEV_SHOW_GENERAL_ALL,
			                                                 tmpl, FALSE, NULL, NULL);
			arr = nmc_dup_fields_array (tmpl, tmpl_len, NMC_OF_FLAG_FIELD_NAMES);
			g_ptr_array_add (nmc->output_data, arr);

			state_str = g_strdup_printf ("%d (%s)", state, nmc_device_state_to_string (state));
			reason_str = g_strdup_printf ("%d (%s)", reason, nmc_device_reason_to_string (reason));
			hwaddr = nm_device_get_hw_address (device);
			mtu_str = g_strdup_printf ("%u", nm_device_get_mtu (device));
			acon = nm_device_get_active_connection (device);

			arr = nmc_dup_fields_array (tmpl, tmpl_len, NMC_OF_FLAG_SECTION_PREFIX);
			set_val_strc (arr, 0, nmc_fields_dev_show_sections[0].name);  /* "GENERAL"*/
			set_val_strc (arr, 1, nm_device_get_iface (device));
			set_val_strc (arr, 2, nm_device_get_type_description (device));
			set_val_strc (arr, 3, G_OBJECT_TYPE_NAME (device));
			set_val_strc (arr, 4, nm_device_get_vendor (device));
			set_val_strc (arr, 5, nm_device_get_product (device));
			set_val_strc (arr, 6, nm_device_get_driver (device) ? nm_device_get_driver (device) : _("(unknown)"));
			set_val_strc (arr, 7, nm_device_get_driver_version (device));
			set_val_strc (arr, 8, nm_device_get_firmware_version (device));
			set_val_strc (arr, 9, hwaddr ? hwaddr : _("(unknown)"));
			set_val_str  (arr, 10, mtu_str);
			set_val_str  (arr, 11, state_str);
			set_val_str  (arr, 12, reason_str);
			set_val_strc (arr, 13, nm_device_get_udi (device));
			set_val_strc (arr, 14, nm_device_get_ip_iface (device));
			set_val_strc (arr, 15, nm_device_is_software (device) ? _("yes") : _("no"));
			set_val_strc (arr, 16, nm_device_get_managed (device) ? _("yes") : _("no"));
			set_val_strc (arr, 17, nm_device_get_autoconnect (device) ? _("yes") : _("no"));
			set_val_strc (arr, 18, nm_device_get_firmware_missing (device) ? _("yes") : _("no"));
			set_val_strc (arr, 19, nm_device_get_nm_plugin_missing (device) ? _("yes") : _("no"));
			set_val_strc (arr, 20, nm_device_get_physical_port_id (device));
			set_val_strc (arr, 21, get_active_connection_id (device));
			set_val_strc (arr, 22, acon ? nm_active_connection_get_uuid (acon) : NULL);
			set_val_strc (arr, 23, acon ? nm_object_get_path (NM_OBJECT (acon)) : NULL);
			set_val_strc (arr, 24, nmc_device_metered_to_string (nm_device_get_metered (device)));
			g_ptr_array_add (nmc->output_data, arr);

			print_data (nmc);  /* Print all data */
			was_output = TRUE;
		}

		/* section CAPABILITIES */
		if (!strcasecmp (nmc_fields_dev_show_sections[section_idx].name, nmc_fields_dev_show_sections[1].name)) {
			tmpl = nmc_fields_dev_show_cap;
			tmpl_len = sizeof (nmc_fields_dev_show_cap);
			nmc->print_fields.indices = parse_output_fields (section_fld ? section_fld : NMC_FIELDS_DEV_SHOW_CAP_ALL,
			                                                 tmpl, FALSE, NULL, NULL);
			arr = nmc_dup_fields_array (tmpl, tmpl_len, NMC_OF_FLAG_FIELD_NAMES);
			g_ptr_array_add (nmc->output_data, arr);

			caps = nm_device_get_capabilities (device);
			speed = 0;
			if (NM_IS_DEVICE_ETHERNET (device)) {
				/* Speed in Mb/s */
				speed = nm_device_ethernet_get_speed (NM_DEVICE_ETHERNET (device));
			} else if (NM_IS_DEVICE_WIFI (device)) {
				/* Speed in b/s */
				speed = nm_device_wifi_get_bitrate (NM_DEVICE_WIFI (device));
				speed /= 1000;
			}
			speed_str = speed ? g_strdup_printf (_("%u Mb/s"), speed) : g_strdup (_("unknown"));

			arr = nmc_dup_fields_array (tmpl, tmpl_len, NMC_OF_FLAG_SECTION_PREFIX);
			set_val_strc (arr, 0, nmc_fields_dev_show_sections[1].name);  /* "CAPABILITIES" */
			set_val_strc (arr, 1, (caps & NM_DEVICE_CAP_CARRIER_DETECT) ? _("yes") : _("no"));
			set_val_str  (arr, 2, speed_str);
			set_val_strc (arr, 3, (caps & NM_DEVICE_CAP_IS_SOFTWARE) ? _("yes") : _("no"));
			g_ptr_array_add (nmc->output_data, arr);

			print_data (nmc);  /* Print all data */
			was_output = TRUE;
		}

		/* Wireless specific information */
		if ((NM_IS_DEVICE_WIFI (device))) {
			NMDeviceWifiCapabilities wcaps;
			NMAccessPoint *active_ap = NULL;
			const char *active_bssid = NULL;
			GPtrArray *aps;

			/* section WIFI-PROPERTIES */
			if (!strcasecmp (nmc_fields_dev_show_sections[section_idx].name, nmc_fields_dev_show_sections[2].name)) {
				wcaps = nm_device_wifi_get_capabilities (NM_DEVICE_WIFI (device));

				tmpl = nmc_fields_dev_show_wifi_prop;
				tmpl_len = sizeof (nmc_fields_dev_show_wifi_prop);
				nmc->print_fields.indices = parse_output_fields (section_fld ? section_fld : NMC_FIELDS_DEV_SHOW_WIFI_PROP_ALL,
				                                                 tmpl, FALSE, NULL, NULL);
				arr = nmc_dup_fields_array (tmpl, tmpl_len, NMC_OF_FLAG_FIELD_NAMES);
				g_ptr_array_add (nmc->output_data, arr);

				arr = nmc_dup_fields_array (tmpl, tmpl_len, NMC_OF_FLAG_SECTION_PREFIX);
				set_val_strc (arr, 0, nmc_fields_dev_show_sections[2].name);  /* "WIFI-PROPERTIES" */
				set_val_strc (arr, 1, (wcaps & (NM_WIFI_DEVICE_CAP_CIPHER_WEP40 | NM_WIFI_DEVICE_CAP_CIPHER_WEP104)) ?
				                        _("yes") : _("no"));
				set_val_strc (arr, 2, (wcaps & NM_WIFI_DEVICE_CAP_WPA) ? _("yes") : _("no"));
				set_val_strc (arr, 3, (wcaps & NM_WIFI_DEVICE_CAP_RSN) ? _("yes") : _("no"));
				set_val_strc (arr, 4, (wcaps & NM_WIFI_DEVICE_CAP_CIPHER_TKIP) ? _("yes") : _("no"));
				set_val_strc (arr, 5, (wcaps & NM_WIFI_DEVICE_CAP_CIPHER_CCMP) ? _("yes") : _("no"));
				set_val_strc (arr, 6, (wcaps & NM_WIFI_DEVICE_CAP_AP) ? _("yes") : _("no"));
				set_val_strc (arr, 7, (wcaps & NM_WIFI_DEVICE_CAP_ADHOC) ? _("yes") : _("no"));
				set_val_strc (arr, 8, !(wcaps & NM_WIFI_DEVICE_CAP_FREQ_VALID) ? _("unknown") :
				                      ((wcaps & NM_WIFI_DEVICE_CAP_FREQ_2GHZ) ? _("yes") : _("no")));
				set_val_strc (arr, 9, !(wcaps & NM_WIFI_DEVICE_CAP_FREQ_VALID) ? _("unknown") :
				                      ((wcaps & NM_WIFI_DEVICE_CAP_FREQ_5GHZ) ? _("yes") : _("no")));
				g_ptr_array_add (nmc->output_data, arr);

				print_data (nmc);  /* Print all data */
				was_output = TRUE;
			}

			/* section AP */
			if (!strcasecmp (nmc_fields_dev_show_sections[section_idx].name, nmc_fields_dev_show_sections[3].name)) {
				if (state == NM_DEVICE_STATE_ACTIVATED) {
					active_ap = nm_device_wifi_get_active_access_point (NM_DEVICE_WIFI (device));
					active_bssid = active_ap ? nm_access_point_get_bssid (active_ap) : NULL;
				}

				tmpl = nmc_fields_dev_wifi_list;
				tmpl_len = sizeof (nmc_fields_dev_wifi_list);
				nmc->print_fields.indices = parse_output_fields (section_fld ? section_fld : NMC_FIELDS_DEV_WIFI_LIST_FOR_DEV_LIST,
				                                                 tmpl, FALSE, NULL, NULL);
				arr = nmc_dup_fields_array (tmpl, tmpl_len, NMC_OF_FLAG_FIELD_NAMES);
				g_ptr_array_add (nmc->output_data, arr);

				info = g_malloc0 (sizeof (APInfo));
				info->nmc = nmc;
				info->index = 1;
				info->output_flags = NMC_OF_FLAG_SECTION_PREFIX;
				info->active_bssid = active_bssid;
				info->device = nm_device_get_iface (device);
				aps = sort_access_points (nm_device_wifi_get_access_points (NM_DEVICE_WIFI (device)));
				g_ptr_array_foreach ((GPtrArray *) aps, fill_output_access_point, (gpointer) info);
				g_ptr_array_free (aps, FALSE);
				g_free (info);
				print_data (nmc);  /* Print all data */
				was_output = TRUE;
			}
		} else if (NM_IS_DEVICE_ETHERNET (device)) {
			/* WIRED-PROPERTIES */
			if (!strcasecmp (nmc_fields_dev_show_sections[section_idx].name, nmc_fields_dev_show_sections[4].name)) {
				tmpl = nmc_fields_dev_show_wired_prop;
				tmpl_len = sizeof (nmc_fields_dev_show_wired_prop);
				nmc->print_fields.indices = parse_output_fields (section_fld ? section_fld : NMC_FIELDS_DEV_SHOW_WIRED_PROP_ALL,
				                                                 tmpl, FALSE, NULL, NULL);
				arr = nmc_dup_fields_array (tmpl, tmpl_len, NMC_OF_FLAG_FIELD_NAMES);
				g_ptr_array_add (nmc->output_data, arr);

				arr = nmc_dup_fields_array (tmpl, tmpl_len, NMC_OF_FLAG_SECTION_PREFIX);
				set_val_strc (arr, 0, nmc_fields_dev_show_sections[4].name);  /* "WIRED-PROPERTIES" */
				set_val_strc (arr, 1, (nm_device_ethernet_get_carrier (NM_DEVICE_ETHERNET (device))) ?
				                        _("on") : _("off"));
				set_val_arrc (arr, 2, ((const char **) nm_device_ethernet_get_s390_subchannels (NM_DEVICE_ETHERNET (device))));
				g_ptr_array_add (nmc->output_data, arr);

				print_data (nmc);  /* Print all data */
				was_output = TRUE;
			}
		}

		/* IP configuration info */
		cfg4 = nm_device_get_ip4_config (device);
		cfg6 = nm_device_get_ip6_config (device);
		dhcp4 = nm_device_get_dhcp4_config (device);
		dhcp6 = nm_device_get_dhcp6_config (device);

		/* IP4 */
		if (cfg4 && !strcasecmp (nmc_fields_dev_show_sections[section_idx].name, nmc_fields_dev_show_sections[7].name))
			was_output = print_ip4_config (cfg4, nmc, nmc_fields_dev_show_sections[7].name, section_fld);

		/* DHCP4 */
		if (dhcp4 && !strcasecmp (nmc_fields_dev_show_sections[section_idx].name, nmc_fields_dev_show_sections[8].name))
			was_output = print_dhcp4_config (dhcp4, nmc, nmc_fields_dev_show_sections[8].name, section_fld);

		/* IP6 */
		if (cfg6 && !strcasecmp (nmc_fields_dev_show_sections[section_idx].name, nmc_fields_dev_show_sections[9].name))
			was_output = print_ip6_config (cfg6, nmc, nmc_fields_dev_show_sections[9].name, section_fld);

		/* DHCP6 */
		if (dhcp6 && !strcasecmp (nmc_fields_dev_show_sections[section_idx].name, nmc_fields_dev_show_sections[10].name))
			was_output = print_dhcp6_config (dhcp6, nmc, nmc_fields_dev_show_sections[10].name, section_fld);

		/* Bond specific information */
		if (NM_IS_DEVICE_BOND (device)) {
			if (!strcasecmp (nmc_fields_dev_show_sections[section_idx].name, nmc_fields_dev_show_sections[11].name))
				was_output = print_bond_bridge_info (device, nmc, nmc_fields_dev_show_sections[11].name, section_fld);
		}

		/* Team specific information */
		if (NM_IS_DEVICE_TEAM (device)) {
			if (!strcasecmp (nmc_fields_dev_show_sections[section_idx].name, nmc_fields_dev_show_sections[12].name))
				was_output = print_team_info (device, nmc, nmc_fields_dev_show_sections[12].name, section_fld);
		}

		/* Bridge specific information */
		if (NM_IS_DEVICE_BRIDGE (device)) {
			if (!strcasecmp (nmc_fields_dev_show_sections[section_idx].name, nmc_fields_dev_show_sections[13].name))
				was_output = print_bond_bridge_info (device, nmc, nmc_fields_dev_show_sections[13].name, section_fld);
		}

		/* VLAN-specific information */
		if ((NM_IS_DEVICE_VLAN (device))) {
			if (!strcasecmp (nmc_fields_dev_show_sections[section_idx].name, nmc_fields_dev_show_sections[14].name)) {
				char * vlan_id_str = g_strdup_printf ("%u", nm_device_vlan_get_vlan_id (NM_DEVICE_VLAN (device)));
				NMDevice *parent = nm_device_vlan_get_parent (NM_DEVICE_VLAN (device));

				tmpl = nmc_fields_dev_show_vlan_prop;
				tmpl_len = sizeof (nmc_fields_dev_show_vlan_prop);
				nmc->print_fields.indices = parse_output_fields (section_fld ? section_fld : NMC_FIELDS_DEV_SHOW_VLAN_PROP_ALL,
				                                                 tmpl, FALSE, NULL, NULL);
				arr = nmc_dup_fields_array (tmpl, tmpl_len, NMC_OF_FLAG_FIELD_NAMES);
				g_ptr_array_add (nmc->output_data, arr);

				arr = nmc_dup_fields_array (tmpl, tmpl_len, NMC_OF_FLAG_SECTION_PREFIX);
				set_val_strc (arr, 0, nmc_fields_dev_show_sections[14].name);  /* "VLAN" */
				set_val_strc (arr, 1, parent ? nm_device_get_iface (parent) : NULL);
				set_val_str  (arr, 2, vlan_id_str);
				g_ptr_array_add (nmc->output_data, arr);

				print_data (nmc);  /* Print all data */

				was_output = TRUE;
			}
		}

		if (NM_IS_DEVICE_BT (device)) {
			if (!strcasecmp (nmc_fields_dev_show_sections[section_idx].name, nmc_fields_dev_show_sections[15].name)) {
				tmpl = nmc_fields_dev_show_bluetooth;
				tmpl_len = sizeof (nmc_fields_dev_show_bluetooth);
				nmc->print_fields.indices = parse_output_fields (section_fld ? section_fld : NMC_FIELDS_DEV_SHOW_BLUETOOTH_ALL,
				                                                 tmpl, FALSE, NULL, NULL);
				arr = nmc_dup_fields_array (tmpl, tmpl_len, NMC_OF_FLAG_FIELD_NAMES);
				g_ptr_array_add (nmc->output_data, arr);

				arr = nmc_dup_fields_array (tmpl, tmpl_len, NMC_OF_FLAG_SECTION_PREFIX);
				set_val_strc (arr, 0, nmc_fields_dev_show_sections[15].name);  /* "BLUETOOTH" */
				set_val_str (arr, 1, bluetooth_caps_to_string (nm_device_bt_get_capabilities (NM_DEVICE_BT (device))));
				g_ptr_array_add (nmc->output_data, arr);

				print_data (nmc);  /* Print all data */
				was_output = TRUE;
			}
		}

		/* section CONNECTIONS */
		if (!strcasecmp (nmc_fields_dev_show_sections[section_idx].name, nmc_fields_dev_show_sections[16].name)) {
			const GPtrArray *avail_cons;
			GString *ac_paths_str;
			char **ac_arr = NULL;
			int i;

			tmpl = nmc_fields_dev_show_connections;
			tmpl_len = sizeof (nmc_fields_dev_show_connections);
			nmc->print_fields.indices = parse_output_fields (section_fld ? section_fld : NMC_FIELDS_DEV_SHOW_CONNECTIONS_ALL,
			                                                 tmpl, FALSE, NULL, NULL);
			arr = nmc_dup_fields_array (tmpl, tmpl_len, NMC_OF_FLAG_FIELD_NAMES);
			g_ptr_array_add (nmc->output_data, arr);

			/* available-connections */
			avail_cons = nm_device_get_available_connections (device);
			ac_paths_str = g_string_new (NULL);
			if (avail_cons->len) {
				ac_arr = g_new (char *, avail_cons->len + 1);
				ac_arr[avail_cons->len] = NULL;
			}
			for (i = 0; i < avail_cons->len; i++) {
				NMRemoteConnection *avail_con = g_ptr_array_index (avail_cons, i);
				const char *ac_path = nm_connection_get_path (NM_CONNECTION (avail_con));
				const char *ac_id = nm_connection_get_id (NM_CONNECTION (avail_con));
				const char *ac_uuid = nm_connection_get_uuid (NM_CONNECTION (avail_con));

				ac_arr[i] = g_strdup_printf ("%s | %s", ac_uuid, ac_id);

				if (i == 0)
					g_string_printf (ac_paths_str, "%s/{", NM_DBUS_PATH_SETTINGS);
				else
					g_string_append_c (ac_paths_str, ',');
				g_string_append (ac_paths_str, strrchr (ac_path, '/') + 1);
			}
			if (ac_paths_str->len > 0)
				g_string_append_c (ac_paths_str, '}');

			arr = nmc_dup_fields_array (tmpl, tmpl_len, NMC_OF_FLAG_SECTION_PREFIX);
			set_val_strc (arr, 0, nmc_fields_dev_show_sections[16].name);  /* "CONNECTIONS" */
			set_val_str  (arr, 1, ac_paths_str->str);
			set_val_arr  (arr, 2, (ac_arr));
			g_ptr_array_add (nmc->output_data, arr);

			print_data (nmc);  /* Print all data */

			g_string_free (ac_paths_str, FALSE);
			was_output = TRUE;
		}
	}

	if (sections_array)
		g_array_free (sections_array, TRUE);
	if (fields_in_section)
		g_ptr_array_free (fields_in_section, TRUE);

	return TRUE;
}

void
nmc_device_state_to_color (NMDeviceState state, NmcTermColor *color, NmcTermFormat *color_fmt)
{
	*color = NMC_TERM_COLOR_NORMAL;
	*color_fmt = NMC_TERM_FORMAT_NORMAL;

	if (state <= NM_DEVICE_STATE_UNAVAILABLE)
		*color_fmt= NMC_TERM_FORMAT_DIM;
	else if (state == NM_DEVICE_STATE_DISCONNECTED)
		*color = NMC_TERM_COLOR_RED;
	else if (state >= NM_DEVICE_STATE_PREPARE && state <= NM_DEVICE_STATE_SECONDARIES)
		*color = NMC_TERM_COLOR_YELLOW;
	else if (state == NM_DEVICE_STATE_ACTIVATED)
		*color = NMC_TERM_COLOR_GREEN;
}

static void
fill_output_device_status (NMDevice *device, NmCli *nmc)
{
	NMActiveConnection *ac;
	NMDeviceState state;
	NmcTermColor color;
	NmcTermFormat color_fmt;
	NmcOutputField *arr = nmc_dup_fields_array (nmc_fields_dev_status,
	                                            sizeof (nmc_fields_dev_status),
	                                            0);

	state = nm_device_get_state (device);
	ac = nm_device_get_active_connection (device);

	/* Show devices in color */
	nmc_device_state_to_color (state, &color, &color_fmt);
	set_val_color_all (arr, color);
	set_val_color_fmt_all (arr, color_fmt);

	set_val_strc (arr, 0, nm_device_get_iface (device));
	set_val_strc (arr, 1, nm_device_get_type_description (device));
	set_val_strc (arr, 2, nmc_device_state_to_string (state));
	set_val_strc (arr, 3, nm_object_get_path (NM_OBJECT (device)));
	set_val_strc (arr, 4, get_active_connection_id (device));
	set_val_strc (arr, 5, ac ? nm_active_connection_get_uuid (ac) : NULL);
	set_val_strc (arr, 6, ac ? nm_object_get_path (NM_OBJECT (ac)) : NULL);

	g_ptr_array_add (nmc->output_data, arr);
}

static NMCResultCode
do_devices_status (NmCli *nmc, int argc, char **argv)
{
	GError *error = NULL;
	NMDevice **devices;
	int i;
	char *fields_str;
	char *fields_all =    NMC_FIELDS_DEV_STATUS_ALL;
	char *fields_common = NMC_FIELDS_DEV_STATUS_COMMON;
	NmcOutputField *tmpl, *arr;
	size_t tmpl_len;

	/* Nothing to complete */
	if (nmc->complete)
		return nmc->return_value;

	if (!nmc_terse_option_check (nmc->print_output, nmc->required_fields, &error)) {
		g_string_printf (nmc->return_text, _("Error: %s."), error->message);
		g_error_free (error);
		return NMC_RESULT_ERROR_USER_INPUT;
	}

	while (argc > 0) {
		g_printerr (_("Unknown parameter: %s\n"), *argv);
		argc--;
		argv++;
	}

	if (!nmc->required_fields || strcasecmp (nmc->required_fields, "common") == 0)
		fields_str = fields_common;
	else if (!nmc->required_fields || strcasecmp (nmc->required_fields, "all") == 0)
		fields_str = fields_all;
	else
		fields_str = nmc->required_fields;

	tmpl = nmc_fields_dev_status;
	tmpl_len = sizeof (nmc_fields_dev_status);
	nmc->print_fields.indices = parse_output_fields (fields_str, tmpl, FALSE, NULL, &error);

	if (error) {
		g_string_printf (nmc->return_text, _("Error: 'device status': %s"), error->message);
		g_error_free (error);
		return NMC_RESULT_ERROR_USER_INPUT;
	}

	/* Add headers */
	nmc->print_fields.header_name = _("Status of devices");
	arr = nmc_dup_fields_array (tmpl, tmpl_len, NMC_OF_FLAG_MAIN_HEADER_ADD | NMC_OF_FLAG_FIELD_NAMES);
	g_ptr_array_add (nmc->output_data, arr);

	devices = nmc_get_devices_sorted (nmc->client);
	for (i = 0; devices[i]; i++)
		fill_output_device_status (devices[i], nmc);

	/* Now print all data */
	print_data (nmc);

	g_free (devices);

	return NMC_RESULT_SUCCESS;
}

static NMCResultCode
do_device_show (NmCli *nmc, int argc, char **argv)
{
	gs_free_error GError *error = NULL;

	if (!nmc->mode_specified)
		nmc->multiline_output = TRUE;  /* multiline mode is default for 'device show' */

	if (argc) {
		NMDevice *device;

		device = get_device (nmc, &argc, &argv, &error);
		if (!device) {
			g_string_printf (nmc->return_text, _("Error: %s."), error->message);
			return error->code;
		}

		if (argc) {
			g_string_printf (nmc->return_text, _("Error: invalid extra argument '%s'."), *argv);
			return NMC_RESULT_ERROR_USER_INPUT;
		}

		if (nmc->complete)
			return nmc->return_value;

		show_device_info (device, nmc);
	} else {
		NMDevice **devices = nmc_get_devices_sorted (nmc->client);
		int i;

		/* nmc_do_cmd() should not call this with argc=0. */
		g_assert (!nmc->complete);

		/* Show details for all devices */
		for (i = 0; devices[i]; i++) {
			nmc_empty_output_fields (nmc);
			if (!show_device_info (devices[i], nmc))
				break;
			if (devices[i + 1])
				g_print ("\n"); /* Empty line */
		}

		g_free (devices);
	}

	return nmc->return_value;
}

static gboolean
timeout_cb (gpointer user_data)
{
	/* Time expired -> exit nmcli */

	NmCli *nmc = (NmCli *) user_data;

	g_string_printf (nmc->return_text, _("Error: Timeout %d sec expired."), nmc->timeout);
	nmc->return_value = NMC_RESULT_ERROR_TIMEOUT_EXPIRED;
	quit ();
	return FALSE;
}

static gboolean
progress_cb (gpointer user_data)
{
	NMDevice *device = (NMDevice *) user_data;

	nmc_terminal_show_progress (device ? nmc_device_state_to_string (nm_device_get_state (device)) : "");

	return TRUE;
}

static void connected_state_cb (NMDevice *device, NMActiveConnection *active);

static void
device_state_cb (NMDevice *device, GParamSpec *pspec, gpointer user_data)
{
	NMActiveConnection *active = (NMActiveConnection *) user_data;

	connected_state_cb (device, active);
}

static void
active_state_cb (NMActiveConnection *active, GParamSpec *pspec, gpointer user_data)
{
	NMDevice *device = (NMDevice *) user_data;

	connected_state_cb (device, active);
}

static void
connected_state_cb (NMDevice *device, NMActiveConnection *active)
{
	NMDeviceState state;
	NMDeviceStateReason reason;
	NMActiveConnectionState ac_state;

	state = nm_device_get_state (device);
	ac_state = nm_active_connection_get_state (active);

	if (ac_state == NM_ACTIVE_CONNECTION_STATE_ACTIVATING)
		return;

	if (state == NM_DEVICE_STATE_ACTIVATED) {
		nmc_terminal_erase_line ();
		g_print (_("Device '%s' successfully activated with '%s'.\n"),
		         nm_device_get_iface (device),
		         nm_active_connection_get_uuid (active));
	} else if (   state <= NM_DEVICE_STATE_DISCONNECTED
	           || state >= NM_DEVICE_STATE_DEACTIVATING) {
		reason = nm_device_get_state_reason (device);
		g_print (_("Error: Connection activation failed: (%d) %s.\n"),
		         reason, nmc_device_reason_to_string (reason));
	} else
		return;

	g_signal_handlers_disconnect_by_func (active, G_CALLBACK (active_state_cb), device);
	g_signal_handlers_disconnect_by_func (device, G_CALLBACK (device_state_cb), active);

	g_object_unref (active);
	g_object_unref (device);

	quit ();
}

typedef struct {
	NmCli *nmc;
	NMDevice *device;
	gboolean hotspot;
} AddAndActivateInfo;

static void
add_and_activate_cb (GObject *client,
                     GAsyncResult *result,
                     gpointer user_data)
{
	AddAndActivateInfo *info = (AddAndActivateInfo *) user_data;
	NmCli *nmc = info->nmc;
	NMDevice *device = info->device;
	NMActiveConnectionState state;
	NMActiveConnection *active;
	GError *error = NULL;

	active = nm_client_add_and_activate_connection_finish (NM_CLIENT (client), result, &error);

	if (error) {
		if (info->hotspot)
			g_string_printf (nmc->return_text, _("Error: Failed to setup a Wi-Fi hotspot: %s"),
			                 error->message);
		else
			g_string_printf (nmc->return_text, _("Error: Failed to add/activate new connection: %s"),
			                 error->message);
		g_error_free (error);
		nmc->return_value = NMC_RESULT_ERROR_CON_ACTIVATION;
		quit ();
	} else {
		state = nm_active_connection_get_state (active);

		if (state == NM_ACTIVE_CONNECTION_STATE_UNKNOWN) {
			if (info->hotspot)
				g_string_printf (nmc->return_text, _("Error: Failed to setup a Wi-Fi hotspot"));
			else
				g_string_printf (nmc->return_text, _("Error: Failed to add/activate new connection: Unknown error"));
			nmc->return_value = NMC_RESULT_ERROR_CON_ACTIVATION;
			g_object_unref (active);
			quit ();
		}

		if (nmc->nowait_flag || state == NM_ACTIVE_CONNECTION_STATE_ACTIVATED) {
			/* User doesn't want to wait or already activated */
			if (state == NM_ACTIVE_CONNECTION_STATE_ACTIVATED) {
				if (nmc->print_output == NMC_PRINT_PRETTY)
					nmc_terminal_erase_line ();
				if (info->hotspot)
					g_print (_("Connection with UUID '%s' created and activated on device '%s'\n"),
					         nm_active_connection_get_uuid (active), nm_device_get_iface (device));
				else
					g_print (_("Hotspot '%s' activated on device '%s'\n"),
					         nm_active_connection_get_id (active), nm_device_get_iface (device));
			}
			g_object_unref (active);
			quit ();
		} else {
			g_object_ref (device);
			g_signal_connect (device, "notify::state", G_CALLBACK (device_state_cb), active);
			g_signal_connect (active, "notify::state", G_CALLBACK (active_state_cb), device);

			g_timeout_add_seconds (nmc->timeout, timeout_cb, nmc);  /* Exit if timeout expires */

			if (nmc->print_output == NMC_PRINT_PRETTY)
				progress_id = g_timeout_add (120, progress_cb, device);
		}
	}

	g_free (info);
}

static void
create_connect_connection_for_device (AddAndActivateInfo *info)
{
	NMConnection *connection;
	NMSettingConnection *s_con;

	/* Create new connection and tie it to the device */
	connection = nm_simple_connection_new ();
	s_con = (NMSettingConnection *) nm_setting_connection_new ();
	nm_connection_add_setting (connection, NM_SETTING (s_con));
	g_object_set (s_con,
	              NM_SETTING_CONNECTION_ID, nm_device_get_iface (info->device),
	              NM_SETTING_CONNECTION_INTERFACE_NAME, nm_device_get_iface (info->device),
	              NULL);

	nm_client_add_and_activate_connection_async (info->nmc->client,
	                                             connection,
	                                             info->device,
	                                             NULL,
	                                             NULL,
	                                             add_and_activate_cb,
	                                             info);
}

static void
connect_device_cb (GObject *client, GAsyncResult *result, gpointer user_data)
{
	AddAndActivateInfo *info = (AddAndActivateInfo *) user_data;
	NmCli *nmc = info->nmc;
	NMActiveConnection *active;
	GError *error = NULL;
	const GPtrArray *devices;
	NMDevice *device;
	NMDeviceState state;

	active = nm_client_activate_connection_finish (NM_CLIENT (client), result, &error);

	if (error) {
		/* If no connection existed for the device, create one and activate it */
		if (g_error_matches (error, NM_MANAGER_ERROR, NM_MANAGER_ERROR_UNKNOWN_CONNECTION)) {
			create_connect_connection_for_device (info);
			return;
		}

		g_string_printf (nmc->return_text, _("Error: Device activation failed: %s"),
		                 error->message);
		g_error_free (error);
		nmc->return_value = NMC_RESULT_ERROR_CON_ACTIVATION;
		quit ();
	} else {
		g_assert (active);
		devices = nm_active_connection_get_devices (active);
		if (devices->len == 0) {
			g_string_printf (nmc->return_text, _("Error: Device activation failed: device was disconnected"));
			nmc->return_value = NMC_RESULT_ERROR_CON_ACTIVATION;
			g_object_unref (active);
			quit ();
			g_free (info);
			return;
		}

		device = g_ptr_array_index (devices, 0);
		state = nm_device_get_state (device);

		if (nmc->nowait_flag || state == NM_DEVICE_STATE_ACTIVATED) {
			/* Don't want to wait or device already activated */
			if (state == NM_DEVICE_STATE_ACTIVATED && nmc->print_output == NMC_PRINT_PRETTY) {
				nmc_terminal_erase_line ();
				g_print (_("Device '%s' has been connected.\n"), nm_device_get_iface (device));
			}
			g_object_unref (active);
			quit ();
		} else {
			if (nmc->secret_agent) {
				NMRemoteConnection *connection = nm_active_connection_get_connection (active);

				nm_secret_agent_simple_enable (NM_SECRET_AGENT_SIMPLE (nmc->secret_agent),
				                               nm_connection_get_path (NM_CONNECTION (connection)));
			}

			g_object_ref (device);
			g_signal_connect (device, "notify::state", G_CALLBACK (device_state_cb), active);
			g_signal_connect (active, "notify::state", G_CALLBACK (active_state_cb), device);
			/* Start timer not to loop forever if "notify::state" signal is not issued */
			g_timeout_add_seconds (nmc->timeout, timeout_cb, nmc);
		}
	}
	g_free (info);
}

static NMCResultCode
do_device_connect (NmCli *nmc, int argc, char **argv)
{
	NMDevice *device = NULL;
	AddAndActivateInfo *info;
	gs_free_error GError *error = NULL;

	/* Set default timeout for connect operation. */
	if (nmc->timeout == -1)
		nmc->timeout = 90;

	device = get_device (nmc, &argc, &argv, &error);
	if (!device) {
		g_string_printf (nmc->return_text, _("Error: %s."), error->message);
		return error->code;
	}

	if (*argv) {
		g_string_printf (nmc->return_text, _("Error: extra argument not allowed: '%s'."), *argv);
		return NMC_RESULT_ERROR_USER_INPUT;
	}

	if (nmc->complete)
		return nmc->return_value;

	/*
	 * Use nowait_flag instead of should_wait, because exiting has to be postponed
	 * till connect_device_cb() is called, giving NM time to check our permissions.
	 */
	nmc->nowait_flag = (nmc->timeout == 0);
	nmc->should_wait++;

	nmc->connections = nm_client_get_connections (nmc->client);

	/* Create secret agent */
	nmc->secret_agent = nm_secret_agent_simple_new ("nmcli-connect");
	if (nmc->secret_agent)
		g_signal_connect (nmc->secret_agent, "request-secrets", G_CALLBACK (nmc_secrets_requested), nmc);

	info = g_malloc0 (sizeof (AddAndActivateInfo));
	info->nmc = nmc;
	info->device = device;
	info->hotspot = FALSE;

	nm_client_activate_connection_async (nmc->client,
	                                     NULL,  /* let NM find a connection automatically */
	                                     device,
	                                     NULL,
	                                     NULL,
	                                     connect_device_cb,
	                                     info);

	/* Start progress indication */
	if (nmc->print_output == NMC_PRINT_PRETTY)
		progress_id = g_timeout_add (120, progress_cb, device);

	return nmc->return_value;
}

typedef struct {
	NmCli *nmc;
	GSList *queue;
	guint timeout_id;
	gboolean cmd_disconnect;
} DeviceCbInfo;

static void device_cb_info_finish (DeviceCbInfo *info, NMDevice *device);

static gboolean
device_op_timeout_cb (gpointer user_data)
{
	DeviceCbInfo *info = user_data;

	timeout_cb (info->nmc);
	device_cb_info_finish (info, NULL);
	return G_SOURCE_REMOVE;
}

static void
device_removed_cb (NMClient *client, NMDevice *device, DeviceCbInfo *info)
{
	/* Success: device has been removed.
	 * It can also happen when disconnecting a software device.
	 */
	if (!g_slist_find (info->queue, device))
		return;

	if (info->cmd_disconnect)
		g_print (_("Device '%s' successfully disconnected.\n"),
		         nm_device_get_iface (device));
	else
		g_print (_("Device '%s' successfully removed.\n"),
		         nm_device_get_iface (device));
	device_cb_info_finish (info, device);
}

static void
disconnect_state_cb (NMDevice *device, GParamSpec *pspec, DeviceCbInfo *info)
{
	if (!g_slist_find (info->queue, device))
		return;

	if (nm_device_get_state (device) <= NM_DEVICE_STATE_DISCONNECTED) {
		g_print (_("Device '%s' successfully disconnected.\n"),
		         nm_device_get_iface (device));
		device_cb_info_finish (info, device);
	}
}

static void
destroy_queue_element (gpointer data)
{
	g_signal_handlers_disconnect_matched (data, G_SIGNAL_MATCH_FUNC, 0, 0, 0,
	                                      disconnect_state_cb, NULL);
	g_object_unref (data);
}

static void
device_cb_info_finish (DeviceCbInfo *info, NMDevice *device)
{
	if (device) {
		GSList *elem = g_slist_find (info->queue, device);
		if (!elem)
			return;
		info->queue = g_slist_delete_link (info->queue, elem);
		destroy_queue_element (device);
	} else {
		g_slist_free_full (info->queue, destroy_queue_element);
		info->queue = NULL;
	}

	if (info->queue)
		return;

	if (info->timeout_id)
		g_source_remove (info->timeout_id);
	g_signal_handlers_disconnect_by_func (info->nmc->client, device_removed_cb, info);
	g_slice_free (DeviceCbInfo, info);
	quit ();
}

static void
reapply_device_cb (GObject *object, GAsyncResult *result, gpointer user_data)
{
	NMDevice *device = NM_DEVICE (object);
	DeviceCbInfo *info = (DeviceCbInfo *) user_data;
	NmCli *nmc = info->nmc;
	GError *error = NULL;

	if (!nm_device_reapply_finish (device, result, &error)) {
		g_string_printf (nmc->return_text, _("Error: Reapplying connection to device '%s' (%s) failed: %s"),
		                 nm_device_get_iface (device),
		                 nm_object_get_path (NM_OBJECT (device)),
		                 error->message);
		g_error_free (error);
		nmc->return_value = NMC_RESULT_ERROR_DEV_DISCONNECT;
		device_cb_info_finish (info, device);
	} else {
		if (nmc->print_output == NMC_PRINT_PRETTY)
			nmc_terminal_erase_line ();
		g_print (_("Connection successfully reapplied to device '%s'.\n"),
		         nm_device_get_iface (device));
		device_cb_info_finish (info, device);
	}
}

static NMCResultCode
do_device_reapply (NmCli *nmc, int argc, char **argv)
{
	NMDevice *device;
	DeviceCbInfo *info = NULL;
	gs_free_error GError *error = NULL;

	/* Set default timeout for reapply operation. */
	if (nmc->timeout == -1)
		nmc->timeout = 10;

	device = get_device (nmc, &argc, &argv, &error);
	if (!device) {
		g_string_printf (nmc->return_text, _("Error: %s."), error->message);
		return error->code;
	}

	if (argc) {
		g_string_printf (nmc->return_text, _("Error: invalid extra argument '%s'."), *argv);
		return NMC_RESULT_ERROR_USER_INPUT;
	}

	if (nmc->complete)
		return nmc->return_value;

	nmc->nowait_flag = (nmc->timeout == 0);
	nmc->should_wait++;

	info = g_slice_new0 (DeviceCbInfo);
	info->nmc = nmc;
	info->queue = g_slist_prepend (info->queue, g_object_ref (device));

	/* Now reapply the connection to the device */
	nm_device_reapply_async (device, NULL, 0, 0, NULL, reapply_device_cb, info);

	return nmc->return_value;
}

typedef struct {
	NmCli *nmc;
	int argc;
	char **argv;
} ModifyInfo;

static void
modify_reapply_cb (GObject *object, GAsyncResult *result, gpointer user_data)
{
	NMDevice *device = NM_DEVICE (object);
	ModifyInfo *info = user_data;
	NmCli *nmc = info->nmc;
	GError *error = NULL;

	if (!nm_device_reapply_finish (device, result, &error)) {
		g_string_printf (nmc->return_text, _("Error: Reapplying connection to device '%s' (%s) failed: %s"),
		                 nm_device_get_iface (device),
		                 nm_object_get_path (NM_OBJECT (device)),
		                 error->message);
		g_error_free (error);
		nmc->return_value = NMC_RESULT_ERROR_DEV_DISCONNECT;
	} else {
		if (nmc->print_output == NMC_PRINT_PRETTY)
			nmc_terminal_erase_line ();
		g_print (_("Connection successfully reapplied to device '%s'.\n"),
		         nm_device_get_iface (device));
	}

	g_slice_free (ModifyInfo, info);
	quit ();
}

static void
modify_get_applied_cb (GObject *object,
                       GAsyncResult *result,
                       gpointer user_data)
{
	NMDevice *device = NM_DEVICE (object);
	ModifyInfo *info = user_data;
	NmCli *nmc = info->nmc;
	gs_free_error GError *error = NULL;
	NMConnection *connection;
	guint64 version_id;

	connection = nm_device_get_applied_connection_finish (device,
	                                                      result,
	                                                      &version_id,
	                                                      &error);
	if (!connection) {
		g_string_printf (nmc->return_text, _("Error: Reading applied connection from device '%s' (%s) failed: %s"),
		                 nm_device_get_iface (device),
		                 nm_object_get_path (NM_OBJECT (device)),
		                 error->message);
		nmc->return_value = NMC_RESULT_ERROR_UNKNOWN;
		g_slice_free (ModifyInfo, info);
		quit ();
		return;
	}

	if (!nmc_read_connection_properties (info->nmc, connection, &info->argc, &info->argv, &error)) {
		g_string_assign (nmc->return_text, error->message);
		nmc->return_value = error->code;
		g_slice_free (ModifyInfo, info);
		quit ();
		return;
	}

	if (nmc->complete)
		quit ();
	else
		nm_device_reapply_async (device, connection, version_id, 0, NULL, modify_reapply_cb, info);
}

static NMCResultCode
do_device_modify (NmCli *nmc, int argc, char **argv)
{
	NMDevice *device = NULL;
	ModifyInfo *info = NULL;
	gs_free_error GError *error = NULL;

	device = get_device (nmc, &argc, &argv, &error);
	if (!device) {
		g_string_printf (nmc->return_text, _("Error: %s."), error->message);
		return error->code;
	}

	if (nmc->timeout == -1)
		nmc->timeout = 10;

	nmc->nowait_flag = (nmc->timeout == 0);
	nmc->should_wait++;

	info = g_slice_new0 (ModifyInfo);
	info->nmc = nmc;
	info->argc = argc;
	info->argv = argv;

	nm_device_get_applied_connection_async (device, 0, NULL, modify_get_applied_cb, info);

	return nmc->return_value;
}

static void
disconnect_device_cb (GObject *object, GAsyncResult *result, gpointer user_data)
{
	NMDevice *device = NM_DEVICE (object);
	DeviceCbInfo *info = (DeviceCbInfo *) user_data;
	NmCli *nmc = info->nmc;
	NMDeviceState state;
	GError *error = NULL;

	if (!nm_device_disconnect_finish (device, result, &error)) {
		g_string_printf (nmc->return_text, _("Error: not all devices disconnected."));
		g_printerr (_("Error: Device '%s' (%s) disconnecting failed: %s\n"),
		            nm_device_get_iface (device),
		            nm_object_get_path (NM_OBJECT (device)),
		            error->message);
		g_error_free (error);
		nmc->return_value = NMC_RESULT_ERROR_DEV_DISCONNECT;
		device_cb_info_finish (info, device);
	} else {
		state = nm_device_get_state (device);
		if (nmc->nowait_flag || state <= NM_DEVICE_STATE_DISCONNECTED) {
			/* Don't want to wait or device already disconnected */
			if (state <= NM_DEVICE_STATE_DISCONNECTED) {
				if (nmc->print_output == NMC_PRINT_PRETTY)
					nmc_terminal_erase_line ();
				g_print (_("Device '%s' successfully disconnected.\n"),
				         nm_device_get_iface (device));
			}
			device_cb_info_finish (info, device);
		}
	}
}

static NMCResultCode
do_devices_disconnect (NmCli *nmc, int argc, char **argv)
{
	NMDevice *device;
	DeviceCbInfo *info = NULL;
	GSList *queue, *iter;

	/* Set default timeout for disconnect operation. */
	if (nmc->timeout == -1)
		nmc->timeout = 10;

	queue = get_device_list (nmc, argc, argv);
	if (!queue)
		return nmc->return_value;
	if (nmc->complete)
		goto out;
	queue = g_slist_reverse (queue);

	info = g_slice_new0 (DeviceCbInfo);
	info->nmc = nmc;
	info->cmd_disconnect = TRUE;
	if (nmc->timeout > 0)
		info->timeout_id = g_timeout_add_seconds (nmc->timeout, device_op_timeout_cb, info);

	g_signal_connect (nmc->client, NM_CLIENT_DEVICE_REMOVED,
	                  G_CALLBACK (device_removed_cb), info);

	nmc->nowait_flag = (nmc->timeout == 0);
	nmc->should_wait++;

	for (iter = queue; iter; iter = g_slist_next (iter)) {
		device = iter->data;

		info->queue = g_slist_prepend (info->queue, g_object_ref (device));
		g_signal_connect (device, "notify::" NM_DEVICE_STATE,
		                  G_CALLBACK (disconnect_state_cb), info);

		/* Now disconnect the device */
		nm_device_disconnect_async (device, NULL, disconnect_device_cb, info);
	}

out:
	g_slist_free (queue);
	return nmc->return_value;
}

static void
delete_device_cb (GObject *object, GAsyncResult *result, gpointer user_data)
{
	NMDevice *device = NM_DEVICE (object);
	DeviceCbInfo *info = (DeviceCbInfo *) user_data;
	NmCli *nmc = info->nmc;
	GError *error = NULL;

	if (!nm_device_delete_finish (device, result, &error)) {
		g_string_printf (nmc->return_text, _("Error: not all devices deleted."));
		g_printerr (_("Error: Device '%s' (%s) deletion failed: %s\n"),
		            nm_device_get_iface (device),
		            nm_object_get_path (NM_OBJECT (device)),
		            error->message);
		g_error_free (error);
		nmc->return_value = NMC_RESULT_ERROR_UNKNOWN;
		device_cb_info_finish (info, device);
	} else {
		if (nmc->nowait_flag)
			device_cb_info_finish (info, device);
	}
}

static NMCResultCode
do_devices_delete (NmCli *nmc, int argc, char **argv)
{
	NMDevice *device;
	DeviceCbInfo *info = NULL;
	GSList *queue, *iter;

	/* Set default timeout for delete operation. */
	if (nmc->timeout == -1)
		nmc->timeout = 10;

	queue = get_device_list (nmc, argc, argv);
	if (!queue)
		return nmc->return_value;
	if (nmc->complete)
		goto out;
	queue = g_slist_reverse (queue);

	info = g_slice_new0 (DeviceCbInfo);
	info->nmc = nmc;
	if (nmc->timeout > 0)
		info->timeout_id = g_timeout_add_seconds (nmc->timeout, device_op_timeout_cb, info);

	g_signal_connect (nmc->client, NM_CLIENT_DEVICE_REMOVED,
	                  G_CALLBACK (device_removed_cb), info);

	nmc->nowait_flag = (nmc->timeout == 0);
	nmc->should_wait++;

	for (iter = queue; iter; iter = g_slist_next (iter)) {
		device = iter->data;

		info->queue = g_slist_prepend (info->queue, g_object_ref (device));

		/* Now delete the device */
		nm_device_delete_async (device, NULL, delete_device_cb, info);
	}

out:
	g_slist_free (queue);
	return nmc->return_value;
}

static NMCResultCode
do_device_set (NmCli *nmc, int argc, char **argv)
{
#define DEV_SET_AUTOCONNECT 0
#define DEV_SET_MANAGED     1
	NMDevice *device = NULL;
	int i;
	struct {
		int idx;
		gboolean value;
	} values[2] = {
		[DEV_SET_AUTOCONNECT] = { -1 },
		[DEV_SET_MANAGED]     = { -1 },
	};
	gs_free_error GError *error = NULL;

	if (argc >= 1 && g_strcmp0 (*argv, "ifname") == 0) {
		argc--;
		argv++;
	}

	device = get_device (nmc, &argc, &argv, &error);
	if (!device) {
		g_string_printf (nmc->return_text, _("Error: %s."), error->message);
		return error->code;
	}

        if (!argc) {
		g_string_printf (nmc->return_text, _("Error: No property specified."));
		return NMC_RESULT_ERROR_USER_INPUT;
	}

	i = 0;
	do {
		gboolean flag;

		if (argc == 1 && nmc->complete)
			nmc_complete_strings (*argv, "managed", "autoconnect", NULL);

		if (matches (*argv, "managed") == 0) {
			if (next_arg (&argc, &argv) != 0) {
				g_string_printf (nmc->return_text, _("Error: '%s' argument is missing."), *(argv-1));
				return NMC_RESULT_ERROR_USER_INPUT;
			}
			if (argc == 1 && nmc->complete)
				nmc_complete_bool (*argv);
			if (!nmc_string_to_bool (*argv, &flag, &error)) {
				g_string_printf (nmc->return_text, _("Error: 'managed': %s."),
				                 error->message);
				return NMC_RESULT_ERROR_USER_INPUT;
			}
			values[DEV_SET_MANAGED].idx = ++i;
			values[DEV_SET_MANAGED].value = flag;
		}
		else if (matches (*argv, "autoconnect") == 0) {
			if (next_arg (&argc, &argv) != 0) {
				g_string_printf (nmc->return_text, _("Error: '%s' argument is missing."), *(argv-1));
				return NMC_RESULT_ERROR_USER_INPUT;
			}
			if (argc == 1 && nmc->complete)
				nmc_complete_bool (*argv);
			if (!nmc_string_to_bool (*argv, &flag, &error)) {
				g_string_printf (nmc->return_text, _("Error: 'autoconnect': %s."),
				                 error->message);
				return NMC_RESULT_ERROR_USER_INPUT;
			}
			values[DEV_SET_AUTOCONNECT].idx = ++i;
			values[DEV_SET_AUTOCONNECT].value = flag;
		}
		else {
			g_string_printf (nmc->return_text, _("Error: property '%s' is not known."), *argv);
			return NMC_RESULT_ERROR_USER_INPUT;
		}
	} while (next_arg (&argc, &argv) == 0);

	if (nmc->complete)
		return nmc->return_value;

	/* when multiple properties are specified, set them in the order as they
	 * are specified on the command line. */
	if (   values[DEV_SET_AUTOCONNECT].idx >= 0
	    && values[DEV_SET_MANAGED].idx >= 0
	    && values[DEV_SET_MANAGED].idx < values[DEV_SET_AUTOCONNECT].idx) {
		nm_device_set_managed (device, values[DEV_SET_MANAGED].value);
		values[DEV_SET_MANAGED].idx = -1;
	}
	if (values[DEV_SET_AUTOCONNECT].idx >= 0)
		nm_device_set_autoconnect (device, values[DEV_SET_AUTOCONNECT].value);
	if (values[DEV_SET_MANAGED].idx >= 0)
		nm_device_set_managed (device, values[DEV_SET_MANAGED].value);

	return nmc->return_value;
}

static void
device_state (NMDevice *device, GParamSpec *pspec, NmCli *nmc)
{
	NMDeviceState state = nm_device_get_state (device);
	NmcTermColor color;
	NmcTermFormat color_fmt;
	char *str;

	nmc_device_state_to_color (state, &color, &color_fmt);
	str = nmc_colorize (nmc, color, color_fmt, "%s: %s\n",
	                    nm_device_get_iface (device),
	                    nmc_device_state_to_string (state));

	g_print ("%s", str);
	g_free (str);
}

static void
device_ac (NMDevice *device, GParamSpec *pspec, NmCli *nmc)
{
	NMActiveConnection *ac = nm_device_get_active_connection (device);
	const char *id = ac ? nm_active_connection_get_id (ac) : NULL;

	if (!id)
		return;

	g_print (_("%s: using connection '%s'\n"), nm_device_get_iface (device), id);
}

static void
device_watch (NmCli *nmc, NMDevice *device)
{
	nmc->should_wait++;
	g_signal_connect (device, "notify::" NM_DEVICE_STATE, G_CALLBACK (device_state), nmc);
	g_signal_connect (device, "notify::" NM_DEVICE_ACTIVE_CONNECTION, G_CALLBACK (device_ac), nmc);
}

static void
device_unwatch (NmCli *nmc, NMDevice *device)
{
	g_signal_handlers_disconnect_by_func (device, device_state, nmc);
	if (g_signal_handlers_disconnect_by_func (device, device_ac, nmc))
		nmc->should_wait--;

	/* Terminate if all the watched devices disappeared. */
	if (!nmc->should_wait)
		quit ();
}

static void
device_added (NMClient *client, NMDevice *device, NmCli *nmc)
{
	g_print (_("%s: device created\n"), nm_device_get_iface (device));
	device_watch (nmc, NM_DEVICE (device));
}

static void
device_removed (NMClient *client, NMDevice *device, NmCli *nmc)
{
	g_print (_("%s: device removed\n"), nm_device_get_iface (device));
	device_unwatch (nmc, device);
}

static NMCResultCode
do_devices_monitor (NmCli *nmc, int argc, char **argv)
{
	GSList *queue = get_device_list (nmc, argc, argv);
	GSList *iter;

	if (nmc->complete)
		return nmc->return_value;

	if (argc == 0) {
		/* No devices specified. Monitor all. */
		const GPtrArray *devices = nm_client_get_devices (nmc->client);
		int i;

		for (i = 0; i < devices->len; i++)
			device_watch (nmc, g_ptr_array_index (devices, i));

		/* We'll watch the device additions too, never exit. */
		nmc->should_wait++;
		g_signal_connect (nmc->client, NM_CLIENT_DEVICE_ADDED, G_CALLBACK (device_added), nmc);
	} else {
		/* Monitor the specified devices. */
		for (iter = queue; iter; iter = g_slist_next (iter))
			device_watch (nmc, NM_DEVICE (iter->data));
		g_slist_free (queue);
	}

	g_signal_connect (nmc->client, NM_CLIENT_DEVICE_REMOVED, G_CALLBACK (device_removed), nmc);
	return nmc->return_value;
}

static void
show_access_point_info (NMDevice *device, NmCli *nmc)
{
	NMAccessPoint *active_ap = NULL;
	const char *active_bssid = NULL;
	GPtrArray *aps;
	APInfo *info;
	NmcOutputField *arr;

	if (nm_device_get_state (device) == NM_DEVICE_STATE_ACTIVATED) {
		active_ap = nm_device_wifi_get_active_access_point (NM_DEVICE_WIFI (device));
		active_bssid = active_ap ? nm_access_point_get_bssid (active_ap) : NULL;
	}

	arr = nmc_dup_fields_array (nmc_fields_dev_wifi_list, sizeof (nmc_fields_dev_wifi_list),
	                            NMC_OF_FLAG_MAIN_HEADER_ADD | NMC_OF_FLAG_FIELD_NAMES);
	g_ptr_array_add (nmc->output_data, arr);

	info = g_malloc0 (sizeof (APInfo));
	info->nmc = nmc;
	info->index = 1;
	info->output_flags = 0;
	info->active_bssid = active_bssid;
	info->device = nm_device_get_iface (device);
	aps = sort_access_points (nm_device_wifi_get_access_points (NM_DEVICE_WIFI (device)));
	g_ptr_array_foreach ((GPtrArray *) aps, fill_output_access_point, (gpointer) info);
	g_ptr_array_free (aps, FALSE);

	print_data (nmc);  /* Print all data */
	nmc_empty_output_fields (nmc);
	g_free (info);
}

/*
 * Find a Wi-Fi device with 'iface' in 'devices' array. If 'iface' is NULL,
 * the first Wi-Fi device is returned. 'idx' parameter is updated to the point
 * where the function finished so that the function can be called repeatedly
 * to get next matching device.
 * Returns: found device or NULL
 */
static NMDevice *
find_wifi_device_by_iface (NMDevice **devices, const char *iface, int *idx)
{
	int i;

	for (i = idx ? *idx : 0; devices[i]; i++) {
		const char *dev_iface = nm_device_get_iface (devices[i]);

		if (!NM_IS_DEVICE_WIFI (devices[i]))
			continue;

		if (iface) {
			/* If a iface was specified then use it. */
			if (g_strcmp0 (dev_iface, iface) == 0)
				break;
		} else {
			/* Else return the first Wi-Fi device. */
			break;
		}
	}

	if (idx)
		*idx = i + 1;
	return devices[i];
}

/*
 * Find AP on 'device' according to 'bssid' or 'ssid' parameter.
 * Returns: found AP or NULL
 */
static NMAccessPoint *
find_ap_on_device (NMDevice *device, GByteArray *bssid, const char *ssid)
{
	const GPtrArray *aps;
	NMAccessPoint *ap = NULL;
	int i;

	g_return_val_if_fail (NM_IS_DEVICE_WIFI (device), NULL);
	g_return_val_if_fail ((bssid && !ssid) || (!bssid && ssid), NULL);

	aps = nm_device_wifi_get_access_points (NM_DEVICE_WIFI (device));
	for (i = 0; i < aps->len; i++) {
		NMAccessPoint *candidate_ap = g_ptr_array_index (aps, i);

		if (ssid) {
			/* Parameter is SSID */
			GBytes *candidate_ssid;

			candidate_ssid = nm_access_point_get_ssid (candidate_ap);
			if (candidate_ssid) {
				char *ssid_tmp = nm_utils_ssid_to_utf8 (g_bytes_get_data (candidate_ssid, NULL),
				                                        g_bytes_get_size (candidate_ssid));

				/* Compare SSIDs */
				if (strcmp (ssid, ssid_tmp) == 0) {
					ap = candidate_ap;
					g_free (ssid_tmp);
					break;
				}
				g_free (ssid_tmp);
			}
		} else if (bssid) {
			/* Parameter is BSSID */
			const char *candidate_bssid = nm_access_point_get_bssid (candidate_ap);
			char *bssid_up = nm_utils_hwaddr_ntoa (bssid->data, bssid->len);

			/* Compare BSSIDs */
			if (strcmp (bssid_up, candidate_bssid) == 0) {
				ap = candidate_ap;
				g_free (bssid_up);
				break;
			}
			g_free (bssid_up);
		}
	}

	return ap;
}

static NMCResultCode
do_device_wifi_list (NmCli *nmc, int argc, char **argv)
{
	GError *error = NULL;
	NMDevice *device = NULL;
	NMAccessPoint *ap = NULL;
	const char *ifname = NULL;
	const char *bssid_user = NULL;
	NMDevice **devices = NULL;
	const GPtrArray *aps;
	APInfo *info;
	int i, j;
	char *fields_str;
	char *fields_all =    NMC_FIELDS_DEV_WIFI_LIST_ALL;
	char *fields_common = NMC_FIELDS_DEV_WIFI_LIST_COMMON;
	NmcOutputField *tmpl, *arr;
	size_t tmpl_len;
	const char *base_hdr = _("Wi-Fi scan list");

	/* Not (yet?) supported */
	if (nmc->complete)
		return nmc->return_value;

	while (argc > 0) {
		if (strcmp (*argv, "ifname") == 0) {
			if (next_arg (&argc, &argv) != 0) {
				g_string_printf (nmc->return_text, _("Error: %s argument is missing."), *(argv-1));
				nmc->return_value = NMC_RESULT_ERROR_USER_INPUT;
				goto error;
			}
			ifname = *argv;
		} else if (strcmp (*argv, "bssid") == 0 || strcmp (*argv, "hwaddr") == 0) {
			/* hwaddr is deprecated and will be removed later */
			if (next_arg (&argc, &argv) != 0) {
				g_string_printf (nmc->return_text, _("Error: %s argument is missing."), *(argv-1));
				nmc->return_value = NMC_RESULT_ERROR_USER_INPUT;
				goto error;
			}
			bssid_user = *argv;
		} else {
			g_printerr (_("Unknown parameter: %s\n"), *argv);
		}

		argc--;
		argv++;
	}

	if (!nmc->required_fields || strcasecmp (nmc->required_fields, "common") == 0)
		fields_str = fields_common;
	else if (!nmc->required_fields || strcasecmp (nmc->required_fields, "all") == 0)
		fields_str = fields_all;
	else
		fields_str = nmc->required_fields;

	tmpl = nmc_fields_dev_wifi_list;
	tmpl_len = sizeof (nmc_fields_dev_wifi_list);
	nmc->print_fields.indices = parse_output_fields (fields_str, tmpl, FALSE, NULL, &error);

	if (error) {
		g_string_printf (nmc->return_text, _("Error: 'device wifi': %s"), error->message);
		g_error_free (error);
		nmc->return_value = NMC_RESULT_ERROR_USER_INPUT;
		goto error;
	}

	devices = nmc_get_devices_sorted (nmc->client);
	if (ifname) {
		/* Device specified - list only APs of this interface */
		for (i = 0; devices[i]; i++) {
			NMDevice *candidate = devices[i];
			const char *dev_iface = nm_device_get_iface (candidate);

			if (!g_strcmp0 (dev_iface, ifname)) {
				device = candidate;
				break;
			}
		}
		if (!device) {
			g_string_printf (nmc->return_text, _("Error: Device '%s' not found."), ifname);
			nmc->return_value = NMC_RESULT_ERROR_NOT_FOUND;
			goto error;
		}

		/* Main header name */
		nmc->print_fields.header_name = (char *) construct_header_name (base_hdr, ifname);

		if (NM_IS_DEVICE_WIFI (device)) {
			if (bssid_user) {
				/* Specific AP requested - list only that */
				aps = nm_device_wifi_get_access_points (NM_DEVICE_WIFI (device));
				for (j = 0; j < aps->len; j++) {
					char *bssid_up;
					NMAccessPoint *candidate_ap = g_ptr_array_index (aps, j);
					const char *candidate_bssid = nm_access_point_get_bssid (candidate_ap);

					bssid_up = g_ascii_strup (bssid_user, -1);
					if (!strcmp (bssid_up, candidate_bssid))
						ap = candidate_ap;
					g_free (bssid_up);
				}
				if (!ap) {
					g_string_printf (nmc->return_text, _("Error: Access point with bssid '%s' not found."),
					                 bssid_user);
					nmc->return_value = NMC_RESULT_ERROR_NOT_FOUND;
					goto error;
				}
				/* Add headers (field names) */
				arr = nmc_dup_fields_array (tmpl, tmpl_len, NMC_OF_FLAG_MAIN_HEADER_ADD | NMC_OF_FLAG_FIELD_NAMES);
				g_ptr_array_add (nmc->output_data, arr);

				info = g_malloc0 (sizeof (APInfo));
				info->nmc = nmc;
				info->index = 1;
				info->output_flags = 0;
				info->active_bssid = NULL;
				info->device = nm_device_get_iface (device);

				fill_output_access_point (ap, info);

				print_data (nmc);  /* Print all data */
				g_free (info);
			} else {
				show_access_point_info (device, nmc);
			}
		} else {
			if (   nm_device_get_device_type (device) == NM_DEVICE_TYPE_GENERIC
			    && g_strcmp0 (nm_device_get_type_description (device), "wifi") == 0) {
				g_string_printf (nmc->return_text,
				                 _("Error: Device '%s' was not recognized as a Wi-Fi device, check NetworkManager Wi-Fi plugin."),
				                 ifname);
			} else {
				g_string_printf (nmc->return_text,
				                 _("Error: Device '%s' is not a Wi-Fi device."),
				                 ifname);
			}
			nmc->return_value = NMC_RESULT_ERROR_UNKNOWN;
			goto error;
		}
	} else {
		gboolean empty_line = FALSE;

		/* List APs for all devices */
		if (bssid_user) {
			/* Specific AP requested - list only that */
			for (i = 0; devices[i]; i++) {
				NMDevice *dev = devices[i];

				if (!NM_IS_DEVICE_WIFI (dev))
					continue;

				/* Main header name */
				nmc->print_fields.header_name = (char *) construct_header_name (base_hdr, nm_device_get_iface (dev));
				nmc->print_fields.indices = parse_output_fields (fields_str, tmpl, FALSE, NULL, NULL);

				arr = nmc_dup_fields_array (tmpl, tmpl_len, NMC_OF_FLAG_MAIN_HEADER_ADD | NMC_OF_FLAG_FIELD_NAMES);
				g_ptr_array_add (nmc->output_data, arr);

				aps = nm_device_wifi_get_access_points (NM_DEVICE_WIFI (dev));
				for (j = 0; j < aps->len; j++) {
					char *bssid_up;
					NMAccessPoint *candidate_ap = g_ptr_array_index (aps, j);
					const char *candidate_bssid = nm_access_point_get_bssid (candidate_ap);

					bssid_up = g_ascii_strup (bssid_user, -1);
					if (!strcmp (bssid_up, candidate_bssid)) {
						ap = candidate_ap;

						info = g_malloc0 (sizeof (APInfo));
						info->nmc = nmc;
						info->index = 1;
						info->output_flags = 0;
						info->active_bssid = NULL;
						info->device = nm_device_get_iface (dev);
						fill_output_access_point (ap, info);
						g_free (info);
					}
					g_free (bssid_up);
				}
				if (empty_line)
					g_print ("\n"); /* Empty line between devices' APs */
				print_data (nmc);  /* Print all data */
				nmc_empty_output_fields (nmc);
				empty_line = TRUE;
			}
			if (!ap) {
				g_string_printf (nmc->return_text, _("Error: Access point with bssid '%s' not found."),
				                 bssid_user);
				nmc->return_value = NMC_RESULT_ERROR_NOT_FOUND;
				goto error;
			}
		} else {
			for (i = 0; devices[i]; i++) {
				NMDevice *dev = devices[i];

				/* Main header name */
				nmc->print_fields.header_name = (char *) construct_header_name (base_hdr,
				                                                                nm_device_get_iface (dev));
				nmc->print_fields.indices = parse_output_fields (fields_str, tmpl, FALSE, NULL, NULL);

				if (NM_IS_DEVICE_WIFI (dev)) {
					if (empty_line)
						g_print ("\n"); /* Empty line between devices' APs */
					show_access_point_info (dev, nmc);
					empty_line = TRUE;
				}
			}
		}
	}

error:
	g_free (devices);
	return nmc->return_value;
}

static NMCResultCode
do_device_wifi_connect_network (NmCli *nmc, int argc, char **argv)
{
	NMDevice *device = NULL;
	NMAccessPoint *ap = NULL;
	NM80211ApFlags ap_flags = NM_802_11_AP_FLAGS_NONE;
	NM80211ApSecurityFlags ap_wpa_flags = NM_802_11_AP_SEC_NONE;
	NM80211ApSecurityFlags ap_rsn_flags = NM_802_11_AP_SEC_NONE;
	NMConnection *connection = NULL;
	NMSettingConnection *s_con;
	NMSettingWireless *s_wifi;
	NMSettingWirelessSecurity *s_wsec;
	AddAndActivateInfo *info;
	const char *param_user = NULL;
	const char *ifname = NULL;
	const char *bssid = NULL;
	const char *password = NULL;
	const char *con_name = NULL;
	gboolean private = FALSE;
	gboolean hidden = FALSE;
	gboolean wep_passphrase = FALSE;
	GByteArray *bssid1_arr = NULL;
	GByteArray *bssid2_arr = NULL;
	gs_free NMDevice **devices = NULL;
	int devices_idx;
	char *ssid_ask = NULL;
	char *passwd_ask = NULL;

	/* Not (yet?) supported */
	if (nmc->complete)
		return nmc->return_value;

	/* Set default timeout waiting for operation completion. */
	if (nmc->timeout == -1)
		nmc->timeout = 90;

	/* Get the first compulsory argument (SSID or BSSID) */
	if (argc > 0) {
		param_user = *argv;
		bssid1_arr = nm_utils_hwaddr_atoba (param_user, ETH_ALEN);

		argc--;
		argv++;
	} else {
		if (nmc->ask) {
			ssid_ask = nmc_readline (_("SSID or BSSID: "));
			param_user = ssid_ask ? ssid_ask : "";
			bssid1_arr = nm_utils_hwaddr_atoba (param_user, ETH_ALEN);
		}
		if (!ssid_ask) {
			g_string_printf (nmc->return_text, _("Error: SSID or BSSID are missing."));
			nmc->return_value = NMC_RESULT_ERROR_USER_INPUT;
			goto error;
		}
	}

	/* Get the rest of the parameters */
	while (argc > 0) {
		if (strcmp (*argv, "ifname") == 0) {
			if (next_arg (&argc, &argv) != 0) {
				g_string_printf (nmc->return_text, _("Error: %s argument is missing."), *(argv-1));
				nmc->return_value = NMC_RESULT_ERROR_USER_INPUT;
				goto error;
			}
			ifname = *argv;
		} else if (strcmp (*argv, "bssid") == 0) {
			if (next_arg (&argc, &argv) != 0) {
				g_string_printf (nmc->return_text, _("Error: %s argument is missing."), *(argv-1));
				nmc->return_value = NMC_RESULT_ERROR_USER_INPUT;
				goto error;
			}
			bssid = *argv;
			bssid2_arr = nm_utils_hwaddr_atoba (bssid, ETH_ALEN);
			if (!bssid2_arr) {
				g_string_printf (nmc->return_text, _("Error: bssid argument value '%s' is not a valid BSSID."),
				                 bssid);
				nmc->return_value = NMC_RESULT_ERROR_USER_INPUT;
				goto error;
			}
		} else if (strcmp (*argv, "password") == 0) {
			if (next_arg (&argc, &argv) != 0) {
				g_string_printf (nmc->return_text, _("Error: %s argument is missing."), *(argv-1));
				nmc->return_value = NMC_RESULT_ERROR_USER_INPUT;
				goto error;
			}
			password = *argv;
		} else if (strcmp (*argv, "wep-key-type") == 0) {
			if (next_arg (&argc, &argv) != 0) {
				g_string_printf (nmc->return_text, _("Error: %s argument is missing."), *(argv-1));
				nmc->return_value = NMC_RESULT_ERROR_USER_INPUT;
				goto error;
			}
			if (strcmp (*argv, "key") == 0)
				wep_passphrase = FALSE;
			else if (strcmp (*argv, "phrase") == 0)
				wep_passphrase = TRUE;
			else {
				g_string_printf (nmc->return_text,
				                 _("Error: wep-key-type argument value '%s' is invalid, use 'key' or 'phrase'."),
				                 *argv);
				nmc->return_value = NMC_RESULT_ERROR_USER_INPUT;
				goto error;
			}
		} else if (strcmp (*argv, "name") == 0) {
			if (next_arg (&argc, &argv) != 0) {
				g_string_printf (nmc->return_text, _("Error: %s argument is missing."), *(argv-1));
				nmc->return_value = NMC_RESULT_ERROR_USER_INPUT;
				goto error;
			}
			con_name = *argv;
		} else if (strcmp (*argv, "private") == 0) {
			GError *err_tmp = NULL;
			if (next_arg (&argc, &argv) != 0) {
				g_string_printf (nmc->return_text, _("Error: %s argument is missing."), *(argv-1));
				nmc->return_value = NMC_RESULT_ERROR_USER_INPUT;
				goto error;
			}
			if (!nmc_string_to_bool (*argv, &private, &err_tmp)) {
				g_string_printf (nmc->return_text, _("Error: %s: %s."), *(argv-1), err_tmp->message);
				nmc->return_value = NMC_RESULT_ERROR_USER_INPUT;
				g_clear_error (&err_tmp);
				goto error;
			}
		} else if (strcmp (*argv, "hidden") == 0) {
			GError *err_tmp = NULL;
			if (next_arg (&argc, &argv) != 0) {
				g_string_printf (nmc->return_text, _("Error: %s argument is missing."), *(argv-1));
				nmc->return_value = NMC_RESULT_ERROR_USER_INPUT;
				goto error;
			}
			if (!nmc_string_to_bool (*argv, &hidden, &err_tmp)) {
				g_string_printf (nmc->return_text, _("Error: %s: %s."), *(argv-1), err_tmp->message);
				nmc->return_value = NMC_RESULT_ERROR_USER_INPUT;
				g_clear_error (&err_tmp);
				goto error;
			}
		} else {
			g_printerr (_("Unknown parameter: %s\n"), *argv);
		}

		argc--;
		argv++;
	}

	/* Verify SSID/BSSID parameters */
	if (bssid1_arr && bssid2_arr && memcmp (bssid1_arr->data, bssid2_arr->data, ETH_ALEN)) {
		g_string_printf (nmc->return_text, _("Error: BSSID to connect to (%s) differs from bssid argument (%s)."),
		                 param_user, bssid);
		nmc->return_value = NMC_RESULT_ERROR_USER_INPUT;
		goto error;
	}
	if (!bssid1_arr && strlen (param_user) > 32) {
		g_string_printf (nmc->return_text, _("Error: Parameter '%s' is neither SSID nor BSSID."), param_user);
		nmc->return_value = NMC_RESULT_ERROR_USER_INPUT;
		goto error;
	}

	devices = nmc_get_devices_sorted (nmc->client);

	/* Find a device to activate the connection on */
	devices_idx = 0;
	device = find_wifi_device_by_iface (devices, ifname, &devices_idx);

	if (!device) {
		if (ifname)
			g_string_printf (nmc->return_text, _("Error: Device '%s' is not a Wi-Fi device."), ifname);
		else
			g_string_printf (nmc->return_text, _("Error: No Wi-Fi device found."));
		nmc->return_value = NMC_RESULT_ERROR_UNKNOWN;
		goto error;
	}

	/* For hidden SSID first scan it so that NM learns about the AP */
	if (hidden) {
		GVariantBuilder builder, array_builder;
		GVariant *options;
		GError *scan_err = NULL;

		g_variant_builder_init (&builder, G_VARIANT_TYPE_VARDICT);
		g_variant_builder_init (&array_builder, G_VARIANT_TYPE ("aay"));
		g_variant_builder_add (&array_builder, "@ay",
		                       g_variant_new_fixed_array (G_VARIANT_TYPE_BYTE, param_user, strlen (param_user), 1));
		g_variant_builder_add (&builder, "{sv}", "ssids", g_variant_builder_end (&array_builder));
		options = g_variant_builder_end (&builder);

		nm_device_wifi_request_scan_options (NM_DEVICE_WIFI (device), options, NULL, &scan_err);
		if (scan_err) {
			g_string_printf (nmc->return_text, _("Error: Failed to scan hidden SSID: %s."),
			                 scan_err->message);
			g_clear_error (&scan_err);
			nmc->return_value = NMC_RESULT_ERROR_NOT_FOUND;
			goto error;
		}
	}

	/* Find an AP to connect to */
	ap = find_ap_on_device (device, bssid1_arr, bssid1_arr ? NULL : param_user);
	if (!ap && !ifname) {
		NMDevice *dev;

		/* AP not found, ifname was not specified, so try finding the AP on another device. */
		while ((dev = find_wifi_device_by_iface (devices, NULL, &devices_idx)) != NULL) {
			ap = find_ap_on_device (dev, bssid1_arr, bssid1_arr ? NULL : param_user);
			if (ap) {
				device = dev;
				break;
			}
		}
	}

	if (!ap) {
		if (!bssid1_arr)
			g_string_printf (nmc->return_text, _("Error: No network with SSID '%s' found."), param_user);
		else
			g_string_printf (nmc->return_text, _("Error: No access point with BSSID '%s' found."), param_user);
		nmc->return_value = NMC_RESULT_ERROR_NOT_FOUND;
		goto error;
	}

	/* If there are some connection data from user, create a connection and
	 * fill them into proper settings. */
	if (con_name || private || bssid2_arr || password || hidden)
		connection = nm_simple_connection_new ();

	if (con_name || private) {
		s_con =  (NMSettingConnection *) nm_setting_connection_new ();
		nm_connection_add_setting (connection, NM_SETTING (s_con));

		/* Set user provided connection name */
		if (con_name)
			g_object_set (s_con, NM_SETTING_CONNECTION_ID, con_name, NULL);

		/* Connection will only be visible to this user when '--private' is specified */
		if (private)
			nm_setting_connection_add_permission (s_con, "user", g_get_user_name (), NULL);
	}
	if (bssid2_arr || hidden) {
		s_wifi = (NMSettingWireless *) nm_setting_wireless_new ();
		nm_connection_add_setting (connection, NM_SETTING (s_wifi));

		/* 'bssid' parameter is used to restrict the connection only to the BSSID */
		if (bssid2_arr)
			g_object_set (s_wifi, NM_SETTING_WIRELESS_BSSID, bssid2_arr, NULL);

		/* 'hidden' parameter is used to indicate that SSID is not broadcasted */
		if (hidden) {
			GBytes *ssid = g_bytes_new (param_user, strlen (param_user));

			g_object_set (s_wifi,
			              NM_SETTING_WIRELESS_SSID, ssid,
			              NM_SETTING_WIRELESS_HIDDEN, hidden,
			              NULL);
			g_bytes_unref (ssid);

			/* Warn when the provided AP identifier looks like BSSID instead of SSID */
			if (bssid1_arr)
				g_printerr (_("Warning: '%s' should be SSID for hidden APs; but it looks like a BSSID.\n"),
				               param_user);
		}
	}

	/* handle password */
	ap_flags = nm_access_point_get_flags (ap);
	ap_wpa_flags = nm_access_point_get_wpa_flags (ap);
	ap_rsn_flags = nm_access_point_get_rsn_flags (ap);

	/* Set password for WEP or WPA-PSK. */
	if (ap_flags & NM_802_11_AP_FLAGS_PRIVACY) {
		/* Ask for missing password when one is expected and '--ask' is used */
		if (!password && nmc->ask)
			password = passwd_ask = nmc_readline_echo (nmc->show_secrets, _("Password: "));

		if (password) {
			if (!connection)
				connection = nm_simple_connection_new ();
			s_wsec = (NMSettingWirelessSecurity *) nm_setting_wireless_security_new ();
			nm_connection_add_setting (connection, NM_SETTING (s_wsec));

			if (ap_wpa_flags == NM_802_11_AP_SEC_NONE && ap_rsn_flags == NM_802_11_AP_SEC_NONE) {
				/* WEP */
				nm_setting_wireless_security_set_wep_key (s_wsec, 0, password);
				g_object_set (G_OBJECT (s_wsec),
				              NM_SETTING_WIRELESS_SECURITY_WEP_KEY_TYPE,
				              wep_passphrase ? NM_WEP_KEY_TYPE_PASSPHRASE: NM_WEP_KEY_TYPE_KEY,
				              NULL);
			} else if (   !(ap_wpa_flags & NM_802_11_AP_SEC_KEY_MGMT_802_1X)
				   && !(ap_rsn_flags & NM_802_11_AP_SEC_KEY_MGMT_802_1X)) {
				/* WPA PSK */
				g_object_set (s_wsec, NM_SETTING_WIRELESS_SECURITY_PSK, password, NULL);
			}
		}
	}
	// FIXME: WPA-Enterprise is not supported yet.
	// We are not able to determine and fill all the parameters for
	// 802.1X authentication automatically without user providing
	// the data. Adding nmcli options for the 8021x setting would
	// clutter the command. However, that could be solved later by
	// implementing add/edit connections support for nmcli.

	/* nowait_flag indicates user input. should_wait says whether quit in start().
	 * We have to delay exit after add_and_activate_cb() is called, even if
	 * the user doesn't want to wait, in order to give NM time to check our
	 * permissions. */
	nmc->nowait_flag = (nmc->timeout == 0);
	nmc->should_wait++;

	info = g_malloc0 (sizeof (AddAndActivateInfo));
	info->nmc = nmc;
	info->device = device;
	info->hotspot = FALSE;

	nm_client_add_and_activate_connection_async (nmc->client,
	                                             connection,
	                                             device,
	                                             nm_object_get_path (NM_OBJECT (ap)),
	                                             NULL,
	                                             add_and_activate_cb,
	                                             info);

error:
	if (bssid1_arr)
		g_byte_array_free (bssid1_arr, TRUE);
	if (bssid2_arr)
		g_byte_array_free (bssid2_arr, TRUE);
	g_free (ssid_ask);
	g_free (passwd_ask);

	return nmc->return_value;
}

static GBytes *
generate_ssid_for_hotspot (const char *ssid)
{
	GBytes *ssid_bytes;
	char *hotspot_ssid = NULL;

	if (!ssid) {
		hotspot_ssid = g_strdup_printf ("Hotspot-%s", g_get_host_name ());
		if (strlen (hotspot_ssid) > 32)
			hotspot_ssid[32] = '\0';
		ssid = hotspot_ssid;
	}
	ssid_bytes = g_bytes_new (ssid, strlen (ssid));
	g_free (hotspot_ssid);
	return ssid_bytes;
}

#define WPA_PASSKEY_SIZE 8
static void
generate_wpa_key (char *key, size_t len)
{
	guint i;

	g_return_if_fail (key);
	g_return_if_fail (len > WPA_PASSKEY_SIZE);

	/* generate a 8-chars ASCII WPA key */
	for (i = 0; i < WPA_PASSKEY_SIZE; i++) {
		int c;
		c = g_random_int_range (33, 126);
		/* too many non alphanumeric characters are hard to remember for humans */
		while (!g_ascii_isalnum (c))
			c = g_random_int_range (33, 126);

		key[i] = (gchar) c;
	}
	key[WPA_PASSKEY_SIZE] = '\0';
}

static void
generate_wep_key (char *key, size_t len)
{
	int i;
	const char *hexdigits = "0123456789abcdef";

	g_return_if_fail (key);
	g_return_if_fail (len > 10);

	/* generate a 10-digit hex WEP key */
	for (i = 0; i < 10; i++) {
		int digit;
		digit = g_random_int_range (0, 16);
		key[i] = hexdigits[digit];
	}
	key[10] = '\0';
}

static gboolean
set_wireless_security_for_hotspot (NMSettingWirelessSecurity *s_wsec,
                                   const char *wifi_mode,
                                   NMDeviceWifiCapabilities caps,
                                   const char *password,
                                   gboolean show_password,
                                   GError **error)
{
        char generated_key[11];
	const char *key;
	const char *key_mgmt;

	if (g_strcmp0 (wifi_mode, NM_SETTING_WIRELESS_MODE_AP) == 0) {
		if (caps & NM_WIFI_DEVICE_CAP_RSN) {
			nm_setting_wireless_security_add_proto (s_wsec, "rsn");
			nm_setting_wireless_security_add_pairwise (s_wsec, "ccmp");
			nm_setting_wireless_security_add_group (s_wsec, "ccmp");
			key_mgmt = "wpa-psk";
		} else if (caps & NM_WIFI_DEVICE_CAP_WPA) {
			nm_setting_wireless_security_add_proto (s_wsec, "wpa");
			nm_setting_wireless_security_add_pairwise (s_wsec, "tkip");
			nm_setting_wireless_security_add_group (s_wsec, "tkip");
			key_mgmt = "wpa-psk";
		} else
			key_mgmt = "none";
	} else
		key_mgmt = "none";

	if (g_strcmp0 (key_mgmt, "wpa-psk") == 0) {
		/* use WPA */
		if (password) {
			if (!nm_utils_wpa_psk_valid (password)) {
				g_set_error (error, NMCLI_ERROR, 0, _("'%s' is not valid WPA PSK"), password);
				return FALSE;
			}
			key = password;
		} else {
			generate_wpa_key (generated_key, sizeof (generated_key));
			key = generated_key;
		}
		g_object_set (s_wsec,
		              NM_SETTING_WIRELESS_SECURITY_KEY_MGMT, key_mgmt,
		              NM_SETTING_WIRELESS_SECURITY_PSK, key,
		              NULL);
	} else {
		/* use WEP */
		if (password) {
			if (!nm_utils_wep_key_valid (password, NM_WEP_KEY_TYPE_KEY)) {
				g_set_error (error, NMCLI_ERROR, 0,
				             _("'%s' is not valid WEP key (it should be 5 or 13 ASCII chars)"),
				             password);
				return FALSE;
			}
			key = password;
		} else {
			generate_wep_key (generated_key, sizeof (generated_key));
			key = generated_key;
		}
		g_object_set (s_wsec,
		              NM_SETTING_WIRELESS_SECURITY_KEY_MGMT, key_mgmt,
		              NM_SETTING_WIRELESS_SECURITY_WEP_KEY0, key,
		              NM_SETTING_WIRELESS_SECURITY_WEP_KEY_TYPE, NM_WEP_KEY_TYPE_KEY,
		              NULL);
	}
	if (show_password)
		g_print (_("Hotspot password: %s\n"), key);

	return TRUE;
}

static NMCResultCode
do_device_wifi_hotspot (NmCli *nmc, int argc, char **argv)
{
	AddAndActivateInfo *info;
	const char *ifname = NULL;
	const char *con_name = NULL;
	char *default_name = NULL;
	const char *ssid = NULL;
	const char *wifi_mode;
	const char *band = NULL;
	const char *channel = NULL;
	unsigned long channel_int;
	const char *password = NULL;
	gboolean show_password = FALSE;
	NMDevice *device = NULL;
	gs_free NMDevice **devices = NULL;
	NMDeviceWifiCapabilities caps;
	NMConnection *connection = NULL;
	NMSettingConnection *s_con;
	NMSettingWireless *s_wifi;
	NMSettingWirelessSecurity *s_wsec;
	NMSettingIPConfig *s_ip4, *s_ip6;
	GBytes *ssid_bytes;
	GError *error = NULL;

	/* Not (yet?) supported */
	if (nmc->complete)
		return nmc->return_value;

	/* Set default timeout waiting for operation completion. */
	if (nmc->timeout == -1)
		nmc->timeout = 60;

	while (argc > 0) {
		if (strcmp (*argv, "ifname") == 0) {
			if (next_arg (&argc, &argv) != 0) {
				g_string_printf (nmc->return_text, _("Error: %s argument is missing."), *(argv-1));
				nmc->return_value = NMC_RESULT_ERROR_USER_INPUT;
				goto error;
			}
			ifname = *argv;
		} else if (strcmp (*argv, "con-name") == 0) {
			if (next_arg (&argc, &argv) != 0) {
				g_string_printf (nmc->return_text, _("Error: %s argument is missing."), *(argv-1));
				nmc->return_value = NMC_RESULT_ERROR_USER_INPUT;
				goto error;
			}
			con_name = *argv;
		} else if (strcmp (*argv, "ssid") == 0) {
			if (next_arg (&argc, &argv) != 0) {
				g_string_printf (nmc->return_text, _("Error: %s argument is missing."), *(argv-1));
				nmc->return_value = NMC_RESULT_ERROR_USER_INPUT;
				goto error;
			}
			ssid = *argv;
			if (strlen (ssid) > 32) {
				g_string_printf (nmc->return_text, _("Error: ssid is too long."));
				nmc->return_value = NMC_RESULT_ERROR_USER_INPUT;
				goto error;
			}
		} else if (strcmp (*argv, "band") == 0) {
			if (next_arg (&argc, &argv) != 0) {
				g_string_printf (nmc->return_text, _("Error: %s argument is missing."), *(argv-1));
				nmc->return_value = NMC_RESULT_ERROR_USER_INPUT;
				goto error;
			}
			band = *argv;
			if (strcmp (band, "a") && strcmp (band, "bg")) {
				g_string_printf (nmc->return_text, _("Error: band argument value '%s' is invalid; use 'a' or 'bg'."),
				                 band);
				nmc->return_value = NMC_RESULT_ERROR_USER_INPUT;
				goto error;
			}
		} else if (strcmp (*argv, "channel") == 0) {
			if (next_arg (&argc, &argv) != 0) {
				g_string_printf (nmc->return_text, _("Error: %s argument is missing."), *(argv-1));
				nmc->return_value = NMC_RESULT_ERROR_USER_INPUT;
				goto error;
			}
			channel = *argv;
		} else if (strcmp (*argv, "password") == 0) {
			if (next_arg (&argc, &argv) != 0) {
				g_string_printf (nmc->return_text, _("Error: %s argument is missing."), *(argv-1));
				nmc->return_value = NMC_RESULT_ERROR_USER_INPUT;
				goto error;
			}
			password = *argv;
		/* --show-password is deprecated in favour of global --show-secrets option */
		/* Keep it here for backwards compatibility */
		} else if (nmc_arg_is_option (*argv, "show-password")) {
			show_password = TRUE;
		} else {
			g_string_printf (nmc->return_text, _("Error: Unknown parameter %s."), *argv);
			nmc->return_value = NMC_RESULT_ERROR_USER_INPUT;
			goto error;
		}

		argc--;
		argv++;
	}
	show_password = nmc->show_secrets || show_password;

	/* Verify band and channel parameters */
	if (!channel) {
		if (g_strcmp0 (band, "bg") == 0)
			channel = "1";
		if (g_strcmp0 (band, "a") == 0)
			channel = "7";
	}
	if (channel) {
		if (!band) {
			g_string_printf (nmc->return_text, _("Error: channel requires band too."));
			nmc->return_value = NMC_RESULT_ERROR_USER_INPUT;
			goto error;
		}
		if (   !nmc_string_to_uint (channel, TRUE, 1, 5825, &channel_int)
		    || !nm_utils_wifi_is_channel_valid (channel_int, band)) {
			g_string_printf (nmc->return_text, _("Error: channel '%s' not valid for band '%s'."),
			                 channel, band);
			nmc->return_value = NMC_RESULT_ERROR_USER_INPUT;
			goto error;
		}
	}

	/* Find Wi-Fi device. When no ifname is provided, the first Wi-Fi is used. */
	devices = nmc_get_devices_sorted (nmc->client);
	device = find_wifi_device_by_iface (devices, ifname, NULL);

	if (!device) {
		if (ifname)
			g_string_printf (nmc->return_text, _("Error: Device '%s' is not a Wi-Fi device."), ifname);
		else
			g_string_printf (nmc->return_text, _("Error: No Wi-Fi device found."));
		nmc->return_value = NMC_RESULT_ERROR_UNKNOWN;
		goto error;
	}

	/* Check device supported mode */
	caps = nm_device_wifi_get_capabilities (NM_DEVICE_WIFI (device));
	if (caps & NM_WIFI_DEVICE_CAP_AP)
		wifi_mode = NM_SETTING_WIRELESS_MODE_AP;
	else if (caps & NM_WIFI_DEVICE_CAP_ADHOC)
		wifi_mode = NM_SETTING_WIRELESS_MODE_ADHOC;
	else {
		g_string_printf (nmc->return_text, _("Error: Device '%s' supports neither AP nor Ad-Hoc mode."),
		                 nm_device_get_iface (device));
		nmc->return_value = NMC_RESULT_ERROR_UNKNOWN;
		goto error;
	}

	/* Create a connection with appropriate parameters */
	connection = nm_simple_connection_new ();
	s_con =  (NMSettingConnection *) nm_setting_connection_new ();
	nm_connection_add_setting (connection, NM_SETTING (s_con));
	if (!con_name)
		con_name = default_name = nmc_unique_connection_name (nm_client_get_connections (nmc->client), "Hotspot");
	g_object_set (s_con,
                      NM_SETTING_CONNECTION_ID, con_name,
	              NM_SETTING_CONNECTION_AUTOCONNECT, FALSE,
	              NULL);
	g_free (default_name);

	s_wifi = (NMSettingWireless *) nm_setting_wireless_new ();
	nm_connection_add_setting (connection, NM_SETTING (s_wifi));
	ssid_bytes = generate_ssid_for_hotspot (ssid);
	g_object_set (s_wifi, NM_SETTING_WIRELESS_MODE, wifi_mode,
	                      NM_SETTING_WIRELESS_SSID, ssid_bytes,
	                      NULL);
	g_bytes_unref (ssid_bytes);
	if (channel)
		g_object_set (s_wifi,
		              NM_SETTING_WIRELESS_CHANNEL, (guint32) channel_int,
		              NM_SETTING_WIRELESS_BAND, band,
		              NULL);

	s_wsec = (NMSettingWirelessSecurity *) nm_setting_wireless_security_new ();
	nm_connection_add_setting (connection, NM_SETTING (s_wsec));
	if (!set_wireless_security_for_hotspot (s_wsec, wifi_mode, caps, password, show_password, &error)) {
		g_object_unref (connection);
		g_string_printf (nmc->return_text, _("Error: Invalid 'password': %s."), error->message);
		nmc->return_value = NMC_RESULT_ERROR_UNKNOWN;
		g_clear_error (&error);
		goto error;
	}

	s_ip4 = (NMSettingIPConfig *) nm_setting_ip4_config_new ();
	nm_connection_add_setting (connection, NM_SETTING (s_ip4));
	g_object_set (s_ip4, NM_SETTING_IP_CONFIG_METHOD, NM_SETTING_IP4_CONFIG_METHOD_SHARED, NULL);

	s_ip6 = (NMSettingIPConfig *) nm_setting_ip6_config_new ();
	nm_connection_add_setting (connection, NM_SETTING (s_ip6));
	g_object_set (s_ip6, NM_SETTING_IP_CONFIG_METHOD, NM_SETTING_IP6_CONFIG_METHOD_IGNORE, NULL);

	/* Activate the connection now */
	nmc->nowait_flag = (nmc->timeout == 0);
	nmc->should_wait++;

	info = g_malloc0 (sizeof (AddAndActivateInfo));
	info->nmc = nmc;
	info->device = device;
	info->hotspot = TRUE;

	nm_client_add_and_activate_connection_async (nmc->client,
	                                             connection,
	                                             device,
	                                             NULL,
	                                             NULL,
	                                             add_and_activate_cb,
	                                             info);

error:
	return nmc->return_value;
}

static void
request_rescan_cb (GObject *object, GAsyncResult *result, gpointer user_data)
{
	NmCli *nmc = (NmCli *) user_data;
	GError *error = NULL;

	nm_device_wifi_request_scan_finish (NM_DEVICE_WIFI (object), result, &error);
	if (error) {
		g_string_printf (nmc->return_text, _("Error: %s."), error->message);
		nmc->return_value = NMC_RESULT_ERROR_UNKNOWN;
		g_error_free (error);
	}
	quit ();
}

static NMCResultCode
do_device_wifi_rescan (NmCli *nmc, int argc, char **argv)
{
	NMDevice *device;
	const char *ifname = NULL;
	GPtrArray *ssids;
	gs_free NMDevice **devices = NULL;
	GVariantBuilder builder, array_builder;
	GVariant *options;
	const char *ssid;
	int i;

	/* Not (yet?) supported */
	if (nmc->complete)
		return nmc->return_value;

	ssids = g_ptr_array_new ();

	/* Get the parameters */
	while (argc > 0) {
		if (strcmp (*argv, "ifname") == 0) {
			if (ifname) {
				g_string_printf (nmc->return_text, _("Error: '%s' cannot repeat."), *(argv-1));
				nmc->return_value = NMC_RESULT_ERROR_USER_INPUT;
				goto error;
			}
			if (next_arg (&argc, &argv) != 0) {
				g_string_printf (nmc->return_text, _("Error: %s argument is missing."), *(argv-1));
				nmc->return_value = NMC_RESULT_ERROR_USER_INPUT;
				goto error;
			}
			ifname = *argv;
		} else if (strcmp (*argv, "ssid") == 0) {
			if (next_arg (&argc, &argv) != 0) {
				g_string_printf (nmc->return_text, _("Error: %s argument is missing."), *(argv-1));
				nmc->return_value = NMC_RESULT_ERROR_USER_INPUT;
				goto error;
			}
			g_ptr_array_add (ssids, *argv);
		} else
			g_printerr (_("Unknown parameter: %s\n"), *argv);

		argc--;
		argv++;
	}

	/* Find Wi-Fi device to scan on. When no ifname is provided, the first Wi-Fi is used. */
	devices = nmc_get_devices_sorted (nmc->client);
	device = find_wifi_device_by_iface (devices, ifname, NULL);

	if (!device) {
		if (ifname)
			g_string_printf (nmc->return_text, _("Error: Device '%s' is not a Wi-Fi device."), ifname);
		else
			g_string_printf (nmc->return_text, _("Error: No Wi-Fi device found."));
		nmc->return_value = NMC_RESULT_ERROR_UNKNOWN;
		goto error;
	}


	if (ssids->len) {
		g_variant_builder_init (&builder, G_VARIANT_TYPE_VARDICT);
		g_variant_builder_init (&array_builder, G_VARIANT_TYPE ("aay"));

		for (i = 0; i < ssids->len; i++) {
			ssid = g_ptr_array_index (ssids, i);
			g_variant_builder_add (&array_builder, "@ay",
			                       g_variant_new_fixed_array (G_VARIANT_TYPE_BYTE, ssid, strlen (ssid), 1));
		}

		g_variant_builder_add (&builder, "{sv}", "ssids", g_variant_builder_end (&array_builder));
		options = g_variant_builder_end (&builder);

		nm_device_wifi_request_scan_options_async (NM_DEVICE_WIFI (device), options,
		                                           NULL, request_rescan_cb, nmc);
	} else
		nm_device_wifi_request_scan_async (NM_DEVICE_WIFI (device),
		                                   NULL, request_rescan_cb, nmc);

	g_ptr_array_free (ssids, FALSE);
	return nmc->return_value;
error:
	nmc->should_wait++;
	g_ptr_array_free (ssids, FALSE);
	return nmc->return_value;
}

static NMCCommand device_wifi_cmds[] = {
	{"list",     do_device_wifi_list,            NULL },
	{"connect",  do_device_wifi_connect_network, NULL },
	{"hotspot",  do_device_wifi_hotspot,         NULL },
	{"rescan",   do_device_wifi_rescan,          NULL },
	{NULL,       do_device_wifi_list,            NULL }
};

static NMCResultCode
do_device_wifi (NmCli *nmc, int argc, char **argv)
{
	GError *error = NULL;

	if (!nmc_terse_option_check (nmc->print_output, nmc->required_fields, &error)) {
		g_string_printf (nmc->return_text, _("Error: %s."), error->message);
		g_error_free (error);
		return NMC_RESULT_ERROR_USER_INPUT;
	}

	return nmc_do_cmd (nmc, device_wifi_cmds, *argv, argc, argv);
}

static int
show_device_lldp_list (NMDevice *device, NmCli *nmc, char *fields_str, int *counter)
{
	NmcOutputField *tmpl, *arr;
	GPtrArray *neighbors;
	size_t tmpl_len;
	const char *str;
	int i;

	neighbors = nm_device_get_lldp_neighbors (device);

	if (!neighbors || !neighbors->len)
		return 0;

	tmpl = nmc_fields_dev_lldp_list;
	tmpl_len = sizeof (nmc_fields_dev_lldp_list);

	/* Main header name */
	nmc->print_fields.header_name = (char *) construct_header_name (_("Device LLDP neighbors"),
	                                                                nm_device_get_iface (device));
	nmc->print_fields.indices = parse_output_fields (fields_str, nmc_fields_dev_lldp_list, FALSE, NULL, NULL);
	arr = nmc_dup_fields_array (tmpl, tmpl_len, NMC_OF_FLAG_MAIN_HEADER_ADD | NMC_OF_FLAG_FIELD_NAMES);
	g_ptr_array_add (nmc->output_data, arr);

	for (i = 0; i < neighbors->len; i++) {
		NMLldpNeighbor *neighbor = neighbors->pdata[i];
		guint value;

		arr = nmc_dup_fields_array (tmpl, tmpl_len, NMC_OF_FLAG_SECTION_PREFIX);
		set_val_str (arr, 0, g_strdup_printf ("NEIGHBOR[%d]", (*counter)++));

		set_val_strc (arr, 1, nm_device_get_iface (device));

		if (nm_lldp_neighbor_get_attr_string_value (neighbor, NM_LLDP_ATTR_CHASSIS_ID, &str))
			set_val_strc (arr, 2, str);

		if (nm_lldp_neighbor_get_attr_string_value (neighbor, NM_LLDP_ATTR_PORT_ID, &str))
			set_val_strc (arr, 3, str);

		if (nm_lldp_neighbor_get_attr_string_value (neighbor, NM_LLDP_ATTR_PORT_DESCRIPTION, &str))
			set_val_strc (arr, 4, str);

		if (nm_lldp_neighbor_get_attr_string_value (neighbor, NM_LLDP_ATTR_SYSTEM_NAME, &str))
			set_val_strc (arr, 5, str);

		if (nm_lldp_neighbor_get_attr_string_value (neighbor, NM_LLDP_ATTR_SYSTEM_DESCRIPTION, &str))
			set_val_strc (arr, 6, str);

		if (nm_lldp_neighbor_get_attr_uint_value (neighbor, NM_LLDP_ATTR_SYSTEM_CAPABILITIES, &value))
			set_val_str (arr, 7, g_strdup_printf ("%u (%s)", value, nmc_parse_lldp_capabilities (value)));

		if (nm_lldp_neighbor_get_attr_uint_value (neighbor, NM_LLDP_ATTR_IEEE_802_1_PVID, &value))
			set_val_str (arr, 8, g_strdup_printf ("%u", value));

		if (nm_lldp_neighbor_get_attr_uint_value (neighbor, NM_LLDP_ATTR_IEEE_802_1_PPVID, &value))
			set_val_str (arr, 9, g_strdup_printf ("%u", value));

		if (nm_lldp_neighbor_get_attr_uint_value (neighbor, NM_LLDP_ATTR_IEEE_802_1_PPVID_FLAGS, &value))
			set_val_str (arr, 10, g_strdup_printf ("%u", value));

		if (nm_lldp_neighbor_get_attr_uint_value (neighbor, NM_LLDP_ATTR_IEEE_802_1_VID, &value))
			set_val_str (arr, 11, g_strdup_printf ("%u", value));

		if (nm_lldp_neighbor_get_attr_string_value (neighbor, NM_LLDP_ATTR_IEEE_802_1_VLAN_NAME, &str))
			set_val_strc (arr, 12, str);

		if (nm_lldp_neighbor_get_attr_string_value (neighbor, NM_LLDP_ATTR_DESTINATION, &str))
			set_val_strc (arr, 13, str);

		if (nm_lldp_neighbor_get_attr_uint_value (neighbor, NM_LLDP_ATTR_CHASSIS_ID_TYPE, &value))
			set_val_strc (arr, 14, g_strdup_printf ("%u", value));

		if (nm_lldp_neighbor_get_attr_uint_value (neighbor, NM_LLDP_ATTR_PORT_ID_TYPE, &value))
			set_val_strc (arr, 15, g_strdup_printf ("%u", value));

		g_ptr_array_add (nmc->output_data, arr);
	}

	print_data (nmc);
	nmc_empty_output_fields (nmc);

	return neighbors->len;
}

static NMCResultCode
do_device_lldp_list (NmCli *nmc, int argc, char **argv)
{
	NMDevice *device = NULL;
	gs_free_error GError *error = NULL;
	char *fields_str;
	int counter = 0;

	while (argc > 0) {
		if (argc == 1 && nmc->complete)
			nmc_complete_strings (*argv, "ifname", NULL);

		if (strcmp (*argv, "ifname") == 0) {
			if (next_arg (&argc, &argv) != 0) {
				g_string_printf (nmc->return_text, _("Error: %s argument is missing."), *(argv-1));
				return NMC_RESULT_ERROR_USER_INPUT;
			}

			device = get_device (nmc, &argc, &argv, &error);
			if (!device) {
				g_string_printf (nmc->return_text, _("Error: %s."), error->message);
				return error->code;
			}
		} else {
			g_string_printf (nmc->return_text, _("Error: invalid extra argument '%s'."), *argv);
			return NMC_RESULT_ERROR_USER_INPUT;
		}

		argc--;
		argv++;
	}

	if (!nmc->required_fields || strcasecmp (nmc->required_fields, "common") == 0)
		fields_str = NMC_FIELDS_DEV_LLDP_LIST_COMMON;
	else if (!nmc->required_fields || strcasecmp (nmc->required_fields, "all") == 0)
		fields_str = NMC_FIELDS_DEV_LLDP_LIST_ALL;
	else
		fields_str = nmc->required_fields;

	nmc->print_fields.indices = parse_output_fields (fields_str, nmc_fields_dev_lldp_list, FALSE, NULL, &error);

	if (error) {
		g_string_printf (nmc->return_text, _("Error: 'device lldp list': %s"), error->message);
		return NMC_RESULT_ERROR_USER_INPUT;
	}

	if (nmc->complete)
		return nmc->return_value;

	if (device) {
		nmc_empty_output_fields (nmc);
		show_device_lldp_list (device, nmc, fields_str, &counter);
	} else {
		NMDevice **devices = nmc_get_devices_sorted (nmc->client);
		int i;

		for (i = 0; devices[i]; i++) {
			nmc_empty_output_fields (nmc);
			show_device_lldp_list (devices[i], nmc, fields_str, &counter);
		}

		g_free (devices);
	}

	return nmc->return_value;
}

static NMCCommand device_lldp_cmds[] = {
	{"list",  do_device_lldp_list,  NULL },
	{NULL,    do_device_lldp_list,  NULL }
};

static NMCResultCode
do_device_lldp (NmCli *nmc, int argc, char **argv)
{
	GError *error = NULL;

	if (!nmc_terse_option_check (nmc->print_output, nmc->required_fields, &error)) {
		g_string_printf (nmc->return_text, _("Error: %s."), error->message);
		g_error_free (error);
		return NMC_RESULT_ERROR_USER_INPUT;
	}

	if (!nmc->mode_specified)
		nmc->multiline_output = TRUE;  /* multiline mode is default for 'device lldp' */

	return nmc_do_cmd (nmc, device_lldp_cmds, *argv, argc, argv);
}

static gboolean
is_single_word (const char* line)
{
	size_t n1, n2, n3;

	n1 = strspn  (line,    " \t");
	n2 = strcspn (line+n1, " \t\0") + n1;
	n3 = strspn  (line+n2, " \t");

	if (n3 == 0)
		return TRUE;
	else
		return FALSE;
}

static char *
gen_func_ifnames (const char *text, int state)
{
	int i;
	const GPtrArray *devices;
	const char **ifnames;
	char *ret;

	nm_cli.get_client (&nm_cli);
	devices = nm_client_get_devices (nm_cli.client);
	if (devices->len == 0)
		return NULL;

	ifnames = g_new (const char *, devices->len + 1);
	for (i = 0; i < devices->len; i++) {
		NMDevice *dev = g_ptr_array_index (devices, i);
		const char *ifname = nm_device_get_iface (dev);
		ifnames[i] = ifname;
	}
	ifnames[i] = NULL;

	ret = nmc_rl_gen_func_basic (text, state, ifnames);

	g_free (ifnames);
	return ret;
}

static char **
nmcli_device_tab_completion (const char *text, int start, int end)
{
	char **match_array = NULL;
	rl_compentry_func_t *generator_func = NULL;

	/* Disable readline's default filename completion */
	rl_attempted_completion_over = 1;

	if (g_strcmp0 (rl_prompt, PROMPT_INTERFACE) == 0) {
		/* Disable appending space after completion */
		rl_completion_append_character = '\0';

		if (!is_single_word (rl_line_buffer))
			return NULL;

		generator_func = gen_func_ifnames;
	} else if (g_strcmp0 (rl_prompt, PROMPT_INTERFACES) == 0) {
		generator_func = gen_func_ifnames;
	}

	if (generator_func)
		match_array = rl_completion_matches (text, generator_func);

	return match_array;
}

static const NMCCommand device_cmds[] = {
	{"status",      do_devices_status,      usage_device_status },
	{"show",        do_device_show,         usage_device_show },
	{"connect",     do_device_connect,      usage_device_connect },
	{"reapply",     do_device_reapply,      usage_device_reapply },
	{"disconnect",  do_devices_disconnect,  usage_device_disconnect },
	{"delete",      do_devices_delete,      usage_device_delete },
	{"set",         do_device_set,          usage_device_set },
	{"monitor",     do_devices_monitor,     usage_device_monitor },
	{"wifi",        do_device_wifi,         usage_device_wifi },
	{"lldp",        do_device_lldp,         usage_device_lldp },
	{"modify",      do_device_modify,       usage_device_modify },
	{NULL,          do_devices_status,      usage },
};

NMCResultCode
do_devices (NmCli *nmc, int argc, char **argv)
{
	/* Register polkit agent */
	nmc_start_polkit_agent_start_try (nmc);

	rl_attempted_completion_function = (rl_completion_func_t *) nmcli_device_tab_completion;

	/* Get NMClient object early */
	nmc->get_client (nmc);

	/* Check whether NetworkManager is running */
	if (!nm_client_get_nm_running (nmc->client)) {
		g_string_printf (nmc->return_text, _("Error: NetworkManager is not running."));
		return NMC_RESULT_ERROR_NM_NOT_RUNNING;
	}

	return nmc_do_cmd (nmc, device_cmds, *argv, argc, argv);
}

void
monitor_devices (NmCli *nmc)
{
	do_devices_monitor (nmc, 0, NULL);
}