summaryrefslogtreecommitdiff
path: root/src/nm-manager.c
blob: 9a97c43f131aa84667537ac49a48fe55f31b3dd9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
/* SPDX-License-Identifier: GPL-2.0+ */
/*
 * Copyright (C) 2007 - 2009 Novell, Inc.
 * Copyright (C) 2007 - 2017 Red Hat, Inc.
 */

#include "nm-default.h"

#include "nm-manager.h"

#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/sendfile.h>
#include <limits.h>

#include "nm-glib-aux/nm-c-list.h"

#include "nm-libnm-core-intern/nm-common-macros.h"
#include "nm-dbus-manager.h"
#include "vpn/nm-vpn-manager.h"
#include "devices/nm-device.h"
#include "devices/nm-device-generic.h"
#include "platform/nm-platform.h"
#include "platform/nmp-object.h"
#include "nm-hostname-manager.h"
#include "nm-keep-alive.h"
#include "nm-rfkill-manager.h"
#include "dhcp/nm-dhcp-manager.h"
#include "settings/nm-settings.h"
#include "settings/nm-settings-connection.h"
#include "nm-auth-utils.h"
#include "nm-auth-manager.h"
#include "NetworkManagerUtils.h"
#include "devices/nm-device-factory.h"
#include "nm-sleep-monitor.h"
#include "nm-connectivity.h"
#include "nm-policy.h"
#include "nm-session-monitor.h"
#include "nm-act-request.h"
#include "nm-core-internal.h"
#include "nm-config.h"
#include "nm-audit-manager.h"
#include "nm-std-aux/nm-dbus-compat.h"
#include "nm-checkpoint.h"
#include "nm-checkpoint-manager.h"
#include "nm-dbus-object.h"
#include "nm-dispatcher.h"
#include "NetworkManagerUtils.h"

#define DEVICE_STATE_PRUNE_RATELIMIT_MAX 100u

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

typedef struct {
    gboolean                     user_enabled;
    gboolean                     sw_enabled;
    gboolean                     hw_enabled;
    RfKillType                   rtype;
    NMConfigRunStatePropertyType key;
    const char *                 desc;
    const char *                 prop;
    const char *                 hw_prop;
} RadioState;

typedef enum {
    ASYNC_OP_TYPE_AC_AUTH_ACTIVATE_INTERNAL,
    ASYNC_OP_TYPE_AC_AUTH_ACTIVATE_USER,
    ASYNC_OP_TYPE_AC_AUTH_ADD_AND_ACTIVATE,
    ASYNC_OP_TYPE_AC_AUTH_ADD_AND_ACTIVATE2,
} AsyncOpType;

typedef struct {
    CList       async_op_lst;
    NMManager * self;
    AsyncOpType async_op_type;
    union {
        struct {
            NMActiveConnection *active;
            union {
                struct {
                    GDBusMethodInvocation *invocation;
                } activate_user;
                struct {
                    GDBusMethodInvocation *         invocation;
                    NMConnection *                  connection;
                    NMSettingsConnectionPersistMode persist_mode;
                    bool                            is_volatile : 1;
                } add_and_activate;
            };
        } ac_auth;
    };
} AsyncOpData;

enum {
    DEVICE_ADDED,
    INTERNAL_DEVICE_ADDED,
    DEVICE_REMOVED,
    INTERNAL_DEVICE_REMOVED,
    ACTIVE_CONNECTION_ADDED,
    ACTIVE_CONNECTION_REMOVED,
    CONFIGURE_QUIT,

    LAST_SIGNAL
};

static guint signals[LAST_SIGNAL] = {0};

NM_GOBJECT_PROPERTIES_DEFINE(NMManager,
                             PROP_VERSION,
                             PROP_CAPABILITIES,
                             PROP_STATE,
                             PROP_STARTUP,
                             PROP_NETWORKING_ENABLED,
                             PROP_WIRELESS_ENABLED,
                             PROP_WIRELESS_HARDWARE_ENABLED,
                             PROP_WWAN_ENABLED,
                             PROP_WWAN_HARDWARE_ENABLED,
                             PROP_WIMAX_ENABLED,
                             PROP_WIMAX_HARDWARE_ENABLED,
                             PROP_ACTIVE_CONNECTIONS,
                             PROP_CONNECTIVITY,
                             PROP_CONNECTIVITY_CHECK_AVAILABLE,
                             PROP_CONNECTIVITY_CHECK_ENABLED,
                             PROP_CONNECTIVITY_CHECK_URI,
                             PROP_PRIMARY_CONNECTION,
                             PROP_PRIMARY_CONNECTION_TYPE,
                             PROP_ACTIVATING_CONNECTION,
                             PROP_DEVICES,
                             PROP_METERED,
                             PROP_GLOBAL_DNS_CONFIGURATION,
                             PROP_ALL_DEVICES,
                             PROP_CHECKPOINTS,

                             /* Not exported */
                             PROP_SLEEPING, );

typedef struct {
    NMPlatform *platform;

    GArray *capabilities;

    CList               active_connections_lst_head;
    CList               async_op_lst_head;
    guint               ac_cleanup_id;
    NMActiveConnection *primary_connection;
    NMActiveConnection *activating_connection;
    NMMetered           metered;

    CList devices_lst_head;

    NMState            state;
    NMConfig *         config;
    NMConnectivity *   concheck_mgr;
    NMPolicy *         policy;
    NMHostnameManager *hostname_manager;

    struct {
        GDBusConnection *connection;
        guint            id;
    } prop_filter;
    NMRfkillManager *rfkill_mgr;

    CList link_cb_lst;

    NMCheckpointManager *checkpoint_mgr;

    NMSettings *settings;

    RadioState    radio_states[RFKILL_TYPE_MAX];
    NMVpnManager *vpn_manager;

    NMSleepMonitor *sleep_monitor;

    NMAuthManager *auth_mgr;

    GHashTable *device_route_metrics;

    CList auth_lst_head;

    GHashTable *sleep_devices;

    /* Firmware dir monitor */
    GFileMonitor *fw_monitor;
    guint         fw_changed_id;

    guint timestamp_update_id;

    guint devices_inited_id;

    NMConnectivityState connectivity_state;

    guint8 device_state_prune_ratelimit_count;

    bool startup : 1;
    bool devices_inited : 1;

    bool sleeping : 1;
    bool net_enabled : 1;

    unsigned connectivity_check_enabled_last : 2;

    guint delete_volatile_connection_idle_id;
    CList delete_volatile_connection_lst_head;
} NMManagerPrivate;

struct _NMManager {
    NMDBusObject     parent;
    NMManagerPrivate _priv;
};

typedef struct {
    NMDBusObjectClass parent;
} NMManagerClass;

G_DEFINE_TYPE(NMManager, nm_manager, NM_TYPE_DBUS_OBJECT)

#define NM_MANAGER_GET_PRIVATE(self) _NM_GET_PRIVATE(self, NMManager, NM_IS_MANAGER)

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

NM_DEFINE_SINGLETON_INSTANCE(NMManager);

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

#define _NMLOG_PREFIX_NAME "manager"
#define _NMLOG(level, domain, ...)                                                                 \
    G_STMT_START                                                                                   \
    {                                                                                              \
        const NMLogLevel  _level  = (level);                                                       \
        const NMLogDomain _domain = (domain);                                                      \
                                                                                                   \
        if (nm_logging_enabled(_level, _domain)) {                                                 \
            const NMManager *const _self = (self);                                                 \
            char                   _sbuf[32];                                                      \
                                                                                                   \
            _nm_log(_level,                                                                        \
                    _domain,                                                                       \
                    0,                                                                             \
                    NULL,                                                                          \
                    NULL,                                                                          \
                    "%s%s: " _NM_UTILS_MACRO_FIRST(__VA_ARGS__),                                   \
                    _NMLOG_PREFIX_NAME,                                                            \
                    ((_self && _self != singleton_instance) ? nm_sprintf_buf(_sbuf, "[%p]", _self) \
                                                            : "")                                  \
                        _NM_UTILS_MACRO_REST(__VA_ARGS__));                                        \
        }                                                                                          \
    }                                                                                              \
    G_STMT_END

#define _NMLOG2(level, domain, device, ...)                                                        \
    G_STMT_START                                                                                   \
    {                                                                                              \
        const NMLogLevel  _level  = (level);                                                       \
        const NMLogDomain _domain = (domain);                                                      \
                                                                                                   \
        if (nm_logging_enabled(_level, _domain)) {                                                 \
            const NMManager *const _self   = (self);                                               \
            const char *const      _ifname = _nm_device_get_iface(device);                         \
            char                   _sbuf[32];                                                      \
                                                                                                   \
            _nm_log(_level,                                                                        \
                    _domain,                                                                       \
                    0,                                                                             \
                    _ifname,                                                                       \
                    NULL,                                                                          \
                    "%s%s: %s%s%s" _NM_UTILS_MACRO_FIRST(__VA_ARGS__),                             \
                    _NMLOG_PREFIX_NAME,                                                            \
                    ((_self && _self != singleton_instance) ? nm_sprintf_buf(_sbuf, "[%p]", _self) \
                                                            : ""),                                 \
                    NM_PRINT_FMT_QUOTED(_ifname, "(", _ifname, "): ", "")                          \
                        _NM_UTILS_MACRO_REST(__VA_ARGS__));                                        \
        }                                                                                          \
    }                                                                                              \
    G_STMT_END

#define _NMLOG3(level, domain, connection, ...)                                                    \
    G_STMT_START                                                                                   \
    {                                                                                              \
        const NMLogLevel  _level  = (level);                                                       \
        const NMLogDomain _domain = (domain);                                                      \
                                                                                                   \
        if (nm_logging_enabled(_level, _domain)) {                                                 \
            const NMManager *const _self       = (self);                                           \
            NMConnection *const    _connection = (connection);                                     \
            const char *const      _con_id     = _nm_connection_get_id(_connection);               \
            char                   _sbuf[32];                                                      \
                                                                                                   \
            _nm_log(_level,                                                                        \
                    _domain,                                                                       \
                    0,                                                                             \
                    NULL,                                                                          \
                    _nm_connection_get_uuid(_connection),                                          \
                    "%s%s: %s%s%s" _NM_UTILS_MACRO_FIRST(__VA_ARGS__),                             \
                    _NMLOG_PREFIX_NAME,                                                            \
                    ((_self && _self != singleton_instance) ? nm_sprintf_buf(_sbuf, "[%p]", _self) \
                                                            : ""),                                 \
                    NM_PRINT_FMT_QUOTED(_con_id, "(", _con_id, ") ", "")                           \
                        _NM_UTILS_MACRO_REST(__VA_ARGS__));                                        \
        }                                                                                          \
    }                                                                                              \
    G_STMT_END

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

static const NMDBusInterfaceInfoExtended interface_info_manager;
static const GDBusSignalInfo             signal_info_check_permissions;
static const GDBusSignalInfo             signal_info_state_changed;
static const GDBusSignalInfo             signal_info_device_added;
static const GDBusSignalInfo             signal_info_device_removed;

static void update_connectivity_value(NMManager *self);

static gboolean add_device(NMManager *self, NMDevice *device, GError **error);

static void _emit_device_added_removed(NMManager *self, NMDevice *device, gboolean is_added);

static NMActiveConnection *_new_active_connection(NMManager *            self,
                                                  gboolean               is_vpn,
                                                  NMSettingsConnection * sett_conn,
                                                  NMConnection *         incompl_conn,
                                                  NMConnection *         applied,
                                                  const char *           specific_object,
                                                  NMDevice *             device,
                                                  NMAuthSubject *        subject,
                                                  NMActivationType       activation_type,
                                                  NMActivationReason     activation_reason,
                                                  NMActivationStateFlags initial_state_flags,
                                                  GError **              error);

static void policy_activating_ac_changed(GObject *object, GParamSpec *pspec, gpointer user_data);

static gboolean find_master(NMManager *            self,
                            NMConnection *         connection,
                            NMDevice *             device,
                            NMSettingsConnection **out_master_connection,
                            NMDevice **            out_master_device,
                            NMActiveConnection **  out_master_ac,
                            GError **              error);

static void nm_manager_update_state(NMManager *manager);

static void connection_changed(NMManager *self, NMSettingsConnection *sett_conn);
static void device_sleep_cb(NMDevice *device, GParamSpec *pspec, NMManager *self);

static void
settings_startup_complete_changed(NMSettings *settings, GParamSpec *pspec, NMManager *self);

static void retry_connections_for_parent_device(NMManager *self, NMDevice *device);

static void
active_connection_state_changed(NMActiveConnection *active, GParamSpec *pspec, NMManager *self);
static void
active_connection_default_changed(NMActiveConnection *active, GParamSpec *pspec, NMManager *self);
static void active_connection_parent_active(NMActiveConnection *active,
                                            NMActiveConnection *parent_ac,
                                            NMManager *         self);

static NMActiveConnection *active_connection_find(NMManager *             self,
                                                  NMSettingsConnection *  sett_conn,
                                                  const char *            uuid,
                                                  NMActiveConnectionState max_state,
                                                  GPtrArray **            out_all_matching);

static NMConnectivity *concheck_get_mgr(NMManager *self);

static void _internal_activation_auth_done(NMManager *         self,
                                           NMActiveConnection *active,
                                           gboolean            success,
                                           const char *        error_desc);
static void _add_and_activate_auth_done(NMManager *                     self,
                                        AsyncOpType                     async_op_type,
                                        NMActiveConnection *            active,
                                        NMConnection *                  connection,
                                        GDBusMethodInvocation *         invocation,
                                        NMSettingsConnectionPersistMode persist_mode,
                                        gboolean                        is_volatile,
                                        gboolean                        success,
                                        const char *                    error_desc);
static void _activation_auth_done(NMManager *            self,
                                  NMActiveConnection *   active,
                                  GDBusMethodInvocation *invocation,
                                  gboolean               success,
                                  const char *           error_desc);

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

static NM_CACHED_QUARK_FCN("autoconnect-root", autoconnect_root_quark);

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

static gboolean
_connection_is_vpn(NMConnection *connection)
{
    const char *type;

    type = nm_connection_get_connection_type(connection);
    if (type)
        return nm_streq(type, NM_SETTING_VPN_SETTING_NAME);

    /* we have an incomplete (invalid) connection at hand. That can only
     * happen during AddAndActivate. Determine whether it's VPN type based
     * on the existence of a [vpn] section. */
    return !!nm_connection_get_setting_vpn(connection);
}

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

static gboolean
concheck_enabled(NMManager *self, gboolean *out_changed)
{
    NMManagerPrivate *priv = NM_MANAGER_GET_PRIVATE(self);
    guint             check_enabled;

    check_enabled = nm_connectivity_check_enabled(concheck_get_mgr(self)) ? 1 : 2;
    if (priv->connectivity_check_enabled_last == check_enabled)
        NM_SET_OUT(out_changed, FALSE);
    else {
        NM_SET_OUT(out_changed, TRUE);
        priv->connectivity_check_enabled_last = check_enabled;
    }
    return check_enabled == 1;
}

static void
concheck_config_changed_cb(NMConnectivity *connectivity, NMManager *self)
{
    NMManagerPrivate *priv = NM_MANAGER_GET_PRIVATE(self);
    NMDevice *        device;
    gboolean          changed;

    concheck_enabled(self, &changed);
    if (changed)
        _notify(self, PROP_CONNECTIVITY_CHECK_ENABLED);

    c_list_for_each_entry (device, &priv->devices_lst_head, devices_lst)
        nm_device_check_connectivity_update_interval(device);
}

static NMConnectivity *
concheck_get_mgr(NMManager *self)
{
    NMManagerPrivate *priv = NM_MANAGER_GET_PRIVATE(self);

    if (G_UNLIKELY(!priv->concheck_mgr)) {
        priv->concheck_mgr = g_object_ref(nm_connectivity_get());
        g_signal_connect(priv->concheck_mgr,
                         NM_CONNECTIVITY_CONFIG_CHANGED,
                         G_CALLBACK(concheck_config_changed_cb),
                         self);
    }
    return priv->concheck_mgr;
}

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

static AsyncOpData *
_async_op_data_new_authorize_activate_internal(NMManager *self, NMActiveConnection *active_take)
{
    AsyncOpData *async_op_data;

    async_op_data                 = g_slice_new0(AsyncOpData);
    async_op_data->async_op_type  = ASYNC_OP_TYPE_AC_AUTH_ACTIVATE_INTERNAL;
    async_op_data->self           = g_object_ref(self);
    async_op_data->ac_auth.active = active_take;
    c_list_link_tail(&NM_MANAGER_GET_PRIVATE(self)->async_op_lst_head,
                     &async_op_data->async_op_lst);
    return async_op_data;
}

static AsyncOpData *
_async_op_data_new_ac_auth_activate_user(NMManager *            self,
                                         NMActiveConnection *   active_take,
                                         GDBusMethodInvocation *invocation_take)
{
    AsyncOpData *async_op_data;

    async_op_data                                   = g_slice_new0(AsyncOpData);
    async_op_data->async_op_type                    = ASYNC_OP_TYPE_AC_AUTH_ACTIVATE_USER;
    async_op_data->self                             = g_object_ref(self);
    async_op_data->ac_auth.active                   = active_take;
    async_op_data->ac_auth.activate_user.invocation = invocation_take;
    c_list_link_tail(&NM_MANAGER_GET_PRIVATE(self)->async_op_lst_head,
                     &async_op_data->async_op_lst);
    return async_op_data;
}

static AsyncOpData *
_async_op_data_new_ac_auth_add_and_activate(NMManager *                     self,
                                            AsyncOpType                     async_op_type,
                                            NMActiveConnection *            active_take,
                                            GDBusMethodInvocation *         invocation_take,
                                            NMConnection *                  connection_take,
                                            NMSettingsConnectionPersistMode persist_mode,
                                            gboolean                        is_volatile)
{
    AsyncOpData *async_op_data;

    nm_assert(NM_IN_SET(async_op_type,
                        ASYNC_OP_TYPE_AC_AUTH_ADD_AND_ACTIVATE,
                        ASYNC_OP_TYPE_AC_AUTH_ADD_AND_ACTIVATE2));

    async_op_data                                        = g_slice_new0(AsyncOpData);
    async_op_data->async_op_type                         = async_op_type;
    async_op_data->self                                  = g_object_ref(self);
    async_op_data->ac_auth.active                        = active_take;
    async_op_data->ac_auth.add_and_activate.invocation   = invocation_take;
    async_op_data->ac_auth.add_and_activate.connection   = connection_take;
    async_op_data->ac_auth.add_and_activate.persist_mode = persist_mode;
    async_op_data->ac_auth.add_and_activate.is_volatile  = is_volatile;
    c_list_link_tail(&NM_MANAGER_GET_PRIVATE(self)->async_op_lst_head,
                     &async_op_data->async_op_lst);
    return async_op_data;
}

static void
_async_op_complete_ac_auth_cb(NMActiveConnection *active,
                              gboolean            success,
                              const char *        error_desc,
                              gpointer            user_data)
{
    AsyncOpData *async_op_data = user_data;

    nm_assert(async_op_data);
    nm_assert(NM_IS_MANAGER(async_op_data->self));
    nm_assert(
        nm_c_list_contains_entry(&NM_MANAGER_GET_PRIVATE(async_op_data->self)->async_op_lst_head,
                                 async_op_data,
                                 async_op_lst));
    nm_assert(NM_IS_ACTIVE_CONNECTION(active));
    nm_assert(active == async_op_data->ac_auth.active);

    c_list_unlink(&async_op_data->async_op_lst);

    switch (async_op_data->async_op_type) {
    case ASYNC_OP_TYPE_AC_AUTH_ACTIVATE_INTERNAL:
        _internal_activation_auth_done(async_op_data->self,
                                       async_op_data->ac_auth.active,
                                       success,
                                       error_desc);
        break;
    case ASYNC_OP_TYPE_AC_AUTH_ACTIVATE_USER:
        _activation_auth_done(async_op_data->self,
                              async_op_data->ac_auth.active,
                              async_op_data->ac_auth.activate_user.invocation,
                              success,
                              error_desc);
        break;
    case ASYNC_OP_TYPE_AC_AUTH_ADD_AND_ACTIVATE:
    case ASYNC_OP_TYPE_AC_AUTH_ADD_AND_ACTIVATE2:
        _add_and_activate_auth_done(async_op_data->self,
                                    async_op_data->async_op_type,
                                    async_op_data->ac_auth.active,
                                    async_op_data->ac_auth.add_and_activate.connection,
                                    async_op_data->ac_auth.add_and_activate.invocation,
                                    async_op_data->ac_auth.add_and_activate.persist_mode,
                                    async_op_data->ac_auth.add_and_activate.is_volatile,
                                    success,
                                    error_desc);
        g_object_unref(async_op_data->ac_auth.add_and_activate.connection);
        break;
    default:
        nm_assert_not_reached();
        break;
    }

    g_object_unref(async_op_data->ac_auth.active);
    g_object_unref(async_op_data->self);
    g_slice_free(AsyncOpData, async_op_data);
}

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

typedef struct {
    int     ifindex;
    guint32 aspired_metric;
    guint32 effective_metric;
} DeviceRouteMetricData;

static DeviceRouteMetricData *
_device_route_metric_data_new(int ifindex, guint32 aspired_metric, guint32 effective_metric)
{
    DeviceRouteMetricData *data;

    nm_assert(ifindex > 0);

    /* For IPv4, metrics can use the entire uint32 bit range. For IPv6,
     * zero is treated like 1024. Since we handle IPv4 and IPv6 identically,
     * we cannot allow a zero metric here.
     */
    nm_assert(aspired_metric > 0);
    nm_assert(effective_metric == 0 || aspired_metric <= effective_metric);

    data                   = g_slice_new0(DeviceRouteMetricData);
    data->ifindex          = ifindex;
    data->aspired_metric   = aspired_metric;
    data->effective_metric = effective_metric ?: aspired_metric;
    return data;
}

static guint
_device_route_metric_data_by_ifindex_hash(gconstpointer p)
{
    const DeviceRouteMetricData *data = p;
    NMHashState                  h;

    nm_hash_init(&h, 1030338191);
    nm_hash_update_vals(&h, data->ifindex);
    return nm_hash_complete(&h);
}

static gboolean
_device_route_metric_data_by_ifindex_equal(gconstpointer pa, gconstpointer pb)
{
    const DeviceRouteMetricData *a = pa;
    const DeviceRouteMetricData *b = pb;

    return a->ifindex == b->ifindex;
}

static guint32
_device_route_metric_get(NMManager *  self,
                         int          ifindex,
                         NMDeviceType device_type,
                         gboolean     lookup_only,
                         guint32 *    out_aspired_metric)
{
    NMManagerPrivate *           priv;
    const DeviceRouteMetricData *d2;
    DeviceRouteMetricData *      data;
    DeviceRouteMetricData        data_lookup;
    const NMDedupMultiHeadEntry *all_links_head;
    NMPObject                    links_needle;
    guint                        n_links;
    gboolean                     cleaned = FALSE;
    GHashTableIter               h_iter;
    guint32                      metric;

    g_return_val_if_fail(NM_IS_MANAGER(self), 0);

    NM_SET_OUT(out_aspired_metric, 0);

    if (ifindex <= 0) {
        if (lookup_only)
            return 0;
        metric = nm_device_get_route_metric_default(device_type);
        NM_SET_OUT(out_aspired_metric, metric);
        return metric;
    }

    priv = NM_MANAGER_GET_PRIVATE(self);

    if (lookup_only && !priv->device_route_metrics)
        return 0;

    if (G_UNLIKELY(!priv->device_route_metrics)) {
        const GHashTable *             h;
        const NMConfigDeviceStateData *device_state;

        priv->device_route_metrics =
            g_hash_table_new_full(_device_route_metric_data_by_ifindex_hash,
                                  _device_route_metric_data_by_ifindex_equal,
                                  NULL,
                                  nm_g_slice_free_fcn(DeviceRouteMetricData));
        cleaned = TRUE;

        /* we need to pre-populate the cache for all (still existing) devices from the state-file */
        h = nm_config_device_state_get_all(priv->config);
        if (!h)
            goto initited;

        g_hash_table_iter_init(&h_iter, (GHashTable *) h);
        while (g_hash_table_iter_next(&h_iter, NULL, (gpointer *) &device_state)) {
            if (!device_state->route_metric_default_effective)
                continue;
            if (!nm_platform_link_get(priv->platform, device_state->ifindex)) {
                /* we have the entry in the state file, but (currently) no such
                 * ifindex exists in platform. Most likely the entry is obsolete,
                 * hence we skip it. */
                continue;
            }
            if (!g_hash_table_add(
                    priv->device_route_metrics,
                    _device_route_metric_data_new(device_state->ifindex,
                                                  device_state->route_metric_default_aspired,
                                                  device_state->route_metric_default_effective)))
                nm_assert_not_reached();
        }
    }

initited:
    data_lookup.ifindex = ifindex;

    data = g_hash_table_lookup(priv->device_route_metrics, &data_lookup);
    if (data)
        goto out;
    if (lookup_only)
        return 0;

    if (!cleaned) {
        /* get the number of all links in the platform cache. */
        all_links_head = nm_platform_lookup_all(priv->platform,
                                                NMP_CACHE_ID_TYPE_OBJECT_TYPE,
                                                nmp_object_stackinit_id_link(&links_needle, 1));
        n_links        = all_links_head ? all_links_head->len : 0;

        /* on systems where a lot of devices are created and go away, the index contains
         * a lot of stale entries. We must from time to time clean them up.
         *
         * Do do this cleanup, whenever we have more entries then 2 times the number of links. */
        if (G_UNLIKELY(g_hash_table_size(priv->device_route_metrics) > NM_MAX(20, n_links * 2))) {
            /* from time to time, we need to do some house-keeping and prune stale entries.
             * Otherwise, on a system where interfaces frequently come and go (docker), we
             * keep growing this cache for ifindexes that no longer exist. */
            g_hash_table_iter_init(&h_iter, priv->device_route_metrics);
            while (g_hash_table_iter_next(&h_iter, NULL, (gpointer *) &d2)) {
                if (!nm_platform_link_get(priv->platform, d2->ifindex))
                    g_hash_table_iter_remove(&h_iter);
            }
            cleaned = TRUE;
        }
    }

    data =
        _device_route_metric_data_new(ifindex, nm_device_get_route_metric_default(device_type), 0);

    /* unfortunately, there is no stright forward way to lookup all reserved metrics.
     * Note, that we don't only have to know which metrics are currently reserved,
     * but also, which metrics are now seemingly un-used but caused another reserved
     * metric to be bumped. Hence, the naive O(n^2) search :(
     *
     * Well, technically, since we limit bumping the metric to 50, this entire
     * loop runs at most 50 times, so it's still O(n). Let's just say, it's not
     * very efficient. */
again:
    g_hash_table_iter_init(&h_iter, priv->device_route_metrics);
    while (g_hash_table_iter_next(&h_iter, NULL, (gpointer *) &d2)) {
        if (data->effective_metric < d2->aspired_metric
            || data->effective_metric > d2->effective_metric) {
            /* no overlap. Skip. */
            continue;
        }
        if (!cleaned && !nm_platform_link_get(priv->platform, d2->ifindex)) {
            /* the metric seems taken, but there is no such interface. This entry
             * is stale, forget about it. */
            g_hash_table_iter_remove(&h_iter);
            continue;
        }

        if (d2->effective_metric == G_MAXUINT32) {
            /* we cannot bump the metric any further. Done.
             *
             * Actually, this can currently not happen because the aspired_metric
             * are small numbers and we limit the bumping to 50. Still, for
             * completeness... */
            data->effective_metric = G_MAXUINT32;
            break;
        }

        if (d2->effective_metric - data->aspired_metric >= 50) {
            /* as one active interface reserves an entire range of metrics
             * (from aspired_metric to effective_metric), that means if you
             * alternatingly activate two interfaces, their metric will
             * bump each other.
             *
             * Limit this, bump the metric at most 50 points. */
            data->effective_metric = data->aspired_metric + 50;
            break;
        }

        /* bump the metric, and search again. */
        data->effective_metric = d2->effective_metric + 1;
        goto again;
    }

    _LOGT(LOGD_DEVICE,
          "default-route-metric: ifindex %d reserves metric %u (aspired %u)",
          data->ifindex,
          data->effective_metric,
          data->aspired_metric);

    if (!g_hash_table_add(priv->device_route_metrics, data))
        nm_assert_not_reached();

out:
    NM_SET_OUT(out_aspired_metric, data->aspired_metric);
    return data->effective_metric;
}

guint32
nm_manager_device_route_metric_reserve(NMManager *self, int ifindex, NMDeviceType device_type)
{
    guint32 metric;

    metric = _device_route_metric_get(self, ifindex, device_type, FALSE, NULL);
    nm_assert(metric != 0);
    return metric;
}

void
nm_manager_device_route_metric_clear(NMManager *self, int ifindex)
{
    NMManagerPrivate *    priv;
    DeviceRouteMetricData data_lookup;

    priv = NM_MANAGER_GET_PRIVATE(self);

    if (!priv->device_route_metrics)
        return;
    data_lookup.ifindex = ifindex;
    if (g_hash_table_remove(priv->device_route_metrics, &data_lookup)) {
        _LOGT(LOGD_DEVICE, "default-route-metric: ifindex %d released", ifindex);
    }
}

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

static void
_delete_volatile_connection_do(NMManager *self, NMSettingsConnection *connection)
{
    NMManagerPrivate *priv = NM_MANAGER_GET_PRIVATE(self);

    if (!NM_FLAGS_ANY(nm_settings_connection_get_flags(connection),
                      NM_SETTINGS_CONNECTION_INT_FLAGS_VOLATILE
                          | NM_SETTINGS_CONNECTION_INT_FLAGS_EXTERNAL))
        return;
    if (!nm_settings_has_connection(priv->settings, connection))
        return;
    if (active_connection_find(self,
                               connection,
                               NULL,
                               NM_ACTIVE_CONNECTION_STATE_DEACTIVATED,
                               NULL))
        return;

    _LOGD(LOGD_DEVICE,
          "volatile connection disconnected. Deleting connection '%s' (%s)",
          nm_settings_connection_get_id(connection),
          nm_settings_connection_get_uuid(connection));
    nm_settings_connection_delete(connection, FALSE);
}

/* Returns: whether to notify D-Bus of the removal or not */
static gboolean
active_connection_remove(NMManager *self, NMActiveConnection *active)
{
    NMManagerPrivate *priv                           = NM_MANAGER_GET_PRIVATE(self);
    gs_unref_object NMSettingsConnection *connection = NULL;
    gboolean                              notify;

    nm_assert(NM_IS_ACTIVE_CONNECTION(active));
    nm_assert(c_list_contains(&priv->active_connections_lst_head, &active->active_connections_lst));

    notify = nm_dbus_object_is_exported(NM_DBUS_OBJECT(active));

    c_list_unlink(&active->active_connections_lst);
    g_signal_emit(self, signals[ACTIVE_CONNECTION_REMOVED], 0, active);
    g_signal_handlers_disconnect_by_func(active, active_connection_state_changed, self);
    g_signal_handlers_disconnect_by_func(active, active_connection_default_changed, self);
    g_signal_handlers_disconnect_by_func(active, active_connection_parent_active, self);

    connection = nm_g_object_ref(nm_active_connection_get_settings_connection(active));

    nm_dbus_object_clear_and_unexport(&active);

    if (connection)
        _delete_volatile_connection_do(self, connection);

    return notify;
}

static gboolean
_active_connection_cleanup(gpointer user_data)
{
    NMManager *         self = NM_MANAGER(user_data);
    NMManagerPrivate *  priv = NM_MANAGER_GET_PRIVATE(self);
    NMActiveConnection *ac, *ac_safe;

    priv->ac_cleanup_id = 0;

    g_object_freeze_notify(G_OBJECT(self));
    c_list_for_each_entry_safe (ac,
                                ac_safe,
                                &priv->active_connections_lst_head,
                                active_connections_lst) {
        if (nm_active_connection_get_state(ac) == NM_ACTIVE_CONNECTION_STATE_DEACTIVATED) {
            if (active_connection_remove(self, ac))
                _notify(self, PROP_ACTIVE_CONNECTIONS);
        }
    }
    g_object_thaw_notify(G_OBJECT(self));

    return FALSE;
}

static void
active_connection_state_changed(NMActiveConnection *active, GParamSpec *pspec, NMManager *self)
{
    NMManagerPrivate *      priv = NM_MANAGER_GET_PRIVATE(self);
    NMActiveConnectionState state;
    NMSettingsConnection *  con;

    state = nm_active_connection_get_state(active);
    if (state == NM_ACTIVE_CONNECTION_STATE_DEACTIVATED) {
        /* Destroy active connections from an idle handler to ensure that
         * their last property change notifications go out, which wouldn't
         * happen if we destroyed them immediately when their state was set
         * to DEACTIVATED.
         */
        if (!priv->ac_cleanup_id)
            priv->ac_cleanup_id = g_idle_add(_active_connection_cleanup, self);

        con = nm_active_connection_get_settings_connection(active);
        if (con)
            g_object_set_qdata(G_OBJECT(con), autoconnect_root_quark(), NULL);
    }

    nm_manager_update_state(self);
}

static void
active_connection_default_changed(NMActiveConnection *active, GParamSpec *pspec, NMManager *self)
{
    nm_manager_update_state(self);
}

/**
 * active_connection_add():
 * @self: the #NMManager
 * @active: the #NMActiveConnection to manage
 *
 * Begins to track and manage @active.  Increases the refcount of @active.
 */
static void
active_connection_add(NMManager *self, NMActiveConnection *active)
{
    NMManagerPrivate *priv = NM_MANAGER_GET_PRIVATE(self);

    nm_assert(NM_IS_ACTIVE_CONNECTION(active));
    nm_assert(!c_list_is_linked(&active->active_connections_lst));

    c_list_link_front(&priv->active_connections_lst_head, &active->active_connections_lst);
    g_object_ref(active);

    g_signal_connect(active,
                     "notify::" NM_ACTIVE_CONNECTION_STATE,
                     G_CALLBACK(active_connection_state_changed),
                     self);
    g_signal_connect(active,
                     "notify::" NM_ACTIVE_CONNECTION_DEFAULT,
                     G_CALLBACK(active_connection_default_changed),
                     self);
    g_signal_connect(active,
                     "notify::" NM_ACTIVE_CONNECTION_DEFAULT6,
                     G_CALLBACK(active_connection_default_changed),
                     self);

    if (!nm_dbus_object_is_exported(NM_DBUS_OBJECT(active)))
        nm_dbus_object_export(NM_DBUS_OBJECT(active));

    g_signal_emit(self, signals[ACTIVE_CONNECTION_ADDED], 0, active);

    _notify(self, PROP_ACTIVE_CONNECTIONS);
}

const CList *
nm_manager_get_active_connections(NMManager *manager)
{
    return &NM_MANAGER_GET_PRIVATE(manager)->active_connections_lst_head;
}

static NMActiveConnection *
active_connection_find(
    NMManager *             self,
    NMSettingsConnection *  sett_conn,
    const char *            uuid,
    NMActiveConnectionState max_state /* candidates in state @max_state will be found */,
    GPtrArray **            out_all_matching)
{
    NMManagerPrivate *  priv = NM_MANAGER_GET_PRIVATE(self);
    NMActiveConnection *ac;
    NMActiveConnection *best_ac = NULL;
    GPtrArray *         all     = NULL;

    nm_assert(!sett_conn || NM_IS_SETTINGS_CONNECTION(sett_conn));
    nm_assert(!out_all_matching || !*out_all_matching);

    c_list_for_each_entry (ac, &priv->active_connections_lst_head, active_connections_lst) {
        NMSettingsConnection *ac_conn;

        ac_conn = nm_active_connection_get_settings_connection(ac);
        if (sett_conn && sett_conn != ac_conn)
            continue;
        if (uuid && !nm_streq0(uuid, nm_settings_connection_get_uuid(ac_conn)))
            continue;
        if (nm_active_connection_get_state(ac) > max_state)
            continue;

        if (!out_all_matching)
            return ac;

        if (!best_ac) {
            best_ac = ac;
            continue;
        }

        if (!all) {
            all = g_ptr_array_new_with_free_func(g_object_unref);
            g_ptr_array_add(all, g_object_ref(best_ac));
        }
        g_ptr_array_add(all, g_object_ref(ac));
    }

    if (!best_ac)
        return NULL;

    /* as an optimization, we only allocate out_all_matching, if there are more
     * than one result. If there is only one result, we only return the single
     * element and don't bother allocating an array. That's the common case.
     *
     * Also, in case we have multiple results, we return the *first* one
     * as @best_ac. */
    nm_assert(!all || (all->len >= 2 && all->pdata[0] == best_ac));

    *out_all_matching = all;
    return best_ac;
}

static NMActiveConnection *
active_connection_find_by_connection(NMManager *             self,
                                     NMSettingsConnection *  sett_conn,
                                     NMConnection *          connection,
                                     NMActiveConnectionState max_state,
                                     GPtrArray **            out_all_matching)
{
    nm_assert(NM_IS_MANAGER(self));
    nm_assert(!sett_conn || NM_IS_SETTINGS_CONNECTION(sett_conn));
    nm_assert(!connection || NM_IS_CONNECTION(connection));
    nm_assert(sett_conn || connection);
    nm_assert(!connection || !sett_conn
              || connection == nm_settings_connection_get_connection(sett_conn));

    /* Depending on whether connection is a settings connection,
     * either lookup by object-identity of @connection, or compare the UUID */
    return active_connection_find(self,
                                  sett_conn,
                                  sett_conn ? NULL : nm_connection_get_uuid(connection),
                                  max_state,
                                  out_all_matching);
}

typedef struct {
    NMManager *self;
    gboolean   for_auto_activation;
} GetActivatableConnectionsFilterData;

static gboolean
_get_activatable_connections_filter(NMSettings *          settings,
                                    NMSettingsConnection *sett_conn,
                                    gpointer              user_data)
{
    const GetActivatableConnectionsFilterData *d = user_data;
    NMConnectionMultiConnect                   multi_connect;

    if (NM_FLAGS_ANY(nm_settings_connection_get_flags(sett_conn),
                     NM_SETTINGS_CONNECTION_INT_FLAGS_VOLATILE
                         | NM_SETTINGS_CONNECTION_INT_FLAGS_EXTERNAL))
        return FALSE;

    multi_connect =
        _nm_connection_get_multi_connect(nm_settings_connection_get_connection(sett_conn));
    if (multi_connect == NM_CONNECTION_MULTI_CONNECT_MULTIPLE
        || (multi_connect == NM_CONNECTION_MULTI_CONNECT_MANUAL_MULTIPLE
            && !d->for_auto_activation))
        return TRUE;

    /* the connection is activatable, if it has no active-connections that are in state
     * activated, activating, or waiting to be activated. */
    return !active_connection_find(d->self,
                                   sett_conn,
                                   NULL,
                                   NM_ACTIVE_CONNECTION_STATE_ACTIVATED,
                                   NULL);
}

NMSettingsConnection **
nm_manager_get_activatable_connections(NMManager *manager,
                                       gboolean   for_auto_activation,
                                       gboolean   sort,
                                       guint *    out_len)
{
    NMManagerPrivate *                        priv = NM_MANAGER_GET_PRIVATE(manager);
    const GetActivatableConnectionsFilterData d    = {
        .self                = manager,
        .for_auto_activation = for_auto_activation,
    };

    return nm_settings_get_connections_clone(
        priv->settings,
        out_len,
        _get_activatable_connections_filter,
        (gpointer) &d,
        sort ? nm_settings_connection_cmp_autoconnect_priority_p_with_data : NULL,
        NULL);
}

static NMActiveConnection *
active_connection_get_by_path(NMManager *self, const char *path)
{
    NMManagerPrivate *  priv = NM_MANAGER_GET_PRIVATE(self);
    NMActiveConnection *ac;

    ac = nm_dbus_manager_lookup_object(nm_dbus_object_get_manager(NM_DBUS_OBJECT(self)), path);
    if (!ac || !NM_IS_ACTIVE_CONNECTION(ac) || c_list_is_empty(&ac->active_connections_lst))
        return NULL;

    nm_assert(c_list_contains(&priv->active_connections_lst_head, &ac->active_connections_lst));
    return ac;
}

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

static void
_config_changed_cb(NMConfig *          config,
                   NMConfigData *      config_data,
                   NMConfigChangeFlags changes,
                   NMConfigData *      old_data,
                   NMManager *         self)
{
    g_object_freeze_notify(G_OBJECT(self));

    if (NM_FLAGS_HAS(changes, NM_CONFIG_CHANGE_GLOBAL_DNS_CONFIG))
        _notify(self, PROP_GLOBAL_DNS_CONFIGURATION);

    if (!nm_streq0(nm_config_data_get_connectivity_uri(config_data),
                   nm_config_data_get_connectivity_uri(old_data))) {
        if ((!nm_config_data_get_connectivity_uri(config_data))
            != (!nm_config_data_get_connectivity_uri(old_data)))
            _notify(self, PROP_CONNECTIVITY_CHECK_AVAILABLE);
        _notify(self, PROP_CONNECTIVITY_CHECK_URI);
    }

    g_object_thaw_notify(G_OBJECT(self));
}

static void
_reload_auth_cb(NMAuthChain *chain, GDBusMethodInvocation *context, gpointer user_data)
{
    NMManager *         self      = NM_MANAGER(user_data);
    NMManagerPrivate *  priv      = NM_MANAGER_GET_PRIVATE(self);
    GError *            ret_error = NULL;
    NMAuthCallResult    result;
    guint32             flags;
    NMAuthSubject *     subject;
    char                s_buf[60];
    NMConfigChangeFlags reload_type = NM_CONFIG_CHANGE_NONE;

    nm_assert(G_IS_DBUS_METHOD_INVOCATION(context));

    c_list_unlink(nm_auth_chain_parent_lst_list(chain));
    flags = GPOINTER_TO_UINT(nm_auth_chain_get_data(chain, "flags"));

    subject = nm_auth_chain_get_subject(chain);

    result = nm_auth_chain_get_result(chain, NM_AUTH_PERMISSION_RELOAD);
    if (result != NM_AUTH_CALL_RESULT_YES) {
        ret_error = g_error_new_literal(NM_MANAGER_ERROR,
                                        NM_MANAGER_ERROR_PERMISSION_DENIED,
                                        "Not authorized to reload configuration");
    } else {
        if (NM_FLAGS_ANY(flags, ~NM_MANAGER_RELOAD_FLAG_ALL)) {
            /* invalid flags */
        } else if (flags == 0)
            reload_type = NM_CONFIG_CHANGE_CAUSE_SIGHUP;
        else {
            if (NM_FLAGS_HAS(flags, NM_MANAGER_RELOAD_FLAG_CONF))
                reload_type |= NM_CONFIG_CHANGE_CAUSE_CONF;
            if (NM_FLAGS_HAS(flags, NM_MANAGER_RELOAD_FLAG_DNS_RC))
                reload_type |= NM_CONFIG_CHANGE_CAUSE_DNS_RC;
            if (NM_FLAGS_HAS(flags, NM_MANAGER_RELOAD_FLAG_DNS_FULL))
                reload_type |= NM_CONFIG_CHANGE_CAUSE_DNS_FULL;
        }

        if (reload_type == NM_CONFIG_CHANGE_NONE) {
            ret_error = g_error_new_literal(NM_MANAGER_ERROR,
                                            NM_MANAGER_ERROR_INVALID_ARGUMENTS,
                                            "Invalid flags for reload");
        }
    }

    nm_audit_log_control_op(NM_AUDIT_OP_RELOAD,
                            nm_sprintf_buf(s_buf, "%u", flags),
                            ret_error == NULL,
                            subject,
                            ret_error ? ret_error->message : NULL);

    if (ret_error) {
        g_dbus_method_invocation_take_error(context, ret_error);
        return;
    }

    nm_config_reload(priv->config, reload_type, TRUE);
    g_dbus_method_invocation_return_value(context, NULL);
}

static void
impl_manager_reload(NMDBusObject *                     obj,
                    const NMDBusInterfaceInfoExtended *interface_info,
                    const NMDBusMethodInfoExtended *   method_info,
                    GDBusConnection *                  connection,
                    const char *                       sender,
                    GDBusMethodInvocation *            invocation,
                    GVariant *                         parameters)
{
    NMManager *       self = NM_MANAGER(obj);
    NMManagerPrivate *priv = NM_MANAGER_GET_PRIVATE(self);
    NMAuthChain *     chain;
    guint32           flags;

    g_variant_get(parameters, "(u)", &flags);

    chain = nm_auth_chain_new_context(invocation, _reload_auth_cb, self);
    if (!chain) {
        g_dbus_method_invocation_return_error_literal(invocation,
                                                      NM_MANAGER_ERROR,
                                                      NM_MANAGER_ERROR_PERMISSION_DENIED,
                                                      NM_UTILS_ERROR_MSG_REQ_AUTH_FAILED);
        return;
    }

    c_list_link_tail(&priv->auth_lst_head, nm_auth_chain_parent_lst_list(chain));
    nm_auth_chain_set_data(chain, "flags", GUINT_TO_POINTER(flags), NULL);
    nm_auth_chain_add_call(chain, NM_AUTH_PERMISSION_RELOAD, TRUE);
}

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

NMDevice *
nm_manager_get_device_by_path(NMManager *self, const char *path)
{
    NMManagerPrivate *priv = NM_MANAGER_GET_PRIVATE(self);
    NMDevice *        device;

    g_return_val_if_fail(path, NULL);

    device = nm_dbus_manager_lookup_object(nm_dbus_object_get_manager(NM_DBUS_OBJECT(self)), path);
    if (!device || !NM_IS_DEVICE(device) || c_list_is_empty(&device->devices_lst))
        return NULL;

    nm_assert(c_list_contains(&priv->devices_lst_head, &device->devices_lst));
    return device;
}

NMDevice *
nm_manager_get_device_by_ifindex(NMManager *self, int ifindex)
{
    NMManagerPrivate *priv = NM_MANAGER_GET_PRIVATE(self);
    NMDevice *        device;

    if (ifindex > 0) {
        c_list_for_each_entry (device, &priv->devices_lst_head, devices_lst) {
            if (nm_device_get_ifindex(device) == ifindex)
                return device;
        }
    }

    return NULL;
}

static NMDevice *
find_device_by_permanent_hw_addr(NMManager *self, const char *hwaddr)
{
    NMManagerPrivate *priv = NM_MANAGER_GET_PRIVATE(self);
    NMDevice *        device;
    const char *      device_addr;
    guint8            hwaddr_bin[NM_UTILS_HWADDR_LEN_MAX];
    gsize             hwaddr_len;

    g_return_val_if_fail(hwaddr != NULL, NULL);

    if (!_nm_utils_hwaddr_aton(hwaddr, hwaddr_bin, sizeof(hwaddr_bin), &hwaddr_len))
        return NULL;

    c_list_for_each_entry (device, &priv->devices_lst_head, devices_lst) {
        device_addr = nm_device_get_permanent_hw_address(device);
        if (device_addr && nm_utils_hwaddr_matches(hwaddr_bin, hwaddr_len, device_addr, -1))
            return device;
    }
    return NULL;
}

static NMDevice *
find_device_by_ip_iface(NMManager *self, const char *iface)
{
    NMManagerPrivate *priv = NM_MANAGER_GET_PRIVATE(self);
    NMDevice *        device;

    g_return_val_if_fail(iface, NULL);

    c_list_for_each_entry (device, &priv->devices_lst_head, devices_lst) {
        if (nm_device_is_real(device) && nm_streq0(nm_device_get_ip_iface(device), iface))
            return device;
    }
    return NULL;
}

/**
 * find_device_by_iface:
 * @self: the #NMManager
 * @iface: the device interface to find
 * @connection: a connection to ensure the returned device is compatible with
 * @slave: a slave connection to ensure a master is compatible with
 *
 * Finds a device by interface name, preferring realized devices.  If @slave
 * is given, this function will only return master devices and will ensure
 * @slave, when activated, can be a slave of the returned master device.  If
 * @connection is given, this function will only consider devices that are
 * compatible with @connection.
 *
 * Returns: the matching #NMDevice
 */
static NMDevice *
find_device_by_iface(NMManager *   self,
                     const char *  iface,
                     NMConnection *connection,
                     NMConnection *slave)
{
    NMManagerPrivate *priv     = NM_MANAGER_GET_PRIVATE(self);
    NMDevice *        fallback = NULL;
    NMDevice *        candidate;

    g_return_val_if_fail(iface != NULL, NULL);

    c_list_for_each_entry (candidate, &priv->devices_lst_head, devices_lst) {
        if (!nm_streq(nm_device_get_iface(candidate), iface))
            continue;
        if (connection && !nm_device_check_connection_compatible(candidate, connection, NULL))
            continue;
        if (slave) {
            if (!nm_device_is_master(candidate))
                continue;
            if (!nm_device_check_slave_connection_compatible(candidate, slave))
                continue;
        }

        if (nm_device_is_real(candidate))
            return candidate;
        else if (!fallback)
            fallback = candidate;
    }
    return fallback;
}

static gboolean
manager_sleeping(NMManager *self)
{
    NMManagerPrivate *priv = NM_MANAGER_GET_PRIVATE(self);

    if (priv->sleeping || !priv->net_enabled)
        return TRUE;
    return FALSE;
}

static const char *
_nm_state_to_string(NMState state)
{
    switch (state) {
    case NM_STATE_ASLEEP:
        return "ASLEEP";
    case NM_STATE_DISCONNECTED:
        return "DISCONNECTED";
    case NM_STATE_DISCONNECTING:
        return "DISCONNECTING";
    case NM_STATE_CONNECTING:
        return "CONNECTING";
    case NM_STATE_CONNECTED_LOCAL:
        return "CONNECTED_LOCAL";
    case NM_STATE_CONNECTED_SITE:
        return "CONNECTED_SITE";
    case NM_STATE_CONNECTED_GLOBAL:
        return "CONNECTED_GLOBAL";
    case NM_STATE_UNKNOWN:
    default:
        return "UNKNOWN";
    }
}

static NMState
find_best_device_state(NMManager *manager)
{
    NMManagerPrivate *  priv       = NM_MANAGER_GET_PRIVATE(manager);
    NMState             best_state = NM_STATE_DISCONNECTED;
    NMActiveConnection *ac;

    c_list_for_each_entry (ac, &priv->active_connections_lst_head, active_connections_lst) {
        NMActiveConnectionState ac_state = nm_active_connection_get_state(ac);

        switch (ac_state) {
        case NM_ACTIVE_CONNECTION_STATE_ACTIVATED:
            if (nm_active_connection_get_default(ac, AF_UNSPEC)) {
                if (priv->connectivity_state == NM_CONNECTIVITY_FULL)
                    return NM_STATE_CONNECTED_GLOBAL;

                best_state = NM_STATE_CONNECTED_SITE;
            } else {
                if (best_state < NM_STATE_CONNECTING)
                    best_state = NM_STATE_CONNECTED_LOCAL;
            }
            break;
        case NM_ACTIVE_CONNECTION_STATE_ACTIVATING:
            if (!NM_IN_SET(nm_active_connection_get_activation_type(ac),
                           NM_ACTIVATION_TYPE_EXTERNAL,
                           NM_ACTIVATION_TYPE_ASSUME)) {
                if (best_state != NM_STATE_CONNECTED_GLOBAL)
                    best_state = NM_STATE_CONNECTING;
            }
            break;
        case NM_ACTIVE_CONNECTION_STATE_DEACTIVATING:
            if (!NM_IN_SET(nm_active_connection_get_activation_type(ac),
                           NM_ACTIVATION_TYPE_EXTERNAL,
                           NM_ACTIVATION_TYPE_ASSUME)) {
                if (best_state < NM_STATE_DISCONNECTING)
                    best_state = NM_STATE_DISCONNECTING;
            }
            break;
        default:
            break;
        }
    }

    return best_state;
}

static void
nm_manager_update_metered(NMManager *self)
{
    NMManagerPrivate *priv;
    NMDevice *        device;
    NMMetered         value = NM_METERED_UNKNOWN;

    g_return_if_fail(NM_IS_MANAGER(self));
    priv = NM_MANAGER_GET_PRIVATE(self);

    if (priv->primary_connection) {
        device = nm_active_connection_get_device(priv->primary_connection);
        if (device)
            value = nm_device_get_metered(device);
    }

    if (value != priv->metered) {
        priv->metered = value;
        _LOGD(LOGD_CORE, "new metered value: %d", (int) priv->metered);
        _notify(self, PROP_METERED);
    }
}

NMMetered
nm_manager_get_metered(NMManager *self)
{
    g_return_val_if_fail(NM_IS_MANAGER(self), NM_METERED_UNKNOWN);

    return NM_MANAGER_GET_PRIVATE(self)->metered;
}

static void
nm_manager_update_state(NMManager *self)
{
    NMManagerPrivate *priv;
    NMState           new_state = NM_STATE_DISCONNECTED;

    g_return_if_fail(NM_IS_MANAGER(self));

    priv = NM_MANAGER_GET_PRIVATE(self);

    if (manager_sleeping(self))
        new_state = NM_STATE_ASLEEP;
    else
        new_state = find_best_device_state(self);

    if (new_state >= NM_STATE_CONNECTED_LOCAL && priv->connectivity_state == NM_CONNECTIVITY_FULL) {
        new_state = NM_STATE_CONNECTED_GLOBAL;
    }

    if (priv->state == new_state)
        return;

    priv->state = new_state;

    _LOGI(LOGD_CORE, "NetworkManager state is now %s", _nm_state_to_string(new_state));

    _notify(self, PROP_STATE);
    nm_dbus_object_emit_signal(NM_DBUS_OBJECT(self),
                               &interface_info_manager,
                               &signal_info_state_changed,
                               "(u)",
                               (guint32) priv->state);
}

static void
manager_device_state_changed(NMDevice *          device,
                             NMDeviceState       new_state,
                             NMDeviceState       old_state,
                             NMDeviceStateReason reason,
                             gpointer            user_data)
{
    NMManager *       self = NM_MANAGER(user_data);
    NMManagerPrivate *priv = NM_MANAGER_GET_PRIVATE(self);

    if (old_state == NM_DEVICE_STATE_UNMANAGED && new_state > NM_DEVICE_STATE_UNMANAGED)
        retry_connections_for_parent_device(self, device);

    if (NM_IN_SET(new_state,
                  NM_DEVICE_STATE_UNMANAGED,
                  NM_DEVICE_STATE_UNAVAILABLE,
                  NM_DEVICE_STATE_DISCONNECTED,
                  NM_DEVICE_STATE_PREPARE,
                  NM_DEVICE_STATE_FAILED))
        _notify(self, PROP_ACTIVE_CONNECTIONS);

    if (NM_IN_SET(new_state,
                  NM_DEVICE_STATE_UNMANAGED,
                  NM_DEVICE_STATE_DISCONNECTED,
                  NM_DEVICE_STATE_ACTIVATED)) {
        nm_manager_write_device_state(self, device, NULL);

        G_STATIC_ASSERT_EXPR(DEVICE_STATE_PRUNE_RATELIMIT_MAX < G_MAXUINT8);
        if (priv->device_state_prune_ratelimit_count++ > DEVICE_STATE_PRUNE_RATELIMIT_MAX) {
            /* We write the device state to /run. The state files are named after the
             * ifindex (which is assumed to be unique and not repeat -- in practice
             * it may repeat). So from time to time, we prune device state files
             * for interfaces that no longer exist.
             *
             * Otherwise, the files might pile up if you create (and destroy) a large
             * number of software devices. */
            priv->device_state_prune_ratelimit_count = 0;
            nm_config_device_state_prune_stale(NULL, priv->platform);
        }
    }

    if (NM_IN_SET(new_state, NM_DEVICE_STATE_UNAVAILABLE, NM_DEVICE_STATE_DISCONNECTED))
        nm_settings_device_added(priv->settings, device);
}

static void device_has_pending_action_changed(NMDevice *device, GParamSpec *pspec, NMManager *self);

static void
check_if_startup_complete(NMManager *self)
{
    NMManagerPrivate *priv = NM_MANAGER_GET_PRIVATE(self);
    NMDevice *        device;
    const char *      reason;

    if (!priv->startup)
        return;

    if (!priv->devices_inited)
        return;

    c_list_for_each_entry (device, &priv->devices_lst_head, devices_lst) {
        reason = nm_device_has_pending_action_reason(device);
        if (reason) {
            _LOGD(LOGD_CORE,
                  "startup complete is waiting for device '%s' (%s)",
                  nm_device_get_iface(device),
                  reason);
            return;
        }
    }

    /* All NMDevice must be ready. But also NMSettings tracks profiles that wait for
     * ready devices via "connection.wait-device-timeout".
     *
     * Note that we only re-check nm_settings_get_startup_complete_blocked_reason() when
     * all of the devices become ready (again).
     *
     * For example, assume we have device "eth1" and "profile-eth2" which waits for "eth2".
     * If "eth1" is ready (no pending action), we only need to re-evaluate "profile-eth2"
     * if we have another device ("eth2"), that becomes non-ready (had pending actions)
     * and again become ready. We don't need to check "profile-eth2" until "eth2" becomes
     * non-ready.
     * That is why nm_settings_get_startup_complete_blocked_reason() only has any significance
     * if all devices are ready too. It allows us to cut down the number of checks whether
     * NMSettings is ready. That's because we don't need to re-evaluate on minor changes of
     * a device, only when all devices become managed and ready. */

    g_signal_handlers_block_by_func(priv->settings, settings_startup_complete_changed, self);
    reason = nm_settings_get_startup_complete_blocked_reason(priv->settings, TRUE);
    g_signal_handlers_unblock_by_func(priv->settings, settings_startup_complete_changed, self);
    if (reason) {
        _LOGD(LOGD_CORE, "startup complete is waiting for connection (%s)", reason);
        return;
    }

    _LOGI(LOGD_CORE, "startup complete");

    priv->startup = FALSE;

    /* we no longer care about these signals. Startup-complete only
     * happens once. */
    g_signal_handlers_disconnect_by_func(priv->settings,
                                         G_CALLBACK(settings_startup_complete_changed),
                                         self);
    c_list_for_each_entry (device, &priv->devices_lst_head, devices_lst) {
        g_signal_handlers_disconnect_by_func(device,
                                             G_CALLBACK(device_has_pending_action_changed),
                                             self);
    }

    _notify(self, PROP_STARTUP);

    if (nm_config_get_configure_and_quit(priv->config))
        g_signal_emit(self, signals[CONFIGURE_QUIT], 0);
}

static void
device_has_pending_action_changed(NMDevice *device, GParamSpec *pspec, NMManager *self)
{
    check_if_startup_complete(self);
}

static void
settings_startup_complete_changed(NMSettings *settings, GParamSpec *pspec, NMManager *self)
{
    check_if_startup_complete(self);
}

static void
_parent_notify_changed(NMManager *self, NMDevice *device, gboolean device_removed)
{
    NMManagerPrivate *priv = NM_MANAGER_GET_PRIVATE(self);
    NMDevice *        candidate;

    nm_assert(NM_IS_DEVICE(device));

again:
    c_list_for_each_entry (candidate, &priv->devices_lst_head, devices_lst) {
        if (nm_device_parent_notify_changed(candidate, device, device_removed)) {
            /* in the unlikely event that this changes anything, we start iterating
             * again, to be sure that the device list is up-to-date. */
            goto again;
        }
    }
}

static gboolean
device_is_wake_on_lan(NMPlatform *platform, NMDevice *device)
{
    int ifindex;

    ifindex = nm_device_get_ip_ifindex(device);
    if (ifindex <= 0)
        return FALSE;
    return nm_platform_link_get_wake_on_lan(platform, ifindex);
}

static void
remove_device(NMManager *self, NMDevice *device, gboolean quitting)
{
    NMManagerPrivate *priv     = NM_MANAGER_GET_PRIVATE(self);
    gboolean          unmanage = FALSE;

    _LOG2D(LOGD_DEVICE,
           device,
           "removing device (managed %d, wol %d)",
           nm_device_get_managed(device, FALSE),
           device_is_wake_on_lan(priv->platform, device));

    if (nm_device_get_managed(device, FALSE)) {
        if (quitting) {
            /* Leave configured if wo(w)lan and quitting */
            if (device_is_wake_on_lan(priv->platform, device))
                unmanage = FALSE;
            else
                unmanage = nm_device_unmanage_on_quit(device);
        } else {
            /* the device is already gone. Unmanage it. */
            unmanage = TRUE;
        }

        if (unmanage) {
            if (quitting)
                nm_device_set_unmanaged_by_quitting(device);
            else {
                nm_device_sys_iface_state_set(device, NM_DEVICE_SYS_IFACE_STATE_REMOVED);
                nm_device_set_unmanaged_by_flags(device,
                                                 NM_UNMANAGED_PLATFORM_INIT,
                                                 TRUE,
                                                 NM_DEVICE_STATE_REASON_REMOVED);
            }
        } else if (quitting
                   && nm_config_get_configure_and_quit(priv->config)
                          == NM_CONFIG_CONFIGURE_AND_QUIT_ENABLED) {
            nm_device_spawn_iface_helper(device);
        }
    }

    g_signal_handlers_disconnect_matched(device, G_SIGNAL_MATCH_DATA, 0, 0, NULL, NULL, self);

    nm_settings_device_removed(priv->settings, device, quitting);

    c_list_unlink(&device->devices_lst);

    _parent_notify_changed(self, device, TRUE);

    if (nm_device_is_real(device)) {
        gboolean unconfigure_ip_config = !quitting || unmanage;

        /* When we don't unmanage the device on shutdown, we want to preserve the DNS
         * configuration in resolv.conf. For that, we must leak the configuration
         * in NMPolicy/NMDnsManager. We do that, by emitting the device-removed signal
         * with device's ip-config object still uncleared. In that case, NMPolicy
         * never learns to unconfigure the ip-config objects and does not remove them
         * from DNS on shutdown (which is ugly, because we don't cleanup the memory
         * properly).
         *
         * Control that by passing @unconfigure_ip_config.  */
        nm_device_removed(device, unconfigure_ip_config);

        _emit_device_added_removed(self, device, FALSE);
    } else {
        /* unrealize() does not release a slave device from master and
         * clear IP configurations, do it here */
        nm_device_removed(device, TRUE);
    }

    g_signal_emit(self, signals[INTERNAL_DEVICE_REMOVED], 0, device);
    _notify(self, PROP_ALL_DEVICES);

    update_connectivity_value(self);

    nm_dbus_object_clear_and_unexport(&device);

    check_if_startup_complete(self);
}

static void
device_removed_cb(NMDevice *device, gpointer user_data)
{
    remove_device(NM_MANAGER(user_data), device, FALSE);
}

NMState
nm_manager_get_state(NMManager *manager)
{
    g_return_val_if_fail(NM_IS_MANAGER(manager), NM_STATE_UNKNOWN);

    return NM_MANAGER_GET_PRIVATE(manager)->state;
}

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

static NMDevice *
find_parent_device_for_connection(NMManager *      self,
                                  NMConnection *   connection,
                                  NMDeviceFactory *cached_factory,
                                  const char **    out_parent_spec)
{
    NMManagerPrivate *    priv = NM_MANAGER_GET_PRIVATE(self);
    NMDeviceFactory *     factory;
    const char *          parent_name = NULL;
    NMSettingsConnection *parent_connection;
    NMDevice *            parent, *first_compatible = NULL;
    NMDevice *            candidate;

    g_return_val_if_fail(NM_IS_CONNECTION(connection), NULL);
    NM_SET_OUT(out_parent_spec, NULL);

    if (!cached_factory) {
        factory = nm_device_factory_manager_find_factory_for_connection(connection);
        if (!factory)
            return NULL;
    } else
        factory = cached_factory;

    parent_name = nm_device_factory_get_connection_parent(factory, connection);
    if (!parent_name)
        return NULL;

    NM_SET_OUT(out_parent_spec, parent_name);

    /* Try as an interface name of a parent device */
    parent = find_device_by_iface(self, parent_name, NULL, NULL);
    if (parent)
        return parent;

    /* Maybe a hardware address */
    parent = find_device_by_permanent_hw_addr(self, parent_name);
    if (parent)
        return parent;

    /* Maybe a connection UUID */
    parent_connection = nm_settings_get_connection_by_uuid(priv->settings, parent_name);
    if (!parent_connection)
        return NULL;

    /* Check if the parent connection is currently activated or is compatible
     * with some known device.
     */
    c_list_for_each_entry (candidate, &priv->devices_lst_head, devices_lst) {
        /* Unmanaged devices are not compatible with any connection */
        if (!nm_device_get_managed(candidate, FALSE))
            continue;

        if (nm_device_get_settings_connection(candidate) == parent_connection)
            return candidate;

        if (!first_compatible
            && nm_device_check_connection_compatible(
                candidate,
                nm_settings_connection_get_connection(parent_connection),
                NULL))
            first_compatible = candidate;
    }

    return first_compatible;
}

/**
 * nm_manager_get_connection_iface:
 * @self: the #NMManager
 * @connection: the #NMConnection to get the interface for
 * @out_parent: on success, the parent device if any
 * @out_parent_spec: on return, a string specifying the parent device
 *   in the connection. This can be a device name, a MAC address or a
 *   connection UUID.
 * @error: an error if determining the virtual interface name failed
 *
 * Given @connection, returns the interface name that the connection
 * would need to use when activated. %NULL is returned if the name
 * is not specified in connection or a the name for a virtual device
 * could not be generated.
 *
 * Returns: the expected interface name (caller takes ownership), or %NULL
 */
char *
nm_manager_get_connection_iface(NMManager *   self,
                                NMConnection *connection,
                                NMDevice **   out_parent,
                                const char ** out_parent_spec,
                                GError **     error)
{
    NMDeviceFactory *factory;
    char *           iface  = NULL;
    NMDevice *       parent = NULL;

    NM_SET_OUT(out_parent, NULL);
    NM_SET_OUT(out_parent_spec, NULL);

    factory = nm_device_factory_manager_find_factory_for_connection(connection);
    if (!factory) {
        if (nm_streq0(nm_connection_get_connection_type(connection),
                      NM_SETTING_GENERIC_SETTING_NAME)) {
            /* the generic type doesn't have a factory. */
            goto return_ifname_fom_connection;
        }

        g_set_error(error,
                    NM_MANAGER_ERROR,
                    NM_MANAGER_ERROR_FAILED,
                    "NetworkManager plugin for '%s' unavailable",
                    nm_connection_get_connection_type(connection));
        return NULL;
    }

    if (!out_parent && !NM_DEVICE_FACTORY_GET_CLASS(factory)->get_connection_iface) {
        /* optimization. Shortcut lookup of the partent device. */
        goto return_ifname_fom_connection;
    }

    parent = find_parent_device_for_connection(self, connection, factory, out_parent_spec);
    iface  = nm_device_factory_get_connection_iface(factory,
                                                   connection,
                                                   parent ? nm_device_get_ip_iface(parent) : NULL,
                                                   error);
    if (!iface)
        return NULL;

    if (out_parent)
        *out_parent = parent;
    return iface;

return_ifname_fom_connection:
    iface = g_strdup(nm_connection_get_interface_name(connection));
    if (!iface) {
        g_set_error(error,
                    NM_MANAGER_ERROR,
                    NM_MANAGER_ERROR_FAILED,
                    "failed to determine interface name: error determine name for %s",
                    nm_connection_get_connection_type(connection));
    }
    return iface;
}

/**
 * nm_manager_iface_for_uuid:
 * @self: the #NMManager
 * @uuid: the connection uuid
 *
 * Gets a link name for the given UUID. Useful for the settings plugins that
 * wish to write configuration files compatible with tooling that can't
 * interpret our UUIDs.
 *
 * Returns: An interface name; %NULL if none matches
 */
const char *
nm_manager_iface_for_uuid(NMManager *self, const char *uuid)
{
    NMManagerPrivate *    priv = NM_MANAGER_GET_PRIVATE(self);
    NMSettingsConnection *sett_conn;

    sett_conn = nm_settings_get_connection_by_uuid(priv->settings, uuid);
    if (!sett_conn)
        return NULL;

    return nm_connection_get_interface_name(nm_settings_connection_get_connection(sett_conn));
}

NMDevice *
nm_manager_get_device(NMManager *self, const char *ifname, NMDeviceType device_type)
{
    NMManagerPrivate *priv = NM_MANAGER_GET_PRIVATE(self);
    NMDevice *        device;

    g_return_val_if_fail(ifname, NULL);
    g_return_val_if_fail(device_type != NM_DEVICE_TYPE_UNKNOWN, NULL);

    c_list_for_each_entry (device, &priv->devices_lst_head, devices_lst) {
        if (nm_device_get_device_type(device) == device_type
            && nm_streq0(nm_device_get_iface(device), ifname))
            return device;
    }

    return NULL;
}

gboolean
nm_manager_remove_device(NMManager *self, const char *ifname, NMDeviceType device_type)
{
    NMDevice *d;

    d = nm_manager_get_device(self, ifname, device_type);
    if (!d)
        return FALSE;

    remove_device(self, d, FALSE);
    return TRUE;
}

/**
 * system_create_virtual_device:
 * @self: the #NMManager
 * @connection: the connection which might require a virtual device
 *
 * If @connection requires a virtual device and one does not yet exist for it,
 * creates that device.
 *
 * Returns: A #NMDevice that was just realized; %NULL if none
 */
static NMDevice *
system_create_virtual_device(NMManager *self, NMConnection *connection)
{
    NMManagerPrivate *priv = NM_MANAGER_GET_PRIVATE(self);
    NMDeviceFactory * factory;
    gs_free NMSettingsConnection **connections = NULL;
    guint                          i;
    gs_free char *                 iface = NULL;
    const char *                   parent_spec;
    NMDevice *                     device = NULL, *parent = NULL;
    NMDevice *                     dev_candidate;
    GError *                       error = NULL;
    NMLogLevel                     log_level;

    g_return_val_if_fail(NM_IS_MANAGER(self), NULL);
    g_return_val_if_fail(NM_IS_CONNECTION(connection), NULL);

    iface = nm_manager_get_connection_iface(self, connection, &parent, &parent_spec, &error);
    if (!iface) {
        _LOG3D(LOGD_DEVICE, connection, "can't get a name of a virtual device: %s", error->message);
        g_error_free(error);
        return NULL;
    }

    if (parent_spec && !parent) {
        /* parent is not ready, wait */
        return NULL;
    }

    /* See if there's a device that is already compatible with this connection */
    c_list_for_each_entry (dev_candidate, &priv->devices_lst_head, devices_lst) {
        if (nm_device_check_connection_compatible(dev_candidate, connection, NULL)) {
            if (nm_device_is_real(dev_candidate)) {
                _LOG3D(LOGD_DEVICE, connection, "already created virtual interface name %s", iface);
                return NULL;
            }

            device = dev_candidate;
            break;
        }
    }

    if (!device) {
        /* No matching device found. Proceed creating a new one. */

        factory = nm_device_factory_manager_find_factory_for_connection(connection);
        if (!factory) {
            _LOG3E(LOGD_DEVICE,
                   connection,
                   "(%s) NetworkManager plugin for '%s' unavailable",
                   iface,
                   nm_connection_get_connection_type(connection));
            return NULL;
        }

        device = nm_device_factory_create_device(factory, iface, NULL, connection, NULL, &error);
        if (!device) {
            _LOG3W(LOGD_DEVICE, connection, "factory can't create the device: %s", error->message);
            g_error_free(error);
            return NULL;
        }

        _LOG3D(LOGD_DEVICE, connection, "create virtual device %s", nm_device_get_iface(device));

        if (!add_device(self, device, &error)) {
            _LOG3W(LOGD_DEVICE,
                   connection,
                   "can't register the device with manager: %s",
                   error->message);
            g_error_free(error);
            g_object_unref(device);
            return NULL;
        }

        /* Add device takes a reference that NMManager still owns, so it's
         * safe to unref here and still return @device.
         */
        g_object_unref(device);
    }

    if (!nm_device_check_unrealized_device_managed(device)) {
        _LOG3D(LOGD_DEVICE,
               connection,
               "skip activation because virtual device '%s' is unmanaged",
               nm_device_get_iface(device));
        return device;
    }

    if (!find_master(self, connection, device, NULL, NULL, NULL, &error)) {
        _LOG3D(LOGD_DEVICE, connection, "skip activation: %s", error->message);
        g_error_free(error);
        return device;
    }

    /* Create backing resources if the device has any autoconnect connections */
    connections = nm_settings_get_connections_clone(
        priv->settings,
        NULL,
        NULL,
        NULL,
        nm_settings_connection_cmp_autoconnect_priority_p_with_data,
        NULL);
    for (i = 0; connections[i]; i++) {
        NMConnection *       candidate = nm_settings_connection_get_connection(connections[i]);
        NMSettingConnection *s_con;

        if (!nm_device_check_connection_compatible(device, candidate, NULL))
            continue;

        s_con = nm_connection_get_setting_connection(candidate);
        g_assert(s_con);
        if (!nm_setting_connection_get_autoconnect(s_con)
            || nm_settings_connection_autoconnect_is_blocked(connections[i]))
            continue;

        /* Create any backing resources the device needs */
        if (!nm_device_create_and_realize(device, connection, parent, &error)) {
            log_level =
                g_error_matches(error, NM_DEVICE_ERROR, NM_DEVICE_ERROR_MISSING_DEPENDENCIES)
                    ? LOGL_DEBUG
                    : LOGL_ERR;
            _NMLOG3(log_level,
                    LOGD_DEVICE,
                    connection,
                    "couldn't create the device: %s",
                    error->message);
            g_error_free(error);
            return NULL;
        }

        retry_connections_for_parent_device(self, device);
        break;
    }

    return device;
}

static void
retry_connections_for_parent_device(NMManager *self, NMDevice *device)
{
    NMManagerPrivate *priv                     = NM_MANAGER_GET_PRIVATE(self);
    gs_free NMSettingsConnection **connections = NULL;
    guint                          i;

    g_return_if_fail(device);

    connections = nm_settings_get_connections_clone(
        priv->settings,
        NULL,
        NULL,
        NULL,
        nm_settings_connection_cmp_autoconnect_priority_p_with_data,
        NULL);
    for (i = 0; connections[i]; i++) {
        NMSettingsConnection *sett_conn  = connections[i];
        NMConnection *        connection = nm_settings_connection_get_connection(sett_conn);
        gs_free_error GError *error      = NULL;
        gs_free char *        ifname     = NULL;
        NMDevice *            parent;

        parent = find_parent_device_for_connection(self, connection, NULL, NULL);
        if (parent == device) {
            /* Only try to activate devices that don't already exist */
            ifname = nm_manager_get_connection_iface(self, connection, &parent, NULL, &error);
            if (ifname) {
                if (!nm_platform_link_get_by_ifname(NM_PLATFORM_GET, ifname))
                    connection_changed(self, sett_conn);
            }
        }
    }
}

static void
connection_changed(NMManager *self, NMSettingsConnection *sett_conn)
{
    NMConnection *connection;
    NMDevice *    device;

    if (NM_FLAGS_ANY(nm_settings_connection_get_flags(sett_conn),
                     NM_SETTINGS_CONNECTION_INT_FLAGS_VOLATILE
                         | NM_SETTINGS_CONNECTION_INT_FLAGS_EXTERNAL))
        return;

    connection = nm_settings_connection_get_connection(sett_conn);

    if (!nm_connection_is_virtual(connection))
        return;

    device = system_create_virtual_device(self, connection);
    if (!device)
        return;

    /* Maybe the device that was created was needed by some other
     * connection's device (parent of a VLAN). Let the connections
     * can use the newly created device as a parent know. */
    retry_connections_for_parent_device(self, device);
}

static void
connection_added_cb(NMSettings *settings, NMSettingsConnection *sett_conn, NMManager *self)
{
    connection_changed(self, sett_conn);
}

static void
connection_updated_cb(NMSettings *          settings,
                      NMSettingsConnection *sett_conn,
                      guint                 update_reason_u,
                      NMManager *           self)
{
    connection_changed(self, sett_conn);
}

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

static void
_delete_volatile_connection_all(NMManager *self, gboolean do_delete)
{
    NMManagerPrivate *priv = NM_MANAGER_GET_PRIVATE(self);
    NMCListElem *     elem;

    while (
        (elem = c_list_first_entry(&priv->delete_volatile_connection_lst_head, NMCListElem, lst))) {
        gs_unref_object NMSettingsConnection *connection = NULL;

        connection = nm_c_list_elem_free_steal(elem);
        if (do_delete)
            _delete_volatile_connection_do(self, connection);
    }
}

static gboolean
_delete_volatile_connection_cb(gpointer user_data)
{
    NMManager *       self = user_data;
    NMManagerPrivate *priv = NM_MANAGER_GET_PRIVATE(self);

    priv->delete_volatile_connection_idle_id = 0;
    _delete_volatile_connection_all(self, TRUE);
    return G_SOURCE_REMOVE;
}

static void
connection_flags_changed(NMSettings *settings, NMSettingsConnection *connection, gpointer user_data)
{
    NMManager *       self = user_data;
    NMManagerPrivate *priv = NM_MANAGER_GET_PRIVATE(self);

    if (!NM_FLAGS_ANY(nm_settings_connection_get_flags(connection),
                      NM_SETTINGS_CONNECTION_INT_FLAGS_VOLATILE
                          | NM_SETTINGS_CONNECTION_INT_FLAGS_EXTERNAL))
        return;

    if (active_connection_find(self,
                               connection,
                               NULL,
                               NM_ACTIVE_CONNECTION_STATE_DEACTIVATED,
                               NULL)) {
        /* the connection still has an active-connection. It will be purged
         * when the active connection(s) get(s) removed. */
        return;
    }

    c_list_link_tail(&priv->delete_volatile_connection_lst_head,
                     &nm_c_list_elem_new_stale(g_object_ref(connection))->lst);
    if (!priv->delete_volatile_connection_idle_id)
        priv->delete_volatile_connection_idle_id = g_idle_add(_delete_volatile_connection_cb, self);
}

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

static void
system_unmanaged_devices_changed_cb(NMSettings *settings, GParamSpec *pspec, gpointer user_data)
{
    NMManager *       self = NM_MANAGER(user_data);
    NMManagerPrivate *priv = NM_MANAGER_GET_PRIVATE(self);
    NMDevice *        device;

    c_list_for_each_entry (device, &priv->devices_lst_head, devices_lst)
        nm_device_set_unmanaged_by_user_settings(device);
}

static void
hostname_changed_cb(NMHostnameManager *hostname_manager, GParamSpec *pspec, NMManager *self)
{
    NMManagerPrivate *priv = NM_MANAGER_GET_PRIVATE(self);
    const char *      hostname;

    hostname = nm_hostname_manager_get_hostname(priv->hostname_manager);

    nm_dispatcher_call_hostname(NULL, NULL, NULL);
    nm_dhcp_manager_set_default_hostname(nm_dhcp_manager_get(), hostname);
}

/*****************************************************************************/
/* General NMManager stuff                                         */
/*****************************************************************************/

static gboolean
radio_enabled_for_rstate(RadioState *rstate, gboolean check_changeable)
{
    gboolean enabled;

    enabled = rstate->user_enabled && rstate->hw_enabled;
    if (check_changeable)
        enabled &= rstate->sw_enabled;
    return enabled;
}

static gboolean
radio_enabled_for_type(NMManager *self, RfKillType rtype, gboolean check_changeable)
{
    NMManagerPrivate *priv = NM_MANAGER_GET_PRIVATE(self);

    return radio_enabled_for_rstate(&priv->radio_states[rtype], check_changeable);
}

static void
manager_update_radio_enabled(NMManager *self, RadioState *rstate, gboolean enabled)
{
    NMManagerPrivate *priv = NM_MANAGER_GET_PRIVATE(self);
    NMDevice *        device;

    /* Do nothing for radio types not yet implemented */
    if (!rstate->prop)
        return;

    g_object_notify(G_OBJECT(self), rstate->prop);

    /* Don't touch devices if asleep/networking disabled */
    if (manager_sleeping(self))
        return;

    /* enable/disable wireless devices as required */
    c_list_for_each_entry (device, &priv->devices_lst_head, devices_lst) {
        if (nm_device_get_rfkill_type(device) == rstate->rtype) {
            _LOG2D(LOGD_RFKILL,
                   device,
                   "rfkill: setting radio %s",
                   enabled ? "enabled" : "disabled");
            nm_device_set_enabled(device, enabled);
        }
    }
}

static void
update_rstate_from_rfkill(NMRfkillManager *rfkill_mgr, RadioState *rstate)
{
    switch (nm_rfkill_manager_get_rfkill_state(rfkill_mgr, rstate->rtype)) {
    case RFKILL_UNBLOCKED:
        rstate->sw_enabled = TRUE;
        rstate->hw_enabled = TRUE;
        break;
    case RFKILL_SOFT_BLOCKED:
        rstate->sw_enabled = FALSE;
        rstate->hw_enabled = TRUE;
        break;
    case RFKILL_HARD_BLOCKED:
        rstate->sw_enabled = FALSE;
        rstate->hw_enabled = FALSE;
        break;
    default:
        g_warn_if_reached();
        break;
    }
}

static void
manager_rfkill_update_one_type(NMManager *self, RadioState *rstate, RfKillType rtype)
{
    NMManagerPrivate *priv = NM_MANAGER_GET_PRIVATE(self);
    gboolean          old_enabled, new_enabled, old_rfkilled, new_rfkilled, old_hwe;

    old_enabled  = radio_enabled_for_rstate(rstate, TRUE);
    old_rfkilled = rstate->hw_enabled && rstate->sw_enabled;
    old_hwe      = rstate->hw_enabled;

    /* recheck kernel rfkill state */
    update_rstate_from_rfkill(priv->rfkill_mgr, rstate);

    /* Print out all states affecting device enablement */
    if (rstate->desc) {
        _LOGD(LOGD_RFKILL,
              "rfkill: %s hw-enabled %d sw-enabled %d",
              rstate->desc,
              rstate->hw_enabled,
              rstate->sw_enabled);
    }

    /* Log new killswitch state */
    new_rfkilled = rstate->hw_enabled && rstate->sw_enabled;
    if (old_rfkilled != new_rfkilled) {
        _LOGI(LOGD_RFKILL,
              "rfkill: %s now %s by radio killswitch",
              rstate->desc,
              new_rfkilled ? "enabled" : "disabled");
    }

    /* Send out property changed signal for HW enabled */
    if (rstate->hw_enabled != old_hwe) {
        if (rstate->hw_prop)
            g_object_notify(G_OBJECT(self), rstate->hw_prop);
    }

    /* And finally update the actual device radio state itself; respect the
     * daemon state here because this is never called from user-triggered
     * radio changes and we only want to ignore the daemon enabled state when
     * handling user radio change requests.
     */
    new_enabled = radio_enabled_for_rstate(rstate, TRUE);
    if (new_enabled != old_enabled)
        manager_update_radio_enabled(self, rstate, new_enabled);
}

static void
nm_manager_rfkill_update(NMManager *self, RfKillType rtype)
{
    NMManagerPrivate *priv = NM_MANAGER_GET_PRIVATE(self);
    guint             i;

    if (rtype != RFKILL_TYPE_UNKNOWN)
        manager_rfkill_update_one_type(self, &priv->radio_states[rtype], rtype);
    else {
        /* Otherwise, sync all radio types */
        for (i = 0; i < RFKILL_TYPE_MAX; i++)
            manager_rfkill_update_one_type(self, &priv->radio_states[i], i);
    }
}

static void
device_auth_done_cb(NMAuthChain *chain, GDBusMethodInvocation *context, gpointer user_data)
{
    NMManager *   self                   = NM_MANAGER(user_data);
    gs_free_error GError *         error = NULL;
    NMAuthCallResult               result;
    NMDevice *                     device;
    GCancellable *                 cancellable;
    const char *                   permission;
    NMManagerDeviceAuthRequestFunc callback;
    NMAuthSubject *                subject;

    nm_assert(G_IS_DBUS_METHOD_INVOCATION(context));

    c_list_unlink(nm_auth_chain_parent_lst_list(chain));

    permission = nm_auth_chain_get_data(chain, "perm");
    nm_assert(permission);
    callback = nm_auth_chain_get_data(chain, "callback");
    nm_assert(callback);
    device = nm_auth_chain_get_data(chain, "device");
    nm_assert(NM_IS_DEVICE(device));

    cancellable = nm_auth_chain_get_cancellable(chain);
    nm_assert(!cancellable || G_IS_CANCELLABLE(cancellable));

    result  = nm_auth_chain_get_result(chain, permission);
    subject = nm_auth_chain_get_subject(chain);

    if (cancellable && g_cancellable_set_error_if_cancelled(cancellable, &error)) {
        /* pass. */
    } else {
        if (result != NM_AUTH_CALL_RESULT_YES) {
            _LOGD(LOGD_CORE, "%s request failed: not authorized", permission);
            error = g_error_new(NM_MANAGER_ERROR,
                                NM_MANAGER_ERROR_PERMISSION_DENIED,
                                "%s request failed: not authorized",
                                permission);
        }

        nm_assert(error || (result == NM_AUTH_CALL_RESULT_YES));
    }

    callback(device, context, subject, error, nm_auth_chain_get_data(chain, "user-data"));
}

static void
_device_auth_done_fail_on_idle(gpointer user_data, GCancellable *cancellable)
{
    gs_unref_object NMManager *self                = NULL;
    gs_unref_object NMDevice *device               = NULL;
    gs_unref_object GDBusMethodInvocation *context = NULL;
    gs_unref_object NMAuthSubject *subject         = NULL;
    gs_free_error GError *error_original           = NULL;
    gs_free_error GError *         error_cancelled = NULL;
    NMManagerDeviceAuthRequestFunc callback;
    gpointer                       callback_user_data;

    nm_utils_user_data_unpack(user_data,
                              &self,
                              &device,
                              &context,
                              &subject,
                              &error_original,
                              &callback,
                              &callback_user_data);

    g_cancellable_set_error_if_cancelled(cancellable, &error_cancelled);

    callback(device, context, subject, error_cancelled ?: error_original, callback_user_data);
}

void
nm_manager_device_auth_request(NMManager *                    self,
                               NMDevice *                     device,
                               GDBusMethodInvocation *        context,
                               NMConnection *                 connection,
                               const char *                   permission,
                               gboolean                       allow_interaction,
                               GCancellable *                 cancellable,
                               NMManagerDeviceAuthRequestFunc callback,
                               gpointer                       user_data)
{
    NMManagerPrivate *priv                 = NM_MANAGER_GET_PRIVATE(self);
    gs_free_error GError *error            = NULL;
    gs_unref_object NMAuthSubject *subject = NULL;
    NMAuthChain *                  chain;
    char *                         permission_dup;

    /* Validate the caller */
    subject = nm_dbus_manager_new_auth_subject_from_context(context);
    if (!subject) {
        g_set_error_literal(&error,
                            NM_MANAGER_ERROR,
                            NM_MANAGER_ERROR_PERMISSION_DENIED,
                            NM_UTILS_ERROR_MSG_REQ_UID_UKNOWN);
        goto fail_on_idle;
    }

    /* Ensure the subject has permissions for this connection */
    if (connection
        && !nm_auth_is_subject_in_acl_set_error(connection,
                                                subject,
                                                NM_MANAGER_ERROR,
                                                NM_MANAGER_ERROR_PERMISSION_DENIED,
                                                &error))
        goto fail_on_idle;

    chain = nm_auth_chain_new_subject(subject, context, device_auth_done_cb, self);
    if (cancellable)
        nm_auth_chain_set_cancellable(chain, cancellable);

    permission_dup = g_strdup(permission);

    c_list_link_tail(&priv->auth_lst_head, nm_auth_chain_parent_lst_list(chain));
    nm_auth_chain_set_data(chain, "device", g_object_ref(device), g_object_unref);
    nm_auth_chain_set_data(chain, "callback", callback, NULL);
    nm_auth_chain_set_data(chain, "user-data", user_data, NULL);
    nm_auth_chain_set_data(chain, "perm", permission_dup /* transfer ownership */, g_free);
    nm_auth_chain_add_call_unsafe(chain, permission_dup, allow_interaction);
    return;

fail_on_idle:
    nm_utils_invoke_on_idle(cancellable,
                            _device_auth_done_fail_on_idle,
                            nm_utils_user_data_pack(g_object_ref(self),
                                                    g_object_ref(device),
                                                    g_object_ref(context),
                                                    g_steal_pointer(&subject),
                                                    g_steal_pointer(&error),
                                                    callback,
                                                    user_data));
}

static gboolean
new_activation_allowed_for_connection(NMManager *self, NMSettingsConnection *connection)
{
    if (NM_IN_SET(
            _nm_connection_get_multi_connect(nm_settings_connection_get_connection(connection)),
            NM_CONNECTION_MULTI_CONNECT_MANUAL_MULTIPLE,
            NM_CONNECTION_MULTI_CONNECT_MULTIPLE))
        return TRUE;

    return !active_connection_find(self,
                                   connection,
                                   NULL,
                                   NM_ACTIVE_CONNECTION_STATE_ACTIVATED,
                                   NULL);
}

/**
 * get_existing_connection:
 * @manager: #NMManager instance
 * @device: #NMDevice instance
 * @out_generated: (allow-none): return TRUE, if the connection was generated.
 *
 * Returns: a #NMSettingsConnection to be assumed by the device, or %NULL if
 *   the device does not support assuming existing connections.
 */
static NMSettingsConnection *
get_existing_connection(NMManager *self, NMDevice *device, gboolean *out_generated)
{
    NMManagerPrivate *priv                   = NM_MANAGER_GET_PRIVATE(self);
    gs_unref_object NMConnection *connection = NULL;
    NMSettingsConnection *        added;
    GError *                      error                = NULL;
    gs_free_error GError *gen_error                    = NULL;
    NMDevice *            master                       = NULL;
    int                   ifindex                      = nm_device_get_ifindex(device);
    NMSettingsConnection *matched                      = NULL;
    NMSettingsConnection *connection_checked           = NULL;
    gboolean              assume_state_guess_assume    = FALSE;
    const char *          assume_state_connection_uuid = NULL;
    gboolean              maybe_later, only_by_uuid = FALSE;

    if (out_generated)
        *out_generated = FALSE;

    nm_device_capture_initial_config(device);

    if (ifindex) {
        int master_ifindex = nm_platform_link_get_master(priv->platform, ifindex);

        /* Check that the master is activating before assuming a
         * slave connection. However, ignore ovs-system master as
         * we never manage it.
         */
        if (master_ifindex
            && nm_platform_link_get_type(priv->platform, master_ifindex)
                   != NM_LINK_TYPE_OPENVSWITCH) {
            master = nm_manager_get_device_by_ifindex(self, master_ifindex);
            if (!master) {
                _LOG2D(LOGD_DEVICE,
                       device,
                       "assume: don't assume because "
                       "cannot generate connection for slave before its master (%s/%d)",
                       nm_platform_link_get_name(priv->platform, master_ifindex),
                       master_ifindex);
                return NULL;
            }
            if (!nm_device_get_act_request(master)) {
                _LOG2D(LOGD_DEVICE,
                       device,
                       "assume: don't assume because "
                       "cannot generate connection for slave before master %s activates",
                       nm_device_get_iface(master));
                return NULL;
            }
        }
    }

    /* The core of the API is nm_device_generate_connection() function and
     * update_connection() virtual method and the convenient connection_type
     * class attribute. Subclasses supporting the new API must have
     * update_connection() implemented, otherwise nm_device_generate_connection()
     * returns NULL.
     */
    connection = nm_device_generate_connection(device, master, &maybe_later, &gen_error);
    if (!connection) {
        if (maybe_later) {
            /* The device can generate a connection, but it failed for now.
             * Give it a chance to match a connection from the state file. */
            only_by_uuid = TRUE;
        } else {
            nm_device_assume_state_reset(device);
            _LOG2D(LOGD_DEVICE,
                   device,
                   "assume: cannot generate connection: %s",
                   gen_error->message);
            return NULL;
        }
    }

    nm_device_assume_state_get(device, &assume_state_guess_assume, &assume_state_connection_uuid);

    /* Now we need to compare the generated connection to each configured
     * connection. The comparison function is the heart of the connection
     * assumption implementation and it must compare the connections very
     * carefully to sort out various corner cases. Also, the comparison is
     * not entirely symmetric.
     *
     * When no configured connection matches the generated connection, we keep
     * the generated connection instead.
     */
    if (assume_state_connection_uuid
        && (connection_checked =
                nm_settings_get_connection_by_uuid(priv->settings, assume_state_connection_uuid))
        && new_activation_allowed_for_connection(self, connection_checked)
        && nm_device_check_connection_compatible(
            device,
            nm_settings_connection_get_connection(connection_checked),
            NULL)) {
        if (connection) {
            NMConnection *con = nm_settings_connection_get_connection(connection_checked);

            if (nm_utils_match_connection((NMConnection *[]){con, NULL},
                                          connection,
                                          TRUE,
                                          nm_device_has_carrier(device),
                                          nm_device_get_route_metric(device, AF_INET),
                                          nm_device_get_route_metric(device, AF_INET6),
                                          NULL,
                                          NULL))
                matched = connection_checked;
        } else
            matched = connection_checked;
    }

    if (!matched && only_by_uuid) {
        _LOG2D(LOGD_DEVICE, device, "assume: cannot generate connection: %s", gen_error->message);
        return NULL;
    }

    if (!matched && assume_state_guess_assume) {
        gs_free NMSettingsConnection **sett_conns = NULL;
        guint                          len, i, j;

        /* the state file doesn't indicate a connection UUID to assume. Search the
         * persistent connections for a matching candidate. */
        sett_conns = nm_manager_get_activatable_connections(self, FALSE, FALSE, &len);
        if (len > 0) {
            for (i = 0, j = 0; i < len; i++) {
                NMSettingsConnection *sett_conn = sett_conns[i];

                if (sett_conn != connection_checked
                    && nm_device_check_connection_compatible(
                        device,
                        nm_settings_connection_get_connection(sett_conn),
                        NULL))
                    sett_conns[j++] = sett_conn;
            }
            sett_conns[j] = NULL;
            len           = j;
            if (len > 0) {
                gs_free NMConnection **conns = NULL;
                NMConnection *         con;

                g_qsort_with_data(sett_conns,
                                  len,
                                  sizeof(sett_conns[0]),
                                  nm_settings_connection_cmp_timestamp_p_with_data,
                                  NULL);

                conns = nm_settings_connections_array_to_connections(sett_conns, len);

                con = nm_utils_match_connection(conns,
                                                connection,
                                                FALSE,
                                                nm_device_has_carrier(device),
                                                nm_device_get_route_metric(device, AF_INET),
                                                nm_device_get_route_metric(device, AF_INET6),
                                                NULL,
                                                NULL);
                if (con) {
                    for (i = 0; i < len; i++) {
                        if (conns[i] == con) {
                            matched = sett_conns[i];
                            break;
                        }
                    }
                    nm_assert(matched);
                }
            }
        }
    }

    if (matched) {
        if (NM_FLAGS_HAS(nm_settings_connection_get_flags(matched),
                         NM_SETTINGS_CONNECTION_INT_FLAGS_EXTERNAL)) {
            _LOG2D(LOGD_DEVICE,
                   device,
                   "assume: take over previous connection '%s' (%s)",
                   nm_settings_connection_get_id(matched),
                   nm_settings_connection_get_uuid(matched));
            NM_SET_OUT(out_generated, TRUE);
        } else {
            _LOG2I(LOGD_DEVICE,
                   device,
                   "assume: will attempt to assume matching connection '%s' (%s)%s",
                   nm_settings_connection_get_id(matched),
                   nm_settings_connection_get_uuid(matched),
                   assume_state_connection_uuid
                           && nm_streq(assume_state_connection_uuid,
                                       nm_settings_connection_get_uuid(matched))
                       ? " (indicated)"
                       : " (guessed)");
        }
        nm_device_assume_state_reset(device);
        return matched;
    }

    _LOG2D(LOGD_DEVICE,
           device,
           "assume: generated connection '%s' (%s)",
           nm_connection_get_id(connection),
           nm_connection_get_uuid(connection));

    nm_device_assume_state_reset(device);

    if (!nm_settings_add_connection(priv->settings,
                                    connection,
                                    NM_SETTINGS_CONNECTION_PERSIST_MODE_IN_MEMORY_ONLY,
                                    NM_SETTINGS_CONNECTION_ADD_REASON_NONE,
                                    NM_SETTINGS_CONNECTION_INT_FLAGS_NM_GENERATED
                                        | NM_SETTINGS_CONNECTION_INT_FLAGS_VOLATILE
                                        | NM_SETTINGS_CONNECTION_INT_FLAGS_EXTERNAL,
                                    &added,
                                    &error)) {
        _LOG2W(LOGD_SETTINGS,
               device,
               "assume: failure to save generated connection '%s': %s",
               nm_connection_get_id(connection),
               error->message);
        g_error_free(error);
        return NULL;
    }

    NM_SET_OUT(out_generated, TRUE);
    return added;
}

static gboolean
copy_lease(const char *src, const char *dst)
{
    nm_auto_close int src_fd = -1;
    int               dst_fd;
    ssize_t           res, size = SSIZE_MAX;

    src_fd = open(src, O_RDONLY | O_CLOEXEC);
    if (src_fd < 0)
        return FALSE;

    dst_fd = open(dst, O_CREAT | O_EXCL | O_CLOEXEC | O_WRONLY, 0644);
    if (dst_fd < 0)
        return FALSE;

    while ((res = sendfile(dst_fd, src_fd, NULL, size)) > 0)
        size -= res;

    nm_close(dst_fd);

    if (res != 0) {
        unlink(dst);
        return FALSE;
    }

    return TRUE;
}

static gboolean
recheck_assume_connection(NMManager *self, NMDevice *device)
{
    NMSettingsConnection *sett_conn;
    gboolean              was_unmanaged = FALSE;
    gboolean              generated     = FALSE;
    NMDeviceState         state;
    gboolean              activation_type_assume;

    g_return_val_if_fail(NM_IS_MANAGER(self), FALSE);
    g_return_val_if_fail(NM_IS_DEVICE(device), FALSE);

    if (!nm_device_get_managed(device, FALSE)) {
        nm_device_assume_state_reset(device);
        _LOG2D(LOGD_DEVICE, device, "assume: don't assume because %s", "not managed");
        return FALSE;
    }

    state = nm_device_get_state(device);
    if (state > NM_DEVICE_STATE_DISCONNECTED) {
        nm_device_assume_state_reset(device);
        _LOG2D(LOGD_DEVICE,
               device,
               "assume: don't assume due to device state %s",
               nm_device_state_to_str(state));
        return FALSE;
    }

    sett_conn = get_existing_connection(self, device, &generated);
    /* log  no reason. get_existing_connection() already does it. */
    if (!sett_conn)
        return FALSE;

    activation_type_assume = !generated;

    if (state == NM_DEVICE_STATE_UNMANAGED) {
        gs_free char *initramfs_lease =
            g_strdup_printf(RUNSTATEDIR "/initramfs/net.%s.lease", nm_device_get_iface(device));
        gs_free char *connection_lease = g_strdup_printf(NMRUNDIR "/dhclient-%s-%s.lease",
                                                         nm_settings_connection_get_uuid(sett_conn),
                                                         nm_device_get_iface(device));

        if (copy_lease(initramfs_lease, connection_lease)) {
            unlink(initramfs_lease);
            /*
             * We've managed to steal the lease used by initramfs before it
             * killed off the dhclient. We need to take ownership of the configured
             * connection and act like the device was configured by us.
             * Otherwise, the address would just expire.
             */
            _LOG2I(LOGD_DEVICE, device, "assume: taking over an initramfs-configured connection");
            activation_type_assume = TRUE;

            if (generated) {
                /* Reset the IPv4 setting to empty method=auto, regardless of what assumption guessed. */
                nm_connection_add_setting(nm_settings_connection_get_connection(sett_conn),
                                          g_object_new(NM_TYPE_SETTING_IP4_CONFIG,
                                                       NM_SETTING_IP_CONFIG_METHOD,
                                                       NM_SETTING_IP4_CONFIG_METHOD_AUTO,
                                                       NULL));

                nm_settings_connection_update(sett_conn,
                                              NULL,
                                              NM_SETTINGS_CONNECTION_PERSIST_MODE_KEEP,
                                              NM_SETTINGS_CONNECTION_INT_FLAGS_NONE,
                                              NM_SETTINGS_CONNECTION_INT_FLAGS_VOLATILE
                                                  | NM_SETTINGS_CONNECTION_INT_FLAGS_EXTERNAL,
                                              NM_SETTINGS_CONNECTION_UPDATE_REASON_NONE,
                                              "assume-initrd",
                                              NULL);
            }
        }
    }

    nm_device_sys_iface_state_set(device,
                                  activation_type_assume ? NM_DEVICE_SYS_IFACE_STATE_ASSUME
                                                         : NM_DEVICE_SYS_IFACE_STATE_EXTERNAL);

    /* Move device to DISCONNECTED to activate the connection */
    if (state == NM_DEVICE_STATE_UNMANAGED) {
        was_unmanaged = TRUE;
        nm_device_state_changed(device,
                                NM_DEVICE_STATE_UNAVAILABLE,
                                NM_DEVICE_STATE_REASON_CONNECTION_ASSUMED);
    }
    if (nm_device_get_state(device) == NM_DEVICE_STATE_UNAVAILABLE) {
        nm_device_state_changed(device,
                                NM_DEVICE_STATE_DISCONNECTED,
                                NM_DEVICE_STATE_REASON_CONNECTION_ASSUMED);
    }

    g_return_val_if_fail(nm_device_get_state(device) >= NM_DEVICE_STATE_DISCONNECTED, FALSE);

    {
        gs_unref_object NMActiveConnection *active = NULL;
        gs_unref_object NMAuthSubject *subject     = NULL;
        NMActiveConnection *           master_ac;
        GError *                       error = NULL;

        subject = nm_auth_subject_new_internal();

        /* Note: the lifetime of the activation connection is always bound to the profiles visibility
         * via NM_ACTIVATION_STATE_FLAG_LIFETIME_BOUND_TO_PROFILE_VISIBILITY.
         *
         * This only makes a difference, if the profile actually has "connection.permissions"
         * set to limit visibility (which is not the case for externally managed, generated profiles).
         *
         * If we assume a previously active connection whose lifetime was unbound, we now bind it
         * after restart. That is not correct, and can mean that the profile becomes subject to
         * deactivation after restart (if the user logs out).
         *
         * This should be improved, but it's unclear how. */
        active = _new_active_connection(
            self,
            FALSE,
            sett_conn,
            NULL,
            NULL,
            NULL,
            device,
            subject,
            activation_type_assume ? NM_ACTIVATION_TYPE_ASSUME : NM_ACTIVATION_TYPE_EXTERNAL,
            activation_type_assume ? NM_ACTIVATION_REASON_ASSUME : NM_ACTIVATION_REASON_EXTERNAL,
            NM_ACTIVATION_STATE_FLAG_LIFETIME_BOUND_TO_PROFILE_VISIBILITY,
            &error);

        if (!active) {
            _LOGW(LOGD_DEVICE,
                  "assume: assumed connection %s failed to activate: %s",
                  nm_dbus_object_get_path(NM_DBUS_OBJECT(sett_conn)),
                  error->message);
            g_error_free(error);

            if (was_unmanaged) {
                nm_device_state_changed(device,
                                        NM_DEVICE_STATE_UNAVAILABLE,
                                        NM_DEVICE_STATE_REASON_CONFIG_FAILED);
            }

            if (generated && !activation_type_assume) {
                _LOG2D(LOGD_DEVICE,
                       device,
                       "assume: deleting generated connection after assuming failed");
                nm_settings_connection_delete(sett_conn, FALSE);
            } else {
                if (nm_device_sys_iface_state_get(device) == NM_DEVICE_SYS_IFACE_STATE_ASSUME)
                    nm_device_sys_iface_state_set(device, NM_DEVICE_SYS_IFACE_STATE_EXTERNAL);
            }
            return FALSE;
        }

        /* If the device is a slave or VLAN, find the master ActiveConnection */
        master_ac = NULL;
        if (find_master(self,
                        nm_settings_connection_get_connection(sett_conn),
                        device,
                        NULL,
                        NULL,
                        &master_ac,
                        NULL)
            && master_ac)
            nm_active_connection_set_master(active, master_ac);

        active_connection_add(self, active);
        nm_device_queue_activation(device, NM_ACT_REQUEST(active));
    }

    return TRUE;
}

static void
recheck_assume_connection_cb(NMManager *self, NMDevice *device)
{
    recheck_assume_connection(self, device);
}

static void
device_ifindex_changed(NMDevice *device, GParamSpec *pspec, NMManager *self)
{
    _parent_notify_changed(self, device, FALSE);
}

static void
device_ip_iface_changed(NMDevice *device, GParamSpec *pspec, NMManager *self)
{
    NMManagerPrivate *priv        = NM_MANAGER_GET_PRIVATE(self);
    const char *      ip_iface    = nm_device_get_ip_iface(device);
    NMDeviceType      device_type = nm_device_get_device_type(device);
    NMDevice *        candidate;

    /* Remove NMDevice objects that are actually child devices of others,
     * when the other device finally knows its IP interface name.  For example,
     * remove the PPP interface that's a child of a WWAN device, since it's
     * not really a standalone NMDevice.
     */
    c_list_for_each_entry (candidate, &priv->devices_lst_head, devices_lst) {
        if (candidate != device && nm_streq0(nm_device_get_iface(candidate), ip_iface)
            && nm_device_get_device_type(candidate) == device_type
            && nm_device_is_real(candidate)) {
            remove_device(self, candidate, FALSE);
            break;
        }
    }
}

static void
device_iface_changed(NMDevice *device, GParamSpec *pspec, NMManager *self)
{
    /* Virtual connections may refer to the new device name as
     * parent device, retry to activate them.
     */
    retry_connections_for_parent_device(self, device);
}

static void
_emit_device_added_removed(NMManager *self, NMDevice *device, gboolean is_added)
{
    nm_dbus_object_emit_signal(NM_DBUS_OBJECT(self),
                               &interface_info_manager,
                               is_added ? &signal_info_device_added : &signal_info_device_removed,
                               "(o)",
                               nm_dbus_object_get_path(NM_DBUS_OBJECT(device)));
    g_signal_emit(self, signals[is_added ? DEVICE_ADDED : DEVICE_REMOVED], 0, device);
    _notify(self, PROP_DEVICES);
}

static void
device_realized(NMDevice *device, GParamSpec *pspec, NMManager *self)
{
    _emit_device_added_removed(self, device, nm_device_is_real(device));
}

static NMConnectivityState
_get_best_connectivity(NMManager *self, int addr_family)
{
    NMManagerPrivate *  priv = NM_MANAGER_GET_PRIVATE(self);
    NMConnectivityState best_state;
    NMDevice *          dev;
    gint64              best_metric;

    if (addr_family == AF_UNSPEC) {
        best_state = _get_best_connectivity(self, AF_INET);
        if (nm_connectivity_state_cmp(best_state, NM_CONNECTIVITY_FULL) >= 0) {
            /* already FULL IPv4 connectivity. No need to check IPv6, it doesn't get
             * better. */
            return best_state;
        }
        return NM_MAX_WITH_CMP(nm_connectivity_state_cmp,
                               best_state,
                               _get_best_connectivity(self, AF_INET6));
    }

    nm_assert_addr_family(addr_family);

    best_state  = NM_CONNECTIVITY_UNKNOWN;
    best_metric = G_MAXINT64;
    c_list_for_each_entry (dev, &priv->devices_lst_head, devices_lst) {
        const NMPObject *   r;
        NMConnectivityState state;
        gint64              metric;

        r = nm_device_get_best_default_route(dev, addr_family);
        if (r)
            metric = NMP_OBJECT_CAST_IP_ROUTE(r)->metric;
        else {
            /* if all devices have no default-route, we still include the best
             * of all connectivity state of all the devices. */
            metric = G_MAXINT64;
        }

        if (metric > best_metric) {
            /* we already have a default route with better metric. The connectivity state
             * of this device is irreleavnt. */
            continue;
        }

        state = nm_device_get_connectivity_state(dev, addr_family);
        if (metric < best_metric) {
            /* this device has a better default route. It wins. */
            best_metric = metric;
            best_state  = state;
        } else {
            best_state = NM_MAX_WITH_CMP(nm_connectivity_state_cmp, best_state, state);
        }

        if (nm_connectivity_state_cmp(best_state, NM_CONNECTIVITY_FULL) >= 0) {
            /* it doesn't get better than FULL. We are done. */
            break;
        }
    }

    return best_state;
}

static void
device_connectivity_changed(NMDevice *device, GParamSpec *pspec, NMManager *self)
{
    update_connectivity_value(self);
}

static void
update_connectivity_value(NMManager *self)
{
    NMManagerPrivate *  priv = NM_MANAGER_GET_PRIVATE(self);
    NMConnectivityState best_state;

    best_state = _get_best_connectivity(self, AF_UNSPEC);
    if (best_state == priv->connectivity_state)
        return;

    priv->connectivity_state = best_state;

    _LOGD(LOGD_CORE,
          "connectivity checking indicates %s",
          nm_connectivity_state_to_string(priv->connectivity_state));

    nm_manager_update_state(self);
    _notify(self, PROP_CONNECTIVITY);
    nm_dispatcher_call_connectivity(priv->connectivity_state, NULL, NULL, NULL);
}

static void
_device_realize_finish(NMManager *self, NMDevice *device, const NMPlatformLink *plink)
{
    g_return_if_fail(NM_IS_MANAGER(self));
    g_return_if_fail(NM_IS_DEVICE(device));

    nm_device_realize_finish(device, plink);

    if (!nm_device_get_managed(device, FALSE)) {
        nm_device_assume_state_reset(device);
        return;
    }

    if (recheck_assume_connection(self, device))
        return;

    /* if we failed to assume a connection for the managed device, but the device
     * is still unavailable. Set UNAVAILABLE state again, this time with NOW_MANAGED. */
    nm_device_state_changed(device,
                            NM_DEVICE_STATE_UNAVAILABLE,
                            NM_DEVICE_STATE_REASON_NOW_MANAGED);
    nm_device_emit_recheck_auto_activate(device);
}

/**
 * add_device:
 * @self: the #NMManager
 * @device: the #NMDevice to add
 * @error: (out): the #GError
 *
 * If successful, this function will increase the references count of @device.
 * Callers should decrease the reference count.
 */
static gboolean
add_device(NMManager *self, NMDevice *device, GError **error)
{
    NMManagerPrivate *priv = NM_MANAGER_GET_PRIVATE(self);
    const char *      iface, *type_desc;
    RfKillType        rtype;
    GSList *          iter, *remove = NULL;
    int               ifindex;
    const char *      dbus_path;
    NMDevice *        candidate;

    /* No duplicates */
    ifindex = nm_device_get_ifindex(device);
    if (ifindex > 0 && nm_manager_get_device_by_ifindex(self, ifindex)) {
        g_set_error(error,
                    NM_MANAGER_ERROR,
                    NM_MANAGER_ERROR_FAILED,
                    "A device with ifindex %d already exists",
                    ifindex);
        return FALSE;
    }

    /* Remove existing devices owned by the new device; eg remove ethernet
     * ports that are owned by a WWAN modem, since udev may announce them
     * before the modem is fully discovered.
     *
     * FIXME: use parent/child device relationships instead of removing
     * the child NMDevice entirely
     */
    c_list_for_each_entry (candidate, &priv->devices_lst_head, devices_lst) {
        if (nm_device_is_real(candidate) && (iface = nm_device_get_ip_iface(candidate))
            && nm_device_owns_iface(device, iface))
            remove = g_slist_prepend(remove, candidate);
    }
    for (iter = remove; iter; iter = iter->next)
        remove_device(self, NM_DEVICE(iter->data), FALSE);
    g_slist_free(remove);

    g_object_ref(device);

    nm_assert(c_list_is_empty(&device->devices_lst));
    c_list_link_tail(&priv->devices_lst_head, &device->devices_lst);

    g_signal_connect(device,
                     NM_DEVICE_STATE_CHANGED,
                     G_CALLBACK(manager_device_state_changed),
                     self);

    g_signal_connect(device, NM_DEVICE_REMOVED, G_CALLBACK(device_removed_cb), self);

    g_signal_connect_data(device,
                          NM_DEVICE_RECHECK_ASSUME,
                          G_CALLBACK(recheck_assume_connection_cb),
                          self,
                          NULL,
                          G_CONNECT_SWAPPED);

    g_signal_connect(device,
                     "notify::" NM_DEVICE_IP_IFACE,
                     G_CALLBACK(device_ip_iface_changed),
                     self);

    g_signal_connect(device,
                     "notify::" NM_DEVICE_IFINDEX,
                     G_CALLBACK(device_ifindex_changed),
                     self);

    g_signal_connect(device, "notify::" NM_DEVICE_IFACE, G_CALLBACK(device_iface_changed), self);

    g_signal_connect(device, "notify::" NM_DEVICE_REAL, G_CALLBACK(device_realized), self);

    g_signal_connect(device,
                     "notify::" NM_DEVICE_IP4_CONNECTIVITY,
                     G_CALLBACK(device_connectivity_changed),
                     self);
    g_signal_connect(device,
                     "notify::" NM_DEVICE_IP6_CONNECTIVITY,
                     G_CALLBACK(device_connectivity_changed),
                     self);

    if (priv->startup) {
        g_signal_connect(device,
                         "notify::" NM_DEVICE_HAS_PENDING_ACTION,
                         G_CALLBACK(device_has_pending_action_changed),
                         self);
    }

    /* Update global rfkill state for this device type with the device's
     * rfkill state, and then set this device's rfkill state based on the
     * global state.
     */
    rtype = nm_device_get_rfkill_type(device);
    if (rtype != RFKILL_TYPE_UNKNOWN) {
        nm_manager_rfkill_update(self, rtype);
        nm_device_set_enabled(device, radio_enabled_for_type(self, rtype, TRUE));
    }

    iface = nm_device_get_iface(device);
    g_assert(iface);
    type_desc = nm_device_get_type_desc(device);
    g_assert(type_desc);

    nm_device_set_unmanaged_by_user_settings(device);

    nm_device_set_unmanaged_flags(device, NM_UNMANAGED_SLEEPING, manager_sleeping(self));

    dbus_path = nm_dbus_object_export(NM_DBUS_OBJECT(device));
    _LOG2I(LOGD_DEVICE, device, "new %s device (%s)", type_desc, dbus_path);

    nm_settings_device_added(priv->settings, device);
    g_signal_emit(self, signals[INTERNAL_DEVICE_ADDED], 0, device);
    _notify(self, PROP_ALL_DEVICES);

    _parent_notify_changed(self, device, FALSE);

    return TRUE;
}

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

static void
factory_device_added_cb(NMDeviceFactory *factory, NMDevice *device, gpointer user_data)
{
    NMManager *self  = user_data;
    GError *   error = NULL;

    g_return_if_fail(NM_IS_MANAGER(self));

    if (nm_device_realize_start(device,
                                NULL,
                                FALSE, /* assume_state_guess_assume */
                                NULL,  /* assume_state_connection_uuid */
                                FALSE, /* set_nm_owned */
                                NM_UNMAN_FLAG_OP_FORGET,
                                NULL,
                                &error)) {
        add_device(self, device, NULL);
        _device_realize_finish(self, device, NULL);
        retry_connections_for_parent_device(self, device);
    } else {
        _LOG2W(LOGD_DEVICE, device, "failed to realize device: %s", error->message);
        g_error_free(error);
    }
}

static void
_register_device_factory(NMDeviceFactory *factory, gpointer user_data)
{
    NMManager *self = NM_MANAGER(user_data);

    g_signal_connect(factory,
                     NM_DEVICE_FACTORY_DEVICE_ADDED,
                     G_CALLBACK(factory_device_added_cb),
                     self);
}

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

void
nm_manager_notify_device_availability_maybe_changed(NMManager *self)
{
    NMManagerPrivate *priv = NM_MANAGER_GET_PRIVATE(self);
    NMDevice *        device;

    c_list_for_each_entry (device, &priv->devices_lst_head, devices_lst)
        nm_device_notify_availability_maybe_changed(device);
}

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

static void
platform_link_added(NMManager *                    self,
                    int                            ifindex,
                    const NMPlatformLink *         plink,
                    gboolean                       guess_assume,
                    const NMConfigDeviceStateData *dev_state)
{
    NMManagerPrivate *priv = NM_MANAGER_GET_PRIVATE(self);
    NMDeviceFactory * factory;
    NMDevice *        device = NULL;
    NMDevice *        candidate;

    g_return_if_fail(ifindex > 0);

    if (nm_manager_get_device_by_ifindex(self, ifindex))
        return;

    /* Let unrealized devices try to realize themselves with the link */
    c_list_for_each_entry (candidate, &priv->devices_lst_head, devices_lst) {
        gboolean      compatible    = TRUE;
        gs_free_error GError *error = NULL;

        if (nm_device_get_link_type(candidate) != plink->type)
            continue;

        if (!nm_streq(nm_device_get_iface(candidate), plink->name))
            continue;

        if (nm_device_is_real(candidate)) {
            /* There's already a realized device with the link's name
             * and a different ifindex.
             */
            if (nm_device_get_ifindex(candidate) <= 0)
                nm_device_update_from_platform_link(candidate, plink);
            else {
                /* The ifindex of a device can't be changed after
                 * initialization because it is used as a key by
                 * the dns-manager.
                 */
                _LOGD(LOGD_DEVICE,
                      "(%s): removing old device %p after ifindex change from %d to %d",
                      plink->name,
                      candidate,
                      nm_device_get_ifindex(candidate),
                      ifindex);
                remove_device(self, candidate, FALSE);
                goto add;
            }
            return;
        } else if (nm_device_realize_start(candidate,
                                           plink,
                                           FALSE, /* assume_state_guess_assume */
                                           NULL,  /* assume_state_connection_uuid */
                                           FALSE, /* set_nm_owned */
                                           NM_UNMAN_FLAG_OP_FORGET,
                                           &compatible,
                                           &error)) {
            _device_realize_finish(self, candidate, plink);
            return;
        }

        _LOGD(LOGD_DEVICE, "(%s): failed to realize from plink: '%s'", plink->name, error->message);

        /* Try next unrealized device */
    }

add:
    /* Try registered device factories */
    factory = nm_device_factory_manager_find_factory_for_link_type(plink->type);
    if (factory) {
        gboolean      ignore        = FALSE;
        gs_free_error GError *error = NULL;

        device =
            nm_device_factory_create_device(factory, plink->name, plink, NULL, &ignore, &error);
        if (!device) {
            if (!ignore) {
                _LOGW(LOGD_PLATFORM,
                      "%s: factory failed to create device: %s",
                      plink->name,
                      error->message);
            } else {
                _LOGD(LOGD_PLATFORM,
                      "%s: factory failed to create device: %s",
                      plink->name,
                      error->message);
            }
            return;
        }
    }

    if (device == NULL) {
        gboolean nm_plugin_missing = FALSE;

        switch (plink->type) {
        case NM_LINK_TYPE_WWAN_NET:
        case NM_LINK_TYPE_BNEP:
        case NM_LINK_TYPE_OLPC_MESH:
        case NM_LINK_TYPE_TEAM:
        case NM_LINK_TYPE_WIFI:
            _LOGI(LOGD_PLATFORM,
                  "(%s): '%s' plugin not available; creating generic device",
                  plink->name,
                  nm_link_type_to_string(plink->type));
            nm_plugin_missing = TRUE;
            /* fall-through */
        default:
            device = nm_device_generic_new(plink, nm_plugin_missing);
            break;
        }
    }

    if (device) {
        gs_free_error GError *error                   = NULL;
        NMUnmanFlagOp         unmanaged_user_explicit = NM_UNMAN_FLAG_OP_FORGET;

        if (dev_state) {
            switch (dev_state->managed) {
            case NM_CONFIG_DEVICE_STATE_MANAGED_TYPE_MANAGED:
                unmanaged_user_explicit = NM_UNMAN_FLAG_OP_SET_MANAGED;
                break;
            case NM_CONFIG_DEVICE_STATE_MANAGED_TYPE_UNMANAGED:
                unmanaged_user_explicit = NM_UNMAN_FLAG_OP_SET_UNMANAGED;
                break;
            case NM_CONFIG_DEVICE_STATE_MANAGED_TYPE_UNKNOWN:
                break;
            }
        }

        if (nm_device_realize_start(device,
                                    plink,
                                    guess_assume,
                                    dev_state ? dev_state->connection_uuid : NULL,
                                    dev_state ? (dev_state->nm_owned == 1) : FALSE,
                                    unmanaged_user_explicit,
                                    NULL,
                                    &error)) {
            add_device(self, device, NULL);
            _device_realize_finish(self, device, plink);
            retry_connections_for_parent_device(self, device);
        } else {
            _LOGW(LOGD_DEVICE, "%s: failed to realize device: %s", plink->name, error->message);
        }
        g_object_unref(device);
    }
}

typedef struct {
    CList      lst;
    NMManager *self;
    int        ifindex;
    guint      idle_id;
} PlatformLinkCbData;

static gboolean
_platform_link_cb_idle(PlatformLinkCbData *data)
{
    int                   ifindex = data->ifindex;
    NMManager *           self    = data->self;
    NMManagerPrivate *    priv    = NM_MANAGER_GET_PRIVATE(self);
    const NMPlatformLink *plink;

    c_list_unlink_stale(&data->lst);
    g_slice_free(PlatformLinkCbData, data);

    plink = nm_platform_link_get(priv->platform, ifindex);
    if (plink) {
        const NMPObject *plink_keep_alive = nmp_object_ref(NMP_OBJECT_UP_CAST(plink));

        platform_link_added(self, ifindex, plink, FALSE, NULL);
        nmp_object_unref(plink_keep_alive);
    } else {
        NMDevice *device;
        GError *  error = NULL;

        device = nm_manager_get_device_by_ifindex(self, ifindex);
        if (device) {
            if (nm_device_is_software(device)) {
                nm_device_sys_iface_state_set(device, NM_DEVICE_SYS_IFACE_STATE_REMOVED);
                /* Our software devices stick around until their connection is removed */
                if (!nm_device_unrealize(device, FALSE, &error)) {
                    _LOG2W(LOGD_DEVICE, device, "failed to unrealize: %s", error->message);
                    g_clear_error(&error);
                    remove_device(self, device, FALSE);
                } else {
                    nm_device_update_from_platform_link(device, NULL);
                }
            } else {
                /* Hardware and external devices always get removed when their kernel link is gone */
                remove_device(self, device, FALSE);
            }
        }
    }

    return G_SOURCE_REMOVE;
}

static void
platform_link_cb(NMPlatform *    platform,
                 int             obj_type_i,
                 int             ifindex,
                 NMPlatformLink *plink,
                 int             change_type_i,
                 gpointer        user_data)
{
    NMManager *                      self;
    NMManagerPrivate *               priv;
    const NMPlatformSignalChangeType change_type = change_type_i;
    PlatformLinkCbData *             data;

    switch (change_type) {
    case NM_PLATFORM_SIGNAL_ADDED:
    case NM_PLATFORM_SIGNAL_REMOVED:
        self = NM_MANAGER(user_data);
        priv = NM_MANAGER_GET_PRIVATE(self);

        data          = g_slice_new(PlatformLinkCbData);
        data->self    = self;
        data->ifindex = ifindex;
        c_list_link_tail(&priv->link_cb_lst, &data->lst);
        data->idle_id = g_idle_add((GSourceFunc) _platform_link_cb_idle, data);
        break;
    default:
        break;
    }
}

static void
platform_query_devices(NMManager *self)
{
    NMManagerPrivate *priv             = NM_MANAGER_GET_PRIVATE(self);
    gs_unref_ptrarray GPtrArray *links = NULL;
    int                          i;
    gboolean                     guess_assume;
    gs_free char *               order = NULL;

    guess_assume = nm_config_get_first_start(nm_config_get());
    order        = nm_config_data_get_value(NM_CONFIG_GET_DATA,
                                     NM_CONFIG_KEYFILE_GROUP_MAIN,
                                     NM_CONFIG_KEYFILE_KEY_MAIN_SLAVES_ORDER,
                                     NM_CONFIG_GET_VALUE_STRIP);
    links        = nm_platform_link_get_all(priv->platform, !nm_streq0(order, "index"));
    if (!links)
        return;
    for (i = 0; i < links->len; i++) {
        const NMPlatformLink *         link = NMP_OBJECT_CAST_LINK(links->pdata[i]);
        const NMConfigDeviceStateData *dev_state;

        dev_state = nm_config_device_state_get(priv->config, link->ifindex);
        platform_link_added(self,
                            link->ifindex,
                            link,
                            guess_assume && (!dev_state || !dev_state->connection_uuid),
                            dev_state);
    }
}

static void
rfkill_manager_rfkill_changed_cb(NMRfkillManager *rfkill_mgr,
                                 RfKillType       rtype,
                                 RfKillState      udev_state,
                                 gpointer         user_data)
{
    nm_manager_rfkill_update(NM_MANAGER(user_data), rtype);
}

const CList *
nm_manager_get_devices(NMManager *manager)
{
    g_return_val_if_fail(NM_IS_MANAGER(manager), NULL);

    return &NM_MANAGER_GET_PRIVATE(manager)->devices_lst_head;
}

typedef enum {
    DEVICE_ACTIVATION_PRIO_NONE,
    DEVICE_ACTIVATION_PRIO_UNMANAGED,
    DEVICE_ACTIVATION_PRIO_UNAVAILABLE,
    DEVICE_ACTIVATION_PRIO_DEACTIVATING,
    DEVICE_ACTIVATION_PRIO_ACTIVATING,
    DEVICE_ACTIVATION_PRIO_ACTIVATED,
    DEVICE_ACTIVATION_PRIO_DISCONNECTED,

    _DEVICE_ACTIVATION_PRIO_BEST = DEVICE_ACTIVATION_PRIO_DISCONNECTED,
} DeviceActivationPrio;

static DeviceActivationPrio
_device_get_activation_prio(NMDevice *device)
{
    if (!nm_device_get_managed(device, TRUE))
        return DEVICE_ACTIVATION_PRIO_NONE;

    switch (nm_device_get_state(device)) {
    case NM_DEVICE_STATE_DISCONNECTED:
        return DEVICE_ACTIVATION_PRIO_DISCONNECTED;
    case NM_DEVICE_STATE_ACTIVATED:
        return DEVICE_ACTIVATION_PRIO_ACTIVATED;
    case NM_DEVICE_STATE_PREPARE:
    case NM_DEVICE_STATE_CONFIG:
    case NM_DEVICE_STATE_NEED_AUTH:
    case NM_DEVICE_STATE_IP_CONFIG:
    case NM_DEVICE_STATE_IP_CHECK:
    case NM_DEVICE_STATE_SECONDARIES:
        return DEVICE_ACTIVATION_PRIO_ACTIVATING;
    case NM_DEVICE_STATE_DEACTIVATING:
    case NM_DEVICE_STATE_FAILED:
        return DEVICE_ACTIVATION_PRIO_DEACTIVATING;
    case NM_DEVICE_STATE_UNAVAILABLE:
        return DEVICE_ACTIVATION_PRIO_UNAVAILABLE;
    case NM_DEVICE_STATE_UNKNOWN:
    case NM_DEVICE_STATE_UNMANAGED:
        return DEVICE_ACTIVATION_PRIO_UNMANAGED;
    }

    g_return_val_if_reached(DEVICE_ACTIVATION_PRIO_UNAVAILABLE);
}

static NMDevice *
nm_manager_get_best_device_for_connection(NMManager *           self,
                                          NMSettingsConnection *sett_conn,
                                          NMConnection *        connection,
                                          gboolean              for_user_request,
                                          GHashTable *          unavailable_devices,
                                          GError **             error)
{
    NMManagerPrivate *      priv = NM_MANAGER_GET_PRIVATE(self);
    NMActiveConnectionState ac_state;
    NMActiveConnection *    ac;
    NMDevice *              ac_device;
    NMDevice *              device;
    struct {
        NMDevice *           device;
        DeviceActivationPrio prio;
    } best = {
        .device = NULL,
        .prio   = DEVICE_ACTIVATION_PRIO_NONE,
    };
    NMDeviceCheckConAvailableFlags flags;
    gs_unref_ptrarray GPtrArray *all_ac_arr = NULL;
    gs_free_error GError *   local_best     = NULL;
    NMConnectionMultiConnect multi_connect;

    nm_assert(!sett_conn || NM_IS_SETTINGS_CONNECTION(sett_conn));
    nm_assert(!connection || NM_IS_CONNECTION(connection));
    nm_assert(sett_conn || connection);
    nm_assert(!connection || !sett_conn
              || connection == nm_settings_connection_get_connection(sett_conn));

    if (!connection)
        connection = nm_settings_connection_get_connection(sett_conn);

    multi_connect = _nm_connection_get_multi_connect(connection);

    if (!for_user_request)
        flags = NM_DEVICE_CHECK_CON_AVAILABLE_NONE;
    else {
        /* if the profile is multi-connect=single, we also consider devices which
         * are marked as unmanaged. And explicit user-request shows sufficient user
         * intent to make the device managed.
         * That is also, because we expect that such profile is suitably tied
         * to the intended device. So when an unmanaged device matches, the user's
         * intent is clear.
         *
         * For multi-connect != single devices that is different. The profile
         * is not restricted to a particular device.
         * For that reason, plain `nmcli connection up "$MULIT_PROFILE"` seems
         * less suitable for multi-connect profiles, because the target device is
         * left unspecified. Anyway, if a user issues
         *
         *   $ nmcli device set "$DEVICE" managed no
         *   $ nmcli connection up "$MULIT_PROFILE"
         *
         * then it is reasonable for multi-connect profiles to not consider
         * the device a suitable candidate.
         *
         * This may be seen inconsistent, but I think that it makes a lot of
         * sense. Also note that "connection.multi-connect" work quite differently
         * in aspects like activation. E.g. `nmcli connection up` of multi-connect
         * "single" profile, will deactivate the profile if it is active already.
         * That is different from multi-connect profiles, where it will aim to
         * activate the profile one more time on an hitherto disconnected device.
         */
        if (multi_connect == NM_CONNECTION_MULTI_CONNECT_SINGLE)
            flags = NM_DEVICE_CHECK_CON_AVAILABLE_FOR_USER_REQUEST;
        else
            flags = NM_DEVICE_CHECK_CON_AVAILABLE_FOR_USER_REQUEST
                    & ~_NM_DEVICE_CHECK_CON_AVAILABLE_FOR_USER_REQUEST_OVERRULE_UNMANAGED;
    }

    if (multi_connect == NM_CONNECTION_MULTI_CONNECT_SINGLE
        && (ac = active_connection_find_by_connection(self,
                                                      sett_conn,
                                                      connection,
                                                      NM_ACTIVE_CONNECTION_STATE_DEACTIVATING,
                                                      &all_ac_arr))) {
        /* if we have a profile which may activate on only one device (multi-connect single), then
         * we prefer the device on which the profile is already active. It means to reactivate
         * the profile on the same device.
         *
         * If the profile can be activated on multiple devices, we don't do this. In fact, the
         * check below for the DeviceActivationPrio will prefer devices which are not already
         * activated (with this or another) profile. */

        ac_device = nm_active_connection_get_device(ac);
        if (ac_device
            && ((unavailable_devices && g_hash_table_contains(unavailable_devices, ac_device))
                || !nm_device_check_connection_available(ac_device, connection, flags, NULL, NULL)))
            ac_device = NULL;

        if (all_ac_arr) {
            guint i;

            ac_state = nm_active_connection_get_state(ac);

            /* we found several active connections. See which one is the most suitable... */
            nm_assert(ac == all_ac_arr->pdata[0]);
            for (i = 1; i < all_ac_arr->len; i++) {
                NMActiveConnection *    ac2        = all_ac_arr->pdata[i];
                NMDevice *              ac_device2 = nm_active_connection_get_device(ac2);
                NMActiveConnectionState ac_state2;

                if (!ac_device2
                    || (unavailable_devices
                        && g_hash_table_contains(unavailable_devices, ac_device2))
                    || !nm_device_check_connection_available(ac_device2,
                                                             connection,
                                                             flags,
                                                             NULL,
                                                             NULL))
                    continue;

                ac_state2 = nm_active_connection_get_state(ac2);

                if (!ac_device)
                    goto found_better;

                if (ac_state == ac_state2) {
                    /* active-connections are in their list in the order in which they are connected.
                     * If we have two with same state, the later (newer) one is preferred. */
                    goto found_better;
                }

                switch (ac_state) {
                case NM_ACTIVE_CONNECTION_STATE_UNKNOWN:
                    if (NM_IN_SET(ac_state2,
                                  NM_ACTIVE_CONNECTION_STATE_ACTIVATING,
                                  NM_ACTIVE_CONNECTION_STATE_ACTIVATED,
                                  NM_ACTIVE_CONNECTION_STATE_DEACTIVATING))
                        goto found_better;
                    break;
                case NM_ACTIVE_CONNECTION_STATE_ACTIVATING:
                    if (NM_IN_SET(ac_state2, NM_ACTIVE_CONNECTION_STATE_ACTIVATED))
                        goto found_better;
                    break;
                case NM_ACTIVE_CONNECTION_STATE_ACTIVATED:
                    break;
                case NM_ACTIVE_CONNECTION_STATE_DEACTIVATING:
                    if (NM_IN_SET(ac_state2,
                                  NM_ACTIVE_CONNECTION_STATE_ACTIVATING,
                                  NM_ACTIVE_CONNECTION_STATE_ACTIVATED))
                        goto found_better;
                    break;
                default:
                    nm_assert_not_reached();
                    goto found_better;
                }

                continue;
found_better:
                ac        = ac2;
                ac_state  = ac_state2;
                ac_device = ac_device2;
            }
        }

        if (ac_device)
            return ac_device;
    }

    /* Pick the first device that's compatible with the connection. */
    c_list_for_each_entry (device, &priv->devices_lst_head, devices_lst) {
        GError *             local = NULL;
        DeviceActivationPrio prio;

        if (unavailable_devices && g_hash_table_contains(unavailable_devices, device))
            continue;

        /* determine the priority of this device. Currently, this priority is independent
         * of the profile (connection) and the device's details (aside the state).
         *
         * Maybe nm_device_check_connection_available() should instead return a priority,
         * as it has more information available.
         *
         * For example, if you have multiple Wi-Fi devices, currently a user-request would
         * also select the device if the AP is not visible. Optimally, if one of the two
         * devices sees the AP and the other one doesn't, the former would be preferred.
         * For that, the priority would need to be determined by nm_device_check_connection_available(). */
        prio = _device_get_activation_prio(device);
        if (prio <= best.prio && best.device) {
            /* we already have a matching device with a better priority. This candidate
             * cannot be better. Skip the check.
             *
             * Also note, that below we collect the best error message @local_best.
             * Since we already have best.device, the error message does not matter
             * either, and we can skip nm_device_check_connection_available() altogether. */
            continue;
        }

        if (nm_device_check_connection_available(device,
                                                 connection,
                                                 flags,
                                                 NULL,
                                                 error ? &local : NULL)) {
            if (prio == _DEVICE_ACTIVATION_PRIO_BEST) {
                /* this device already has the best priority. It cannot get better
                 * and finish the search. */
                return device;
            }
            best.prio   = prio;
            best.device = device;
            continue;
        }

        if (error) {
            gboolean reset_error;

            if (!local_best)
                reset_error = TRUE;
            else if (local_best->domain != NM_UTILS_ERROR)
                reset_error = (local->domain == NM_UTILS_ERROR);
            else {
                reset_error = (local->domain == NM_UTILS_ERROR && local_best->code < local->code);
            }

            if (reset_error) {
                g_clear_error(&local_best);
                g_set_error(&local_best,
                            local->domain,
                            local->code,
                            "device %s not available because %s",
                            nm_device_get_iface(device),
                            local->message);
            }
            g_error_free(local);
        }
    }

    if (best.device)
        return best.device;

    if (error) {
        if (local_best)
            g_propagate_error(error, g_steal_pointer(&local_best));
        else {
            nm_utils_error_set_literal(error, NM_UTILS_ERROR_UNKNOWN, "no suitable device found");
        }
    }
    return NULL;
}

static const char **
_get_devices_paths(NMManager *self, gboolean all_devices)
{
    NMManagerPrivate *priv  = NM_MANAGER_GET_PRIVATE(self);
    const char **     paths = NULL;
    guint             i;
    NMDevice *        device;

    paths = g_new(const char *, c_list_length(&priv->devices_lst_head) + 1);

    i = 0;
    c_list_for_each_entry (device, &priv->devices_lst_head, devices_lst) {
        const char *path;

        path = nm_dbus_object_get_path(NM_DBUS_OBJECT(device));
        if (!path)
            continue;

        if (!all_devices && !nm_device_is_real(device))
            continue;

        paths[i++] = path;
    }
    paths[i++] = NULL;

    return paths;
}

static void
impl_manager_get_devices(NMDBusObject *                     obj,
                         const NMDBusInterfaceInfoExtended *interface_info,
                         const NMDBusMethodInfoExtended *   method_info,
                         GDBusConnection *                  connection,
                         const char *                       sender,
                         GDBusMethodInvocation *            invocation,
                         GVariant *                         parameters)
{
    NMManager *          self  = NM_MANAGER(obj);
    gs_free const char **paths = NULL;

    paths = _get_devices_paths(self, FALSE);
    g_dbus_method_invocation_return_value(invocation, g_variant_new("(^ao)", (char **) paths));
}

static void
impl_manager_get_all_devices(NMDBusObject *                     obj,
                             const NMDBusInterfaceInfoExtended *interface_info,
                             const NMDBusMethodInfoExtended *   method_info,
                             GDBusConnection *                  connection,
                             const char *                       sender,
                             GDBusMethodInvocation *            invocation,
                             GVariant *                         parameters)
{
    NMManager *          self  = NM_MANAGER(obj);
    gs_free const char **paths = NULL;

    paths = _get_devices_paths(self, TRUE);
    g_dbus_method_invocation_return_value(invocation, g_variant_new("(^ao)", (char **) paths));
}

static void
impl_manager_get_device_by_ip_iface(NMDBusObject *                     obj,
                                    const NMDBusInterfaceInfoExtended *interface_info,
                                    const NMDBusMethodInfoExtended *   method_info,
                                    GDBusConnection *                  connection,
                                    const char *                       sender,
                                    GDBusMethodInvocation *            invocation,
                                    GVariant *                         parameters)
{
    NMManager * self = NM_MANAGER(obj);
    NMDevice *  device;
    const char *path = NULL;
    const char *iface;

    g_variant_get(parameters, "(&s)", &iface);

    device = find_device_by_ip_iface(self, iface);
    if (device)
        path = nm_dbus_object_get_path(NM_DBUS_OBJECT(device));

    if (!path) {
        g_dbus_method_invocation_return_error(invocation,
                                              NM_MANAGER_ERROR,
                                              NM_MANAGER_ERROR_UNKNOWN_DEVICE,
                                              "No device found for the requested iface.");
        return;
    }

    g_dbus_method_invocation_return_value(invocation, g_variant_new("(o)", path));
}

static gboolean
is_compatible_with_slave(NMConnection *master, NMConnection *slave)
{
    NMSettingConnection *s_con;

    g_return_val_if_fail(master, FALSE);
    g_return_val_if_fail(slave, FALSE);

    s_con = nm_connection_get_setting_connection(slave);
    g_assert(s_con);

    return nm_connection_is_type(master, nm_setting_connection_get_slave_type(s_con));
}

/**
 * find_master:
 * @self: #NMManager object
 * @connection: the #NMConnection to find the master connection and device for
 * @device: the #NMDevice, if any, which will activate @connection
 * @out_master_connection: on success, the master connection of @connection if
 *   that master connection was found
 * @out_master_device: on success, the master device of @connection if that
 *   master device was found
 * @out_master_ac: on success, the master ActiveConnection of @connection if
 *   there already is one
 * @error: the error, if an error occurred
 *
 * Given an #NMConnection, attempts to find its master. If @connection has
 * no master, this will return %TRUE and @out_master_connection and
 * @out_master_device will be untouched.
 *
 * If @connection does have a master, then the outputs depend on what is in its
 * #NMSettingConnection:master property:
 *
 * If "master" is the ifname of an existing #NMDevice, and that device has a
 * compatible master connection activated or activating on it, then
 * @out_master_device, @out_master_connection, and @out_master_ac will all be
 * set. If the device exists and is idle, only @out_master_device will be set.
 * If the device exists and has an incompatible connection on it, an error
 * will be returned.
 *
 * If "master" is the ifname of a non-existent device, then @out_master_device
 * will be %NULL, and @out_master_connection will be a connection whose
 * activation would cause the creation of that device. @out_master_ac MAY be
 * set in this case as well (if the connection has started activating, but has
 * not yet created its device).
 *
 * If "master" is the UUID of a compatible master connection, then
 * @out_master_connection will be the identified connection, and @out_master_device
 * and/or @out_master_ac will be set if the connection is currently activating.
 * (@out_master_device will not be set if the device exists but does not have
 * @out_master_connection active/activating on it.)
 *
 * Returns: %TRUE if the master device and/or connection could be found or if
 *  the connection did not require a master, %FALSE otherwise
 **/
static gboolean
find_master(NMManager *            self,
            NMConnection *         connection,
            NMDevice *             device,
            NMSettingsConnection **out_master_connection,
            NMDevice **            out_master_device,
            NMActiveConnection **  out_master_ac,
            GError **              error)
{
    NMManagerPrivate *    priv = NM_MANAGER_GET_PRIVATE(self);
    NMSettingConnection * s_con;
    const char *          master;
    NMDevice *            master_device = NULL;
    NMSettingsConnection *master_connection;

    s_con = nm_connection_get_setting_connection(connection);
    g_assert(s_con);
    master = nm_setting_connection_get_master(s_con);

    if (master == NULL)
        return TRUE; /* success, but no master */

    /* Try as an interface name first */
    master_device = find_device_by_iface(self, master, NULL, connection);
    if (master_device) {
        if (master_device == device) {
            g_set_error_literal(error,
                                NM_MANAGER_ERROR,
                                NM_MANAGER_ERROR_DEPENDENCY_FAILED,
                                "Device cannot be its own master");
            return FALSE;
        }

        master_connection = nm_device_get_settings_connection(master_device);
        if (master_connection
            && !is_compatible_with_slave(nm_settings_connection_get_connection(master_connection),
                                         connection)) {
            g_set_error(error,
                        NM_MANAGER_ERROR,
                        NM_MANAGER_ERROR_DEPENDENCY_FAILED,
                        "The active connection on %s is not compatible",
                        nm_device_get_iface(master_device));
            return FALSE;
        }
    } else {
        /* Try master as a connection UUID */
        master_connection = nm_settings_get_connection_by_uuid(priv->settings, master);
        if (master_connection) {
            NMDevice *candidate;

            /* Check if the master connection is activated on some device already */
            c_list_for_each_entry (candidate, &priv->devices_lst_head, devices_lst) {
                if (candidate == device)
                    continue;

                if (nm_device_get_settings_connection(candidate) == master_connection) {
                    master_device = candidate;
                    break;
                }
            }
        }
    }

    if (out_master_connection)
        *out_master_connection = master_connection;
    if (out_master_device)
        *out_master_device = master_device;
    if (out_master_ac && master_connection) {
        *out_master_ac = active_connection_find(self,
                                                master_connection,
                                                NULL,
                                                NM_ACTIVE_CONNECTION_STATE_DEACTIVATING,
                                                NULL);
    }

    if (master_device || master_connection)
        return TRUE;
    else {
        g_set_error_literal(error,
                            NM_MANAGER_ERROR,
                            NM_MANAGER_ERROR_UNKNOWN_DEVICE,
                            "Master connection not found or invalid");
        return FALSE;
    }
}

/**
 * ensure_master_active_connection:
 * @self: the #NMManager
 * @subject: the #NMAuthSubject representing the requestor of this activation
 * @connection: the connection that should depend on @master_connection
 * @device: the #NMDevice, if any, which will activate @connection
 * @master_connection: the master connection, or %NULL
 * @master_device: the master device, or %NULL
 * @activation_reason: the reason for activation
 * @error: the error, if an error occurred
 *
 * Determines whether a given #NMConnection depends on another connection to
 * be activated, and if so, finds that master connection or creates it.
 *
 * If @master_device and @master_connection are both set then @master_connection
 * MUST already be activated or activating on @master_device, and the function will
 * return the existing #NMActiveConnection.
 *
 * If only @master_device is set, and it has an #NMActiveConnection, then the
 * function will return it if it is a compatible master, or an error if not. If it
 * doesn't have an AC, then the function will create one if a compatible master
 * connection exists, or return an error if not.
 *
 * If only @master_connection is set, then this will try to find or create a compatible
 * #NMDevice, and either activate @master_connection on that device or return an error.
 *
 * Returns: the master #NMActiveConnection that the caller should depend on, or
 * %NULL if an error occurred
 */
static NMActiveConnection *
ensure_master_active_connection(NMManager *           self,
                                NMAuthSubject *       subject,
                                NMConnection *        connection,
                                NMDevice *            device,
                                NMSettingsConnection *master_connection,
                                NMDevice *            master_device,
                                NMActivationReason    activation_reason,
                                GError **             error)
{
    NMManagerPrivate *  priv = NM_MANAGER_GET_PRIVATE(self);
    NMActiveConnection *ac;
    NMActiveConnection *master_ac = NULL;
    NMDeviceState       master_state;
    gboolean            bind_lifetime_to_profile_visibility;

    g_return_val_if_fail(connection, NULL);
    g_return_val_if_fail(master_connection || master_device, FALSE);

    bind_lifetime_to_profile_visibility =
        NM_FLAGS_HAS(nm_device_get_activation_state_flags(device),
                     NM_ACTIVATION_STATE_FLAG_LIFETIME_BOUND_TO_PROFILE_VISIBILITY);

    /* If the master device isn't activated then we need to activate it using
     * compatible connection.  If it's already activating we can just proceed.
     */
    if (master_device) {
        NMSettingsConnection *device_connection = nm_device_get_settings_connection(master_device);

        /* If we're passed a connection and a device, we require that connection
         * be already activated on the device, eg returned from find_master().
         */
        g_assert(!master_connection || master_connection == device_connection);
        if (device_connection
            && !is_compatible_with_slave(nm_settings_connection_get_connection(device_connection),
                                         connection)) {
            g_set_error(error,
                        NM_MANAGER_ERROR,
                        NM_MANAGER_ERROR_DEPENDENCY_FAILED,
                        "The active connection %s is not compatible",
                        nm_connection_get_id(connection));
            return NULL;
        }

        master_state = nm_device_get_state(master_device);
        if ((master_state == NM_DEVICE_STATE_ACTIVATED) || nm_device_is_activating(master_device)) {
            /* Device already using master_connection */
            ac = NM_ACTIVE_CONNECTION(nm_device_get_act_request(master_device));
            g_return_val_if_fail(device_connection, ac);

            if (!bind_lifetime_to_profile_visibility) {
                /* unbind the lifetime. */
                nm_active_connection_set_state_flags_clear(
                    ac,
                    NM_ACTIVATION_STATE_FLAG_LIFETIME_BOUND_TO_PROFILE_VISIBILITY);
            }

            return ac;
        }

        /* If the device is disconnected, find a compatible connection and
         * activate it on the device.
         */
        if (master_state == NM_DEVICE_STATE_DISCONNECTED || !nm_device_is_real(master_device)) {
            gs_free NMSettingsConnection **connections = NULL;
            guint                          i;

            g_assert(master_connection == NULL);

            /* Find a compatible connection and activate this device using it */
            connections = nm_manager_get_activatable_connections(self, FALSE, TRUE, NULL);
            for (i = 0; connections[i]; i++) {
                NMSettingsConnection *candidate = connections[i];
                NMConnection *        cand_conn = nm_settings_connection_get_connection(candidate);

                /* Ensure eg bond/team slave and the candidate master is a
                 * bond/team master
                 */
                if (!is_compatible_with_slave(cand_conn, connection))
                    continue;

                if (nm_device_check_connection_available(
                        master_device,
                        cand_conn,
                        NM_DEVICE_CHECK_CON_AVAILABLE_FOR_USER_REQUEST,
                        NULL,
                        NULL)) {
                    master_ac = nm_manager_activate_connection(
                        self,
                        candidate,
                        NULL,
                        NULL,
                        master_device,
                        subject,
                        NM_ACTIVATION_TYPE_MANAGED,
                        activation_reason,
                        bind_lifetime_to_profile_visibility
                            ? NM_ACTIVATION_STATE_FLAG_LIFETIME_BOUND_TO_PROFILE_VISIBILITY
                            : NM_ACTIVATION_STATE_FLAG_NONE,
                        error);
                    return master_ac;
                }
            }

            g_set_error(error,
                        NM_MANAGER_ERROR,
                        NM_MANAGER_ERROR_UNKNOWN_CONNECTION,
                        "No compatible connection found.");
            return NULL;
        }

        /* Otherwise, the device is unmanaged, unavailable, or disconnecting */
        g_set_error(error,
                    NM_MANAGER_ERROR,
                    NM_MANAGER_ERROR_DEPENDENCY_FAILED,
                    "Device unmanaged or not available for activation");
    } else if (master_connection) {
        NMDevice *candidate;

        /* Find a compatible device and activate it using this connection */
        c_list_for_each_entry (candidate, &priv->devices_lst_head, devices_lst) {
            if (candidate == device) {
                /* A device obviously can't be its own master */
                continue;
            }

            if (!nm_device_check_connection_available(
                    candidate,
                    nm_settings_connection_get_connection(master_connection),
                    NM_DEVICE_CHECK_CON_AVAILABLE_FOR_USER_REQUEST,
                    NULL,
                    NULL))
                continue;

            if (!nm_device_is_software(candidate)) {
                master_state = nm_device_get_state(candidate);
                if (nm_device_is_real(candidate) && master_state != NM_DEVICE_STATE_DISCONNECTED)
                    continue;
            }

            master_ac = nm_manager_activate_connection(
                self,
                master_connection,
                NULL,
                NULL,
                candidate,
                subject,
                NM_ACTIVATION_TYPE_MANAGED,
                activation_reason,
                bind_lifetime_to_profile_visibility
                    ? NM_ACTIVATION_STATE_FLAG_LIFETIME_BOUND_TO_PROFILE_VISIBILITY
                    : NM_ACTIVATION_STATE_FLAG_NONE,
                error);
            return master_ac;
        }

        g_set_error(error,
                    NM_MANAGER_ERROR,
                    NM_MANAGER_ERROR_UNKNOWN_DEVICE,
                    "No device available");
    } else
        g_assert_not_reached();

    return NULL;
}

typedef struct {
    NMSettingsConnection *connection;
    NMDevice *            device;
} SlaveConnectionInfo;

/**
 * find_slaves:
 * @manager: #NMManager object
 * @sett_conn: the master #NMSettingsConnection to find slave connections for
 * @device: the master #NMDevice for the @sett_conn
 * @out_n_slaves: on return, the number of slaves found
 *
 * Given an #NMSettingsConnection, attempts to find its slaves. If @sett_conn is not
 * master, or has not any slaves, this will return %NULL.
 *
 * Returns: an array of #SlaveConnectionInfo for given master @sett_conn, or %NULL
 **/
static SlaveConnectionInfo *
find_slaves(NMManager *           manager,
            NMSettingsConnection *sett_conn,
            NMDevice *            device,
            guint *               out_n_slaves,
            gboolean              for_user_request)
{
    NMManagerPrivate *priv                         = NM_MANAGER_GET_PRIVATE(manager);
    gs_free NMSettingsConnection **all_connections = NULL;
    guint                          n_all_connections;
    guint                          i;
    SlaveConnectionInfo *          slaves   = NULL;
    guint                          n_slaves = 0;
    NMSettingConnection *          s_con;
    gs_unref_hashtable GHashTable *devices = NULL;

    nm_assert(out_n_slaves);

    s_con = nm_connection_get_setting_connection(nm_settings_connection_get_connection(sett_conn));
    g_return_val_if_fail(s_con, NULL);

    devices = g_hash_table_new(nm_direct_hash, NULL);

    /* Search through all connections, not only inactive ones, because
     * even if a slave was already active, it might be deactivated during
     * master reactivation.
     */
    all_connections = nm_settings_get_connections_clone(
        priv->settings,
        &n_all_connections,
        NULL,
        NULL,
        nm_settings_connection_cmp_autoconnect_priority_p_with_data,
        NULL);
    for (i = 0; i < n_all_connections; i++) {
        NMSettingsConnection *master_connection = NULL;
        NMDevice *            master_device     = NULL, *slave_device;
        NMSettingsConnection *candidate         = all_connections[i];

        find_master(manager,
                    nm_settings_connection_get_connection(candidate),
                    NULL,
                    &master_connection,
                    &master_device,
                    NULL,
                    NULL);
        if ((master_connection && master_connection == sett_conn)
            || (master_device && master_device == device)) {
            slave_device = nm_manager_get_best_device_for_connection(manager,
                                                                     candidate,
                                                                     NULL,
                                                                     for_user_request,
                                                                     devices,
                                                                     NULL);

            if (!slaves) {
                /* what we allocate is quite likely much too large. Don't bother, it is only
                 * a temporary buffer. */
                slaves = g_new(SlaveConnectionInfo, n_all_connections);
            }

            nm_assert(n_slaves < n_all_connections);
            slaves[n_slaves].connection = candidate, slaves[n_slaves].device = slave_device,
            n_slaves++;

            if (slave_device)
                g_hash_table_add(devices, slave_device);
        }
    }

    *out_n_slaves = n_slaves;

    /* Warning: returns NULL if n_slaves is zero. */
    return slaves;
}

static gboolean
should_connect_slaves(NMConnection *connection, NMDevice *device)
{
    NMSettingConnection *                s_con;
    NMSettingConnectionAutoconnectSlaves val;

    s_con = nm_connection_get_setting_connection(connection);
    g_assert(s_con);

    val = nm_setting_connection_get_autoconnect_slaves(s_con);
    if (val != NM_SETTING_CONNECTION_AUTOCONNECT_SLAVES_DEFAULT)
        goto out;

    val =
        nm_config_data_get_connection_default_int64(NM_CONFIG_GET_DATA,
                                                    NM_CON_DEFAULT("connection.autoconnect-slaves"),
                                                    device,
                                                    0,
                                                    1,
                                                    -1);

out:
    if (val == NM_SETTING_CONNECTION_AUTOCONNECT_SLAVES_NO)
        return FALSE;
    if (val == NM_SETTING_CONNECTION_AUTOCONNECT_SLAVES_YES)
        return TRUE;
    return FALSE;
}

static int
compare_slaves(gconstpointer a, gconstpointer b, gpointer sort_by_name)
{
    const SlaveConnectionInfo *a_info = a;
    const SlaveConnectionInfo *b_info = b;

    /* Slaves without a device at the end */
    if (!a_info->device)
        return 1;
    if (!b_info->device)
        return -1;

    if (GPOINTER_TO_INT(sort_by_name)) {
        return nm_strcmp0(nm_device_get_iface(a_info->device), nm_device_get_iface(b_info->device));
    }

    return nm_device_get_ifindex(a_info->device) - nm_device_get_ifindex(b_info->device);
}

static void
autoconnect_slaves(NMManager *           self,
                   NMSettingsConnection *master_connection,
                   NMDevice *            master_device,
                   NMAuthSubject *       subject,
                   gboolean              for_user_request)
{
    GError *local_err = NULL;

    if (should_connect_slaves(nm_settings_connection_get_connection(master_connection),
                              master_device)) {
        gs_free SlaveConnectionInfo *slaves = NULL;
        guint                        i, n_slaves = 0;
        gboolean                     bind_lifetime_to_profile_visibility;

        slaves = find_slaves(self, master_connection, master_device, &n_slaves, for_user_request);
        if (n_slaves > 1) {
            gs_free char *value = NULL;

            value = nm_config_data_get_value(NM_CONFIG_GET_DATA,
                                             NM_CONFIG_KEYFILE_GROUP_MAIN,
                                             NM_CONFIG_KEYFILE_KEY_MAIN_SLAVES_ORDER,
                                             NM_CONFIG_GET_VALUE_STRIP);
            g_qsort_with_data(slaves,
                              n_slaves,
                              sizeof(slaves[0]),
                              compare_slaves,
                              GINT_TO_POINTER(!nm_streq0(value, "index")));
        }

        bind_lifetime_to_profile_visibility =
            n_slaves > 0
            && NM_FLAGS_HAS(nm_device_get_activation_state_flags(master_device),
                            NM_ACTIVATION_STATE_FLAG_LIFETIME_BOUND_TO_PROFILE_VISIBILITY);

        for (i = 0; i < n_slaves; i++) {
            SlaveConnectionInfo *slave = &slaves[i];
            const char *         uuid;

            /* To avoid loops when autoconnecting slaves, we propagate
             * the UUID of the initial connection down to slaves until
             * the same connection is found.
             */
            uuid = g_object_get_qdata(G_OBJECT(master_connection), autoconnect_root_quark());
            if (nm_streq0(nm_settings_connection_get_uuid(slave->connection), uuid)) {
                _LOGI(LOGD_CORE,
                      "will NOT activate slave connection '%s' (%s) as a dependency for master "
                      "'%s' (%s): "
                      "circular dependency detected",
                      nm_settings_connection_get_id(slave->connection),
                      nm_settings_connection_get_uuid(slave->connection),
                      nm_settings_connection_get_id(master_connection),
                      nm_settings_connection_get_uuid(master_connection));
                continue;
            }

            if (!uuid)
                uuid = nm_settings_connection_get_uuid(master_connection);
            g_object_set_qdata_full(G_OBJECT(slave->connection),
                                    autoconnect_root_quark(),
                                    g_strdup(uuid),
                                    g_free);

            if (!slave->device) {
                _LOGD(LOGD_CORE,
                      "will NOT activate slave connection '%s' (%s) as a dependency for master "
                      "'%s' (%s): "
                      "no compatible device found",
                      nm_settings_connection_get_id(slave->connection),
                      nm_settings_connection_get_uuid(slave->connection),
                      nm_settings_connection_get_id(master_connection),
                      nm_settings_connection_get_uuid(master_connection));
                continue;
            }

            _LOGD(LOGD_CORE,
                  "will activate slave connection '%s' (%s) as a dependency for master '%s' (%s)",
                  nm_settings_connection_get_id(slave->connection),
                  nm_settings_connection_get_uuid(slave->connection),
                  nm_settings_connection_get_id(master_connection),
                  nm_settings_connection_get_uuid(master_connection));

            /* Schedule slave activation */
            nm_manager_activate_connection(
                self,
                slave->connection,
                NULL,
                NULL,
                slave->device,
                subject,
                NM_ACTIVATION_TYPE_MANAGED,
                NM_ACTIVATION_REASON_AUTOCONNECT_SLAVES,
                bind_lifetime_to_profile_visibility
                    ? NM_ACTIVATION_STATE_FLAG_LIFETIME_BOUND_TO_PROFILE_VISIBILITY
                    : NM_ACTIVATION_STATE_FLAG_NONE,
                &local_err);
            if (local_err) {
                _LOGW(LOGD_CORE, "Slave connection activation failed: %s", local_err->message);
                g_clear_error(&local_err);
            }
        }
    }
}

static gboolean
_internal_activate_vpn(NMManager *self, NMActiveConnection *active, GError **error)
{
    nm_assert(NM_IS_VPN_CONNECTION(active));

    nm_dbus_object_export(NM_DBUS_OBJECT(active));
    if (!nm_vpn_manager_activate_connection(NM_MANAGER_GET_PRIVATE(self)->vpn_manager,
                                            NM_VPN_CONNECTION(active),
                                            error)) {
        nm_dbus_object_unexport(NM_DBUS_OBJECT(active));
        return FALSE;
    }

    active_connection_add(self, active);
    return TRUE;
}

/* Traverse the device to disconnected state. This means that the device is ready
 * for connection and will proceed activating if there's an activation request
 * enqueued.
 */
static void
unmanaged_to_disconnected(NMDevice *device)
{
    /* when creating the software device, it can happen that the device is
     * still unmanaged by NM_UNMANAGED_PLATFORM_INIT because we didn't yet
     * get the udev event. At this point, we can no longer delay the activation
     * and force the device to be managed. */
    nm_device_set_unmanaged_by_flags(device,
                                     NM_UNMANAGED_PLATFORM_INIT,
                                     FALSE,
                                     NM_DEVICE_STATE_REASON_USER_REQUESTED);

    nm_device_set_unmanaged_by_flags(device,
                                     NM_UNMANAGED_USER_EXPLICIT,
                                     FALSE,
                                     NM_DEVICE_STATE_REASON_USER_REQUESTED);

    if (!nm_device_get_managed(device, FALSE)) {
        /* the device is still marked as unmanaged. Nothing to do. */
        return;
    }

    if (nm_device_get_state(device) == NM_DEVICE_STATE_UNMANAGED) {
        nm_device_state_changed(device,
                                NM_DEVICE_STATE_UNAVAILABLE,
                                NM_DEVICE_STATE_REASON_USER_REQUESTED);
    }

    if (nm_device_get_state(device) == NM_DEVICE_STATE_UNAVAILABLE
        && nm_device_is_available(device, NM_DEVICE_CHECK_DEV_AVAILABLE_FOR_USER_REQUEST)) {
        nm_device_state_changed(device,
                                NM_DEVICE_STATE_DISCONNECTED,
                                NM_DEVICE_STATE_REASON_USER_REQUESTED);
    }
}

static NMActivationStateFlags
_activation_bind_lifetime_to_profile_visibility(NMAuthSubject *subject)
{
    if (nm_auth_subject_get_subject_type(subject) == NM_AUTH_SUBJECT_TYPE_INTERNAL
        || nm_auth_subject_get_unix_process_uid(subject) == 0) {
        /* internal requests and requests from root are always unbound. */
        return NM_ACTIVATION_STATE_FLAG_NONE;
    }

    /* if the activation was not done by internal decision nor root, there
     * are the following cases:
     *
     * - the connection has "connection.permissions" unset and the profile
     *   is not restricted to a user and commonly always visible. It does
     *   not hurt to bind the lifetime, because we expect the profile to be
     *   visible at the moment. If the profile changes (while still being active),
     *   we want to pick-up changes to the visibility and possibly disconnect.
     *
     * - the connection has "connection.permissions" set, and the current user
     *   is the owner:
     *
     *      - Usually, we would expect that the profile is visible at the moment,
     *        and of course we want to bind the lifetime. The moment the user
     *        logs out, the connection becomes invisible and disconnects.
     *
     *      - the profile at this time could already be invisible (e.g. if the
     *        user didn't create a proper session (sudo) and manually activates
     *        an invisible profile. In this case, we still want to bind the
     *        lifetime, and it will disconnect after the user logs in and logs
     *        out again. NMKeepAlive takes care of that.
     */
    return NM_ACTIVATION_STATE_FLAG_LIFETIME_BOUND_TO_PROFILE_VISIBILITY;
}

/* The parent connection is ready; we can proceed realizing the device and
 * progressing the device to disconencted state.
 */
static void
active_connection_parent_active(NMActiveConnection *active,
                                NMActiveConnection *parent_ac,
                                NMManager *         self)
{
    NMDevice *            device = nm_active_connection_get_device(active);
    GError *              error  = NULL;
    NMSettingsConnection *sett_conn;
    NMDevice *            parent;

    g_signal_handlers_disconnect_by_func(active, (GCallback) active_connection_parent_active, self);

    if (!parent_ac) {
        _LOGW(LOGD_CORE,
              "The parent connection device '%s' depended on disappeared.",
              nm_device_get_iface(device));
        nm_active_connection_set_state_fail(active,
                                            NM_ACTIVE_CONNECTION_STATE_REASON_DEVICE_REMOVED,
                                            "parent device disappeared");
        return;
    }

    sett_conn = nm_active_connection_get_settings_connection(active);
    parent    = nm_active_connection_get_device(parent_ac);

    if (!nm_device_create_and_realize(device,
                                      nm_settings_connection_get_connection(sett_conn),
                                      parent,
                                      &error)) {
        _LOGW(LOGD_CORE,
              "Could not realize device '%s': %s",
              nm_device_get_iface(device),
              error->message);
        nm_active_connection_set_state_fail(active,
                                            NM_ACTIVE_CONNECTION_STATE_REASON_DEVICE_REALIZE_FAILED,
                                            "failure to realize device");
        return;
    }

    /* We can now proceed to disconnected state so that activation proceeds. */
    unmanaged_to_disconnected(device);
}

static gboolean
_internal_activate_device(NMManager *self, NMActiveConnection *active, GError **error)
{
    NMDevice *               device, *master_device = NULL;
    NMConnection *           applied;
    NMSettingsConnection *   sett_conn;
    NMSettingsConnection *   master_connection   = NULL;
    NMConnection *           existing_connection = NULL;
    NMActiveConnection *     master_ac           = NULL;
    NMAuthSubject *          subject;
    GError *                 local = NULL;
    NMConnectionMultiConnect multi_connect;
    const char *             parent_spec;

    g_return_val_if_fail(NM_IS_MANAGER(self), FALSE);
    g_return_val_if_fail(NM_IS_ACTIVE_CONNECTION(active), FALSE);
    g_return_val_if_fail(error == NULL || *error == NULL, FALSE);

    g_assert(NM_IS_VPN_CONNECTION(active) == FALSE);

    device = nm_active_connection_get_device(active);
    g_return_val_if_fail(device != NULL, FALSE);

    sett_conn = nm_active_connection_get_settings_connection(active);
    nm_assert(sett_conn);

    applied = nm_active_connection_get_applied_connection(active);

    /* If the device is active and its connection is not visible to the
     * user that's requesting this new activation, fail, since other users
     * should not be allowed to implicitly deactivate private connections
     * by activating a connection of their own.
     */
    existing_connection = nm_device_get_applied_connection(device);
    subject             = nm_active_connection_get_subject(active);
    if (existing_connection
        && !nm_auth_is_subject_in_acl_set_error(existing_connection,
                                                subject,
                                                NM_MANAGER_ERROR,
                                                NM_MANAGER_ERROR_PERMISSION_DENIED,
                                                error)) {
        g_prefix_error(error, "Private connection already active on the device: ");
        return FALSE;
    }

    /* Final connection must be available on device */
    if (!nm_device_check_connection_available(device,
                                              applied,
                                              NM_DEVICE_CHECK_CON_AVAILABLE_FOR_USER_REQUEST,
                                              NULL,
                                              &local)) {
        g_set_error(error,
                    NM_MANAGER_ERROR,
                    NM_MANAGER_ERROR_UNKNOWN_CONNECTION,
                    "Connection '%s' is not available on device %s because %s",
                    nm_settings_connection_get_id(sett_conn),
                    nm_device_get_iface(device),
                    local->message);
        g_error_free(local);
        return FALSE;
    }

    if (nm_active_connection_get_activation_type(active) == NM_ACTIVATION_TYPE_MANAGED)
        nm_device_sys_iface_state_set(device, NM_DEVICE_SYS_IFACE_STATE_MANAGED);

    /* Try to find the master connection/device if the connection has a dependency */
    if (!find_master(self,
                     applied,
                     device,
                     &master_connection,
                     &master_device,
                     &master_ac,
                     error)) {
        g_prefix_error(error,
                       "Can not find a master for %s: ",
                       nm_settings_connection_get_id(sett_conn));
        return FALSE;
    }

    /* Create any backing resources the device needs */
    if (!nm_device_is_real(device)) {
        NMDevice *parent;

        parent = find_parent_device_for_connection(self,
                                                   nm_settings_connection_get_connection(sett_conn),
                                                   NULL,
                                                   &parent_spec);

        if (parent_spec && !parent) {
            g_set_error(error,
                        NM_MANAGER_ERROR,
                        NM_MANAGER_ERROR_DEPENDENCY_FAILED,
                        "parent device '%s' not found",
                        parent_spec);
            return FALSE;
        }

        if (parent && !nm_device_is_real(parent)) {
            NMSettingsConnection *parent_con;
            NMActiveConnection *  parent_ac;

            parent_con = nm_device_get_best_connection(parent, NULL, error);
            if (!parent_con) {
                g_prefix_error(error, "%s failed to create parent: ", nm_device_get_iface(device));
                return FALSE;
            }

            if (nm_active_connection_get_activation_reason(active)
                    == NM_ACTIVATION_REASON_AUTOCONNECT
                && NM_FLAGS_HAS(nm_settings_connection_autoconnect_blocked_reason_get(parent_con),
                                NM_SETTINGS_AUTO_CONNECT_BLOCKED_REASON_USER_REQUEST)) {
                g_set_error(error,
                            NM_MANAGER_ERROR,
                            NM_MANAGER_ERROR_DEPENDENCY_FAILED,
                            "the parent connection of %s cannot autoactivate because it is blocked "
                            "due to user request",
                            nm_device_get_iface(device));
                return FALSE;
            }

            parent_ac = nm_manager_activate_connection(
                self,
                parent_con,
                NULL,
                NULL,
                parent,
                subject,
                NM_ACTIVATION_TYPE_MANAGED,
                nm_active_connection_get_activation_reason(active),
                nm_active_connection_get_state_flags(active)
                    & NM_ACTIVATION_STATE_FLAG_LIFETIME_BOUND_TO_PROFILE_VISIBILITY,
                error);
            if (!parent_ac) {
                g_prefix_error(error,
                               "%s failed to activate parent: ",
                               nm_device_get_iface(device));
                return FALSE;
            }

            /* We can't realize now; defer until the parent device is ready. */
            g_signal_connect(active,
                             NM_ACTIVE_CONNECTION_PARENT_ACTIVE,
                             (GCallback) active_connection_parent_active,
                             self);
            nm_active_connection_set_parent(active, parent_ac);
        } else {
            /* We can realize now; no need to wait for a parent device. */
            if (!nm_device_create_and_realize(device,
                                              nm_settings_connection_get_connection(sett_conn),
                                              parent,
                                              error)) {
                g_prefix_error(error,
                               "%s failed to create resources: ",
                               nm_device_get_iface(device));
                return FALSE;
            }
        }
    }

    /* Ensure there's a master active connection the new connection we're
     * activating can depend on.
     */
    if (master_connection || master_device) {
        if (master_connection) {
            _LOGD(LOGD_CORE,
                  "Activation of '%s' requires master connection '%s'",
                  nm_settings_connection_get_id(sett_conn),
                  nm_settings_connection_get_id(master_connection));
        }
        if (master_device) {
            _LOGD(LOGD_CORE,
                  "Activation of '%s' requires master device '%s'",
                  nm_settings_connection_get_id(sett_conn),
                  nm_device_get_ip_iface(master_device));
        }

        /* Ensure eg bond slave and the candidate master is a bond master */
        if (master_connection
            && !is_compatible_with_slave(nm_settings_connection_get_connection(master_connection),
                                         applied)) {
            g_set_error(error,
                        NM_MANAGER_ERROR,
                        NM_MANAGER_ERROR_DEPENDENCY_FAILED,
                        "The master connection '%s' is not compatible with '%s'",
                        nm_settings_connection_get_id(master_connection),
                        nm_settings_connection_get_id(sett_conn));
            return FALSE;
        }

        if (!master_ac) {
            master_ac =
                ensure_master_active_connection(self,
                                                nm_active_connection_get_subject(active),
                                                applied,
                                                device,
                                                master_connection,
                                                master_device,
                                                nm_active_connection_get_activation_reason(active),
                                                error);
            if (!master_ac) {
                if (master_device) {
                    g_prefix_error(error,
                                   "Master device '%s' can't be activated: ",
                                   nm_device_get_ip_iface(device));
                } else {
                    g_prefix_error(error,
                                   "Master connection '%s' can't be activated: ",
                                   nm_settings_connection_get_id(sett_conn));
                }
                return FALSE;
            }
        }

        /* Now that we're activating a slave for that master, make sure the master just
         * decides to go unmanaged while we're activating (perhaps because other slaves
         * go away leaving him with no kids).
         */
        if (master_device) {
            nm_device_set_unmanaged_by_flags(master_device,
                                             NM_UNMANAGED_EXTERNAL_DOWN,
                                             NM_UNMAN_FLAG_OP_FORGET,
                                             NM_DEVICE_STATE_REASON_USER_REQUESTED);
        }

        nm_active_connection_set_master(active, master_ac);
        _LOGD(LOGD_CORE,
              "Activation of '%s' depends on active connection %p %s",
              nm_settings_connection_get_id(sett_conn),
              master_ac,
              nm_dbus_object_get_path(NM_DBUS_OBJECT(master_ac)) ?: "");
    }

    /* Check slaves for master connection and possibly activate them */
    autoconnect_slaves(self,
                       sett_conn,
                       device,
                       nm_active_connection_get_subject(active),
                       nm_active_connection_get_activation_reason(active)
                           == NM_ACTIVATION_REASON_USER_REQUEST);

    multi_connect =
        _nm_connection_get_multi_connect(nm_settings_connection_get_connection(sett_conn));
    if (multi_connect == NM_CONNECTION_MULTI_CONNECT_MULTIPLE
        || (multi_connect == NM_CONNECTION_MULTI_CONNECT_MANUAL_MULTIPLE
            && NM_IN_SET(nm_active_connection_get_activation_reason(active),
                         NM_ACTIVATION_REASON_ASSUME,
                         NM_ACTIVATION_REASON_AUTOCONNECT_SLAVES,
                         NM_ACTIVATION_REASON_USER_REQUEST))) {
        /* the profile can be activated multiple times. Proceed. */
    } else {
        gs_unref_ptrarray GPtrArray *all_ac_arr = NULL;
        NMActiveConnection *         ac;
        guint                        i, n_all;

        /* Disconnect the connection if already connected or queued for activation.
         * The connection cannot be active multiple times (at the same time).  */
        ac = active_connection_find(self,
                                    sett_conn,
                                    NULL,
                                    NM_ACTIVE_CONNECTION_STATE_ACTIVATED,
                                    &all_ac_arr);
        if (ac) {
            n_all = all_ac_arr ? all_ac_arr->len : ((guint) 1);
            for (i = 0; i < n_all; i++) {
                nm_device_disconnect_active_connection(all_ac_arr ? all_ac_arr->pdata[i] : ac,
                                                       NM_DEVICE_STATE_REASON_NEW_ACTIVATION,
                                                       NM_ACTIVE_CONNECTION_STATE_REASON_UNKNOWN);
            }
        }
    }

    /* If the device is there, we can ready it for the activation. */
    if (nm_device_is_real(device)) {
        unmanaged_to_disconnected(device);

        if (!nm_device_get_managed(device, FALSE)) {
            /* Unexpectedly, the device is still unmanaged. That can happen for example,
             * if the device is forcibly unmanaged due to NM_UNMANAGED_USER_SETTINGS. */
            g_set_error_literal(error,
                                NM_MANAGER_ERROR,
                                NM_MANAGER_ERROR_DEPENDENCY_FAILED,
                                "Activation failed because the device is unmanaged");
            return FALSE;
        }
    }

    /* Export the new ActiveConnection to clients and start it on the device */
    active_connection_add(self, active);
    nm_device_queue_activation(device, NM_ACT_REQUEST(active));
    return TRUE;
}

static gboolean
_internal_activate_generic(NMManager *self, NMActiveConnection *active, GError **error)
{
    NMManagerPrivate *priv    = NM_MANAGER_GET_PRIVATE(self);
    gboolean          success = FALSE;

    /* Ensure activation request is still valid, eg that its device hasn't gone
     * away or that some other dependency has not failed.
     */
    if (nm_active_connection_get_state(active) >= NM_ACTIVE_CONNECTION_STATE_DEACTIVATING) {
        g_set_error_literal(error,
                            NM_MANAGER_ERROR,
                            NM_MANAGER_ERROR_DEPENDENCY_FAILED,
                            "Activation failed because dependencies failed.");
        return FALSE;
    }

    if (NM_IS_VPN_CONNECTION(active))
        success = _internal_activate_vpn(self, active, error);
    else
        success = _internal_activate_device(self, active, error);

    if (success) {
        /* Force an update of the Manager's activating-connection property.
         * The device changes state before the AC gets exported, which causes
         * the manager's 'activating-connection' property to be NULL since the
         * AC only gets a D-Bus path when it's exported.  So now that the AC
         * is exported, make sure the manager's activating-connection property
         * is up-to-date.
         */
        policy_activating_ac_changed(G_OBJECT(priv->policy), NULL, self);
    }

    return success;
}

static NMActiveConnection *
_new_active_connection(NMManager *            self,
                       gboolean               is_vpn,
                       NMSettingsConnection * sett_conn,
                       NMConnection *         incompl_conn,
                       NMConnection *         applied,
                       const char *           specific_object,
                       NMDevice *             device,
                       NMAuthSubject *        subject,
                       NMActivationType       activation_type,
                       NMActivationReason     activation_reason,
                       NMActivationStateFlags initial_state_flags,
                       GError **              error)
{
    NMManagerPrivate *priv = NM_MANAGER_GET_PRIVATE(self);
    NMDevice *        parent_device;

    nm_assert(!sett_conn || NM_IS_SETTINGS_CONNECTION(sett_conn));
    nm_assert(!incompl_conn || NM_IS_CONNECTION(incompl_conn));
    nm_assert((!incompl_conn) ^ (!sett_conn));
    nm_assert(NM_IS_AUTH_SUBJECT(subject));
    nm_assert(is_vpn
              == _connection_is_vpn(sett_conn ? nm_settings_connection_get_connection(sett_conn)
                                              : incompl_conn));
    nm_assert(is_vpn || NM_IS_DEVICE(device));
    nm_assert(!nm_streq0(specific_object, "/"));
    nm_assert(!applied || NM_IS_CONNECTION(applied));
    nm_assert(!is_vpn || !applied);

    if (is_vpn) {
        NMActiveConnection *parent;

        /* FIXME: for VPN connections, we don't allow re-activating an
         * already active connection. It's a bug, and should be fixed together
         * when reworking VPN handling. */
        if (active_connection_find_by_connection(self,
                                                 sett_conn,
                                                 incompl_conn,
                                                 NM_ACTIVE_CONNECTION_STATE_ACTIVATED,
                                                 NULL)) {
            g_set_error(error,
                        NM_MANAGER_ERROR,
                        NM_MANAGER_ERROR_CONNECTION_ALREADY_ACTIVE,
                        "Connection '%s' is already active",
                        sett_conn ? nm_settings_connection_get_id(sett_conn)
                                  : nm_connection_get_id(incompl_conn));
            return NULL;
        }

        if (activation_type != NM_ACTIVATION_TYPE_MANAGED)
            g_return_val_if_reached(NULL);

        if (specific_object) {
            /* Find the specific connection the client requested we use */
            parent = active_connection_get_by_path(self, specific_object);
            if (!parent) {
                g_set_error_literal(error,
                                    NM_MANAGER_ERROR,
                                    NM_MANAGER_ERROR_CONNECTION_NOT_ACTIVE,
                                    "Base connection for VPN connection not active.");
                return NULL;
            }
        } else
            parent = priv->primary_connection;

        if (!parent) {
            g_set_error_literal(error,
                                NM_MANAGER_ERROR,
                                NM_MANAGER_ERROR_UNKNOWN_CONNECTION,
                                "Could not find source connection.");
            return NULL;
        }

        parent_device = nm_active_connection_get_device(parent);
        if (!parent_device) {
            g_set_error_literal(error,
                                NM_MANAGER_ERROR,
                                NM_MANAGER_ERROR_UNKNOWN_DEVICE,
                                "Source connection had no active device");
            return NULL;
        }

        if (device && device != parent_device) {
            g_set_error_literal(error,
                                NM_MANAGER_ERROR,
                                NM_MANAGER_ERROR_UNKNOWN_DEVICE,
                                "The device doesn't match the active connection.");
            return NULL;
        }

        return (NMActiveConnection *) nm_vpn_connection_new(
            sett_conn,
            parent_device,
            nm_dbus_object_get_path(NM_DBUS_OBJECT(parent)),
            activation_reason,
            initial_state_flags,
            subject);
    }

    return (NMActiveConnection *) nm_act_request_new(sett_conn,
                                                     applied,
                                                     specific_object,
                                                     subject,
                                                     activation_type,
                                                     activation_reason,
                                                     initial_state_flags,
                                                     device);
}

static void
_internal_activation_auth_done(NMManager *         self,
                               NMActiveConnection *active,
                               gboolean            success,
                               const char *        error_desc)
{
    NMManagerPrivate *  priv = NM_MANAGER_GET_PRIVATE(self);
    NMActiveConnection *ac;
    gs_free_error GError *error = NULL;

    nm_assert(NM_IS_ACTIVE_CONNECTION(active));

    if (!success)
        goto fail;

    /* Don't continue with an autoconnect-activation if a more important activation
     * already exists.
     * We also check this earlier, but there we may fail to detect a duplicate
     * if the existing active connection was undergoing authorization.
     */
    if (NM_IN_SET(nm_active_connection_get_activation_reason(active),
                  NM_ACTIVATION_REASON_EXTERNAL,
                  NM_ACTIVATION_REASON_ASSUME,
                  NM_ACTIVATION_REASON_AUTOCONNECT)) {
        c_list_for_each_entry (ac, &priv->active_connections_lst_head, active_connections_lst) {
            if (nm_active_connection_get_device(ac) == nm_active_connection_get_device(active)
                && nm_active_connection_get_settings_connection(ac)
                       == nm_active_connection_get_settings_connection(active)
                && nm_active_connection_get_state(ac) <= NM_ACTIVE_CONNECTION_STATE_ACTIVATED) {
                g_set_error(&error,
                            NM_MANAGER_ERROR,
                            NM_MANAGER_ERROR_CONNECTION_ALREADY_ACTIVE,
                            "Connection '%s' is already active",
                            nm_active_connection_get_settings_connection_id(active));
                goto fail;
            }
        }
    }

    if (_internal_activate_generic(self, active, &error))
        return;

fail:
    nm_assert(error_desc || error);
    nm_active_connection_set_state_fail(active,
                                        NM_ACTIVE_CONNECTION_STATE_REASON_UNKNOWN,
                                        error_desc ?: error->message);
}

/**
 * nm_manager_activate_connection():
 * @self: the #NMManager
 * @sett_conn: the #NMSettingsConnection to activate on @device
 * @applied: (allow-none): the applied connection to activate on @device
 * @specific_object: the specific object path, if any, for the activation
 * @device: the #NMDevice to activate @sett_conn on. Can be %NULL for VPNs.
 * @subject: the subject which requested activation
 * @activation_type: whether to assume the connection. That is, take over gracefully,
 *   non-destructible.
 * @activation_reason: the reason for activation
 * @initial_state_flags: the initial state flags for the activation.
 * @error: return location for an error
 *
 * Begins a new internally-initiated activation of @sett_conn on @device.
 * @subject should be the subject of the activation that triggered this
 * one, or if this is an autoconnect request, a new internal subject.
 * The returned #NMActiveConnection is owned by the Manager and should be
 * referenced by the caller if the caller continues to use it. If @applied
 * is supplied, it shall not be modified by the caller afterwards.
 *
 * Returns: (transfer none): the new #NMActiveConnection that tracks
 * activation of @sett_conn on @device
 */
NMActiveConnection *
nm_manager_activate_connection(NMManager *            self,
                               NMSettingsConnection * sett_conn,
                               NMConnection *         applied,
                               const char *           specific_object,
                               NMDevice *             device,
                               NMAuthSubject *        subject,
                               NMActivationType       activation_type,
                               NMActivationReason     activation_reason,
                               NMActivationStateFlags initial_state_flags,
                               GError **              error)
{
    NMManagerPrivate *  priv;
    NMActiveConnection *active;
    AsyncOpData *       async_op_data;
    gboolean            is_vpn;

    g_return_val_if_fail(NM_IS_MANAGER(self), NULL);
    g_return_val_if_fail(NM_IS_SETTINGS_CONNECTION(sett_conn), NULL);
    is_vpn = _connection_is_vpn(nm_settings_connection_get_connection(sett_conn));
    g_return_val_if_fail(is_vpn || NM_IS_DEVICE(device), NULL);
    g_return_val_if_fail(!error || !*error, NULL);
    nm_assert(!nm_streq0(specific_object, "/"));

    priv = NM_MANAGER_GET_PRIVATE(self);

    if (!nm_auth_is_subject_in_acl_set_error(nm_settings_connection_get_connection(sett_conn),
                                             subject,
                                             NM_MANAGER_ERROR,
                                             NM_MANAGER_ERROR_PERMISSION_DENIED,
                                             error))
        return NULL;

    /* Look for a active connection that's equivalent and is already pending authorization
     * and eventual activation. This is used to de-duplicate concurrent activations which would
     * otherwise race and cause the device to disconnect and reconnect repeatedly.
     * In particular, this allows the master and multiple slaves to concurrently auto-activate
     * while all the slaves would use the same active-connection. */
    c_list_for_each_entry (async_op_data, &priv->async_op_lst_head, async_op_lst) {
        if (async_op_data->async_op_type != ASYNC_OP_TYPE_AC_AUTH_ACTIVATE_INTERNAL)
            continue;

        active = async_op_data->ac_auth.active;
        if (sett_conn == nm_active_connection_get_settings_connection(active)
            && nm_streq0(nm_active_connection_get_specific_object(active), specific_object)
            && (!device || nm_active_connection_get_device(active) == device)
            && nm_auth_subject_get_subject_type(nm_active_connection_get_subject(active))
                   == NM_AUTH_SUBJECT_TYPE_INTERNAL
            && nm_auth_subject_get_subject_type(subject) == NM_AUTH_SUBJECT_TYPE_INTERNAL
            && nm_active_connection_get_activation_reason(active) == activation_reason)
            return active;
    }

    active = _new_active_connection(self,
                                    is_vpn,
                                    sett_conn,
                                    NULL,
                                    applied,
                                    specific_object,
                                    device,
                                    subject,
                                    activation_type,
                                    activation_reason,
                                    initial_state_flags,
                                    error);
    if (!active)
        return NULL;

    nm_active_connection_authorize(active,
                                   NULL,
                                   _async_op_complete_ac_auth_cb,
                                   _async_op_data_new_authorize_activate_internal(self, active));
    return active;
}

/**
 * validate_activation_request:
 * @self: the #NMManager
 * @context: the D-Bus context of the requestor
 * @sett_conn: the #NMSettingsConnection to be activated, or %NULL if there
 *   is only a partial activation.
 * @connection: the partial #NMConnection to be activated (if @sett_conn is unspecified)
 * @device_path: the object path of the device to be activated, or NULL
 * @out_device: on successful return, the #NMDevice to be activated with @connection
 *   The caller may pass in a device which shortcuts the lookup by path.
 *   In this case, the passed in device must have the matching @device_path
 *   already.
 * @out_is_vpn: on successful return, %TRUE if @connection is a VPN connection
 * @error: location to store an error on failure
 *
 * Performs basic validation on an activation request, including ensuring that
 * the requestor is a valid Unix process, is not disallowed in @connection
 * permissions, and that a device exists that can activate @connection.
 *
 * Returns: on success, the #NMAuthSubject representing the requestor, or
 *   %NULL on error
 */
static NMAuthSubject *
validate_activation_request(NMManager *            self,
                            GDBusMethodInvocation *context,
                            NMSettingsConnection * sett_conn,
                            NMConnection *         connection,
                            const char *           device_path,
                            NMDevice **            out_device,
                            gboolean *             out_is_vpn,
                            GError **              error)
{
    NMDevice *      device                 = NULL;
    gboolean        is_vpn                 = FALSE;
    gs_unref_object NMAuthSubject *subject = NULL;

    nm_assert(!sett_conn || NM_IS_SETTINGS_CONNECTION(sett_conn));
    nm_assert(!connection || NM_IS_CONNECTION(connection));
    nm_assert(sett_conn || connection);
    nm_assert(!connection || !sett_conn
              || connection == nm_settings_connection_get_connection(sett_conn));
    nm_assert(out_device);
    nm_assert(out_is_vpn);

    if (!connection)
        connection = nm_settings_connection_get_connection(sett_conn);

    /* Validate the caller */
    subject = nm_dbus_manager_new_auth_subject_from_context(context);
    if (!subject) {
        g_set_error_literal(error,
                            NM_MANAGER_ERROR,
                            NM_MANAGER_ERROR_PERMISSION_DENIED,
                            NM_UTILS_ERROR_MSG_REQ_UID_UKNOWN);
        return NULL;
    }

    if (!nm_auth_is_subject_in_acl_set_error(connection,
                                             subject,
                                             NM_MANAGER_ERROR,
                                             NM_MANAGER_ERROR_PERMISSION_DENIED,
                                             error))
        return NULL;

    is_vpn = _connection_is_vpn(connection);

    if (*out_device) {
        device = *out_device;
        nm_assert(NM_IS_DEVICE(device));
        nm_assert(device_path);
        nm_assert(nm_streq0(device_path, nm_dbus_object_get_path(NM_DBUS_OBJECT(device))));
        nm_assert(device == nm_manager_get_device_by_path(self, device_path));
    } else if (device_path) {
        device = nm_manager_get_device_by_path(self, device_path);
        if (!device) {
            g_set_error_literal(error,
                                NM_MANAGER_ERROR,
                                NM_MANAGER_ERROR_UNKNOWN_DEVICE,
                                "Device not found");
            return NULL;
        }
    } else if (!is_vpn) {
        gs_free_error GError *local = NULL;

        device = nm_manager_get_best_device_for_connection(self,
                                                           sett_conn,
                                                           connection,
                                                           TRUE,
                                                           NULL,
                                                           &local);
        if (!device) {
            gs_free char *iface = NULL;

            /* VPN and software-device connections don't need a device yet,
             * but non-virtual connections do ... */
            if (!nm_connection_is_virtual(connection)) {
                g_set_error(error,
                            NM_MANAGER_ERROR,
                            NM_MANAGER_ERROR_UNKNOWN_DEVICE,
                            "No suitable device found for this connection (%s).",
                            local->message);
                return NULL;
            }

            /* Look for an existing device with the connection's interface name */
            iface = nm_manager_get_connection_iface(self, connection, NULL, NULL, error);
            if (!iface)
                return NULL;

            device = find_device_by_iface(self, iface, connection, NULL);
            if (!device) {
                g_set_error_literal(error,
                                    NM_MANAGER_ERROR,
                                    NM_MANAGER_ERROR_UNKNOWN_DEVICE,
                                    "Failed to find a compatible device for this connection");
                return NULL;
            }
        }
    }

    nm_assert(is_vpn || NM_IS_DEVICE(device));

    *out_device = device;
    *out_is_vpn = is_vpn;
    return g_steal_pointer(&subject);
}

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

static void
_activation_auth_done(NMManager *            self,
                      NMActiveConnection *   active,
                      GDBusMethodInvocation *invocation,
                      gboolean               success,
                      const char *           error_desc)
{
    GError *              error = NULL;
    NMAuthSubject *       subject;
    NMSettingsConnection *connection;

    subject    = nm_active_connection_get_subject(active);
    connection = nm_active_connection_get_settings_connection(active);

    if (!success) {
        error =
            g_error_new_literal(NM_MANAGER_ERROR, NM_MANAGER_ERROR_PERMISSION_DENIED, error_desc);
        goto fail;
    }

    if (!_internal_activate_generic(self, active, &error))
        goto fail;

    nm_settings_connection_autoconnect_blocked_reason_set(
        connection,
        NM_SETTINGS_AUTO_CONNECT_BLOCKED_REASON_USER_REQUEST,
        FALSE);
    g_dbus_method_invocation_return_value(
        invocation,
        g_variant_new("(o)", nm_dbus_object_get_path(NM_DBUS_OBJECT(active))));
    nm_audit_log_connection_op(NM_AUDIT_OP_CONN_ACTIVATE, connection, TRUE, NULL, subject, NULL);
    return;

fail:
    nm_audit_log_connection_op(NM_AUDIT_OP_CONN_ACTIVATE,
                               connection,
                               FALSE,
                               NULL,
                               subject,
                               error->message);
    nm_active_connection_set_state_fail(active,
                                        NM_ACTIVE_CONNECTION_STATE_REASON_UNKNOWN,
                                        error->message);

    g_dbus_method_invocation_take_error(invocation, error);
}

static void
impl_manager_activate_connection(NMDBusObject *                     obj,
                                 const NMDBusInterfaceInfoExtended *interface_info,
                                 const NMDBusMethodInfoExtended *   method_info,
                                 GDBusConnection *                  dbus_connection,
                                 const char *                       sender,
                                 GDBusMethodInvocation *            invocation,
                                 GVariant *                         parameters)
{
    NMManager *       self                     = NM_MANAGER(obj);
    NMManagerPrivate *priv                     = NM_MANAGER_GET_PRIVATE(self);
    gs_unref_object NMActiveConnection *active = NULL;
    gs_unref_object NMAuthSubject *subject     = NULL;
    NMSettingsConnection *         sett_conn   = NULL;
    NMDevice *                     device      = NULL;
    gboolean                       is_vpn      = FALSE;
    GError *                       error       = NULL;
    const char *                   connection_path;
    const char *                   device_path;
    const char *                   specific_object_path;

    g_variant_get(parameters, "(&o&o&o)", &connection_path, &device_path, &specific_object_path);

    connection_path      = nm_dbus_path_not_empty(connection_path);
    specific_object_path = nm_dbus_path_not_empty(specific_object_path);
    device_path          = nm_dbus_path_not_empty(device_path);

    /* If the connection path is given and valid, that connection is activated.
     * Otherwise, the "best" connection for the device is chosen and activated,
     * regardless of whether that connection is autoconnect-enabled or not
     * (since this is an explicit request, not an auto-activation request).
     */
    if (connection_path) {
        sett_conn = nm_settings_get_connection_by_path(priv->settings, connection_path);
        if (!sett_conn) {
            error = g_error_new_literal(NM_MANAGER_ERROR,
                                        NM_MANAGER_ERROR_UNKNOWN_CONNECTION,
                                        "Connection could not be found.");
            goto error;
        }
    } else {
        /* If no connection is given, find a suitable connection for the given device path */
        if (!device_path) {
            error = g_error_new_literal(
                NM_MANAGER_ERROR,
                NM_MANAGER_ERROR_UNKNOWN_DEVICE,
                "Only devices may be activated without a specifying a connection");
            goto error;
        }
        device = nm_manager_get_device_by_path(self, device_path);
        if (!device) {
            error = g_error_new(NM_MANAGER_ERROR,
                                NM_MANAGER_ERROR_UNKNOWN_DEVICE,
                                "Can not activate an unknown device '%s'",
                                device_path);
            goto error;
        }

        sett_conn = nm_device_get_best_connection(device, specific_object_path, &error);
        if (!sett_conn)
            goto error;
    }

    subject = validate_activation_request(self,
                                          invocation,
                                          sett_conn,
                                          NULL,
                                          device_path,
                                          &device,
                                          &is_vpn,
                                          &error);
    if (!subject)
        goto error;

    active = _new_active_connection(self,
                                    is_vpn,
                                    sett_conn,
                                    NULL,
                                    NULL,
                                    specific_object_path,
                                    device,
                                    subject,
                                    NM_ACTIVATION_TYPE_MANAGED,
                                    NM_ACTIVATION_REASON_USER_REQUEST,
                                    _activation_bind_lifetime_to_profile_visibility(subject),
                                    &error);
    if (!active)
        goto error;

    nm_active_connection_authorize(
        active,
        NULL,
        _async_op_complete_ac_auth_cb,
        _async_op_data_new_ac_auth_activate_user(self, active, invocation));

    /* we passed the pointer on to _async_op_data_new_ac_auth_activate_user() */
    g_steal_pointer(&active);

    return;

error:
    if (sett_conn) {
        nm_audit_log_connection_op(NM_AUDIT_OP_CONN_ACTIVATE,
                                   sett_conn,
                                   FALSE,
                                   NULL,
                                   subject,
                                   error->message);
    }
    g_dbus_method_invocation_take_error(invocation, error);
}

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

static void
activation_add_done(NMSettings *           settings,
                    NMSettingsConnection * new_connection,
                    GError *               error,
                    GDBusMethodInvocation *context,
                    NMAuthSubject *        subject,
                    gpointer               user_data)
{
    NMManager *     self;
    gs_unref_object NMActiveConnection *active = NULL;
    gs_free_error GError *local                = NULL;
    gpointer              async_op_type_ptr;
    AsyncOpType           async_op_type;
    GVariant *            result_floating;

    nm_utils_user_data_unpack(user_data, &self, &active, &async_op_type_ptr);
    async_op_type = GPOINTER_TO_INT(async_op_type_ptr);

    if (error)
        goto fail;

    nm_active_connection_set_settings_connection(active, new_connection);

    if (!_internal_activate_generic(self, active, &local))
        goto fail;

    if (async_op_type == ASYNC_OP_TYPE_AC_AUTH_ADD_AND_ACTIVATE) {
        result_floating = g_variant_new("(oo)",
                                        nm_dbus_object_get_path(NM_DBUS_OBJECT(new_connection)),
                                        nm_dbus_object_get_path(NM_DBUS_OBJECT(active)));
    } else {
        result_floating = g_variant_new("(oo@a{sv})",
                                        nm_dbus_object_get_path(NM_DBUS_OBJECT(new_connection)),
                                        nm_dbus_object_get_path(NM_DBUS_OBJECT(active)),
                                        g_variant_new_array(G_VARIANT_TYPE("{sv}"), NULL, 0));
    }
    g_dbus_method_invocation_return_value(context, result_floating);

    nm_audit_log_connection_op(NM_AUDIT_OP_CONN_ADD_ACTIVATE,
                               nm_active_connection_get_settings_connection(active),
                               TRUE,
                               NULL,
                               nm_active_connection_get_subject(active),
                               NULL);
    return;

fail:
    if (local) {
        nm_assert(!error);
        error = local;
    } else
        nm_assert(error);

    nm_active_connection_set_state_fail(active,
                                        NM_ACTIVE_CONNECTION_STATE_REASON_UNKNOWN,
                                        error->message);
    if (new_connection)
        nm_settings_connection_delete(new_connection, FALSE);
    g_dbus_method_invocation_return_gerror(context, error);
    nm_audit_log_connection_op(NM_AUDIT_OP_CONN_ADD_ACTIVATE,
                               NULL,
                               FALSE,
                               NULL,
                               nm_active_connection_get_subject(active),
                               error->message);
}

static void
_add_and_activate_auth_done(NMManager *                     self,
                            AsyncOpType                     async_op_type,
                            NMActiveConnection *            active,
                            NMConnection *                  connection,
                            GDBusMethodInvocation *         invocation,
                            NMSettingsConnectionPersistMode persist_mode,
                            gboolean                        is_volatile,
                            gboolean                        success,
                            const char *                    error_desc)
{
    NMManagerPrivate *priv;
    GError *          error = NULL;

    if (!success) {
        error =
            g_error_new_literal(NM_MANAGER_ERROR, NM_MANAGER_ERROR_PERMISSION_DENIED, error_desc);
        nm_audit_log_connection_op(NM_AUDIT_OP_CONN_ADD_ACTIVATE,
                                   NULL,
                                   FALSE,
                                   NULL,
                                   nm_active_connection_get_subject(active),
                                   error->message);
        g_dbus_method_invocation_take_error(invocation, error);
        return;
    }

    priv = NM_MANAGER_GET_PRIVATE(self);

    /* FIXME(shutdown): nm_settings_add_connection_dbus() cannot be cancelled. It should be made
     * cancellable and tracked via AsyncOpData to be able to do a clean
     * shutdown. */
    nm_settings_add_connection_dbus(
        priv->settings,
        connection,
        persist_mode,
        NM_SETTINGS_CONNECTION_ADD_REASON_NONE,
        (is_volatile ? NM_SETTINGS_CONNECTION_INT_FLAGS_VOLATILE
                     : NM_SETTINGS_CONNECTION_INT_FLAGS_NONE),
        nm_active_connection_get_subject(active),
        invocation,
        activation_add_done,
        nm_utils_user_data_pack(self, g_object_ref(active), GINT_TO_POINTER(async_op_type)));
}

static void
impl_manager_add_and_activate_connection(NMDBusObject *                     obj,
                                         const NMDBusInterfaceInfoExtended *interface_info,
                                         const NMDBusMethodInfoExtended *   method_info,
                                         GDBusConnection *                  dbus_connection,
                                         const char *                       sender,
                                         GDBusMethodInvocation *            invocation,
                                         GVariant *                         parameters)
{
    NMManager *       self                     = NM_MANAGER(obj);
    NMManagerPrivate *priv                     = NM_MANAGER_GET_PRIVATE(self);
    gs_unref_object NMConnection *incompl_conn = NULL;
    gs_unref_object NMActiveConnection *active = NULL;
    gs_unref_object NMAuthSubject *subject     = NULL;
    GError *                       error       = NULL;
    NMDevice *                     device      = NULL;
    gboolean                       is_vpn      = FALSE;
    gs_unref_variant GVariant *settings        = NULL;
    gs_unref_variant GVariant *options         = NULL;
    const char *               device_path;
    const char *               specific_object_path;
    gs_free NMConnection **         conns            = NULL;
    NMSettingsConnectionPersistMode persist_mode     = NM_SETTINGS_CONNECTION_PERSIST_MODE_TO_DISK;
    gboolean                        is_volatile      = FALSE;
    gboolean                        bind_dbus_client = FALSE;
    AsyncOpType                     async_op_type;

    if (nm_streq(method_info->parent.name, "AddAndActivateConnection2")) {
        async_op_type = ASYNC_OP_TYPE_AC_AUTH_ADD_AND_ACTIVATE2;
        g_variant_get(parameters,
                      "(@a{sa{sv}}&o&o@a{sv})",
                      &settings,
                      &device_path,
                      &specific_object_path,
                      &options);
    } else {
        nm_assert(nm_streq(method_info->parent.name, "AddAndActivateConnection"));
        async_op_type = ASYNC_OP_TYPE_AC_AUTH_ADD_AND_ACTIVATE;
        g_variant_get(parameters,
                      "(@a{sa{sv}}&o&o)",
                      &settings,
                      &device_path,
                      &specific_object_path);
    }

    if (options) {
        GVariantIter iter;
        const char * option_name;
        GVariant *   option_value;

        g_variant_iter_init(&iter, options);
        while (g_variant_iter_next(&iter, "{&sv}", &option_name, &option_value)) {
            gs_unref_variant GVariant *option_value_free = NULL;
            const char *               s;

            option_value_free = option_value;

            if (nm_streq(option_name, "persist")
                && g_variant_is_of_type(option_value, G_VARIANT_TYPE_STRING)) {
                s = g_variant_get_string(option_value, NULL);

                is_volatile  = FALSE;
                persist_mode = NM_SETTINGS_CONNECTION_PERSIST_MODE_TO_DISK;

                if (nm_streq(s, "volatile")) {
                    persist_mode = NM_SETTINGS_CONNECTION_PERSIST_MODE_IN_MEMORY_ONLY;
                    is_volatile  = TRUE;
                } else if (nm_streq(s, "memory"))
                    persist_mode = NM_SETTINGS_CONNECTION_PERSIST_MODE_IN_MEMORY_ONLY;
                else if (nm_streq(s, "disk")) {
                    /* pass */
                } else {
                    error = g_error_new_literal(
                        NM_MANAGER_ERROR,
                        NM_MANAGER_ERROR_INVALID_ARGUMENTS,
                        "Option \"persist\" must be one of \"volatile\", \"memory\" or \"disk\"");
                    goto error;
                }
            } else if (nm_streq(option_name, "bind-activation")
                       && g_variant_is_of_type(option_value, G_VARIANT_TYPE_STRING)) {
                s = g_variant_get_string(option_value, NULL);

                if (nm_streq(s, "dbus-client"))
                    bind_dbus_client = TRUE;
                else if (nm_streq(s, "none"))
                    bind_dbus_client = FALSE;
                else {
                    error = g_error_new_literal(
                        NM_MANAGER_ERROR,
                        NM_MANAGER_ERROR_INVALID_ARGUMENTS,
                        "Option \"bind-activation\" must be one of \"dbus-client\" or \"none\"");
                    goto error;
                }
            } else {
                error = g_error_new_literal(NM_MANAGER_ERROR,
                                            NM_MANAGER_ERROR_INVALID_ARGUMENTS,
                                            "Unknown extra option passed");
                goto error;
            }
        }
    }

    specific_object_path = nm_dbus_path_not_empty(specific_object_path);
    device_path          = nm_dbus_path_not_empty(device_path);

    /* Try to create a new connection with the given settings.
     * We allow empty settings for AddAndActivateConnection(). In that case,
     * the connection will be completed in nm_utils_complete_generic() or
     * nm_device_complete_connection() below. Just make sure we don't expect
     * specific data being in the connection till then (especially in
     * validate_activation_request()).
     */
    incompl_conn = nm_simple_connection_new();
    if (settings && g_variant_n_children(settings))
        _nm_connection_replace_settings(incompl_conn,
                                        settings,
                                        NM_SETTING_PARSE_FLAGS_STRICT,
                                        NULL);

    subject = validate_activation_request(self,
                                          invocation,
                                          NULL,
                                          incompl_conn,
                                          device_path,
                                          &device,
                                          &is_vpn,
                                          &error);
    if (!subject)
        goto error;

    if (is_vpn) {
        /* Try to fill the VPN's connection setting and name at least */
        if (!nm_connection_get_setting_vpn(incompl_conn)) {
            error = g_error_new_literal(NM_CONNECTION_ERROR,
                                        NM_CONNECTION_ERROR_MISSING_SETTING,
                                        "VPN connections require a 'vpn' setting");
            g_prefix_error(&error, "%s: ", NM_SETTING_VPN_SETTING_NAME);
            goto error;
        }

        conns = nm_settings_connections_array_to_connections(
            nm_settings_get_connections(priv->settings, NULL),
            -1);

        nm_utils_complete_generic(priv->platform,
                                  incompl_conn,
                                  NM_SETTING_VPN_SETTING_NAME,
                                  conns,
                                  NULL,
                                  _("VPN connection"),
                                  NULL,
                                  NULL,
                                  FALSE); /* No IPv6 by default for now */
    } else {
        conns = nm_settings_connections_array_to_connections(
            nm_settings_get_connections(priv->settings, NULL),
            -1);
        /* Let each device subclass complete the connection */
        if (!nm_device_complete_connection(device,
                                           incompl_conn,
                                           specific_object_path,
                                           conns,
                                           &error))
            goto error;
    }

    nm_assert(_nm_connection_verify(incompl_conn, NULL) == NM_SETTING_VERIFY_SUCCESS);

    active = _new_active_connection(self,
                                    is_vpn,
                                    NULL,
                                    incompl_conn,
                                    NULL,
                                    specific_object_path,
                                    device,
                                    subject,
                                    NM_ACTIVATION_TYPE_MANAGED,
                                    NM_ACTIVATION_REASON_USER_REQUEST,
                                    _activation_bind_lifetime_to_profile_visibility(subject),
                                    &error);
    if (!active)
        goto error;

    if (bind_dbus_client) {
        NMKeepAlive *keep_alive;

        keep_alive = nm_active_connection_get_keep_alive(active);
        nm_keep_alive_set_dbus_client_watch(keep_alive, dbus_connection, sender);
        nm_keep_alive_arm(keep_alive);
    }

    nm_active_connection_authorize(active,
                                   incompl_conn,
                                   _async_op_complete_ac_auth_cb,
                                   _async_op_data_new_ac_auth_add_and_activate(self,
                                                                               async_op_type,
                                                                               active,
                                                                               invocation,
                                                                               incompl_conn,
                                                                               persist_mode,
                                                                               is_volatile));

    /* we passed the pointers on to _async_op_data_new_ac_auth_add_and_activate() */
    g_steal_pointer(&incompl_conn);
    g_steal_pointer(&active);
    return;

error:
    nm_audit_log_connection_op(NM_AUDIT_OP_CONN_ADD_ACTIVATE,
                               NULL,
                               FALSE,
                               NULL,
                               subject,
                               error->message);
    g_dbus_method_invocation_take_error(invocation, error);
}

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

gboolean
nm_manager_deactivate_connection(NMManager *         manager,
                                 NMActiveConnection *active,
                                 NMDeviceStateReason reason,
                                 GError **           error)
{
    if (NM_IS_VPN_CONNECTION(active)) {
        NMActiveConnectionStateReason vpn_reason =
            NM_ACTIVE_CONNECTION_STATE_REASON_USER_DISCONNECTED;

        if (nm_device_state_reason_check(reason) == NM_DEVICE_STATE_REASON_CONNECTION_REMOVED)
            vpn_reason = NM_ACTIVE_CONNECTION_STATE_REASON_CONNECTION_REMOVED;

        if (!nm_vpn_connection_deactivate(NM_VPN_CONNECTION(active), vpn_reason, FALSE)) {
            g_set_error_literal(error,
                                NM_MANAGER_ERROR,
                                NM_MANAGER_ERROR_CONNECTION_NOT_ACTIVE,
                                "The VPN connection was not active.");
            return FALSE;
        }
    } else {
        nm_assert(NM_IS_ACT_REQUEST(active));
        nm_device_disconnect_active_connection(active,
                                               reason,
                                               NM_ACTIVE_CONNECTION_STATE_REASON_UNKNOWN);
    }

    _notify(manager, PROP_ACTIVE_CONNECTIONS);
    return TRUE;
}

static void
deactivate_net_auth_done_cb(NMAuthChain *chain, GDBusMethodInvocation *context, gpointer user_data)
{
    NMManager *         self  = NM_MANAGER(user_data);
    GError *            error = NULL;
    NMAuthCallResult    result;
    NMActiveConnection *active;
    char *              path;

    nm_assert(G_IS_DBUS_METHOD_INVOCATION(context));

    c_list_unlink(nm_auth_chain_parent_lst_list(chain));

    path   = nm_auth_chain_get_data(chain, "path");
    result = nm_auth_chain_get_result(chain, NM_AUTH_PERMISSION_NETWORK_CONTROL);
    active = active_connection_get_by_path(self, path);

    if (result != NM_AUTH_CALL_RESULT_YES) {
        error = g_error_new_literal(NM_MANAGER_ERROR,
                                    NM_MANAGER_ERROR_PERMISSION_DENIED,
                                    "Not authorized to deactivate connections");
    } else if (!active) {
        error = g_error_new_literal(NM_MANAGER_ERROR,
                                    NM_MANAGER_ERROR_CONNECTION_NOT_ACTIVE,
                                    "The connection was not active.");
    } else {
        /* success; deactivation allowed */
        if (!nm_manager_deactivate_connection(self,
                                              active,
                                              NM_DEVICE_STATE_REASON_USER_REQUESTED,
                                              &error))
            nm_assert(error);
    }

    if (active) {
        nm_audit_log_connection_op(NM_AUDIT_OP_CONN_DEACTIVATE,
                                   nm_active_connection_get_settings_connection(active),
                                   !error,
                                   NULL,
                                   nm_auth_chain_get_subject(chain),
                                   error ? error->message : NULL);
    }

    if (error)
        g_dbus_method_invocation_take_error(context, error);
    else
        g_dbus_method_invocation_return_value(context, NULL);
}

static void
impl_manager_deactivate_connection(NMDBusObject *                     obj,
                                   const NMDBusInterfaceInfoExtended *interface_info,
                                   const NMDBusMethodInfoExtended *   method_info,
                                   GDBusConnection *                  dbus_connection,
                                   const char *                       sender,
                                   GDBusMethodInvocation *            invocation,
                                   GVariant *                         parameters)
{
    NMManager *           self = NM_MANAGER(obj);
    NMManagerPrivate *    priv = NM_MANAGER_GET_PRIVATE(self);
    NMActiveConnection *  ac;
    NMSettingsConnection *sett_conn = NULL;
    GError *              error     = NULL;
    NMAuthSubject *       subject   = NULL;
    NMAuthChain *         chain;
    const char *          active_path;

    g_variant_get(parameters, "(&o)", &active_path);

    /* Find the connection by its object path */
    ac = active_connection_get_by_path(self, active_path);
    if (ac)
        sett_conn = nm_active_connection_get_settings_connection(ac);

    if (!sett_conn) {
        error = g_error_new_literal(NM_MANAGER_ERROR,
                                    NM_MANAGER_ERROR_CONNECTION_NOT_ACTIVE,
                                    "The connection was not active.");
        goto done;
    }

    /* Validate the caller */
    subject = nm_dbus_manager_new_auth_subject_from_context(invocation);
    if (!subject) {
        error = g_error_new_literal(NM_MANAGER_ERROR,
                                    NM_MANAGER_ERROR_PERMISSION_DENIED,
                                    NM_UTILS_ERROR_MSG_REQ_UID_UKNOWN);
        goto done;
    }

    if (!nm_auth_is_subject_in_acl_set_error(nm_settings_connection_get_connection(sett_conn),
                                             subject,
                                             NM_MANAGER_ERROR,
                                             NM_MANAGER_ERROR_PERMISSION_DENIED,
                                             &error))
        goto done;

    chain = nm_auth_chain_new_subject(subject, invocation, deactivate_net_auth_done_cb, self);
    c_list_link_tail(&priv->auth_lst_head, nm_auth_chain_parent_lst_list(chain));
    nm_auth_chain_set_data(chain, "path", g_strdup(active_path), g_free);
    nm_auth_chain_add_call(chain, NM_AUTH_PERMISSION_NETWORK_CONTROL, TRUE);

done:
    if (error) {
        if (sett_conn) {
            nm_audit_log_connection_op(NM_AUDIT_OP_CONN_DEACTIVATE,
                                       sett_conn,
                                       FALSE,
                                       NULL,
                                       subject,
                                       error->message);
        }
        g_dbus_method_invocation_take_error(invocation, error);
    }
    g_clear_object(&subject);
}

static gboolean
sleep_devices_add(NMManager *self, NMDevice *device, gboolean suspending)
{
    NMManagerPrivate *             priv   = NM_MANAGER_GET_PRIVATE(self);
    NMSleepMonitorInhibitorHandle *handle = NULL;

    if (g_hash_table_lookup_extended(priv->sleep_devices, device, NULL, (gpointer *) &handle)) {
        if (suspending) {
            /* if we are suspending, always insert a new handle in sleep_devices.
             * Even if we had an old handle, it might be stale by now. */
            g_hash_table_insert(priv->sleep_devices,
                                device,
                                nm_sleep_monitor_inhibit_take(priv->sleep_monitor));
            if (handle)
                nm_sleep_monitor_inhibit_release(priv->sleep_monitor, handle);
        }
        return FALSE;
    }

    g_hash_table_insert(priv->sleep_devices,
                        g_object_ref(device),
                        suspending ? nm_sleep_monitor_inhibit_take(priv->sleep_monitor) : NULL);
    g_signal_connect(device, "notify::" NM_DEVICE_STATE, (GCallback) device_sleep_cb, self);
    return TRUE;
}

static gboolean
sleep_devices_remove(NMManager *self, NMDevice *device)
{
    NMManagerPrivate *             priv = NM_MANAGER_GET_PRIVATE(self);
    NMSleepMonitorInhibitorHandle *handle;

    if (!g_hash_table_lookup_extended(priv->sleep_devices, device, NULL, (gpointer *) &handle))
        return FALSE;

    if (handle)
        nm_sleep_monitor_inhibit_release(priv->sleep_monitor, handle);

    /* Remove device from hash */
    g_signal_handlers_disconnect_by_func(device, device_sleep_cb, self);
    g_hash_table_remove(priv->sleep_devices, device);
    g_object_unref(device);
    return TRUE;
}

static void
sleep_devices_clear(NMManager *self)
{
    NMManagerPrivate *             priv = NM_MANAGER_GET_PRIVATE(self);
    NMDevice *                     device;
    NMSleepMonitorInhibitorHandle *handle;
    GHashTableIter                 iter;

    if (!priv->sleep_devices)
        return;

    g_hash_table_iter_init(&iter, priv->sleep_devices);
    while (g_hash_table_iter_next(&iter, (gpointer *) &device, (gpointer *) &handle)) {
        g_signal_handlers_disconnect_by_func(device, device_sleep_cb, self);
        if (handle)
            nm_sleep_monitor_inhibit_release(priv->sleep_monitor, handle);
        g_object_unref(device);
        g_hash_table_iter_remove(&iter);
    }
}

static void
device_sleep_cb(NMDevice *device, GParamSpec *pspec, NMManager *self)
{
    switch (nm_device_get_state(device)) {
    case NM_DEVICE_STATE_DISCONNECTED:
        _LOGD(LOGD_SUSPEND, "sleep: unmanaging device %s", nm_device_get_ip_iface(device));
        nm_device_set_unmanaged_by_flags_queue(device,
                                               NM_UNMANAGED_SLEEPING,
                                               TRUE,
                                               NM_DEVICE_STATE_REASON_SLEEPING);
        break;
    case NM_DEVICE_STATE_UNMANAGED:
        _LOGD(LOGD_SUSPEND, "sleep: device %s is ready", nm_device_get_ip_iface(device));

        if (!sleep_devices_remove(self, device))
            g_return_if_reached();

        break;
    default:
        return;
    }
}

static void
do_sleep_wake(NMManager *self, gboolean sleeping_changed)
{
    NMManagerPrivate *priv = NM_MANAGER_GET_PRIVATE(self);
    gboolean          suspending, waking_from_suspend;
    NMDevice *        device;

    suspending          = sleeping_changed && priv->sleeping;
    waking_from_suspend = sleeping_changed && !priv->sleeping;

    if (manager_sleeping(self)) {
        _LOGD(LOGD_SUSPEND, "sleep: %s...", suspending ? "sleeping" : "disabling");

        /* FIXME: are there still hardware devices that need to be disabled around
         * suspend/resume?
         */
        c_list_for_each_entry (device, &priv->devices_lst_head, devices_lst) {
            if (nm_device_is_software(device)) {
                /* If a user disables networking we consider that as an
                 * indication that also software devices must be disconnected.
                 * But we don't want to destroy them for external events as
                 * a system suspend.
                 */
                if (suspending)
                    continue;
            }
            /* Wake-on-LAN devices will be taken down post-suspend rather than pre- */
            if (suspending && device_is_wake_on_lan(priv->platform, device)) {
                _LOGD(LOGD_SUSPEND,
                      "sleep: device %s has wake-on-lan, skipping",
                      nm_device_get_ip_iface(device));
                continue;
            }

            if (nm_device_is_activating(device)
                || nm_device_get_state(device) == NM_DEVICE_STATE_ACTIVATED) {
                _LOGD(LOGD_SUSPEND,
                      "sleep: wait disconnection of device %s",
                      nm_device_get_ip_iface(device));

                if (sleep_devices_add(self, device, suspending))
                    nm_device_queue_state(device,
                                          NM_DEVICE_STATE_DEACTIVATING,
                                          NM_DEVICE_STATE_REASON_SLEEPING);
            } else {
                nm_device_set_unmanaged_by_flags(device,
                                                 NM_UNMANAGED_SLEEPING,
                                                 TRUE,
                                                 NM_DEVICE_STATE_REASON_SLEEPING);
            }
        }
    } else {
        _LOGD(LOGD_SUSPEND, "sleep: %s...", waking_from_suspend ? "waking up" : "re-enabling");

        sleep_devices_clear(self);

        if (waking_from_suspend) {
            c_list_for_each_entry (device, &priv->devices_lst_head, devices_lst) {
                if (nm_device_is_software(device))
                    continue;

                /* Belatedly take down Wake-on-LAN devices; ideally we wouldn't have to do this
                 * but for now it's the only way to make sure we re-check their connectivity.
                 */
                if (device_is_wake_on_lan(priv->platform, device))
                    nm_device_set_unmanaged_by_flags(device,
                                                     NM_UNMANAGED_SLEEPING,
                                                     TRUE,
                                                     NM_DEVICE_STATE_REASON_SLEEPING);

                /* Check if the device is unmanaged but the state transition is still pending.
                 * If so, change state now so that later we re-manage the device forcing a
                 * re-check of available connections.
                 */
                if (!nm_device_get_managed(device, FALSE)
                    && nm_device_get_state(device) != NM_DEVICE_STATE_UNMANAGED) {
                    nm_device_state_changed(device,
                                            NM_DEVICE_STATE_UNMANAGED,
                                            NM_DEVICE_STATE_REASON_SLEEPING);
                }
            }
        }

        /* Ensure rfkill state is up-to-date since we don't respond to state
         * changes during sleep.
         */
        nm_manager_rfkill_update(self, RFKILL_TYPE_UNKNOWN);

        /* Re-manage managed devices */
        c_list_for_each_entry (device, &priv->devices_lst_head, devices_lst) {
            guint i;

            if (nm_device_is_software(device)
                && !nm_device_get_unmanaged_flags(device, NM_UNMANAGED_SLEEPING)) {
                /* DHCP leases of software devices could have gone stale
                 * so we need to renew them. */
                nm_device_update_dynamic_ip_setup(device);
                continue;
            }

            /* enable/disable wireless devices since that we don't respond
             * to killswitch changes during sleep.
             */
            for (i = 0; i < RFKILL_TYPE_MAX; i++) {
                RadioState *rstate  = &priv->radio_states[i];
                gboolean    enabled = radio_enabled_for_rstate(rstate, TRUE);

                if (rstate->desc) {
                    _LOGD(LOGD_RFKILL,
                          "rfkill: %s %s devices (hw_enabled %d, sw_enabled %d, user_enabled %d)",
                          enabled ? "enabling" : "disabling",
                          rstate->desc,
                          rstate->hw_enabled,
                          rstate->sw_enabled,
                          rstate->user_enabled);
                }
                if (nm_device_get_rfkill_type(device) == rstate->rtype)
                    nm_device_set_enabled(device, enabled);
            }

            nm_device_set_unmanaged_by_flags(device,
                                             NM_UNMANAGED_SLEEPING,
                                             FALSE,
                                             NM_DEVICE_STATE_REASON_NOW_MANAGED);
        }
    }

    nm_manager_update_state(self);
}

static void
_internal_sleep(NMManager *self, gboolean do_sleep)
{
    NMManagerPrivate *priv;

    g_return_if_fail(NM_IS_MANAGER(self));

    priv = NM_MANAGER_GET_PRIVATE(self);

    if (priv->sleeping == do_sleep)
        return;

    _LOGI(LOGD_SUSPEND,
          "sleep: %s requested (sleeping: %s  enabled: %s)",
          do_sleep ? "sleep" : "wake",
          priv->sleeping ? "yes" : "no",
          priv->net_enabled ? "yes" : "no");

    priv->sleeping = do_sleep;

    do_sleep_wake(self, TRUE);

    _notify(self, PROP_SLEEPING);
}

static void
impl_manager_sleep(NMDBusObject *                     obj,
                   const NMDBusInterfaceInfoExtended *interface_info,
                   const NMDBusMethodInfoExtended *   method_info,
                   GDBusConnection *                  connection,
                   const char *                       sender,
                   GDBusMethodInvocation *            invocation,
                   GVariant *                         parameters)
{
    NMManager *       self                 = NM_MANAGER(obj);
    NMManagerPrivate *priv                 = NM_MANAGER_GET_PRIVATE(self);
    GError *          error                = NULL;
    gs_unref_object NMAuthSubject *subject = NULL;
    gboolean                       do_sleep;

    g_variant_get(parameters, "(b)", &do_sleep);

    subject = nm_dbus_manager_new_auth_subject_from_context(invocation);

    if (priv->sleeping == do_sleep) {
        error = g_error_new(NM_MANAGER_ERROR,
                            NM_MANAGER_ERROR_ALREADY_ASLEEP_OR_AWAKE,
                            "Already %s",
                            do_sleep ? "asleep" : "awake");
        nm_audit_log_control_op(NM_AUDIT_OP_SLEEP_CONTROL,
                                do_sleep ? "on" : "off",
                                FALSE,
                                subject,
                                error->message);
        g_dbus_method_invocation_take_error(invocation, error);
        return;
    }

    /* Unconditionally allow the request.  Previously it was polkit protected
     * but unfortunately that doesn't work for short-lived processes like
     * pm-utils.  It uses dbus-send without --print-reply, which quits
     * immediately after sending the request, and NM is unable to obtain the
     * sender's UID as dbus-send has already dropped off the bus.  Thus NM
     * fails the request.  Instead, don't validate the request, but rely on
     * D-Bus permissions to restrict the call to root.
     */
    _internal_sleep(self, do_sleep);
    nm_audit_log_control_op(NM_AUDIT_OP_SLEEP_CONTROL,
                            do_sleep ? "on" : "off",
                            TRUE,
                            subject,
                            NULL);
    g_dbus_method_invocation_return_value(invocation, NULL);
    return;
}

static void
sleeping_cb(NMSleepMonitor *monitor, gboolean is_about_to_suspend, gpointer user_data)
{
    NMManager *self = user_data;

    _LOGT(LOGD_SUSPEND, "sleep: received %s signal", is_about_to_suspend ? "sleeping" : "resuming");
    _internal_sleep(self, is_about_to_suspend);
}

static void
_internal_enable(NMManager *self, gboolean enable)
{
    NMManagerPrivate *priv = NM_MANAGER_GET_PRIVATE(self);

    nm_config_state_set(priv->config,
                        TRUE,
                        FALSE,
                        NM_CONFIG_STATE_PROPERTY_NETWORKING_ENABLED,
                        enable);

    _LOGI(LOGD_SUSPEND,
          "%s requested (sleeping: %s  enabled: %s)",
          enable ? "enable" : "disable",
          priv->sleeping ? "yes" : "no",
          priv->net_enabled ? "yes" : "no");

    priv->net_enabled = enable;

    do_sleep_wake(self, FALSE);

    _notify(self, PROP_NETWORKING_ENABLED);
}

static void
enable_net_done_cb(NMAuthChain *chain, GDBusMethodInvocation *context, gpointer user_data)
{
    NMManager *      self = NM_MANAGER(user_data);
    NMAuthCallResult result;
    gboolean         enable;
    NMAuthSubject *  subject;

    nm_assert(G_IS_DBUS_METHOD_INVOCATION(context));

    c_list_unlink(nm_auth_chain_parent_lst_list(chain));
    enable  = GPOINTER_TO_UINT(nm_auth_chain_get_data(chain, "enable"));
    subject = nm_auth_chain_get_subject(chain);

    result = nm_auth_chain_get_result(chain, NM_AUTH_PERMISSION_ENABLE_DISABLE_NETWORK);
    if (result != NM_AUTH_CALL_RESULT_YES) {
        GError *ret_error;

        ret_error = g_error_new_literal(NM_MANAGER_ERROR,
                                        NM_MANAGER_ERROR_PERMISSION_DENIED,
                                        "Not authorized to enable/disable networking");
        nm_audit_log_control_op(NM_AUDIT_OP_NET_CONTROL,
                                enable ? "on" : "off",
                                FALSE,
                                subject,
                                ret_error->message);
        g_dbus_method_invocation_take_error(context, ret_error);
        return;
    }

    _internal_enable(self, enable);
    g_dbus_method_invocation_return_value(context, NULL);
    nm_audit_log_control_op(NM_AUDIT_OP_NET_CONTROL, enable ? "on" : "off", TRUE, subject, NULL);
}

static void
impl_manager_enable(NMDBusObject *                     obj,
                    const NMDBusInterfaceInfoExtended *interface_info,
                    const NMDBusMethodInfoExtended *   method_info,
                    GDBusConnection *                  connection,
                    const char *                       sender,
                    GDBusMethodInvocation *            invocation,
                    GVariant *                         parameters)
{
    NMManager *       self = NM_MANAGER(obj);
    NMManagerPrivate *priv = NM_MANAGER_GET_PRIVATE(self);
    NMAuthChain *     chain;
    GError *          error = NULL;
    gboolean          enable;

    g_variant_get(parameters, "(b)", &enable);

    if (priv->net_enabled == enable) {
        error = g_error_new(NM_MANAGER_ERROR,
                            NM_MANAGER_ERROR_ALREADY_ENABLED_OR_DISABLED,
                            "Already %s",
                            enable ? "enabled" : "disabled");
        goto done;
    }

    chain = nm_auth_chain_new_context(invocation, enable_net_done_cb, self);
    if (!chain) {
        error = g_error_new_literal(NM_MANAGER_ERROR,
                                    NM_MANAGER_ERROR_PERMISSION_DENIED,
                                    NM_UTILS_ERROR_MSG_REQ_AUTH_FAILED);
        goto done;
    }

    c_list_link_tail(&priv->auth_lst_head, nm_auth_chain_parent_lst_list(chain));
    nm_auth_chain_set_data(chain, "enable", GUINT_TO_POINTER(enable), NULL);
    nm_auth_chain_add_call(chain, NM_AUTH_PERMISSION_ENABLE_DISABLE_NETWORK, TRUE);

done:
    if (error)
        g_dbus_method_invocation_take_error(invocation, error);
}

/* Permissions */

static void
get_permissions_done_cb(NMAuthChain *chain, GDBusMethodInvocation *context, gpointer user_data)
{
    GVariantBuilder results;
    int             i;

    nm_assert(G_IS_DBUS_METHOD_INVOCATION(context));

    c_list_unlink(nm_auth_chain_parent_lst_list(chain));

    g_variant_builder_init(&results, G_VARIANT_TYPE("a{ss}"));

    for (i = 0; i < (int) G_N_ELEMENTS(nm_auth_permission_sorted); i++) {
        const char *permission = nm_auth_permission_names_by_idx[nm_auth_permission_sorted[i] - 1];
        NMAuthCallResult result;
        const char *     result_str;

        result     = nm_auth_chain_get_result(chain, permission);
        result_str = nm_client_permission_result_to_string(nm_auth_call_result_to_client(result));
        g_variant_builder_add(&results, "{ss}", permission, result_str);
    }

    g_dbus_method_invocation_return_value(context, g_variant_new("(a{ss})", &results));
}

static void
impl_manager_get_permissions(NMDBusObject *                     obj,
                             const NMDBusInterfaceInfoExtended *interface_info,
                             const NMDBusMethodInfoExtended *   method_info,
                             GDBusConnection *                  connection,
                             const char *                       sender,
                             GDBusMethodInvocation *            invocation,
                             GVariant *                         parameters)
{
    NMManager *       self = NM_MANAGER(obj);
    NMManagerPrivate *priv = NM_MANAGER_GET_PRIVATE(self);
    NMAuthChain *     chain;
    int               i;

    chain = nm_auth_chain_new_context(invocation, get_permissions_done_cb, self);
    if (!chain) {
        g_dbus_method_invocation_return_error_literal(invocation,
                                                      NM_MANAGER_ERROR,
                                                      NM_MANAGER_ERROR_PERMISSION_DENIED,
                                                      NM_UTILS_ERROR_MSG_REQ_AUTH_FAILED);
        return;
    }

    c_list_link_tail(&priv->auth_lst_head, nm_auth_chain_parent_lst_list(chain));

    for (i = 0; i < (int) G_N_ELEMENTS(nm_auth_permission_sorted); i++) {
        const char *permission = nm_auth_permission_names_by_idx[nm_auth_permission_sorted[i] - 1];

        nm_auth_chain_add_call_unsafe(chain, permission, FALSE);
    }
}

static void
impl_manager_state(NMDBusObject *                     obj,
                   const NMDBusInterfaceInfoExtended *interface_info,
                   const NMDBusMethodInfoExtended *   method_info,
                   GDBusConnection *                  connection,
                   const char *                       sender,
                   GDBusMethodInvocation *            invocation,
                   GVariant *                         parameters)
{
    NMManager *self = NM_MANAGER(obj);

    nm_manager_update_state(self);
    g_dbus_method_invocation_return_value(
        invocation,
        g_variant_new("(u)", NM_MANAGER_GET_PRIVATE(self)->state));
}

static void
impl_manager_set_logging(NMDBusObject *                     obj,
                         const NMDBusInterfaceInfoExtended *interface_info,
                         const NMDBusMethodInfoExtended *   method_info,
                         GDBusConnection *                  connection,
                         const char *                       sender,
                         GDBusMethodInvocation *            invocation,
                         GVariant *                         parameters)
{
    NMManager * self  = NM_MANAGER(obj);
    GError *    error = NULL;
    const char *level;
    const char *domains;

    /* The permission is already enforced by the D-Bus daemon, but we ensure
     * that the caller is still alive so that clients are forced to wait and
     * we'll be able to switch to polkit without breaking behavior.
     */
    if (!nm_dbus_manager_ensure_uid(nm_dbus_object_get_manager(NM_DBUS_OBJECT(self)),
                                    invocation,
                                    G_MAXULONG,
                                    NM_MANAGER_ERROR,
                                    NM_MANAGER_ERROR_PERMISSION_DENIED))
        return;

    g_variant_get(parameters, "(&s&s)", &level, &domains);

    if (nm_logging_setup(level, domains, NULL, &error)) {
        _LOGI(LOGD_CORE,
              "logging: level '%s' domains '%s'",
              nm_logging_level_to_string(),
              nm_logging_domains_to_string());
    }

    if (error)
        g_dbus_method_invocation_take_error(invocation, error);
    else
        g_dbus_method_invocation_return_value(invocation, NULL);
}

static void
impl_manager_get_logging(NMDBusObject *                     obj,
                         const NMDBusInterfaceInfoExtended *interface_info,
                         const NMDBusMethodInfoExtended *   method_info,
                         GDBusConnection *                  connection,
                         const char *                       sender,
                         GDBusMethodInvocation *            invocation,
                         GVariant *                         parameters)
{
    g_dbus_method_invocation_return_value(
        invocation,
        g_variant_new("(ss)", nm_logging_level_to_string(), nm_logging_domains_to_string()));
}

typedef struct {
    NMManager *            self;
    GDBusMethodInvocation *context;
    guint                  remaining;
} ConnectivityCheckData;

static void
device_connectivity_done(NMDevice *                  device,
                         NMDeviceConnectivityHandle *handle,
                         NMConnectivityState         state,
                         GError *                    error,
                         gpointer                    user_data)
{
    ConnectivityCheckData *data = user_data;
    NMManager *            self;
    NMManagerPrivate *     priv;

    nm_assert(data);
    nm_assert(data->remaining > 0);
    nm_assert(NM_IS_MANAGER(data->self));

    data->remaining--;

    self = data->self;
    priv = NM_MANAGER_GET_PRIVATE(self);

    if (data->context
        && (data->remaining == 0
            || (state == NM_CONNECTIVITY_FULL
                && priv->connectivity_state == NM_CONNECTIVITY_FULL))) {
        /* despite having a @handle and @state returned by the requests, we always
         * return the current connectivity_state. That is, because the connectivity_state
         * and the answer to the connectivity check shall agree.
         *
         * However, if one of the requests (early) returns full connectivity and agrees with
         * the accumulated connectivity state, we no longer have to wait. The result is set.
         *
         * This also works well, because NMDevice first emits change signals to its own
         * connectivity state, which is then taken into account for the accumulated global
         * state. All this happens, before the callback is invoked. */
        g_dbus_method_invocation_return_value(
            g_steal_pointer(&data->context),
            g_variant_new("(u)", (guint) priv->connectivity_state));
    }

    if (data->remaining == 0) {
        g_object_unref(self);
        g_slice_free(ConnectivityCheckData, data);
    }
}

static void
check_connectivity_auth_done_cb(NMAuthChain *          chain,
                                GDBusMethodInvocation *context,
                                gpointer               user_data)
{
    NMManager *            self  = NM_MANAGER(user_data);
    NMManagerPrivate *     priv  = NM_MANAGER_GET_PRIVATE(self);
    GError *               error = NULL;
    NMAuthCallResult       result;
    ConnectivityCheckData *data;
    NMDevice *             device;

    c_list_unlink(nm_auth_chain_parent_lst_list(chain));

    result = nm_auth_chain_get_result(chain, NM_AUTH_PERMISSION_NETWORK_CONTROL);

    if (result != NM_AUTH_CALL_RESULT_YES) {
        error = g_error_new_literal(NM_MANAGER_ERROR,
                                    NM_MANAGER_ERROR_PERMISSION_DENIED,
                                    "Not authorized to recheck connectivity");
    }
    if (error) {
        g_dbus_method_invocation_take_error(context, error);
        return;
    }

    data            = g_slice_new(ConnectivityCheckData);
    data->self      = g_object_ref(self);
    data->context   = context;
    data->remaining = 0;

    c_list_for_each_entry (device, &priv->devices_lst_head, devices_lst) {
        if (nm_device_check_connectivity(device, AF_INET, device_connectivity_done, data))
            data->remaining++;
        if (nm_device_check_connectivity(device, AF_INET6, device_connectivity_done, data))
            data->remaining++;
    }

    if (data->remaining == 0) {
        /* call the handler at least once. */
        data->remaining = 1;
        device_connectivity_done(NULL, NULL, NM_CONNECTIVITY_UNKNOWN, NULL, data);
        /* @data got destroyed. */
    }
}

static void
impl_manager_check_connectivity(NMDBusObject *                     obj,
                                const NMDBusInterfaceInfoExtended *interface_info,
                                const NMDBusMethodInfoExtended *   method_info,
                                GDBusConnection *                  connection,
                                const char *                       sender,
                                GDBusMethodInvocation *            invocation,
                                GVariant *                         parameters)
{
    NMManager *       self = NM_MANAGER(obj);
    NMManagerPrivate *priv = NM_MANAGER_GET_PRIVATE(self);
    NMAuthChain *     chain;

    chain = nm_auth_chain_new_context(invocation, check_connectivity_auth_done_cb, self);
    if (!chain) {
        g_dbus_method_invocation_return_error_literal(invocation,
                                                      NM_MANAGER_ERROR,
                                                      NM_MANAGER_ERROR_PERMISSION_DENIED,
                                                      NM_UTILS_ERROR_MSG_REQ_AUTH_FAILED);
        return;
    }

    c_list_link_tail(&priv->auth_lst_head, nm_auth_chain_parent_lst_list(chain));
    nm_auth_chain_add_call(chain, NM_AUTH_PERMISSION_NETWORK_CONTROL, TRUE);
}

static void
start_factory(NMDeviceFactory *factory, gpointer user_data)
{
    nm_device_factory_start(factory);
}

gboolean
nm_manager_write_device_state(NMManager *self, NMDevice *device, int *out_ifindex)
{
    NMManagerPrivate *             priv = NM_MANAGER_GET_PRIVATE(self);
    int                            ifindex;
    gboolean                       managed;
    NMConfigDeviceStateManagedType managed_type;
    const char *                   uuid              = NULL;
    const char *                   perm_hw_addr_fake = NULL;
    gboolean                       perm_hw_addr_is_fake;
    guint32                        route_metric_default_aspired;
    guint32                        route_metric_default_effective;
    NMTernary                      nm_owned;
    NMDhcpConfig *                 dhcp_config;
    const char *                   next_server = NULL;
    const char *                   root_path   = NULL;

    NM_SET_OUT(out_ifindex, 0);

    ifindex = nm_device_get_ip_ifindex(device);
    if (ifindex <= 0)
        return FALSE;
    if (ifindex == 1) {
        /* ignore loopback */
        return FALSE;
    }

    if (!nm_platform_link_get(priv->platform, ifindex))
        return FALSE;

    managed = nm_device_get_managed(device, FALSE);
    if (managed) {
        NMSettingsConnection *sett_conn = NULL;

        if (nm_device_get_state(device) <= NM_DEVICE_STATE_ACTIVATED)
            sett_conn = nm_device_get_settings_connection(device);
        if (sett_conn)
            uuid = nm_settings_connection_get_uuid(sett_conn);
        managed_type = NM_CONFIG_DEVICE_STATE_MANAGED_TYPE_MANAGED;
    } else if (nm_device_get_unmanaged_flags(device, NM_UNMANAGED_USER_EXPLICIT))
        managed_type = NM_CONFIG_DEVICE_STATE_MANAGED_TYPE_UNMANAGED;
    else
        managed_type = NM_CONFIG_DEVICE_STATE_MANAGED_TYPE_UNKNOWN;

    perm_hw_addr_fake =
        nm_device_get_permanent_hw_address_full(device, FALSE, &perm_hw_addr_is_fake);
    if (perm_hw_addr_fake && !perm_hw_addr_is_fake)
        perm_hw_addr_fake = NULL;

    nm_owned = nm_device_is_software(device) ? nm_device_is_nm_owned(device) : NM_TERNARY_DEFAULT;

    route_metric_default_effective = _device_route_metric_get(self,
                                                              ifindex,
                                                              NM_DEVICE_TYPE_UNKNOWN,
                                                              TRUE,
                                                              &route_metric_default_aspired);

    dhcp_config = nm_device_get_dhcp_config(device, AF_INET);
    if (dhcp_config) {
        root_path   = nm_dhcp_config_get_option(dhcp_config, "root_path");
        next_server = nm_dhcp_config_get_option(dhcp_config, "next_server");
    }

    if (!nm_config_device_state_write(ifindex,
                                      managed_type,
                                      perm_hw_addr_fake,
                                      uuid,
                                      nm_owned,
                                      route_metric_default_aspired,
                                      route_metric_default_effective,
                                      next_server,
                                      root_path))
        return FALSE;

    NM_SET_OUT(out_ifindex, ifindex);
    return TRUE;
}

void
nm_manager_write_device_state_all(NMManager *self)
{
    NMManagerPrivate * priv                           = NM_MANAGER_GET_PRIVATE(self);
    gs_unref_hashtable GHashTable *preserve_ifindexes = NULL;
    NMDevice *                     device;

    preserve_ifindexes = g_hash_table_new(nm_direct_hash, NULL);

    c_list_for_each_entry (device, &priv->devices_lst_head, devices_lst) {
        int ifindex;

        if (nm_manager_write_device_state(self, device, &ifindex)) {
            g_hash_table_add(preserve_ifindexes, GINT_TO_POINTER(ifindex));
        }
    }

    nm_config_device_state_prune_stale(preserve_ifindexes, NULL);
}

static gboolean
devices_inited_cb(gpointer user_data)
{
    NMManager *       self = user_data;
    NMManagerPrivate *priv = NM_MANAGER_GET_PRIVATE(self);

    priv->devices_inited_id = 0;
    priv->devices_inited    = TRUE;
    check_if_startup_complete(self);
    return G_SOURCE_REMOVE;
}

gboolean
nm_manager_start(NMManager *self, GError **error)
{
    NMManagerPrivate *priv                     = NM_MANAGER_GET_PRIVATE(self);
    gs_free NMSettingsConnection **connections = NULL;
    guint                          i;

    nm_device_factory_manager_load_factories(_register_device_factory, self);

    nm_device_factory_manager_for_each_factory(start_factory, NULL);

    /* Set initial radio enabled/disabled state */
    for (i = 0; i < RFKILL_TYPE_MAX; i++) {
        RadioState *rstate = &priv->radio_states[i];
        gboolean    enabled;

        if (!rstate->desc)
            continue;

        /* recheck kernel rfkill state */
        update_rstate_from_rfkill(priv->rfkill_mgr, rstate);

        if (rstate->desc) {
            _LOGI(LOGD_RFKILL,
                  "rfkill: %s %s by radio killswitch; %s by state file",
                  rstate->desc,
                  (rstate->hw_enabled && rstate->sw_enabled) ? "enabled" : "disabled",
                  rstate->user_enabled ? "enabled" : "disabled");
        }
        enabled = radio_enabled_for_rstate(rstate, TRUE);
        manager_update_radio_enabled(self, rstate, enabled);
    }

    _LOGI(LOGD_CORE, "Networking is %s by state file", priv->net_enabled ? "enabled" : "disabled");

    system_unmanaged_devices_changed_cb(priv->settings, NULL, self);

    hostname_changed_cb(priv->hostname_manager, NULL, self);

    if (!nm_settings_start(priv->settings, error))
        return FALSE;

    nm_platform_process_events(priv->platform);

    g_signal_connect(priv->platform,
                     NM_PLATFORM_SIGNAL_LINK_CHANGED,
                     G_CALLBACK(platform_link_cb),
                     self);

    platform_query_devices(self);

    /* Load VPN plugins */
    priv->vpn_manager = g_object_ref(nm_vpn_manager_get());

    _LOGD(LOGD_CORE, "creating virtual devices...");
    g_signal_connect(priv->settings,
                     NM_SETTINGS_SIGNAL_CONNECTION_ADDED,
                     G_CALLBACK(connection_added_cb),
                     self);
    g_signal_connect(priv->settings,
                     NM_SETTINGS_SIGNAL_CONNECTION_UPDATED,
                     G_CALLBACK(connection_updated_cb),
                     self);
    connections = nm_settings_get_connections_clone(
        priv->settings,
        NULL,
        NULL,
        NULL,
        nm_settings_connection_cmp_autoconnect_priority_p_with_data,
        NULL);
    for (i = 0; connections[i]; i++)
        connection_changed(self, connections[i]);

    nm_clear_g_source(&priv->devices_inited_id);
    priv->devices_inited_id = g_idle_add_full(G_PRIORITY_LOW + 10, devices_inited_cb, self, NULL);

    return TRUE;
}

void
nm_manager_stop(NMManager *self)
{
    NMManagerPrivate *priv = NM_MANAGER_GET_PRIVATE(self);
    NMDevice *        device;

    /* FIXME(shutdown): we don't do a proper shutdown yet:
     *  - need to ensure that all pending async operations are cancelled
     *    - e.g. operations in priv->async_op_lst_head
     *  - need to ensure that no more asynchronous requests are started,
     *    or that they complete quickly, or that they fail quickly.
     *  - note that cancelling some operations is not possible synchronously.
     *    Hence, stop() only prepares shutdown and tells everybody to not
     *    accept new work, and to complete in a timely manner.
     *    We need to still iterate the mainloop for a bit, to give everybody
     *    the chance to complete.
     *    - e.g. see comment at nm_auth_manager_force_shutdown()
     */

    nm_dbus_manager_stop(nm_dbus_object_get_manager(NM_DBUS_OBJECT(self)));

    while ((device = c_list_first_entry(&priv->devices_lst_head, NMDevice, devices_lst)))
        remove_device(self, device, TRUE);

    _active_connection_cleanup(self);

    nm_clear_g_source(&priv->devices_inited_id);
}

static gboolean
handle_firmware_changed(gpointer user_data)
{
    NMManager *       self = NM_MANAGER(user_data);
    NMManagerPrivate *priv = NM_MANAGER_GET_PRIVATE(self);
    NMDevice *        device;

    priv->fw_changed_id = 0;

    /* Try to re-enable devices with missing firmware */
    c_list_for_each_entry (device, &priv->devices_lst_head, devices_lst) {
        NMDeviceState state = nm_device_get_state(device);

        if (nm_device_get_firmware_missing(device) && (state == NM_DEVICE_STATE_UNAVAILABLE)) {
            _LOG2I(LOGD_CORE, device, "firmware may now be available");

            /* Re-set unavailable state to try bringing the device up again */
            nm_device_state_changed(device,
                                    NM_DEVICE_STATE_UNAVAILABLE,
                                    NM_DEVICE_STATE_REASON_NONE);
        }
    }

    return FALSE;
}

static void
firmware_dir_changed(GFileMonitor *    monitor,
                     GFile *           file,
                     GFile *           other_file,
                     GFileMonitorEvent event_type,
                     gpointer          user_data)
{
    NMManager *       self = NM_MANAGER(user_data);
    NMManagerPrivate *priv = NM_MANAGER_GET_PRIVATE(self);

    switch (event_type) {
    case G_FILE_MONITOR_EVENT_CREATED:
    case G_FILE_MONITOR_EVENT_CHANGED:
    case G_FILE_MONITOR_EVENT_MOVED:
    case G_FILE_MONITOR_EVENT_ATTRIBUTE_CHANGED:
    case G_FILE_MONITOR_EVENT_CHANGES_DONE_HINT:
        if (!priv->fw_changed_id) {
            priv->fw_changed_id = g_timeout_add_seconds(4, handle_firmware_changed, self);
            _LOGI(LOGD_CORE, "kernel firmware directory '%s' changed", KERNEL_FIRMWARE_DIR);
        }
        break;
    default:
        break;
    }
}

static void
connection_metered_changed(GObject *object, NMMetered metered, gpointer user_data)
{
    nm_manager_update_metered(NM_MANAGER(user_data));
}

static void
policy_default_ac_changed(GObject *object, GParamSpec *pspec, gpointer user_data)
{
    NMManager *         self = NM_MANAGER(user_data);
    NMManagerPrivate *  priv = NM_MANAGER_GET_PRIVATE(self);
    NMActiveConnection *ac;

    /* Note: this assumes that it's not possible for the IP4 default
     * route to be going over the default-ip6-device. If that changes,
     * we need something more complicated here.
     */
    ac = nm_policy_get_default_ip4_ac(priv->policy);
    if (!ac)
        ac = nm_policy_get_default_ip6_ac(priv->policy);

    if (ac != priv->primary_connection) {
        if (priv->primary_connection) {
            g_signal_handlers_disconnect_by_func(priv->primary_connection,
                                                 G_CALLBACK(connection_metered_changed),
                                                 self);
            g_clear_object(&priv->primary_connection);
        }

        priv->primary_connection = ac ? g_object_ref(ac) : NULL;

        if (priv->primary_connection) {
            g_signal_connect(priv->primary_connection,
                             NM_ACTIVE_CONNECTION_DEVICE_METERED_CHANGED,
                             G_CALLBACK(connection_metered_changed),
                             self);
        }
        _LOGD(LOGD_CORE,
              "PrimaryConnection now %s",
              ac ? nm_active_connection_get_settings_connection_id(ac) : "(none)");
        _notify(self, PROP_PRIMARY_CONNECTION);
        _notify(self, PROP_PRIMARY_CONNECTION_TYPE);
        nm_manager_update_metered(self);
    }
}

static void
policy_activating_ac_changed(GObject *object, GParamSpec *pspec, gpointer user_data)
{
    NMManager *         self = NM_MANAGER(user_data);
    NMManagerPrivate *  priv = NM_MANAGER_GET_PRIVATE(self);
    NMActiveConnection *activating, *best;

    /* We only look at activating-ip6-ac if activating-ip4-ac
     * AND default-ip4-ac are NULL; if default-ip4-ac is
     * non-NULL, then activating-ip6-ac is irrelevant, since while
     * that AC might become the new default-ip6-ac, it can't
     * become primary-connection while default-ip4-ac is set to
     * something else.
     */
    activating = nm_policy_get_activating_ip4_ac(priv->policy);
    best       = nm_policy_get_default_ip4_ac(priv->policy);
    if (!activating && !best)
        activating = nm_policy_get_activating_ip6_ac(priv->policy);

    if (nm_g_object_ref_set(&priv->activating_connection, activating)) {
        _LOGD(LOGD_CORE,
              "ActivatingConnection now %s",
              activating ? nm_active_connection_get_settings_connection_id(activating) : "(none)");
        _notify(self, PROP_ACTIVATING_CONNECTION);
    }
}

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

typedef struct {
    NMManager *                        self;
    NMDBusObject *                     obj;
    const NMDBusInterfaceInfoExtended *interface_info;
    const NMDBusPropertyInfoExtended * property_info;
    GVariant *                         value;
    guint64                            export_version_id;
} DBusSetPropertyHandle;

#define NM_PERM_DENIED_ERROR "org.freedesktop.NetworkManager.PermissionDenied"

static void
_dbus_set_property_auth_cb(NMAuthChain *          chain,
                           GDBusMethodInvocation *invocation,
                           gpointer               user_data)
{
    DBusSetPropertyHandle *handle_data                = user_data;
    gs_unref_object NMDBusObject *     obj            = handle_data->obj;
    const NMDBusInterfaceInfoExtended *interface_info = handle_data->interface_info;
    const NMDBusPropertyInfoExtended * property_info  = handle_data->property_info;
    gs_unref_variant GVariant *value                  = handle_data->value;
    guint64                    export_version_id      = handle_data->export_version_id;
    gs_unref_object NMManager *self                   = handle_data->self;
    NMManagerPrivate *         priv                   = NM_MANAGER_GET_PRIVATE(self);
    NMAuthCallResult           result;
    gs_free_error GError *local         = NULL;
    const char *          error_name    = NULL;
    const char *          error_message = NULL;
    GValue                gvalue;

    g_slice_free(DBusSetPropertyHandle, handle_data);

    c_list_unlink(nm_auth_chain_parent_lst_list(chain));
    result = nm_auth_chain_get_result(chain, property_info->writable.permission);

    if (result != NM_AUTH_CALL_RESULT_YES) {
        error_name    = NM_PERM_DENIED_ERROR;
        error_message = "Not authorized to perform this operation";
        goto out;
    }

    if (export_version_id != nm_dbus_object_get_export_version_id(obj)) {
        error_name    = "org.freedesktop.DBus.Error.UnknownObject";
        error_message = "Object was deleted while authenticating";
        goto out;
    }

    /* Handle some properties specially *sigh* */
    if (interface_info == &interface_info_manager
        && nm_streq(property_info->property_name, NM_MANAGER_GLOBAL_DNS_CONFIGURATION)) {
        const NMGlobalDnsConfig *global_dns;

        global_dns = nm_config_data_get_global_dns_config(nm_config_get_data(priv->config));
        if (global_dns && !nm_global_dns_config_is_internal(global_dns)) {
            error_name    = NM_PERM_DENIED_ERROR;
            error_message = "Global DNS configuration already set via configuration file";
            goto out;
        }
    }

    g_dbus_gvariant_to_gvalue(value, &gvalue);
    if (!nm_g_object_set_property(G_OBJECT(obj), property_info->property_name, &gvalue, &local)) {
        error_name    = "org.freedesktop.DBus.Error.InvalidArgs";
        error_message = local->message;
    }
    g_value_unset(&gvalue);

out:
    nm_audit_log_control_op(property_info->writable.audit_op,
                            property_info->property_name,
                            !error_message,
                            nm_auth_chain_get_subject(chain),
                            error_message);
    if (error_message)
        g_dbus_method_invocation_return_dbus_error(invocation, error_name, error_message);
    else
        g_dbus_method_invocation_return_value(invocation, NULL);
}

void
nm_manager_dbus_set_property_handle(NMDBusObject *                     obj,
                                    const NMDBusInterfaceInfoExtended *interface_info,
                                    const NMDBusPropertyInfoExtended * property_info,
                                    GDBusConnection *                  connection,
                                    const char *                       sender,
                                    GDBusMethodInvocation *            invocation,
                                    GVariant *                         value,
                                    gpointer                           user_data)
{
    NMManager *       self = user_data;
    NMManagerPrivate *priv = NM_MANAGER_GET_PRIVATE(self);
    NMAuthChain *     chain;
    const char *      error_message        = NULL;
    gs_unref_object NMAuthSubject *subject = NULL;
    DBusSetPropertyHandle *        handle_data;

    subject = nm_dbus_manager_new_auth_subject_from_context(invocation);
    if (!subject) {
        error_message = NM_UTILS_ERROR_MSG_REQ_UID_UKNOWN;
        goto err;
    }

    handle_data                    = g_slice_new0(DBusSetPropertyHandle);
    handle_data->self              = g_object_ref(self);
    handle_data->obj               = g_object_ref(obj);
    handle_data->interface_info    = interface_info;
    handle_data->property_info     = property_info;
    handle_data->value             = g_variant_ref(value);
    handle_data->export_version_id = nm_dbus_object_get_export_version_id(obj);

    chain = nm_auth_chain_new_subject(subject, invocation, _dbus_set_property_auth_cb, handle_data);
    c_list_link_tail(&priv->auth_lst_head, nm_auth_chain_parent_lst_list(chain));
    nm_auth_chain_add_call_unsafe(chain, property_info->writable.permission, TRUE);
    return;

err:
    nm_audit_log_control_op(property_info->writable.audit_op,
                            property_info->property_name,
                            FALSE,
                            invocation,
                            error_message);
    g_dbus_method_invocation_return_error_literal(invocation,
                                                  G_DBUS_ERROR,
                                                  G_DBUS_ERROR_AUTH_FAILED,
                                                  error_message);
}

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

static NMCheckpointManager *
_checkpoint_mgr_get(NMManager *self, gboolean create_as_needed)
{
    NMManagerPrivate *priv = NM_MANAGER_GET_PRIVATE(self);

    if (G_UNLIKELY(!priv->checkpoint_mgr) && create_as_needed)
        priv->checkpoint_mgr = nm_checkpoint_manager_new(self, obj_properties[PROP_CHECKPOINTS]);
    return priv->checkpoint_mgr;
}

static void
checkpoint_auth_done_cb(NMAuthChain *chain, GDBusMethodInvocation *context, gpointer user_data)
{
    NMManager *      self = NM_MANAGER(user_data);
    char *           op;
    char *           checkpoint_path = NULL;
    char **          devices;
    NMCheckpoint *   checkpoint;
    NMAuthCallResult result;
    guint32          timeout, flags;
    GVariant *       variant = NULL;
    GError *         error   = NULL;
    const char *     arg     = NULL;
    guint32          add_timeout;

    op = nm_auth_chain_get_data(chain, "audit-op");
    c_list_unlink(nm_auth_chain_parent_lst_list(chain));
    result = nm_auth_chain_get_result(chain, NM_AUTH_PERMISSION_CHECKPOINT_ROLLBACK);

    if (NM_IN_STRSET(op,
                     NM_AUDIT_OP_CHECKPOINT_DESTROY,
                     NM_AUDIT_OP_CHECKPOINT_ROLLBACK,
                     NM_AUDIT_OP_CHECKPOINT_ADJUST_ROLLBACK_TIMEOUT))
        arg = checkpoint_path = nm_auth_chain_get_data(chain, "checkpoint_path");

    if (result != NM_AUTH_CALL_RESULT_YES) {
        error = g_error_new_literal(NM_MANAGER_ERROR,
                                    NM_MANAGER_ERROR_PERMISSION_DENIED,
                                    "Not authorized to checkpoint/rollback");
    } else {
        if (nm_streq0(op, NM_AUDIT_OP_CHECKPOINT_CREATE)) {
            timeout = GPOINTER_TO_UINT(nm_auth_chain_get_data(chain, "timeout"));
            flags   = GPOINTER_TO_UINT(nm_auth_chain_get_data(chain, "flags"));
            devices = nm_auth_chain_get_data(chain, "devices");

            checkpoint = nm_checkpoint_manager_create(_checkpoint_mgr_get(self, TRUE),
                                                      (const char *const *) devices,
                                                      timeout,
                                                      (NMCheckpointCreateFlags) flags,
                                                      &error);
            if (checkpoint) {
                arg     = nm_dbus_object_get_path(NM_DBUS_OBJECT(checkpoint));
                variant = g_variant_new("(o)", arg);
            }
        } else if (nm_streq0(op, NM_AUDIT_OP_CHECKPOINT_DESTROY)) {
            nm_checkpoint_manager_destroy(_checkpoint_mgr_get(self, TRUE), checkpoint_path, &error);
        } else if (nm_streq0(op, NM_AUDIT_OP_CHECKPOINT_ROLLBACK)) {
            nm_checkpoint_manager_rollback(_checkpoint_mgr_get(self, TRUE),
                                           checkpoint_path,
                                           &variant,
                                           &error);
        } else if (nm_streq0(op, NM_AUDIT_OP_CHECKPOINT_ADJUST_ROLLBACK_TIMEOUT)) {
            add_timeout = GPOINTER_TO_UINT(nm_auth_chain_get_data(chain, "add_timeout"));
            nm_checkpoint_manager_adjust_rollback_timeout(_checkpoint_mgr_get(self, TRUE),
                                                          checkpoint_path,
                                                          add_timeout,
                                                          &error);
        } else
            g_return_if_reached();
    }

    nm_audit_log_checkpoint_op(op,
                               arg ?: "",
                               !error,
                               nm_auth_chain_get_subject(chain),
                               error ? error->message : NULL);

    if (error)
        g_dbus_method_invocation_take_error(context, error);
    else
        g_dbus_method_invocation_return_value(context, variant);
}

static void
impl_manager_checkpoint_create(NMDBusObject *                     obj,
                               const NMDBusInterfaceInfoExtended *interface_info,
                               const NMDBusMethodInfoExtended *   method_info,
                               GDBusConnection *                  connection,
                               const char *                       sender,
                               GDBusMethodInvocation *            invocation,
                               GVariant *                         parameters)
{
    NMManager *       self = NM_MANAGER(obj);
    NMManagerPrivate *priv = NM_MANAGER_GET_PRIVATE(self);
    NMAuthChain *     chain;
    char **           devices;
    guint32           rollback_timeout;
    guint32           flags;

    G_STATIC_ASSERT_EXPR(sizeof(flags) <= sizeof(NMCheckpointCreateFlags));

    chain = nm_auth_chain_new_context(invocation, checkpoint_auth_done_cb, self);
    if (!chain) {
        g_dbus_method_invocation_return_error_literal(invocation,
                                                      NM_MANAGER_ERROR,
                                                      NM_MANAGER_ERROR_PERMISSION_DENIED,
                                                      NM_UTILS_ERROR_MSG_REQ_AUTH_FAILED);
        return;
    }

    g_variant_get(parameters, "(^aouu)", &devices, &rollback_timeout, &flags);

    c_list_link_tail(&priv->auth_lst_head, nm_auth_chain_parent_lst_list(chain));
    nm_auth_chain_set_data(chain, "audit-op", NM_AUDIT_OP_CHECKPOINT_CREATE, NULL);
    nm_auth_chain_set_data(chain, "devices", devices, (GDestroyNotify) g_strfreev);
    nm_auth_chain_set_data(chain, "flags", GUINT_TO_POINTER(flags), NULL);
    nm_auth_chain_set_data(chain, "timeout", GUINT_TO_POINTER(rollback_timeout), NULL);
    nm_auth_chain_add_call(chain, NM_AUTH_PERMISSION_CHECKPOINT_ROLLBACK, TRUE);
}

static void
impl_manager_checkpoint_destroy(NMDBusObject *                     obj,
                                const NMDBusInterfaceInfoExtended *interface_info,
                                const NMDBusMethodInfoExtended *   method_info,
                                GDBusConnection *                  connection,
                                const char *                       sender,
                                GDBusMethodInvocation *            invocation,
                                GVariant *                         parameters)
{
    NMManager *       self = NM_MANAGER(obj);
    NMManagerPrivate *priv = NM_MANAGER_GET_PRIVATE(self);
    NMAuthChain *     chain;
    const char *      checkpoint_path;

    chain = nm_auth_chain_new_context(invocation, checkpoint_auth_done_cb, self);
    if (!chain) {
        g_dbus_method_invocation_return_error_literal(invocation,
                                                      NM_MANAGER_ERROR,
                                                      NM_MANAGER_ERROR_PERMISSION_DENIED,
                                                      NM_UTILS_ERROR_MSG_REQ_AUTH_FAILED);
        return;
    }

    g_variant_get(parameters, "(&o)", &checkpoint_path);

    c_list_link_tail(&priv->auth_lst_head, nm_auth_chain_parent_lst_list(chain));
    nm_auth_chain_set_data(chain, "audit-op", NM_AUDIT_OP_CHECKPOINT_DESTROY, NULL);
    nm_auth_chain_set_data(chain, "checkpoint_path", g_strdup(checkpoint_path), g_free);
    nm_auth_chain_add_call(chain, NM_AUTH_PERMISSION_CHECKPOINT_ROLLBACK, TRUE);
}

static void
impl_manager_checkpoint_rollback(NMDBusObject *                     obj,
                                 const NMDBusInterfaceInfoExtended *interface_info,
                                 const NMDBusMethodInfoExtended *   method_info,
                                 GDBusConnection *                  connection,
                                 const char *                       sender,
                                 GDBusMethodInvocation *            invocation,
                                 GVariant *                         parameters)
{
    NMManager *       self = NM_MANAGER(obj);
    NMManagerPrivate *priv = NM_MANAGER_GET_PRIVATE(self);
    NMAuthChain *     chain;
    const char *      checkpoint_path;

    chain = nm_auth_chain_new_context(invocation, checkpoint_auth_done_cb, self);
    if (!chain) {
        g_dbus_method_invocation_return_error_literal(invocation,
                                                      NM_MANAGER_ERROR,
                                                      NM_MANAGER_ERROR_PERMISSION_DENIED,
                                                      NM_UTILS_ERROR_MSG_REQ_AUTH_FAILED);
        return;
    }

    g_variant_get(parameters, "(&o)", &checkpoint_path);

    c_list_link_tail(&priv->auth_lst_head, nm_auth_chain_parent_lst_list(chain));
    nm_auth_chain_set_data(chain, "audit-op", NM_AUDIT_OP_CHECKPOINT_ROLLBACK, NULL);
    nm_auth_chain_set_data(chain, "checkpoint_path", g_strdup(checkpoint_path), g_free);
    nm_auth_chain_add_call(chain, NM_AUTH_PERMISSION_CHECKPOINT_ROLLBACK, TRUE);
}

static void
impl_manager_checkpoint_adjust_rollback_timeout(NMDBusObject *                     obj,
                                                const NMDBusInterfaceInfoExtended *interface_info,
                                                const NMDBusMethodInfoExtended *   method_info,
                                                GDBusConnection *                  connection,
                                                const char *                       sender,
                                                GDBusMethodInvocation *            invocation,
                                                GVariant *                         parameters)
{
    NMManager *       self = NM_MANAGER(obj);
    NMManagerPrivate *priv = NM_MANAGER_GET_PRIVATE(self);
    NMAuthChain *     chain;
    const char *      checkpoint_path;
    guint32           add_timeout;

    chain = nm_auth_chain_new_context(invocation, checkpoint_auth_done_cb, self);
    if (!chain) {
        g_dbus_method_invocation_return_error_literal(invocation,
                                                      NM_MANAGER_ERROR,
                                                      NM_MANAGER_ERROR_PERMISSION_DENIED,
                                                      NM_UTILS_ERROR_MSG_REQ_AUTH_FAILED);
        return;
    }

    g_variant_get(parameters, "(&ou)", &checkpoint_path, &add_timeout);

    c_list_link_tail(&priv->auth_lst_head, nm_auth_chain_parent_lst_list(chain));
    nm_auth_chain_set_data(chain, "audit-op", NM_AUDIT_OP_CHECKPOINT_ADJUST_ROLLBACK_TIMEOUT, NULL);
    nm_auth_chain_set_data(chain, "checkpoint_path", g_strdup(checkpoint_path), g_free);
    nm_auth_chain_set_data(chain, "add_timeout", GUINT_TO_POINTER(add_timeout), NULL);
    nm_auth_chain_add_call(chain, NM_AUTH_PERMISSION_CHECKPOINT_ROLLBACK, TRUE);
}

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

static void
auth_mgr_changed(NMAuthManager *auth_manager, gpointer user_data)
{
    /* Let clients know they should re-check their authorization */
    nm_dbus_object_emit_signal(user_data,
                               &interface_info_manager,
                               &signal_info_check_permissions,
                               "()");
}

#define KERN_RFKILL_OP_CHANGE_ALL 3
#define KERN_RFKILL_TYPE_WLAN     1
#define KERN_RFKILL_TYPE_WWAN     5
struct rfkill_event {
    __u32 idx;
    __u8  type;
    __u8  op;
    __u8  soft, hard;
} _nm_packed;

static void
rfkill_change(NMManager *self, const char *desc, RfKillType rtype, gboolean enabled)
{
    int                 fd;
    struct rfkill_event event;
    ssize_t             len;
    int                 errsv;

    g_return_if_fail(rtype == RFKILL_TYPE_WLAN || rtype == RFKILL_TYPE_WWAN);

    fd = open("/dev/rfkill", O_RDWR | O_CLOEXEC);
    if (fd < 0) {
        if (errno == EACCES)
            _LOGW(LOGD_RFKILL, "rfkill: (%s): failed to open killswitch device", desc);
        return;
    }

    if (fcntl(fd, F_SETFL, O_NONBLOCK) < 0) {
        _LOGW(LOGD_RFKILL,
              "rfkill: (%s): failed to set killswitch device for "
              "non-blocking operation",
              desc);
        nm_close(fd);
        return;
    }

    memset(&event, 0, sizeof(event));
    event.op = KERN_RFKILL_OP_CHANGE_ALL;
    switch (rtype) {
    case RFKILL_TYPE_WLAN:
        event.type = KERN_RFKILL_TYPE_WLAN;
        break;
    case RFKILL_TYPE_WWAN:
        event.type = KERN_RFKILL_TYPE_WWAN;
        break;
    default:
        g_assert_not_reached();
    }
    event.soft = enabled ? 0 : 1;

    len = write(fd, &event, sizeof(event));
    if (len < 0) {
        errsv = errno;
        _LOGW(LOGD_RFKILL,
              "rfkill: (%s): failed to change Wi-Fi killswitch state: (%d) %s",
              desc,
              errsv,
              nm_strerror_native(errsv));
    } else if (len == sizeof(event)) {
        _LOGI(LOGD_RFKILL,
              "rfkill: %s hardware radio set %s",
              desc,
              enabled ? "enabled" : "disabled");
    } else {
        /* Failed to write full structure */
        _LOGW(LOGD_RFKILL, "rfkill: (%s): failed to change Wi-Fi killswitch state", desc);
    }

    nm_close(fd);
}

static void
manager_radio_user_toggled(NMManager *self, RadioState *rstate, gboolean enabled)
{
    NMManagerPrivate *priv = NM_MANAGER_GET_PRIVATE(self);
    gboolean          old_enabled, new_enabled;

    /* Don't touch devices if asleep/networking disabled */
    if (manager_sleeping(self))
        return;

    if (rstate->desc) {
        _LOGD(LOGD_RFKILL,
              "rfkill: (%s): setting radio %s by user",
              rstate->desc,
              enabled ? "enabled" : "disabled");
    }

    /* Update enabled key in state file */
    nm_config_state_set(priv->config, TRUE, FALSE, rstate->key, enabled);

    /* When the user toggles the radio, their request should override any
     * daemon (like ModemManager) enabled state that can be changed.  For WWAN
     * for example, we want the WwanEnabled property to reflect the daemon state
     * too so that users can toggle the modem powered, but we don't want that
     * daemon state to affect whether or not the user *can* turn it on, which is
     * what the kernel rfkill state does.  So we ignore daemon enabled state
     * when determining what the new state should be since it shouldn't block
     * the user's request.
     */
    old_enabled          = radio_enabled_for_rstate(rstate, TRUE);
    rstate->user_enabled = enabled;
    new_enabled          = radio_enabled_for_rstate(rstate, FALSE);
    if (new_enabled != old_enabled) {
        /* Try to change the kernel rfkill state */
        if (rstate->rtype == RFKILL_TYPE_WLAN || rstate->rtype == RFKILL_TYPE_WWAN)
            rfkill_change(self, rstate->desc, rstate->rtype, new_enabled);

        manager_update_radio_enabled(self, rstate, new_enabled);
    }
}

static gboolean
periodic_update_active_connection_timestamps(gpointer user_data)
{
    NMManager *         manager = NM_MANAGER(user_data);
    NMManagerPrivate *  priv    = NM_MANAGER_GET_PRIVATE(manager);
    NMActiveConnection *ac;
    gboolean            has_time = FALSE;
    guint64             t        = 0;

    c_list_for_each_entry (ac, &priv->active_connections_lst_head, active_connections_lst) {
        if (nm_active_connection_get_state(ac) != NM_ACTIVE_CONNECTION_STATE_ACTIVATED)
            continue;

        if (!has_time) {
            t        = time(NULL);
            has_time = TRUE;
        }
        nm_settings_connection_update_timestamp(nm_active_connection_get_settings_connection(ac),
                                                t);
    }
    return G_SOURCE_CONTINUE;
}

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

void
nm_manager_set_capability(NMManager *self, NMCapability cap)
{
    NMManagerPrivate *priv;
    guint32           cap_i;
    gssize            idx;

    g_return_if_fail(NM_IS_MANAGER(self));
    if (cap < 1 || cap > _NM_CAPABILITY_MAX)
        g_return_if_reached();

    cap_i = (guint32) cap;

    priv = NM_MANAGER_GET_PRIVATE(self);

    idx = nm_utils_array_find_binary_search(&g_array_index(priv->capabilities, guint32, 0),
                                            sizeof(guint32),
                                            priv->capabilities->len,
                                            &cap_i,
                                            nm_cmp_uint32_p_with_data,
                                            NULL);
    if (idx >= 0)
        return;

    nm_assert((~idx) <= (gssize) priv->capabilities->len);

    g_array_insert_val(priv->capabilities, ~idx, cap_i);
    _notify(self, PROP_CAPABILITIES);
}

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

NM_DEFINE_SINGLETON_REGISTER(NMManager);

NMManager *
nm_manager_get(void)
{
    g_return_val_if_fail(singleton_instance, NULL);
    return singleton_instance;
}

NMSettings *
nm_settings_get(void)
{
    g_return_val_if_fail(singleton_instance, NULL);

    return NM_MANAGER_GET_PRIVATE(singleton_instance)->settings;
}

NMManager *
nm_manager_setup(void)
{
    NMManager *self;

    g_return_val_if_fail(!singleton_instance, singleton_instance);

    self = g_object_new(NM_TYPE_MANAGER, NULL);
    nm_assert(NM_IS_MANAGER(self));
    singleton_instance = self;

    nm_singleton_instance_register();
    nm_log_dbg(LOGD_CORE,
               "setup %s singleton (" NM_HASH_OBFUSCATE_PTR_FMT ")",
               "NMManager",
               NM_HASH_OBFUSCATE_PTR(singleton_instance));

    nm_dbus_object_export(NM_DBUS_OBJECT(self));
    return self;
}

static void
constructed(GObject *object)
{
    NMManager *          self = NM_MANAGER(object);
    NMManagerPrivate *   priv = NM_MANAGER_GET_PRIVATE(self);
    const NMConfigState *state;

    G_OBJECT_CLASS(nm_manager_parent_class)->constructed(object);

    priv->settings = nm_settings_new(self);

    nm_dbus_object_export(NM_DBUS_OBJECT(priv->settings));

    g_signal_connect(priv->settings,
                     "notify::" NM_SETTINGS_STARTUP_COMPLETE,
                     G_CALLBACK(settings_startup_complete_changed),
                     self);
    g_signal_connect(priv->settings,
                     "notify::" NM_SETTINGS_UNMANAGED_SPECS,
                     G_CALLBACK(system_unmanaged_devices_changed_cb),
                     self);
    g_signal_connect(priv->settings,
                     NM_SETTINGS_SIGNAL_CONNECTION_FLAGS_CHANGED,
                     G_CALLBACK(connection_flags_changed),
                     self);

    priv->hostname_manager = g_object_ref(nm_hostname_manager_get());
    g_signal_connect(priv->hostname_manager,
                     "notify::" NM_HOSTNAME_MANAGER_HOSTNAME,
                     G_CALLBACK(hostname_changed_cb),
                     self);

    /*
     * Do not delete existing virtual devices to keep connectivity up.
     * Virtual devices are reused when NetworkManager is restarted.
     * Hence, don't react on NM_SETTINGS_SIGNAL_CONNECTION_REMOVED.
     */

    priv->policy = nm_policy_new(self, priv->settings);
    g_signal_connect(priv->policy,
                     "notify::" NM_POLICY_DEFAULT_IP4_AC,
                     G_CALLBACK(policy_default_ac_changed),
                     self);
    g_signal_connect(priv->policy,
                     "notify::" NM_POLICY_DEFAULT_IP6_AC,
                     G_CALLBACK(policy_default_ac_changed),
                     self);
    g_signal_connect(priv->policy,
                     "notify::" NM_POLICY_ACTIVATING_IP4_AC,
                     G_CALLBACK(policy_activating_ac_changed),
                     self);
    g_signal_connect(priv->policy,
                     "notify::" NM_POLICY_ACTIVATING_IP6_AC,
                     G_CALLBACK(policy_activating_ac_changed),
                     self);

    priv->config = g_object_ref(nm_config_get());
    g_signal_connect(G_OBJECT(priv->config),
                     NM_CONFIG_SIGNAL_CONFIG_CHANGED,
                     G_CALLBACK(_config_changed_cb),
                     self);

    state = nm_config_state_get(priv->config);

    priv->net_enabled = state->net_enabled;

    priv->radio_states[RFKILL_TYPE_WLAN].user_enabled = state->wifi_enabled;
    priv->radio_states[RFKILL_TYPE_WWAN].user_enabled = state->wwan_enabled;

    priv->rfkill_mgr = nm_rfkill_manager_new();
    g_signal_connect(priv->rfkill_mgr,
                     NM_RFKILL_MANAGER_SIGNAL_RFKILL_CHANGED,
                     G_CALLBACK(rfkill_manager_rfkill_changed_cb),
                     self);

    /* Force kernel Wi-Fi/WWAN rfkill state to follow NM saved Wi-Fi/WWAN state
     * in case the BIOS doesn't save rfkill state, and to be consistent with user
     * changes to the WirelessEnabled/WWANEnabled properties which toggle kernel
     * rfkill.
     */
    rfkill_change(self,
                  priv->radio_states[RFKILL_TYPE_WLAN].desc,
                  RFKILL_TYPE_WLAN,
                  priv->radio_states[RFKILL_TYPE_WLAN].user_enabled);
    rfkill_change(self,
                  priv->radio_states[RFKILL_TYPE_WWAN].desc,
                  RFKILL_TYPE_WWAN,
                  priv->radio_states[RFKILL_TYPE_WWAN].user_enabled);
}

static void
nm_manager_init(NMManager *self)
{
    NMManagerPrivate *priv = NM_MANAGER_GET_PRIVATE(self);
    guint             i;
    GFile *           file;

    c_list_init(&priv->auth_lst_head);
    c_list_init(&priv->link_cb_lst);
    c_list_init(&priv->devices_lst_head);
    c_list_init(&priv->active_connections_lst_head);
    c_list_init(&priv->async_op_lst_head);
    c_list_init(&priv->delete_volatile_connection_lst_head);

    priv->platform = g_object_ref(NM_PLATFORM_GET);

    priv->capabilities = g_array_new(FALSE, FALSE, sizeof(guint32));

    /* Initialize rfkill structures and states */
    memset(priv->radio_states, 0, sizeof(priv->radio_states));

    priv->radio_states[RFKILL_TYPE_WLAN].user_enabled = TRUE;
    priv->radio_states[RFKILL_TYPE_WLAN].key          = NM_CONFIG_STATE_PROPERTY_WIFI_ENABLED;
    priv->radio_states[RFKILL_TYPE_WLAN].prop         = NM_MANAGER_WIRELESS_ENABLED;
    priv->radio_states[RFKILL_TYPE_WLAN].hw_prop      = NM_MANAGER_WIRELESS_HARDWARE_ENABLED;
    priv->radio_states[RFKILL_TYPE_WLAN].desc         = "Wi-Fi";
    priv->radio_states[RFKILL_TYPE_WLAN].rtype        = RFKILL_TYPE_WLAN;

    priv->radio_states[RFKILL_TYPE_WWAN].user_enabled = TRUE;
    priv->radio_states[RFKILL_TYPE_WWAN].key          = NM_CONFIG_STATE_PROPERTY_WWAN_ENABLED;
    priv->radio_states[RFKILL_TYPE_WWAN].prop         = NM_MANAGER_WWAN_ENABLED;
    priv->radio_states[RFKILL_TYPE_WWAN].hw_prop      = NM_MANAGER_WWAN_HARDWARE_ENABLED;
    priv->radio_states[RFKILL_TYPE_WWAN].desc         = "WWAN";
    priv->radio_states[RFKILL_TYPE_WWAN].rtype        = RFKILL_TYPE_WWAN;

    for (i = 0; i < RFKILL_TYPE_MAX; i++)
        priv->radio_states[i].hw_enabled = TRUE;

    priv->sleeping = FALSE;
    priv->state    = NM_STATE_DISCONNECTED;
    priv->startup  = TRUE;

    /* sleep/wake handling */
    priv->sleep_monitor = nm_sleep_monitor_new();
    g_signal_connect(priv->sleep_monitor, NM_SLEEP_MONITOR_SLEEPING, G_CALLBACK(sleeping_cb), self);

    /* Listen for authorization changes */
    priv->auth_mgr = g_object_ref(nm_auth_manager_get());
    g_signal_connect(priv->auth_mgr,
                     NM_AUTH_MANAGER_SIGNAL_CHANGED,
                     G_CALLBACK(auth_mgr_changed),
                     self);

    /* Monitor the firmware directory */
    if (strlen(KERNEL_FIRMWARE_DIR)) {
        file             = g_file_new_for_path(KERNEL_FIRMWARE_DIR "/");
        priv->fw_monitor = g_file_monitor_directory(file, G_FILE_MONITOR_NONE, NULL, NULL);
        g_object_unref(file);
    }

    if (priv->fw_monitor) {
        g_signal_connect(priv->fw_monitor, "changed", G_CALLBACK(firmware_dir_changed), self);
        _LOGI(LOGD_CORE, "monitoring kernel firmware directory '%s'.", KERNEL_FIRMWARE_DIR);
    } else {
        _LOGW(LOGD_CORE, "failed to monitor kernel firmware directory '%s'.", KERNEL_FIRMWARE_DIR);
    }

    /* Update timestamps in active connections */
    priv->timestamp_update_id =
        g_timeout_add_seconds(300,
                              (GSourceFunc) periodic_update_active_connection_timestamps,
                              self);

    priv->metered       = NM_METERED_UNKNOWN;
    priv->sleep_devices = g_hash_table_new(nm_direct_hash, NULL);
}

static void
get_property(GObject *object, guint prop_id, GValue *value, GParamSpec *pspec)
{
    NMManager *              self = NM_MANAGER(object);
    NMManagerPrivate *       priv = NM_MANAGER_GET_PRIVATE(self);
    NMConfigData *           config_data;
    const NMGlobalDnsConfig *dns_config;
    const char *             type;
    const char *             path;
    NMActiveConnection *     ac;
    GPtrArray *              ptrarr;

    switch (prop_id) {
    case PROP_VERSION:
        g_value_set_string(value, VERSION);
        break;
    case PROP_CAPABILITIES:
        g_value_set_variant(value,
                            g_variant_new_fixed_array(G_VARIANT_TYPE("u"),
                                                      priv->capabilities->data,
                                                      priv->capabilities->len,
                                                      sizeof(guint32)));
        break;
    case PROP_STATE:
        g_value_set_uint(value, priv->state);
        break;
    case PROP_STARTUP:
        g_value_set_boolean(value, priv->startup);
        break;
    case PROP_NETWORKING_ENABLED:
        g_value_set_boolean(value, priv->net_enabled);
        break;
    case PROP_WIRELESS_ENABLED:
        g_value_set_boolean(value, radio_enabled_for_type(self, RFKILL_TYPE_WLAN, TRUE));
        break;
    case PROP_WIRELESS_HARDWARE_ENABLED:
        g_value_set_boolean(value, priv->radio_states[RFKILL_TYPE_WLAN].hw_enabled);
        break;
    case PROP_WWAN_ENABLED:
        g_value_set_boolean(value, radio_enabled_for_type(self, RFKILL_TYPE_WWAN, TRUE));
        break;
    case PROP_WWAN_HARDWARE_ENABLED:
        g_value_set_boolean(value, priv->radio_states[RFKILL_TYPE_WWAN].hw_enabled);
        break;
    case PROP_WIMAX_ENABLED:
        g_value_set_boolean(value, FALSE);
        break;
    case PROP_WIMAX_HARDWARE_ENABLED:
        g_value_set_boolean(value, FALSE);
        break;
    case PROP_ACTIVE_CONNECTIONS:
        ptrarr = g_ptr_array_new();
        c_list_for_each_entry (ac, &priv->active_connections_lst_head, active_connections_lst) {
            path = nm_dbus_object_get_path(NM_DBUS_OBJECT(ac));
            if (path)
                g_ptr_array_add(ptrarr, g_strdup(path));
        }
        g_ptr_array_add(ptrarr, NULL);
        g_value_take_boxed(value, g_ptr_array_free(ptrarr, FALSE));
        break;
    case PROP_CONNECTIVITY:
        g_value_set_uint(value, priv->connectivity_state);
        break;
    case PROP_CONNECTIVITY_CHECK_AVAILABLE:
        config_data = nm_config_get_data(priv->config);
        g_value_set_boolean(value, nm_config_data_get_connectivity_uri(config_data) != NULL);
        break;
    case PROP_CONNECTIVITY_CHECK_ENABLED:
        g_value_set_boolean(value, concheck_enabled(self, NULL));
        break;
    case PROP_CONNECTIVITY_CHECK_URI:
        config_data = nm_config_get_data(priv->config);
        g_value_set_string(value, nm_config_data_get_connectivity_uri(config_data));
        break;
    case PROP_PRIMARY_CONNECTION:
        nm_dbus_utils_g_value_set_object_path(value, priv->primary_connection);
        break;
    case PROP_PRIMARY_CONNECTION_TYPE:
        type = NULL;
        if (priv->primary_connection) {
            NMConnection *con;

            con = nm_active_connection_get_applied_connection(priv->primary_connection);
            if (con)
                type = nm_connection_get_connection_type(con);
        }
        g_value_set_string(value, type ?: "");
        break;
    case PROP_ACTIVATING_CONNECTION:
        nm_dbus_utils_g_value_set_object_path(value, priv->activating_connection);
        break;
    case PROP_SLEEPING:
        g_value_set_boolean(value, priv->sleeping);
        break;
    case PROP_DEVICES:
        g_value_take_boxed(value, nm_utils_strv_make_deep_copied(_get_devices_paths(self, FALSE)));
        break;
    case PROP_METERED:
        g_value_set_uint(value, priv->metered);
        break;
    case PROP_GLOBAL_DNS_CONFIGURATION:
        config_data = nm_config_get_data(priv->config);
        dns_config  = nm_config_data_get_global_dns_config(config_data);
        nm_global_dns_config_to_dbus(dns_config, value);
        break;
    case PROP_ALL_DEVICES:
        g_value_take_boxed(value, nm_utils_strv_make_deep_copied(_get_devices_paths(self, TRUE)));
        break;
    case PROP_CHECKPOINTS:
        g_value_take_boxed(
            value,
            priv->checkpoint_mgr ? nm_utils_strv_make_deep_copied(
                nm_checkpoint_manager_get_checkpoint_paths(priv->checkpoint_mgr, NULL))
                                 : NULL);
        break;
    default:
        G_OBJECT_WARN_INVALID_PROPERTY_ID(object, prop_id, pspec);
        break;
    }
}

static void
set_property(GObject *object, guint prop_id, const GValue *value, GParamSpec *pspec)
{
    NMManager *        self = NM_MANAGER(object);
    NMManagerPrivate * priv = NM_MANAGER_GET_PRIVATE(self);
    NMGlobalDnsConfig *dns_config;
    GError *           error = NULL;

    switch (prop_id) {
    case PROP_WIRELESS_ENABLED:
        manager_radio_user_toggled(NM_MANAGER(object),
                                   &priv->radio_states[RFKILL_TYPE_WLAN],
                                   g_value_get_boolean(value));
        break;
    case PROP_WWAN_ENABLED:
        manager_radio_user_toggled(NM_MANAGER(object),
                                   &priv->radio_states[RFKILL_TYPE_WWAN],
                                   g_value_get_boolean(value));
        break;
    case PROP_WIMAX_ENABLED:
        /* WIMAX is deprecated. This does nothing. */
        break;
    case PROP_CONNECTIVITY_CHECK_ENABLED:
        nm_config_set_connectivity_check_enabled(priv->config, g_value_get_boolean(value));
        break;
    case PROP_GLOBAL_DNS_CONFIGURATION:
        dns_config = nm_global_dns_config_from_dbus(value, &error);
        if (!error)
            nm_config_set_global_dns(priv->config, dns_config, &error);

        nm_global_dns_config_free(dns_config);

        if (error) {
            _LOGD(LOGD_CORE, "set global DNS failed with error: %s", error->message);
            g_error_free(error);
        }
        break;
    default:
        G_OBJECT_WARN_INVALID_PROPERTY_ID(object, prop_id, pspec);
        break;
    }
}

static void
_deinit_device_factory(NMDeviceFactory *factory, gpointer user_data)
{
    g_signal_handlers_disconnect_matched(factory,
                                         G_SIGNAL_MATCH_DATA,
                                         0,
                                         0,
                                         NULL,
                                         NULL,
                                         NM_MANAGER(user_data));
}

static void
dispose(GObject *object)
{
    NMManager *       self = NM_MANAGER(object);
    NMManagerPrivate *priv = NM_MANAGER_GET_PRIVATE(self);
    CList *           iter;

    nm_assert(c_list_is_empty(&priv->async_op_lst_head));

    g_signal_handlers_disconnect_by_func(priv->platform, G_CALLBACK(platform_link_cb), self);
    while ((iter = c_list_first(&priv->link_cb_lst))) {
        PlatformLinkCbData *data = c_list_entry(iter, PlatformLinkCbData, lst);

        g_source_remove(data->idle_id);
        c_list_unlink_stale(&data->lst);
        g_slice_free(PlatformLinkCbData, data);
    }

    while ((iter = c_list_first(&priv->auth_lst_head)))
        nm_auth_chain_destroy(nm_auth_chain_parent_lst_entry(iter));

    nm_clear_g_source(&priv->devices_inited_id);

    nm_clear_pointer(&priv->checkpoint_mgr, nm_checkpoint_manager_free);

    if (priv->concheck_mgr) {
        g_signal_handlers_disconnect_by_func(priv->concheck_mgr,
                                             G_CALLBACK(concheck_config_changed_cb),
                                             self);
        g_clear_object(&priv->concheck_mgr);
    }

    if (priv->auth_mgr) {
        g_signal_handlers_disconnect_by_func(priv->auth_mgr, G_CALLBACK(auth_mgr_changed), self);
        g_clear_object(&priv->auth_mgr);
    }

    nm_assert(c_list_is_empty(&priv->devices_lst_head));

    nm_clear_g_source(&priv->ac_cleanup_id);

    while ((iter = c_list_first(&priv->active_connections_lst_head)))
        active_connection_remove(self,
                                 c_list_entry(iter, NMActiveConnection, active_connections_lst));

    nm_assert(c_list_is_empty(&priv->active_connections_lst_head));
    g_clear_object(&priv->primary_connection);
    g_clear_object(&priv->activating_connection);

    if (priv->config) {
        g_signal_handlers_disconnect_by_func(priv->config, _config_changed_cb, self);
        g_clear_object(&priv->config);
    }

    if (priv->policy) {
        g_signal_handlers_disconnect_by_func(priv->policy, policy_default_ac_changed, self);
        g_signal_handlers_disconnect_by_func(priv->policy, policy_activating_ac_changed, self);
        g_clear_object(&priv->policy);
    }

    if (priv->settings) {
        g_signal_handlers_disconnect_by_func(priv->settings,
                                             settings_startup_complete_changed,
                                             self);
        g_signal_handlers_disconnect_by_func(priv->settings,
                                             system_unmanaged_devices_changed_cb,
                                             self);
        g_signal_handlers_disconnect_by_func(priv->settings, connection_added_cb, self);
        g_signal_handlers_disconnect_by_func(priv->settings, connection_updated_cb, self);
        g_signal_handlers_disconnect_by_func(priv->settings, connection_flags_changed, self);
        g_clear_object(&priv->settings);
    }

    if (priv->hostname_manager) {
        g_signal_handlers_disconnect_by_func(priv->hostname_manager, hostname_changed_cb, self);
        g_clear_object(&priv->hostname_manager);
    }

    g_clear_object(&priv->vpn_manager);

    sleep_devices_clear(self);
    nm_clear_pointer(&priv->sleep_devices, g_hash_table_unref);

    if (priv->sleep_monitor) {
        g_signal_handlers_disconnect_by_func(priv->sleep_monitor, sleeping_cb, self);
        g_clear_object(&priv->sleep_monitor);
    }

    if (priv->fw_monitor) {
        g_signal_handlers_disconnect_by_func(priv->fw_monitor, firmware_dir_changed, self);

        nm_clear_g_source(&priv->fw_changed_id);

        g_file_monitor_cancel(priv->fw_monitor);
        g_clear_object(&priv->fw_monitor);
    }

    if (priv->rfkill_mgr) {
        g_signal_handlers_disconnect_by_func(priv->rfkill_mgr,
                                             rfkill_manager_rfkill_changed_cb,
                                             self);
        g_clear_object(&priv->rfkill_mgr);
    }

    nm_clear_g_source(&priv->delete_volatile_connection_idle_id);
    _delete_volatile_connection_all(self, FALSE);
    nm_assert(!priv->delete_volatile_connection_idle_id);
    nm_assert(c_list_is_empty(&priv->delete_volatile_connection_lst_head));

    nm_device_factory_manager_for_each_factory(_deinit_device_factory, self);

    nm_clear_g_source(&priv->timestamp_update_id);

    nm_clear_pointer(&priv->device_route_metrics, g_hash_table_destroy);

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

static void
finalize(GObject *object)
{
    NMManagerPrivate *priv = NM_MANAGER_GET_PRIVATE(object);

    g_array_free(priv->capabilities, TRUE);

    G_OBJECT_CLASS(nm_manager_parent_class)->finalize(object);

    g_object_unref(priv->platform);
}

static const GDBusSignalInfo signal_info_check_permissions =
    NM_DEFINE_GDBUS_SIGNAL_INFO_INIT("CheckPermissions", );

static const GDBusSignalInfo signal_info_state_changed = NM_DEFINE_GDBUS_SIGNAL_INFO_INIT(
    "StateChanged",
    .args = NM_DEFINE_GDBUS_ARG_INFOS(NM_DEFINE_GDBUS_ARG_INFO("state", "u"), ), );

static const GDBusSignalInfo signal_info_device_added = NM_DEFINE_GDBUS_SIGNAL_INFO_INIT(
    "DeviceAdded",
    .args = NM_DEFINE_GDBUS_ARG_INFOS(NM_DEFINE_GDBUS_ARG_INFO("device_path", "o"), ), );

static const GDBusSignalInfo signal_info_device_removed = NM_DEFINE_GDBUS_SIGNAL_INFO_INIT(
    "DeviceRemoved",
    .args = NM_DEFINE_GDBUS_ARG_INFOS(NM_DEFINE_GDBUS_ARG_INFO("device_path", "o"), ), );

static const NMDBusInterfaceInfoExtended interface_info_manager = {
    .parent = NM_DEFINE_GDBUS_INTERFACE_INFO_INIT(
        NM_DBUS_INTERFACE,
        .methods = NM_DEFINE_GDBUS_METHOD_INFOS(
            NM_DEFINE_DBUS_METHOD_INFO_EXTENDED(
                NM_DEFINE_GDBUS_METHOD_INFO_INIT("Reload",
                                                 .in_args = NM_DEFINE_GDBUS_ARG_INFOS(
                                                     NM_DEFINE_GDBUS_ARG_INFO("flags", "u"), ), ),
                .handle = impl_manager_reload, ),
            NM_DEFINE_DBUS_METHOD_INFO_EXTENDED(
                NM_DEFINE_GDBUS_METHOD_INFO_INIT(
                    "GetDevices",
                    .out_args =
                        NM_DEFINE_GDBUS_ARG_INFOS(NM_DEFINE_GDBUS_ARG_INFO("devices", "ao"), ), ),
                .handle = impl_manager_get_devices, ),
            NM_DEFINE_DBUS_METHOD_INFO_EXTENDED(
                NM_DEFINE_GDBUS_METHOD_INFO_INIT(
                    "GetAllDevices",
                    .out_args =
                        NM_DEFINE_GDBUS_ARG_INFOS(NM_DEFINE_GDBUS_ARG_INFO("devices", "ao"), ), ),
                .handle = impl_manager_get_all_devices, ),
            NM_DEFINE_DBUS_METHOD_INFO_EXTENDED(
                NM_DEFINE_GDBUS_METHOD_INFO_INIT(
                    "GetDeviceByIpIface",
                    .in_args = NM_DEFINE_GDBUS_ARG_INFOS(NM_DEFINE_GDBUS_ARG_INFO("iface", "s"), ),
                    .out_args =
                        NM_DEFINE_GDBUS_ARG_INFOS(NM_DEFINE_GDBUS_ARG_INFO("device", "o"), ), ),
                .handle = impl_manager_get_device_by_ip_iface, ),
            NM_DEFINE_DBUS_METHOD_INFO_EXTENDED(
                NM_DEFINE_GDBUS_METHOD_INFO_INIT(
                    "ActivateConnection",
                    .in_args = NM_DEFINE_GDBUS_ARG_INFOS(
                        NM_DEFINE_GDBUS_ARG_INFO("connection", "o"),
                        NM_DEFINE_GDBUS_ARG_INFO("device", "o"),
                        NM_DEFINE_GDBUS_ARG_INFO("specific_object", "o"), ),
                    .out_args = NM_DEFINE_GDBUS_ARG_INFOS(
                        NM_DEFINE_GDBUS_ARG_INFO("active_connection", "o"), ), ),
                .handle = impl_manager_activate_connection, ),
            NM_DEFINE_DBUS_METHOD_INFO_EXTENDED(
                NM_DEFINE_GDBUS_METHOD_INFO_INIT(
                    "AddAndActivateConnection",
                    .in_args = NM_DEFINE_GDBUS_ARG_INFOS(
                        NM_DEFINE_GDBUS_ARG_INFO("connection", "a{sa{sv}}"),
                        NM_DEFINE_GDBUS_ARG_INFO("device", "o"),
                        NM_DEFINE_GDBUS_ARG_INFO("specific_object", "o"), ),
                    .out_args = NM_DEFINE_GDBUS_ARG_INFOS(
                        NM_DEFINE_GDBUS_ARG_INFO("path", "o"),
                        NM_DEFINE_GDBUS_ARG_INFO("active_connection", "o"), ), ),
                .handle = impl_manager_add_and_activate_connection, ),
            NM_DEFINE_DBUS_METHOD_INFO_EXTENDED(
                NM_DEFINE_GDBUS_METHOD_INFO_INIT(
                    "AddAndActivateConnection2",
                    .in_args = NM_DEFINE_GDBUS_ARG_INFOS(
                        NM_DEFINE_GDBUS_ARG_INFO("connection", "a{sa{sv}}"),
                        NM_DEFINE_GDBUS_ARG_INFO("device", "o"),
                        NM_DEFINE_GDBUS_ARG_INFO("specific_object", "o"),
                        NM_DEFINE_GDBUS_ARG_INFO("options", "a{sv}"), ),
                    .out_args = NM_DEFINE_GDBUS_ARG_INFOS(
                        NM_DEFINE_GDBUS_ARG_INFO("path", "o"),
                        NM_DEFINE_GDBUS_ARG_INFO("active_connection", "o"),
                        NM_DEFINE_GDBUS_ARG_INFO("result", "a{sv}"), ), ),
                .handle = impl_manager_add_and_activate_connection, ),
            NM_DEFINE_DBUS_METHOD_INFO_EXTENDED(
                NM_DEFINE_GDBUS_METHOD_INFO_INIT(
                    "DeactivateConnection",
                    .in_args = NM_DEFINE_GDBUS_ARG_INFOS(
                        NM_DEFINE_GDBUS_ARG_INFO("active_connection", "o"), ), ),
                .handle = impl_manager_deactivate_connection, ),
            NM_DEFINE_DBUS_METHOD_INFO_EXTENDED(
                NM_DEFINE_GDBUS_METHOD_INFO_INIT("Sleep",
                                                 .in_args = NM_DEFINE_GDBUS_ARG_INFOS(
                                                     NM_DEFINE_GDBUS_ARG_INFO("sleep", "b"), ), ),
                .handle = impl_manager_sleep, ),
            NM_DEFINE_DBUS_METHOD_INFO_EXTENDED(
                NM_DEFINE_GDBUS_METHOD_INFO_INIT("Enable",
                                                 .in_args = NM_DEFINE_GDBUS_ARG_INFOS(
                                                     NM_DEFINE_GDBUS_ARG_INFO("enable", "b"), ), ),
                .handle = impl_manager_enable, ),
            NM_DEFINE_DBUS_METHOD_INFO_EXTENDED(
                NM_DEFINE_GDBUS_METHOD_INFO_INIT(
                    "GetPermissions",
                    .out_args = NM_DEFINE_GDBUS_ARG_INFOS(
                        NM_DEFINE_GDBUS_ARG_INFO("permissions", "a{ss}"), ), ),
                .handle = impl_manager_get_permissions, ),
            NM_DEFINE_DBUS_METHOD_INFO_EXTENDED(
                NM_DEFINE_GDBUS_METHOD_INFO_INIT("SetLogging",
                                                 .in_args = NM_DEFINE_GDBUS_ARG_INFOS(
                                                     NM_DEFINE_GDBUS_ARG_INFO("level", "s"),
                                                     NM_DEFINE_GDBUS_ARG_INFO("domains", "s"), ), ),
                .handle = impl_manager_set_logging, ),
            NM_DEFINE_DBUS_METHOD_INFO_EXTENDED(
                NM_DEFINE_GDBUS_METHOD_INFO_INIT("GetLogging",
                                                 .out_args = NM_DEFINE_GDBUS_ARG_INFOS(
                                                     NM_DEFINE_GDBUS_ARG_INFO("level", "s"),
                                                     NM_DEFINE_GDBUS_ARG_INFO("domains", "s"), ), ),
                .handle = impl_manager_get_logging, ),
            NM_DEFINE_DBUS_METHOD_INFO_EXTENDED(
                NM_DEFINE_GDBUS_METHOD_INFO_INIT(
                    "CheckConnectivity",
                    .out_args = NM_DEFINE_GDBUS_ARG_INFOS(
                        NM_DEFINE_GDBUS_ARG_INFO("connectivity", "u"), ), ),
                .handle = impl_manager_check_connectivity, ),
            NM_DEFINE_DBUS_METHOD_INFO_EXTENDED(
                NM_DEFINE_GDBUS_METHOD_INFO_INIT("state",
                                                 .out_args = NM_DEFINE_GDBUS_ARG_INFOS(
                                                     NM_DEFINE_GDBUS_ARG_INFO("state", "u"), ), ),
                .handle = impl_manager_state, ),
            NM_DEFINE_DBUS_METHOD_INFO_EXTENDED(
                NM_DEFINE_GDBUS_METHOD_INFO_INIT(
                    "CheckpointCreate",
                    .in_args =
                        NM_DEFINE_GDBUS_ARG_INFOS(NM_DEFINE_GDBUS_ARG_INFO("devices", "ao"),
                                                  NM_DEFINE_GDBUS_ARG_INFO("rollback_timeout", "u"),
                                                  NM_DEFINE_GDBUS_ARG_INFO("flags", "u"), ),
                    .out_args =
                        NM_DEFINE_GDBUS_ARG_INFOS(NM_DEFINE_GDBUS_ARG_INFO("checkpoint", "o"), ), ),
                .handle = impl_manager_checkpoint_create, ),
            NM_DEFINE_DBUS_METHOD_INFO_EXTENDED(
                NM_DEFINE_GDBUS_METHOD_INFO_INIT(
                    "CheckpointDestroy",
                    .in_args =
                        NM_DEFINE_GDBUS_ARG_INFOS(NM_DEFINE_GDBUS_ARG_INFO("checkpoint", "o"), ), ),
                .handle = impl_manager_checkpoint_destroy, ),
            NM_DEFINE_DBUS_METHOD_INFO_EXTENDED(
                NM_DEFINE_GDBUS_METHOD_INFO_INIT(
                    "CheckpointRollback",
                    .in_args =
                        NM_DEFINE_GDBUS_ARG_INFOS(NM_DEFINE_GDBUS_ARG_INFO("checkpoint", "o"), ),
                    .out_args =
                        NM_DEFINE_GDBUS_ARG_INFOS(NM_DEFINE_GDBUS_ARG_INFO("result", "a{su}"), ), ),
                .handle = impl_manager_checkpoint_rollback, ),
            NM_DEFINE_DBUS_METHOD_INFO_EXTENDED(
                NM_DEFINE_GDBUS_METHOD_INFO_INIT(
                    "CheckpointAdjustRollbackTimeout",
                    .in_args = NM_DEFINE_GDBUS_ARG_INFOS(
                        NM_DEFINE_GDBUS_ARG_INFO("checkpoint", "o"),
                        NM_DEFINE_GDBUS_ARG_INFO("add_timeout", "u"), ), ),
                .handle = impl_manager_checkpoint_adjust_rollback_timeout, ), ),
        .signals    = NM_DEFINE_GDBUS_SIGNAL_INFOS(&nm_signal_info_property_changed_legacy,
                                                &signal_info_check_permissions,
                                                &signal_info_state_changed,
                                                &signal_info_device_added,
                                                &signal_info_device_removed, ),
        .properties = NM_DEFINE_GDBUS_PROPERTY_INFOS(
            NM_DEFINE_DBUS_PROPERTY_INFO_EXTENDED_READABLE_L("Devices", "ao", NM_MANAGER_DEVICES),
            NM_DEFINE_DBUS_PROPERTY_INFO_EXTENDED_READABLE_L("AllDevices",
                                                             "ao",
                                                             NM_MANAGER_ALL_DEVICES),
            NM_DEFINE_DBUS_PROPERTY_INFO_EXTENDED_READABLE_L("Checkpoints",
                                                             "ao",
                                                             NM_MANAGER_CHECKPOINTS),
            NM_DEFINE_DBUS_PROPERTY_INFO_EXTENDED_READABLE_L("NetworkingEnabled",
                                                             "b",
                                                             NM_MANAGER_NETWORKING_ENABLED),
            NM_DEFINE_DBUS_PROPERTY_INFO_EXTENDED_READWRITABLE_L(
                "WirelessEnabled",
                "b",
                NM_MANAGER_WIRELESS_ENABLED,
                NM_AUTH_PERMISSION_ENABLE_DISABLE_WIFI,
                NM_AUDIT_OP_RADIO_CONTROL),
            NM_DEFINE_DBUS_PROPERTY_INFO_EXTENDED_READABLE_L("WirelessHardwareEnabled",
                                                             "b",
                                                             NM_MANAGER_WIRELESS_HARDWARE_ENABLED),
            NM_DEFINE_DBUS_PROPERTY_INFO_EXTENDED_READWRITABLE_L(
                "WwanEnabled",
                "b",
                NM_MANAGER_WWAN_ENABLED,
                NM_AUTH_PERMISSION_ENABLE_DISABLE_WWAN,
                NM_AUDIT_OP_RADIO_CONTROL),
            NM_DEFINE_DBUS_PROPERTY_INFO_EXTENDED_READABLE_L("WwanHardwareEnabled",
                                                             "b",
                                                             NM_MANAGER_WWAN_HARDWARE_ENABLED),
            NM_DEFINE_DBUS_PROPERTY_INFO_EXTENDED_READWRITABLE_L(
                "WimaxEnabled",
                "b",
                NM_MANAGER_WIMAX_ENABLED,
                NM_AUTH_PERMISSION_ENABLE_DISABLE_WIMAX,
                NM_AUDIT_OP_RADIO_CONTROL),
            NM_DEFINE_DBUS_PROPERTY_INFO_EXTENDED_READABLE_L("WimaxHardwareEnabled",
                                                             "b",
                                                             NM_MANAGER_WIMAX_HARDWARE_ENABLED),
            NM_DEFINE_DBUS_PROPERTY_INFO_EXTENDED_READABLE_L("ActiveConnections",
                                                             "ao",
                                                             NM_MANAGER_ACTIVE_CONNECTIONS),
            NM_DEFINE_DBUS_PROPERTY_INFO_EXTENDED_READABLE_L("PrimaryConnection",
                                                             "o",
                                                             NM_MANAGER_PRIMARY_CONNECTION),
            NM_DEFINE_DBUS_PROPERTY_INFO_EXTENDED_READABLE_L("PrimaryConnectionType",
                                                             "s",
                                                             NM_MANAGER_PRIMARY_CONNECTION_TYPE),
            NM_DEFINE_DBUS_PROPERTY_INFO_EXTENDED_READABLE_L("Metered", "u", NM_MANAGER_METERED),
            NM_DEFINE_DBUS_PROPERTY_INFO_EXTENDED_READABLE_L("ActivatingConnection",
                                                             "o",
                                                             NM_MANAGER_ACTIVATING_CONNECTION),
            NM_DEFINE_DBUS_PROPERTY_INFO_EXTENDED_READABLE_L("Startup", "b", NM_MANAGER_STARTUP),
            NM_DEFINE_DBUS_PROPERTY_INFO_EXTENDED_READABLE_L("Version", "s", NM_MANAGER_VERSION),
            NM_DEFINE_DBUS_PROPERTY_INFO_EXTENDED_READABLE_L("Capabilities",
                                                             "au",
                                                             NM_MANAGER_CAPABILITIES),
            NM_DEFINE_DBUS_PROPERTY_INFO_EXTENDED_READABLE_L("State", "u", NM_MANAGER_STATE),
            NM_DEFINE_DBUS_PROPERTY_INFO_EXTENDED_READABLE_L("Connectivity",
                                                             "u",
                                                             NM_MANAGER_CONNECTIVITY),
            NM_DEFINE_DBUS_PROPERTY_INFO_EXTENDED_READABLE_L(
                "ConnectivityCheckAvailable",
                "b",
                NM_MANAGER_CONNECTIVITY_CHECK_AVAILABLE),
            NM_DEFINE_DBUS_PROPERTY_INFO_EXTENDED_READWRITABLE_L(
                "ConnectivityCheckEnabled",
                "b",
                NM_MANAGER_CONNECTIVITY_CHECK_ENABLED,
                NM_AUTH_PERMISSION_ENABLE_DISABLE_CONNECTIVITY_CHECK,
                NM_AUDIT_OP_NET_CONTROL),
            NM_DEFINE_DBUS_PROPERTY_INFO_EXTENDED_READABLE("ConnectivityCheckUri",
                                                           "s",
                                                           NM_MANAGER_CONNECTIVITY_CHECK_URI),
            NM_DEFINE_DBUS_PROPERTY_INFO_EXTENDED_READWRITABLE_L(
                "GlobalDnsConfiguration",
                "a{sv}",
                NM_MANAGER_GLOBAL_DNS_CONFIGURATION,
                NM_AUTH_PERMISSION_SETTINGS_MODIFY_GLOBAL_DNS,
                NM_AUDIT_OP_NET_CONTROL), ), ),
    .legacy_property_changed = TRUE,
};

static void
nm_manager_class_init(NMManagerClass *manager_class)
{
    GObjectClass *     object_class      = G_OBJECT_CLASS(manager_class);
    NMDBusObjectClass *dbus_object_class = NM_DBUS_OBJECT_CLASS(manager_class);

    dbus_object_class->export_path     = NM_DBUS_EXPORT_PATH_STATIC(NM_DBUS_PATH);
    dbus_object_class->interface_infos = NM_DBUS_INTERFACE_INFOS(&interface_info_manager);

    object_class->constructed  = constructed;
    object_class->set_property = set_property;
    object_class->get_property = get_property;
    object_class->dispose      = dispose;
    object_class->finalize     = finalize;

    obj_properties[PROP_VERSION] = g_param_spec_string(NM_MANAGER_VERSION,
                                                       "",
                                                       "",
                                                       NULL,
                                                       G_PARAM_READABLE | G_PARAM_STATIC_STRINGS);

    obj_properties[PROP_CAPABILITIES] =
        g_param_spec_variant(NM_MANAGER_CAPABILITIES,
                             "",
                             "",
                             G_VARIANT_TYPE("au"),
                             NULL,
                             G_PARAM_READABLE | G_PARAM_STATIC_STRINGS);

    obj_properties[PROP_STATE] = g_param_spec_uint(NM_MANAGER_STATE,
                                                   "",
                                                   "",
                                                   0,
                                                   NM_STATE_DISCONNECTED,
                                                   0,
                                                   G_PARAM_READABLE | G_PARAM_STATIC_STRINGS);

    obj_properties[PROP_STARTUP] = g_param_spec_boolean(NM_MANAGER_STARTUP,
                                                        "",
                                                        "",
                                                        TRUE,
                                                        G_PARAM_READABLE | G_PARAM_STATIC_STRINGS);

    obj_properties[PROP_NETWORKING_ENABLED] =
        g_param_spec_boolean(NM_MANAGER_NETWORKING_ENABLED,
                             "",
                             "",
                             TRUE,
                             G_PARAM_READABLE | G_PARAM_STATIC_STRINGS);

    obj_properties[PROP_WIRELESS_ENABLED] =
        g_param_spec_boolean(NM_MANAGER_WIRELESS_ENABLED,
                             "",
                             "",
                             TRUE,
                             G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS);

    obj_properties[PROP_WIRELESS_HARDWARE_ENABLED] =
        g_param_spec_boolean(NM_MANAGER_WIRELESS_HARDWARE_ENABLED,
                             "",
                             "",
                             TRUE,
                             G_PARAM_READABLE | G_PARAM_STATIC_STRINGS);

    obj_properties[PROP_WWAN_ENABLED] =
        g_param_spec_boolean(NM_MANAGER_WWAN_ENABLED,
                             "",
                             "",
                             TRUE,
                             G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS);

    obj_properties[PROP_WWAN_HARDWARE_ENABLED] =
        g_param_spec_boolean(NM_MANAGER_WWAN_HARDWARE_ENABLED,
                             "",
                             "",
                             TRUE,
                             G_PARAM_READABLE | G_PARAM_STATIC_STRINGS);

    obj_properties[PROP_WIMAX_ENABLED] =
        g_param_spec_boolean(NM_MANAGER_WIMAX_ENABLED,
                             "",
                             "",
                             TRUE,
                             G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS);

    obj_properties[PROP_WIMAX_HARDWARE_ENABLED] =
        g_param_spec_boolean(NM_MANAGER_WIMAX_HARDWARE_ENABLED,
                             "",
                             "",
                             TRUE,
                             G_PARAM_READABLE | G_PARAM_STATIC_STRINGS);

    obj_properties[PROP_ACTIVE_CONNECTIONS] =
        g_param_spec_boxed(NM_MANAGER_ACTIVE_CONNECTIONS,
                           "",
                           "",
                           G_TYPE_STRV,
                           G_PARAM_READABLE | G_PARAM_STATIC_STRINGS);

    obj_properties[PROP_CONNECTIVITY] =
        g_param_spec_uint(NM_MANAGER_CONNECTIVITY,
                          "",
                          "",
                          NM_CONNECTIVITY_UNKNOWN,
                          NM_CONNECTIVITY_FULL,
                          NM_CONNECTIVITY_UNKNOWN,
                          G_PARAM_READABLE | G_PARAM_STATIC_STRINGS);

    obj_properties[PROP_CONNECTIVITY_CHECK_AVAILABLE] =
        g_param_spec_boolean(NM_MANAGER_CONNECTIVITY_CHECK_AVAILABLE,
                             "",
                             "",
                             TRUE,
                             G_PARAM_READABLE | G_PARAM_STATIC_STRINGS);

    obj_properties[PROP_CONNECTIVITY_CHECK_ENABLED] =
        g_param_spec_boolean(NM_MANAGER_CONNECTIVITY_CHECK_ENABLED,
                             "",
                             "",
                             TRUE,
                             G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS);

    obj_properties[PROP_CONNECTIVITY_CHECK_URI] =
        g_param_spec_string(NM_MANAGER_CONNECTIVITY_CHECK_URI,
                            "",
                            "",
                            NULL,
                            G_PARAM_READABLE | G_PARAM_STATIC_STRINGS);

    obj_properties[PROP_PRIMARY_CONNECTION] =
        g_param_spec_string(NM_MANAGER_PRIMARY_CONNECTION,
                            "",
                            "",
                            NULL,
                            G_PARAM_READABLE | G_PARAM_STATIC_STRINGS);

    obj_properties[PROP_PRIMARY_CONNECTION_TYPE] =
        g_param_spec_string(NM_MANAGER_PRIMARY_CONNECTION_TYPE,
                            "",
                            "",
                            NULL,
                            G_PARAM_READABLE | G_PARAM_STATIC_STRINGS);

    obj_properties[PROP_ACTIVATING_CONNECTION] =
        g_param_spec_string(NM_MANAGER_ACTIVATING_CONNECTION,
                            "",
                            "",
                            NULL,
                            G_PARAM_READABLE | G_PARAM_STATIC_STRINGS);

    /* Sleeping is not exported over D-Bus */
    obj_properties[PROP_SLEEPING] = g_param_spec_boolean(NM_MANAGER_SLEEPING,
                                                         "",
                                                         "",
                                                         FALSE,
                                                         G_PARAM_READABLE | G_PARAM_STATIC_STRINGS);

    obj_properties[PROP_DEVICES] = g_param_spec_boxed(NM_MANAGER_DEVICES,
                                                      "",
                                                      "",
                                                      G_TYPE_STRV,
                                                      G_PARAM_READABLE | G_PARAM_STATIC_STRINGS);

    /**
     * NMManager:metered:
     *
     * Whether the connectivity is metered.
     *
     * Since: 1.2
     **/
    obj_properties[PROP_METERED] = g_param_spec_uint(NM_MANAGER_METERED,
                                                     "",
                                                     "",
                                                     0,
                                                     G_MAXUINT32,
                                                     NM_METERED_UNKNOWN,
                                                     G_PARAM_READABLE | G_PARAM_STATIC_STRINGS);

    /**
     * NMManager:global-dns-configuration:
     *
     * The global DNS configuration.
     *
     * Since: 1.2
     **/
    obj_properties[PROP_GLOBAL_DNS_CONFIGURATION] =
        g_param_spec_variant(NM_MANAGER_GLOBAL_DNS_CONFIGURATION,
                             "",
                             "",
                             G_VARIANT_TYPE("a{sv}"),
                             NULL,
                             G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS);

    /**
     * NMManager:all-devices:
     *
     * All devices, including those that are not realized.
     *
     * Since: 1.2
     **/
    obj_properties[PROP_ALL_DEVICES] =
        g_param_spec_boxed(NM_MANAGER_ALL_DEVICES,
                           "",
                           "",
                           G_TYPE_STRV,
                           G_PARAM_READABLE | G_PARAM_STATIC_STRINGS);

    obj_properties[PROP_CHECKPOINTS] =
        g_param_spec_boxed(NM_MANAGER_CHECKPOINTS,
                           "",
                           "",
                           G_TYPE_STRV,
                           G_PARAM_READABLE | G_PARAM_STATIC_STRINGS);

    g_object_class_install_properties(object_class, _PROPERTY_ENUMS_LAST, obj_properties);

    /* signals */

    /* emitted only for realized devices */
    signals[DEVICE_ADDED] = g_signal_new(NM_MANAGER_DEVICE_ADDED,
                                         G_OBJECT_CLASS_TYPE(object_class),
                                         G_SIGNAL_RUN_FIRST,
                                         0,
                                         NULL,
                                         NULL,
                                         NULL,
                                         G_TYPE_NONE,
                                         1,
                                         NM_TYPE_DEVICE);

    /* Emitted for both realized devices and placeholder devices */
    signals[INTERNAL_DEVICE_ADDED] = g_signal_new(NM_MANAGER_INTERNAL_DEVICE_ADDED,
                                                  G_OBJECT_CLASS_TYPE(object_class),
                                                  G_SIGNAL_RUN_FIRST,
                                                  0,
                                                  NULL,
                                                  NULL,
                                                  NULL,
                                                  G_TYPE_NONE,
                                                  1,
                                                  G_TYPE_OBJECT);

    /* emitted only for realized devices when a device
     * becomes unrealized or removed */
    signals[DEVICE_REMOVED] = g_signal_new(NM_MANAGER_DEVICE_REMOVED,
                                           G_OBJECT_CLASS_TYPE(object_class),
                                           G_SIGNAL_RUN_FIRST,
                                           0,
                                           NULL,
                                           NULL,
                                           NULL,
                                           G_TYPE_NONE,
                                           1,
                                           NM_TYPE_DEVICE);

    /* Emitted for both realized devices and placeholder devices */
    signals[INTERNAL_DEVICE_REMOVED] = g_signal_new(NM_MANAGER_INTERNAL_DEVICE_REMOVED,
                                                    G_OBJECT_CLASS_TYPE(object_class),
                                                    G_SIGNAL_RUN_FIRST,
                                                    0,
                                                    NULL,
                                                    NULL,
                                                    NULL,
                                                    G_TYPE_NONE,
                                                    1,
                                                    G_TYPE_OBJECT);

    signals[ACTIVE_CONNECTION_ADDED] = g_signal_new(NM_MANAGER_ACTIVE_CONNECTION_ADDED,
                                                    G_OBJECT_CLASS_TYPE(object_class),
                                                    G_SIGNAL_RUN_FIRST,
                                                    0,
                                                    NULL,
                                                    NULL,
                                                    NULL,
                                                    G_TYPE_NONE,
                                                    1,
                                                    NM_TYPE_ACTIVE_CONNECTION);

    signals[ACTIVE_CONNECTION_REMOVED] = g_signal_new(NM_MANAGER_ACTIVE_CONNECTION_REMOVED,
                                                      G_OBJECT_CLASS_TYPE(object_class),
                                                      G_SIGNAL_RUN_FIRST,
                                                      0,
                                                      NULL,
                                                      NULL,
                                                      NULL,
                                                      G_TYPE_NONE,
                                                      1,
                                                      NM_TYPE_ACTIVE_CONNECTION);

    signals[CONFIGURE_QUIT] = g_signal_new(NM_MANAGER_CONFIGURE_QUIT,
                                           G_OBJECT_CLASS_TYPE(object_class),
                                           G_SIGNAL_RUN_FIRST,
                                           0,
                                           NULL,
                                           NULL,
                                           NULL,
                                           G_TYPE_NONE,
                                           0);
}