summaryrefslogtreecommitdiff
path: root/src/settings/nm-settings.c
blob: 78361804db97f80844ab43eab06e4db8bc25602e (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
// SPDX-License-Identifier: GPL-2.0+
/*
 * Søren Sandmann <sandmann@daimi.au.dk>
 * Dan Williams <dcbw@redhat.com>
 * Tambet Ingo <tambet@gmail.com>
 * Copyright (C) 2007 - 2011 Red Hat, Inc.
 * Copyright (C) 2008 Novell, Inc.
 */

#include "nm-default.h"

#include "nm-settings.h"

#include <unistd.h>
#include <sys/stat.h>
#include <gmodule.h>
#include <pwd.h>

#if HAVE_SELINUX
#include <selinux/selinux.h>
#endif

#include "nm-libnm-core-intern/nm-common-macros.h"
#include "nm-glib-aux/nm-keyfile-aux.h"
#include "nm-keyfile/nm-keyfile-internal.h"
#include "nm-dbus-interface.h"
#include "nm-connection.h"
#include "nm-setting-8021x.h"
#include "nm-setting-bluetooth.h"
#include "nm-setting-cdma.h"
#include "nm-setting-connection.h"
#include "nm-setting-gsm.h"
#include "nm-setting-ip4-config.h"
#include "nm-setting-ip6-config.h"
#include "nm-setting-olpc-mesh.h"
#include "nm-setting-ppp.h"
#include "nm-setting-pppoe.h"
#include "nm-setting-serial.h"
#include "nm-setting-vpn.h"
#include "nm-setting-wired.h"
#include "nm-setting-adsl.h"
#include "nm-setting-wireless.h"
#include "nm-setting-wireless-security.h"
#include "nm-setting-proxy.h"
#include "nm-setting-bond.h"
#include "nm-utils.h"
#include "nm-core-internal.h"

#include "nm-std-aux/c-list-util.h"
#include "nm-glib-aux/nm-c-list.h"
#include "nm-dbus-object.h"
#include "devices/nm-device-ethernet.h"
#include "nm-settings-connection.h"
#include "nm-settings-plugin.h"
#include "nm-dbus-manager.h"
#include "nm-auth-utils.h"
#include "nm-libnm-core-intern/nm-auth-subject.h"
#include "nm-session-monitor.h"
#include "plugins/keyfile/nms-keyfile-plugin.h"
#include "plugins/keyfile/nms-keyfile-storage.h"
#include "nm-agent-manager.h"
#include "nm-config.h"
#include "nm-audit-manager.h"
#include "NetworkManagerUtils.h"
#include "nm-dispatcher.h"
#include "nm-hostname-manager.h"

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

static
NM_CACHED_QUARK_FCN ("default-wired-connection", _default_wired_connection_quark)

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

typedef struct _StorageData {
	CList sd_lst;
	NMSettingsStorage *storage;
	NMConnection *connection;
	bool prioritize:1;
} StorageData;

static StorageData *
_storage_data_new_stale (NMSettingsStorage *storage,
                         NMConnection *connection)
{
	StorageData *sd;

	sd = g_slice_new (StorageData);
	sd->storage    = g_object_ref (storage);
	sd->connection = nm_g_object_ref (connection);
	sd->prioritize = FALSE;
	return sd;
}

static void
_storage_data_destroy (StorageData *sd)
{
	c_list_unlink_stale (&sd->sd_lst);
	g_object_unref (sd->storage);
	nm_g_object_unref (sd->connection);
	g_slice_free (StorageData, sd);
}

static StorageData *
_storage_data_find_in_lst (CList *head,
                           NMSettingsStorage *storage)
{
	StorageData *sd;

	nm_assert (head);
	nm_assert (NM_IS_SETTINGS_STORAGE (storage));

	c_list_for_each_entry (sd, head, sd_lst) {
		if (sd->storage == storage)
			return sd;
	}
	return NULL;
}

static void
nm_assert_storage_data_lst (CList *head)
{
#if NM_MORE_ASSERTS > 5
	const char *uuid = NULL;
	StorageData *sd;
	CList *iter;

	nm_assert (head);

	if (c_list_is_empty (head))
		return;

	c_list_for_each_entry (sd, head, sd_lst) {
		const char *u;

		nm_assert (NM_IS_SETTINGS_STORAGE (sd->storage));
		nm_assert (!sd->connection || NM_IS_CONNECTION (sd->connection));
		u = nm_settings_storage_get_uuid (sd->storage);
		if (!uuid) {
			uuid = u;
			nm_assert (nm_utils_is_uuid (uuid));
		} else
			nm_assert (nm_streq0 (uuid, u));
	}

	/* assert that all storages are unique. */
	c_list_for_each_entry (sd, head, sd_lst) {
		for (iter = sd->sd_lst.next; iter != head; iter = iter->next)
			nm_assert (c_list_entry (iter, StorageData, sd_lst)->storage != sd->storage);
	}
#endif
}

static gboolean
_storage_data_is_alive (StorageData *sd)
{
	/* If the storage tracks a connection, it is considered alive.
	 *
	 * Meta-data storages are special: they never track a connection.
	 * We need to check them specially to know when to drop them. */
	return    sd->connection
	       || nm_settings_storage_is_meta_data_alive (sd->storage);
}

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

typedef struct {
	const char *uuid;
	NMSettingsConnection *sett_conn;
	NMSettingsStorage *storage;
	CList sd_lst_head;
	CList dirty_sd_lst_head;

	CList sce_dirty_lst;

	char _uuid_data[];
} SettConnEntry;

static SettConnEntry *
_sett_conn_entry_new (const char *uuid)
{
	SettConnEntry *sett_conn_entry;
	gsize l_p_1;

	nm_assert (nm_utils_is_uuid (uuid));

	l_p_1 = strlen (uuid) + 1;

	sett_conn_entry = g_malloc (sizeof (SettConnEntry) + l_p_1);
	sett_conn_entry->uuid = sett_conn_entry->_uuid_data;
	sett_conn_entry->sett_conn = NULL;
	sett_conn_entry->storage = NULL;
	c_list_init (&sett_conn_entry->sd_lst_head);
	c_list_init (&sett_conn_entry->dirty_sd_lst_head);
	c_list_init (&sett_conn_entry->sce_dirty_lst);
	memcpy (sett_conn_entry->_uuid_data, uuid, l_p_1);
	return sett_conn_entry;
}

static void
_sett_conn_entry_free (SettConnEntry *sett_conn_entry)
{
	c_list_unlink_stale (&sett_conn_entry->sce_dirty_lst);
	nm_c_list_free_all (&sett_conn_entry->sd_lst_head,       StorageData, sd_lst, _storage_data_destroy);
	nm_c_list_free_all (&sett_conn_entry->dirty_sd_lst_head, StorageData, sd_lst, _storage_data_destroy);
	nm_g_object_unref (sett_conn_entry->sett_conn);
	nm_g_object_unref (sett_conn_entry->storage);
	g_free (sett_conn_entry);
}

static NMSettingsConnection *
_sett_conn_entry_get_conn (SettConnEntry *sett_conn_entry)
{
	return sett_conn_entry ? sett_conn_entry->sett_conn : NULL;
}

/**
 * _sett_conn_entry_storage_find_conflicting_storage:
 * @sett_conn_entry: the list of settings-storages for the given UUID.
 * @target_plugin: the settings plugin to check
 * @storage_check_including: (allow-none): optionally compare against this storage.
 * @plugins: the list of plugins sorted in descending priority. This determines
 *   the priority and whether a storage conflicts.
 *
 * If we were to add the a storage to @target_plugin, then this function checks
 * whether there are already other storages that would hide the storage after we
 * add it. Those conflicting/hiding storages are a problem, because they have higher
 * priority, so we cannot add the storage.
 *
 * @storage_check_including is optional, and if given then it checks whether updating
 * the profile in this storage would result in confict. This is the check before
 * update-connection. If this parameter is omitted, then it's about what happens
 * when adding a new profile (add-connection).
 *
 * Returns: the conflicting storage or %NULL if there is none.
 */
static NMSettingsStorage *
_sett_conn_entry_storage_find_conflicting_storage (SettConnEntry *sett_conn_entry,
                                                   NMSettingsPlugin *target_plugin,
                                                   NMSettingsStorage *storage_check_including,
                                                   const GSList *plugins)
{
	StorageData *sd;

	if (!sett_conn_entry)
		return NULL;

	if (   storage_check_including
	    && nm_settings_storage_is_keyfile_run (storage_check_including)) {
		/* the storage we check against is in-memory. It always has highest
		 * priority, so there can be no other conflicting storages. */
		return NULL;
	}

	/* Finds the first (highest priority) storage that has a connection.
	 * Note that due to tombstones (that have a high priority), the connection
	 * may not actually be exposed. This is to find hidden/shadowed storages
	 * that provide a connection. */
	c_list_for_each_entry (sd, &sett_conn_entry->sd_lst_head, sd_lst) {
		nm_assert (NM_IS_SETTINGS_STORAGE (sd->storage));

		if (!sd->connection) {
			/* We only consider storages with connection. In particular,
			 * tombstones are not relevant, because we can delete them to
			 * resolve the conflict. */
			continue;
		}

		if (sd->storage == storage_check_including) {
			/* ok, the storage is the one we are about to check. All other
			 * storages are lower priority, so there is no storage that hides
			 * our storage_check_including. */
			return NULL;
		}

		if (nm_settings_plugin_cmp_by_priority (nm_settings_storage_get_plugin (sd->storage),
		                                        target_plugin,
		                                        plugins) <= 0) {
			/* the plugin of the existing storage is less important than @target_plugin.
			 * We have no conflicting/hiding storage. */
			return NULL;
		}

		/* Found. If we would add the profile to @target_plugin, then it would be hidden
		 * by existing_storage. */
		return sd->storage;
	}

	return NULL;
}

static NMSettingsStorage *
_sett_conn_entry_find_shadowed_storage (SettConnEntry *sett_conn_entry,
                                        const char *shadowed_storage_filename,
                                        NMSettingsStorage *blacklisted_storage)
{
	StorageData *sd;

	if (!shadowed_storage_filename)
		return NULL;

	c_list_for_each_entry (sd, &sett_conn_entry->sd_lst_head, sd_lst) {

		nm_assert (NM_IS_SETTINGS_STORAGE (sd->storage));

		if (!sd->connection)
			continue;

		if (blacklisted_storage == sd->storage)
			continue;

		if (!nm_streq0 (nm_settings_storage_get_filename_for_shadowed_storage (sd->storage), shadowed_storage_filename))
			continue;

		return sd->storage;
	}

	return NULL;
}

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

NM_GOBJECT_PROPERTIES_DEFINE (NMSettings,
	PROP_UNMANAGED_SPECS,
	PROP_HOSTNAME,
	PROP_CAN_MODIFY,
	PROP_CONNECTIONS,
	PROP_STARTUP_COMPLETE,
);

enum {
	CONNECTION_ADDED,
	CONNECTION_UPDATED,
	CONNECTION_REMOVED,
	CONNECTION_FLAGS_CHANGED,
	LAST_SIGNAL
};

static guint signals[LAST_SIGNAL] = { 0 };

typedef struct {
	NMAgentManager *agent_mgr;

	NMConfig *config;

	NMPlatform *platform;

	NMHostnameManager *hostname_manager;

	NMSessionMonitor *session_monitor;

	CList auth_lst_head;

	NMSKeyfilePlugin *keyfile_plugin;

	GSList *plugins;

	NMKeyFileDB *kf_db_timestamps;
	NMKeyFileDB *kf_db_seen_bssids;

	GHashTable *sce_idx;

	CList sce_dirty_lst_head;

	CList connections_lst_head;

	NMSettingsConnection **connections_cached_list;

	GSList *unmanaged_specs;
	GSList *unrecognized_specs;

	GHashTable *startup_complete_idx;
	NMSettingsConnection *startup_complete_blocked_by;
	gulong startup_complete_platform_change_id;
	guint startup_complete_timeout_id;

	guint connections_len;

	guint connections_generation;

	guint kf_db_flush_idle_id_timestamps;
	guint kf_db_flush_idle_id_seen_bssids;

	bool started:1;

} NMSettingsPrivate;

struct _NMSettings {
	NMDBusObject parent;
	NMSettingsPrivate _priv;
};

struct _NMSettingsClass {
	NMDBusObjectClass parent;
};

G_DEFINE_TYPE (NMSettings, nm_settings, NM_TYPE_DBUS_OBJECT);

#define NM_SETTINGS_GET_PRIVATE(self) _NM_GET_PRIVATE (self, NMSettings, NM_IS_SETTINGS)

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

/* FIXME: a lot of logging lines are directly connected to a profile. Set the @con_uuid
 *   argument for structured logging. */

#define _NMLOG_DOMAIN         LOGD_SETTINGS
#define _NMLOG(level, ...) __NMLOG_DEFAULT (level, _NMLOG_DOMAIN, "settings", __VA_ARGS__)

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

static const NMDBusInterfaceInfoExtended interface_info_settings;
static const GDBusSignalInfo signal_info_new_connection;
static const GDBusSignalInfo signal_info_connection_removed;

static void default_wired_clear_tag (NMSettings *self,
                                     NMDevice *device,
                                     NMSettingsConnection *sett_conn,
                                     gboolean add_to_no_auto_default);

static void _clear_connections_cached_list (NMSettingsPrivate *priv);

static void _startup_complete_check (NMSettings *self,
                                     gint64 now_us);

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

static void
_emit_connection_added (NMSettings *self,
                        NMSettingsConnection *sett_conn)
{
	g_signal_emit (self, signals[CONNECTION_ADDED], 0, sett_conn);
}

static void
_emit_connection_updated (NMSettings *self,
                          NMSettingsConnection *sett_conn,
                          NMSettingsConnectionUpdateReason update_reason)
{
	_nm_settings_connection_emit_signal_updated_internal (sett_conn, update_reason);
	g_signal_emit (self, signals[CONNECTION_UPDATED], 0, sett_conn, (guint) update_reason);
}

static void
_emit_connection_removed (NMSettings *self,
                          NMSettingsConnection *sett_conn)
{
	g_signal_emit (self, signals[CONNECTION_REMOVED], 0, sett_conn);
}

static void
_emit_connection_flags_changed (NMSettings *self,
                                NMSettingsConnection *sett_conn)
{
	g_signal_emit (self, signals[CONNECTION_FLAGS_CHANGED], 0, sett_conn);
}

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

typedef struct {
	NMSettingsConnection *sett_conn;
	gint64 start_at;
	gint64 timeout;
} StartupCompleteData;

static void
_startup_complete_data_destroy (StartupCompleteData *scd)
{
	g_object_unref (scd->sett_conn);
	g_slice_free (StartupCompleteData, scd);
}

static gboolean
_startup_complete_check_is_ready (NMPlatform *platform,
                                  NMSettingsConnection *sett_conn)
{
	const NMPlatformLink *plink;
	const char *ifname;

	/* FIXME: instead of just looking for the interface name, it would be better
	 *        to wait for a device that is compatible with the profile. */

	ifname = nm_connection_get_interface_name (nm_settings_connection_get_connection (sett_conn));

	if (!ifname)
		return TRUE;

	plink = nm_platform_link_get_by_ifname (platform, ifname);
	return plink && plink->initialized;
}

static gboolean
_startup_complete_timeout_cb (gpointer user_data)
{
	NMSettings *self = user_data;
	NMSettingsPrivate *priv = NM_SETTINGS_GET_PRIVATE (self);

	priv->startup_complete_timeout_id = 0;
	_startup_complete_check (self, 0);
	return G_SOURCE_REMOVE;
}

static void
_startup_complete_platform_change_cb (NMPlatform *platform,
                                      int obj_type_i,
                                      int ifindex,
                                      const NMPlatformLink *link,
                                      int change_type_i,
                                      NMSettings *self)
{
	const NMPlatformSignalChangeType change_type = change_type_i;
	NMSettingsPrivate *priv;
	const char *ifname;

	if (change_type == NM_PLATFORM_SIGNAL_REMOVED)
		return;

	if (!link->initialized)
		return;

	priv = NM_SETTINGS_GET_PRIVATE (self);

	ifname = nm_connection_get_interface_name (nm_settings_connection_get_connection (priv->startup_complete_blocked_by));
	if (   ifname
	    && !nm_streq (ifname, link->name))
		return;

	nm_assert (priv->startup_complete_timeout_id > 0);

	nm_clear_g_source (&priv->startup_complete_timeout_id);
	priv->startup_complete_timeout_id = g_idle_add (_startup_complete_timeout_cb, self);
}

static void
_startup_complete_check (NMSettings *self,
                         gint64 now_us)
{
	NMSettingsPrivate *priv = NM_SETTINGS_GET_PRIVATE (self);
	gint64 next_expiry;
	StartupCompleteData *scd;
	NMSettingsConnection *next_sett_conn = NULL;
	GHashTableIter iter;

	if (!priv->started) {
		/* before we are started, we don't setup the timers... */
		return;
	}

	if (!priv->startup_complete_idx)
		goto ready;

	if (!now_us)
		now_us = nm_utils_get_monotonic_timestamp_usec ();

	next_expiry = 0;

	g_hash_table_iter_init (&iter, priv->startup_complete_idx);
	while (g_hash_table_iter_next (&iter, (gpointer *) &scd, NULL)) {
		gint64 expiry;

		if (scd->start_at == 0) {
			/* once ready, the decision is remembered and there is nothing
			 * left to check. */
			continue;
		}

		expiry = scd->start_at + scd->timeout;
		if (expiry <= now_us) {
			scd->start_at = 0;
			continue;
		}

		if (_startup_complete_check_is_ready (priv->platform, scd->sett_conn)) {
			scd->start_at = 0;
			continue;
		}

		next_expiry = expiry;
		next_sett_conn = scd->sett_conn;
		/* we found one timeout for which to wait. that's good enough. */
		break;
	}

	nm_clear_g_source (&priv->startup_complete_timeout_id);
	nm_g_object_ref_set (&priv->startup_complete_blocked_by, next_sett_conn);
	if (next_expiry > 0) {
		nm_assert (priv->startup_complete_blocked_by);
		if (priv->startup_complete_platform_change_id == 0) {
			priv->startup_complete_platform_change_id = g_signal_connect (priv->platform,
			                                                              NM_PLATFORM_SIGNAL_LINK_CHANGED,
			                                                              G_CALLBACK (_startup_complete_platform_change_cb),
			                                                              self);
		}
		priv->startup_complete_timeout_id = g_timeout_add (NM_MIN (3600u*1000u, (next_expiry - now_us) / 1000u),
		                                                   _startup_complete_timeout_cb,
		                                                   self);
		_LOGT ("startup-complete: wait for device \"%s\" due to connection %s (%s)",
		       nm_connection_get_interface_name (nm_settings_connection_get_connection (priv->startup_complete_blocked_by)),
		       nm_settings_connection_get_uuid (priv->startup_complete_blocked_by),
		       nm_settings_connection_get_id (priv->startup_complete_blocked_by));
		return;
	}

	nm_clear_pointer (&priv->startup_complete_idx, g_hash_table_destroy);
	nm_clear_g_signal_handler (priv->platform, &priv->startup_complete_platform_change_id);

ready:
	_LOGT ("startup-complete: ready, no profiles to wait for");
	nm_assert (priv->started);
	nm_assert (!priv->startup_complete_blocked_by);
	nm_assert (!priv->startup_complete_idx);
	nm_assert (priv->startup_complete_timeout_id == 0);
	nm_assert (priv->startup_complete_platform_change_id == 0);
	_notify (self, PROP_STARTUP_COMPLETE);
}

static void
_startup_complete_notify_connection (NMSettings *self,
                                     NMSettingsConnection *sett_conn,
                                     gboolean forget)
{
	NMSettingsPrivate *priv = NM_SETTINGS_GET_PRIVATE (self);
	gint64 timeout;
	gint64 now_us = 0;

	nm_assert (   !priv->started
	           || priv->startup_complete_idx);

	timeout = 0;
	if (!forget) {
		NMSettingConnection *s_con;
		gint32 v;

		s_con = nm_connection_get_setting_connection (nm_settings_connection_get_connection (sett_conn));
		v = nm_setting_connection_get_wait_device_timeout (s_con);
		if (v > 0) {
			nm_assert (nm_setting_connection_get_interface_name (s_con));
			timeout = ((gint64) v) * 1000;
		}
	}

	if (timeout == 0) {
		if (   !priv->startup_complete_idx
		    || !g_hash_table_remove (priv->startup_complete_idx, &sett_conn))
			return;
	} else {
		StartupCompleteData *scd;

		if (!priv->startup_complete_idx) {
			nm_assert (!priv->started);
			priv->startup_complete_idx = g_hash_table_new_full (nm_pdirect_hash,
			                                                    nm_pdirect_equal,
			                                                    NULL,
			                                                    (GDestroyNotify) _startup_complete_data_destroy);
			scd = NULL;
		} else
			scd = g_hash_table_lookup (priv->startup_complete_idx, &sett_conn);
		if (!scd) {
			now_us = nm_utils_get_monotonic_timestamp_usec ();
			scd = g_slice_new (StartupCompleteData);
			*scd = (StartupCompleteData) {
				.sett_conn = g_object_ref (sett_conn),
				.start_at  = now_us,
				.timeout   = timeout,
			};
			g_hash_table_add (priv->startup_complete_idx, scd);
		} else {
			if (scd->start_at == 0) {
				/* the entry already is ready and no longer relevant. Ignore it. */
				return;
			}
			scd->timeout = timeout;
		}
	}

	_startup_complete_check (self, now_us);
}

const char *
nm_settings_get_startup_complete_blocked_reason (NMSettings *self)
{
	NMSettingsPrivate *priv = NM_SETTINGS_GET_PRIVATE (self);
	const char *uuid = NULL;

	if (priv->started) {
		if (!priv->startup_complete_idx)
			return NULL;
		if (priv->startup_complete_blocked_by)
			uuid = nm_settings_connection_get_uuid (priv->startup_complete_blocked_by);
	}
	return uuid ?: "unknown";
}

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

const GSList *
nm_settings_get_unmanaged_specs (NMSettings *self)
{
	NMSettingsPrivate *priv = NM_SETTINGS_GET_PRIVATE (self);

	return priv->unmanaged_specs;
}

static gboolean
update_specs (NMSettings *self, GSList **specs_ptr,
              GSList * (*get_specs_func) (NMSettingsPlugin *))
{
	NMSettingsPrivate *priv = NM_SETTINGS_GET_PRIVATE (self);
	GSList *new = NULL;
	GSList *iter;

	for (iter = priv->plugins; iter; iter = g_slist_next (iter)) {
		GSList *specs;

		specs = get_specs_func (iter->data);
		while (specs) {
			GSList *s = specs;

			specs = g_slist_remove_link (specs, s);
			if (nm_utils_g_slist_find_str (new, s->data)) {
				g_free (s->data);
				g_slist_free_1 (s);
				continue;
			}
			s->next = new;
			new = s;
		}
	}

	if (nm_utils_g_slist_strlist_cmp (new, *specs_ptr) == 0) {
		g_slist_free_full (new, g_free);
		return FALSE;
	}

	g_slist_free_full (*specs_ptr, g_free);
	*specs_ptr = new;
	return TRUE;

}

static void
_plugin_unmanaged_specs_changed (NMSettingsPlugin *config,
                                 gpointer user_data)
{
	NMSettings *self = NM_SETTINGS (user_data);
	NMSettingsPrivate *priv = NM_SETTINGS_GET_PRIVATE (self);

	if (update_specs (self, &priv->unmanaged_specs,
	                  nm_settings_plugin_get_unmanaged_specs))
		_notify (self, PROP_UNMANAGED_SPECS);
}

static void
_plugin_unrecognized_specs_changed (NMSettingsPlugin *config,
                                    gpointer user_data)
{
	NMSettings *self = NM_SETTINGS (user_data);
	NMSettingsPrivate *priv = NM_SETTINGS_GET_PRIVATE (self);

	update_specs (self, &priv->unrecognized_specs,
	              nm_settings_plugin_get_unrecognized_specs);
}

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

static void
connection_flags_changed (NMSettingsConnection *sett_conn,
                          gpointer user_data)
{
	_emit_connection_flags_changed (NM_SETTINGS (user_data), sett_conn);
}

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

static SettConnEntry *
_sett_conn_entries_get (NMSettings *self,
                        const char *uuid)
{
	nm_assert (uuid);
	return g_hash_table_lookup (NM_SETTINGS_GET_PRIVATE (self)->sce_idx, &uuid);
}

static SettConnEntry *
_sett_conn_entries_create_and_add (NMSettings *self,
                                   const char *uuid)
{
	NMSettingsPrivate *priv = NM_SETTINGS_GET_PRIVATE (self);
	SettConnEntry *sett_conn_entry;

	sett_conn_entry = _sett_conn_entry_new (uuid);

	if (!g_hash_table_add (priv->sce_idx, sett_conn_entry))
		nm_assert_not_reached ();
	else if (g_hash_table_size (priv->sce_idx) == 1)
		g_object_ref (self);

	return sett_conn_entry;
}

static void
_sett_conn_entries_remove_and_destroy (NMSettings *self,
                                       SettConnEntry *sett_conn_entry)
{
	NMSettingsPrivate *priv = NM_SETTINGS_GET_PRIVATE (self);

	if (!g_hash_table_remove (priv->sce_idx, sett_conn_entry))
		nm_assert_not_reached ();
	else if (g_hash_table_size (priv->sce_idx) == 0)
		g_object_unref (self);
}

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

static int
_sett_conn_entry_sds_update_cmp_ascending (const StorageData *sd_a,
                                           const StorageData *sd_b,
                                           const GSList *plugins)
{
	const NMSettingsMetaData *meta_data_a;
	const NMSettingsMetaData *meta_data_b;
	bool is_keyfile_run_a;
	bool is_keyfile_run_b;

	/* Sort storages by priority. More important storages are sorted
	 * higher (ascending sort). For example, if "sd_a" is more important than
	 * "sd_b" (sd_a>sd_b), a positive integer is returned. */

	meta_data_a = nm_settings_storage_is_meta_data (sd_a->storage);
	meta_data_b = nm_settings_storage_is_meta_data (sd_b->storage);

	/* runtime storages (both connections and meta-data) are always more
	 * important. */
	is_keyfile_run_a = nm_settings_storage_is_keyfile_run (sd_a->storage);
	is_keyfile_run_b = nm_settings_storage_is_keyfile_run (sd_b->storage);
	if (is_keyfile_run_a != is_keyfile_run_b) {

		if (   !meta_data_a
		    && !meta_data_b) {
			/* Ok, both are non-meta-data providing actual profiles. But one is in /run and one is in
			 * another storage. In this case we first honor whether one of the storages is explicitly
			 * prioritized. The prioritize flag is an in-memory hack to overwrite relative priorities
			 * contrary to what exists on-disk.
			 *
			 * This is done because when we use explicit D-Bus API (like update-connection)
			 * to update a profile, then we really want to prioritize the candidate
			 * despite having multiple other profiles.
			 *
			 * The example is if you have the same UUID twice in /run (one of them shadowed).
			 * If you move it to disk, then one of the profiles gets deleted and re-created
			 * on disk, but that on-disk profile must win against the remainging profile in
			 * /run. At least until the next reload/restart. */
			NM_CMP_FIELD_UNSAFE (sd_a, sd_b, prioritize);
		}

		/* in-memory has higher priority. That is regardless of whether any of
		 * them is meta-data/tombstone or a profile.
		 *
		 * That works, because if any of them are tombstones/metadata, then we are in full
		 * control. There can by only one meta-data file, which is fully owned (and accordingly
		 * created/deleted) by NetworkManager.
		 *
		 * The only case where this might not be right is if we have profiles
		 * in /run that are shadowed. When we move such a profile to disk, then
		 * a conflict might arise. That is handled by "prioritize" above! */
		NM_CMP_DIRECT (is_keyfile_run_a, is_keyfile_run_b);
	}

	/* After we determined that both profiles are either in /run or not,
	 * tombstones are always more important than non-tombstones. */
	NM_CMP_DIRECT (meta_data_a && meta_data_a->is_tombstone,
	               meta_data_b && meta_data_b->is_tombstone);

	/* Again, prioritized entries are sorted first (higher priority). */
	NM_CMP_FIELD_UNSAFE (sd_a, sd_b, prioritize);

	/* finally, compare the storages. This basically honors the timestamp
	 * of the profile and the relative order of the source plugin (via the
	 * @plugins list). */
	return nm_settings_storage_cmp (sd_a->storage, sd_b->storage, plugins);
}

static int
_sett_conn_entry_sds_update_cmp (const CList *ls_a,
                                 const CList *ls_b,
                                 gconstpointer user_data)
{
	/* we sort highest priority storages first (descending). Hence, the order is swapped. */
	return _sett_conn_entry_sds_update_cmp_ascending (c_list_entry (ls_b, StorageData, sd_lst),
	                                                  c_list_entry (ls_a, StorageData, sd_lst),
	                                                  user_data);
}

static void
_sett_conn_entry_sds_update (NMSettings *self,
                             SettConnEntry *sett_conn_entry)
{
	StorageData *sd;
	StorageData *sd_safe;
	StorageData *sd_dirty;
	gboolean reprioritize;

	nm_assert_storage_data_lst (&sett_conn_entry->sd_lst_head);
	nm_assert_storage_data_lst (&sett_conn_entry->dirty_sd_lst_head);

	/* we merge the dirty list with the previous list.
	 *
	 * The idea is:
	 *
	 *  - _connection_changed_track() appends events for the same UUID. Meaning:
	 *    if the storage is new, it get appended (having lower priority).
	 *    If it already exist and is an update for an event that we already
	 *    track it, it keeps the list position in @dirty_sd_lst_head unchanged.
	 *
	 *  - during merge, we want to preserve the previous order (with higher
	 *    priority first in the list).
	 */

	/* first go through all storages that we track and check whether they
	 * got an update...*/

	reprioritize = FALSE;
	c_list_for_each_entry (sd, &sett_conn_entry->dirty_sd_lst_head, sd_lst) {
		if (sd->prioritize) {
			reprioritize = TRUE;
			break;
		}
	}

	nm_assert_storage_data_lst (&sett_conn_entry->sd_lst_head);

	c_list_for_each_entry_safe (sd, sd_safe, &sett_conn_entry->sd_lst_head, sd_lst) {

		sd_dirty = _storage_data_find_in_lst (&sett_conn_entry->dirty_sd_lst_head, sd->storage);
		if (!sd_dirty) {
			/* there is no update for this storage (except maybe reprioritize). */
			if (reprioritize)
				sd->prioritize = FALSE;
			continue;
		}

		nm_g_object_ref_set (&sd->connection, sd_dirty->connection);
		sd->prioritize = sd_dirty->prioritize;

		_storage_data_destroy (sd_dirty);
	}

	nm_assert_storage_data_lst (&sett_conn_entry->sd_lst_head);

	/* all remaining (so far unseen) dirty entries are appended to the merged list.
	 * (append means lower priority). */

	c_list_splice (&sett_conn_entry->sd_lst_head, &sett_conn_entry->dirty_sd_lst_head);

	nm_assert_storage_data_lst (&sett_conn_entry->sd_lst_head);

	/* we drop the entries that are no longer "alive" (meaning, they no longer
	 * indicate a connection and are not a tombstone). */
	c_list_for_each_entry_safe (sd, sd_safe, &sett_conn_entry->sd_lst_head, sd_lst) {
		if (!_storage_data_is_alive (sd))
			_storage_data_destroy (sd);
	}

	nm_assert_storage_data_lst (&sett_conn_entry->sd_lst_head);
	nm_assert (c_list_is_empty (&sett_conn_entry->dirty_sd_lst_head));

	/* as last, we sort the entries. Note that this is a stable-sort... */
	c_list_sort (&sett_conn_entry->sd_lst_head,
	             _sett_conn_entry_sds_update_cmp,
	             NM_SETTINGS_GET_PRIVATE (self)->plugins);

	nm_assert_storage_data_lst (&sett_conn_entry->sd_lst_head);
	nm_assert (c_list_is_empty (&sett_conn_entry->dirty_sd_lst_head));
}

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

static NMConnection *
_connection_changed_normalize_connection (NMSettingsStorage *storage,
                                          NMConnection *connection,
                                          GVariant *secrets_to_merge,
                                          NMConnection **out_connection_cloned)
{
	gs_unref_object NMConnection *connection_cloned = NULL;
	gs_free_error GError *error = NULL;
	const char *uuid;

	nm_assert (NM_IS_SETTINGS_STORAGE (storage));
	nm_assert (out_connection_cloned && !*out_connection_cloned);

	if (!connection)
		return NULL;

	nm_assert (NM_IS_CONNECTION (connection));

	uuid = nm_settings_storage_get_uuid (storage);

	if (secrets_to_merge) {
		connection_cloned = nm_simple_connection_new_clone (connection);
		connection = connection_cloned;
		nm_connection_update_secrets (connection,
		                              NULL,
		                              secrets_to_merge,
		                              NULL);
	}

	if (!_nm_connection_ensure_normalized (connection,
	                                       !!connection_cloned,
	                                       uuid,
	                                       FALSE,
	                                       connection_cloned ? NULL : &connection_cloned,
	                                       &error)) {
		/* this is most likely a bug in the plugin. It provided a connection that no longer verifies.
		 * Well, I guess it could also happen when we merge @secrets_to_merge above. In any case
		 * somewhere is a bug. */
		_LOGT ("storage[%s,"NM_SETTINGS_STORAGE_PRINT_FMT"]: plugin provided an invalid connection: %s",
		       uuid,
		       NM_SETTINGS_STORAGE_PRINT_ARG (storage),
		       error->message);
		return NULL;
	}
	if (connection_cloned)
		connection = connection_cloned;

	*out_connection_cloned = g_steal_pointer (&connection_cloned);
	return connection;
}

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

static void
_connection_changed_update (NMSettings *self,
                            SettConnEntry *sett_conn_entry,
                            NMConnection *connection,
                            NMSettingsConnectionIntFlags sett_flags,
                            NMSettingsConnectionIntFlags sett_mask,
                            NMSettingsConnectionUpdateReason update_reason)
{
	NMSettingsPrivate *priv = NM_SETTINGS_GET_PRIVATE (self);
	gs_unref_object NMConnection *connection_old = NULL;
	NMSettingsStorage *storage = sett_conn_entry->storage;
	gs_unref_object NMSettingsConnection *sett_conn = g_object_ref (sett_conn_entry->sett_conn);
	const char *path;
	gboolean is_new;

	nm_assert (!NM_FLAGS_ANY (sett_mask, ~_NM_SETTINGS_CONNECTION_INT_FLAGS_PERSISTENT_MASK));
	nm_assert (!NM_FLAGS_ANY (sett_flags, ~sett_mask));

	is_new = c_list_is_empty (&sett_conn->_connections_lst);

	_LOGT ("update[%s]: %s connection \"%s\" ("NM_SETTINGS_STORAGE_PRINT_FMT")",
	       nm_settings_storage_get_uuid (storage),
	       is_new ? "adding" : "updating",
	       nm_connection_get_id (connection),
	       NM_SETTINGS_STORAGE_PRINT_ARG (storage));

	_nm_settings_connection_set_storage (sett_conn, storage);

	_nm_settings_connection_set_connection (sett_conn, connection, &connection_old, update_reason);


	if (is_new) {
		_nm_settings_connection_register_kf_dbs (sett_conn,
		                                         priv->kf_db_timestamps,
		                                         priv->kf_db_seen_bssids);

		_clear_connections_cached_list (priv);
		c_list_link_tail (&priv->connections_lst_head, &sett_conn->_connections_lst);
		priv->connections_len++;
		priv->connections_generation++;

		g_signal_connect (sett_conn, NM_SETTINGS_CONNECTION_FLAGS_CHANGED, G_CALLBACK (connection_flags_changed), self);
	}

	if (NM_FLAGS_HAS (update_reason, NM_SETTINGS_CONNECTION_UPDATE_REASON_BLOCK_AUTOCONNECT)) {
		nm_settings_connection_autoconnect_blocked_reason_set (sett_conn,
		                                                       NM_SETTINGS_AUTO_CONNECT_BLOCKED_REASON_USER_REQUEST,
		                                                       TRUE);
	}

	sett_mask |= NM_SETTINGS_CONNECTION_INT_FLAGS_VISIBLE;
	if (nm_settings_connection_check_visibility (sett_conn, priv->session_monitor))
		sett_flags |= NM_SETTINGS_CONNECTION_INT_FLAGS_VISIBLE;
	else
		nm_assert (!NM_FLAGS_HAS (sett_flags, NM_SETTINGS_CONNECTION_INT_FLAGS_VISIBLE));

	sett_mask |= NM_SETTINGS_CONNECTION_INT_FLAGS_UNSAVED;
	if (nm_settings_storage_is_keyfile_run (storage))
		sett_flags |= NM_SETTINGS_CONNECTION_INT_FLAGS_UNSAVED;
	else {
		nm_assert (!NM_FLAGS_HAS (sett_flags, NM_SETTINGS_CONNECTION_INT_FLAGS_UNSAVED));

		/* Profiles that don't reside in /run, are never nm-generated
		 * and never volatile. */
		sett_mask |= (  NM_SETTINGS_CONNECTION_INT_FLAGS_NM_GENERATED
		              | NM_SETTINGS_CONNECTION_INT_FLAGS_VOLATILE);
		sett_flags &= ~(  NM_SETTINGS_CONNECTION_INT_FLAGS_NM_GENERATED
		                | NM_SETTINGS_CONNECTION_INT_FLAGS_VOLATILE);
	}

	nm_settings_connection_set_flags_full (sett_conn,
	                                       sett_mask,
	                                       sett_flags);

	if (is_new) {
		/* FIXME(shutdown): The NMSettings instance can't be disposed
		 * while there is any exported connection. Ideally we should
		 * unexport all connections on NMSettings' disposal, but for now
		 * leak @self on termination when there are connections alive. */
		path = nm_dbus_object_export (NM_DBUS_OBJECT (sett_conn));
	} else
		path = nm_dbus_object_get_path (NM_DBUS_OBJECT (sett_conn));

	if (   is_new
	    || connection_old) {
		nm_utils_log_connection_diff (nm_settings_connection_get_connection (sett_conn),
		                              connection_old,
		                              LOGL_DEBUG,
		                              LOGD_CORE,
		                              is_new ? "new connection" : "update connection",
		                              "++ ",
		                              path);
	}

	if (is_new) {
		nm_dbus_object_emit_signal (NM_DBUS_OBJECT (self),
		                            &interface_info_settings,
		                            &signal_info_new_connection,
		                            "(o)",
		                            path);
		_notify (self, PROP_CONNECTIONS);
		_emit_connection_added (self, sett_conn);
	} else {
		_nm_settings_connection_emit_dbus_signal_updated (sett_conn);
		_emit_connection_updated (self, sett_conn, update_reason);
	}

	if (   !priv->started
	    || priv->startup_complete_idx) {
		if (nm_settings_has_connection (self, sett_conn))
			_startup_complete_notify_connection (self, sett_conn, FALSE);
	}
}

static void
_connection_changed_delete (NMSettings *self,
                            NMSettingsStorage *storage,
                            NMSettingsConnection *sett_conn,
                            gboolean allow_add_to_no_auto_default)
{
	NMSettingsPrivate *priv = NM_SETTINGS_GET_PRIVATE (self);
	gs_unref_object NMConnection *connection_for_agents = NULL;
	NMDevice *device;
	const char *uuid;

	nm_assert (NM_IS_SETTINGS_CONNECTION (sett_conn));
	nm_assert (c_list_contains (&priv->connections_lst_head, &sett_conn->_connections_lst));
	nm_assert (nm_dbus_object_is_exported (NM_DBUS_OBJECT (sett_conn)));

	uuid = nm_settings_storage_get_uuid (storage);

	_LOGT ("update[%s]: delete connection \"%s\" ("NM_SETTINGS_STORAGE_PRINT_FMT")",
	       uuid,
	       nm_settings_connection_get_id (sett_conn),
	       NM_SETTINGS_STORAGE_PRINT_ARG (storage));

	/* When the default wired sett_conn is removed (either deleted or saved to
	 * a new persistent sett_conn by a plugin), write the MAC address of the
	 * wired device to the config file and don't create a new default wired
	 * sett_conn for that device again.
	 */
	device = nm_settings_connection_default_wired_get_device (sett_conn);
	if (device)
		default_wired_clear_tag (self, device, sett_conn, allow_add_to_no_auto_default);

	g_signal_handlers_disconnect_by_func (sett_conn, G_CALLBACK (connection_flags_changed), self);

	_clear_connections_cached_list (priv);
	c_list_unlink (&sett_conn->_connections_lst);
	priv->connections_len--;
	priv->connections_generation++;

	/* Tell agents to remove secrets for this connection */
	connection_for_agents = nm_simple_connection_new_clone (nm_settings_connection_get_connection (sett_conn));
	nm_connection_clear_secrets (connection_for_agents);
	nm_agent_manager_delete_secrets (priv->agent_mgr,
	                                 nm_dbus_object_get_path (NM_DBUS_OBJECT (self)),
	                                 connection_for_agents);

	_notify (self, PROP_CONNECTIONS);
	_nm_settings_connection_emit_dbus_signal_removed (sett_conn);
	nm_dbus_object_emit_signal (NM_DBUS_OBJECT (self),
	                            &interface_info_settings,
	                            &signal_info_connection_removed,
	                            "(o)",
	                            nm_dbus_object_get_path (NM_DBUS_OBJECT (sett_conn)));

	nm_dbus_object_unexport (NM_DBUS_OBJECT (sett_conn));

	nm_settings_connection_set_flags (sett_conn,
	                                    NM_SETTINGS_CONNECTION_INT_FLAGS_VISIBLE
	                                  | NM_SETTINGS_CONNECTION_INT_FLAGS_VOLATILE,
	                                  FALSE);

	_emit_connection_removed (self, sett_conn);

	_nm_settings_connection_cleanup_after_remove (sett_conn);

	nm_key_file_db_remove_key (priv->kf_db_timestamps, uuid);
	nm_key_file_db_remove_key (priv->kf_db_seen_bssids, uuid);

	if (   !priv->started
	    || priv->startup_complete_idx)
		_startup_complete_notify_connection (self, sett_conn, TRUE);
}

static void
_connection_changed_process_one (NMSettings *self,
                                 SettConnEntry *sett_conn_entry,
                                 gboolean allow_add_to_no_auto_default,
                                 NMSettingsConnectionIntFlags sett_flags,
                                 NMSettingsConnectionIntFlags sett_mask,
                                 gboolean override_sett_flags,
                                 NMSettingsConnectionUpdateReason update_reason)
{
	StorageData *sd_best;

	c_list_unlink (&sett_conn_entry->sce_dirty_lst);

	_sett_conn_entry_sds_update (self, sett_conn_entry);

	sd_best = c_list_first_entry (&sett_conn_entry->sd_lst_head, StorageData, sd_lst);;

	if (   !sd_best
	    || !sd_best->connection) {
		gs_unref_object NMSettingsConnection *sett_conn = NULL;
		gs_unref_object NMSettingsStorage *storage = NULL;

		if (!sett_conn_entry->sett_conn) {

			if (!sd_best) {
				_sett_conn_entries_remove_and_destroy (self, sett_conn_entry);
				return;
			}

			if (sett_conn_entry->storage != sd_best->storage) {
				_LOGT ("update[%s]: shadow UUID ("NM_SETTINGS_STORAGE_PRINT_FMT")",
				       sett_conn_entry->uuid,
				       NM_SETTINGS_STORAGE_PRINT_ARG (sd_best->storage));
			}

			nm_g_object_ref_set (&sett_conn_entry->storage, sd_best->storage);
			return;
		}

		sett_conn = g_steal_pointer (&sett_conn_entry->sett_conn);
		if (sd_best) {
			storage = g_object_ref (sd_best->storage);
			nm_g_object_ref_set (&sett_conn_entry->storage, storage);
			nm_assert_valid_settings_storage (NULL, storage);
		} else {
			storage = g_object_ref (sett_conn_entry->storage);
			_sett_conn_entries_remove_and_destroy (self, sett_conn_entry);
		}

		_connection_changed_delete (self, storage, sett_conn, allow_add_to_no_auto_default);
		return;
	}

	if (override_sett_flags) {
		NMSettingsConnectionIntFlags s_f, s_m;

		nm_settings_storage_load_sett_flags (sd_best->storage, &s_f, &s_m);

		nm_assert (!NM_FLAGS_ANY (s_f, ~s_m));

		sett_mask |= s_m;
		sett_flags = (sett_flags & ~s_m) | (s_f & s_m);
	}

	nm_g_object_ref_set (&sett_conn_entry->storage, sd_best->storage);

	if (!sett_conn_entry->sett_conn)
		sett_conn_entry->sett_conn = nm_settings_connection_new ();

	_connection_changed_update (self,
	                            sett_conn_entry,
	                            sd_best->connection,
	                            sett_flags,
	                            sett_mask,
	                            update_reason);
}

static void
_connection_changed_process_all_dirty (NMSettings *self,
                                       gboolean allow_add_to_no_auto_default,
                                       NMSettingsConnectionIntFlags sett_flags,
                                       NMSettingsConnectionIntFlags sett_mask,
                                       gboolean override_sett_flags,
                                       NMSettingsConnectionUpdateReason update_reason)
{
	NMSettingsPrivate *priv = NM_SETTINGS_GET_PRIVATE (self);
	SettConnEntry *sett_conn_entry;

	while ((sett_conn_entry = c_list_first_entry (&priv->sce_dirty_lst_head, SettConnEntry, sce_dirty_lst))) {
		_connection_changed_process_one (self,
		                                 sett_conn_entry,
		                                 allow_add_to_no_auto_default,
		                                 sett_flags,
		                                 sett_mask,
		                                 override_sett_flags,
		                                 update_reason);
	}
}

static SettConnEntry *
_connection_changed_track (NMSettings *self,
                           NMSettingsStorage *storage,
                           NMConnection *connection,
                           gboolean prioritize)
{
	NMSettingsPrivate *priv = NM_SETTINGS_GET_PRIVATE (self);
	SettConnEntry *sett_conn_entry;
	StorageData *sd;
	const char *uuid;

	nm_assert_valid_settings_storage (NULL, storage);

	uuid = nm_settings_storage_get_uuid (storage);

	nm_assert (!connection || NM_IS_CONNECTION (connection));
	nm_assert (!connection || (_nm_connection_verify (connection, NULL) == NM_SETTING_VERIFY_SUCCESS));
	nm_assert (!connection || nm_streq0 (uuid, nm_connection_get_uuid (connection)));

	nmtst_connection_assert_unchanging (connection);

	sett_conn_entry =    _sett_conn_entries_get (self, uuid)
	                  ?: _sett_conn_entries_create_and_add (self, uuid);

	if (_LOGT_ENABLED ()) {
		const char *filename;
		const NMSettingsMetaData *meta_data;
		const char *shadowed_storage;
		gboolean shadowed_owned;

		filename = nm_settings_storage_get_filename (storage);
		if (connection) {
			shadowed_storage = nm_settings_storage_get_shadowed_storage (storage, &shadowed_owned);
			_LOGT ("storage[%s,"NM_SETTINGS_STORAGE_PRINT_FMT"]: change event with connection \"%s\"%s%s%s%s%s%s",
			       sett_conn_entry->uuid,
			       NM_SETTINGS_STORAGE_PRINT_ARG (storage),
			       nm_connection_get_id (connection),
			       NM_PRINT_FMT_QUOTED (filename, " (file \"", filename, "\")", ""),
			       NM_PRINT_FMT_QUOTED (shadowed_storage, shadowed_owned ? " (owns \"" : " (shadows \"", shadowed_storage, "\")", ""));
		} else if ((meta_data = nm_settings_storage_is_meta_data (storage))) {
			nm_assert (meta_data->is_tombstone);
			shadowed_storage = nm_settings_storage_get_shadowed_storage (storage, &shadowed_owned);
			_LOGT ("storage[%s,"NM_SETTINGS_STORAGE_PRINT_FMT"]: change event for %shiding profile%s%s%s%s%s%s",
			       sett_conn_entry->uuid,
			       NM_SETTINGS_STORAGE_PRINT_ARG (storage),
			       nm_settings_storage_is_meta_data_alive  (storage) ? "" : "dropping ",
			       NM_PRINT_FMT_QUOTED (filename, " (file \"", filename, "\")", ""),
			       NM_PRINT_FMT_QUOTED (shadowed_storage, shadowed_owned ? " (owns \"" : " (shadows \"", shadowed_storage, "\")", ""));
		} else {
			_LOGT ("storage[%s,"NM_SETTINGS_STORAGE_PRINT_FMT"]: change event for dropping profile%s%s%s",
			       sett_conn_entry->uuid,
			       NM_SETTINGS_STORAGE_PRINT_ARG (storage),
			       NM_PRINT_FMT_QUOTED (filename, " (file \"", filename, "\")", ""));
		}
	}

	/* see _sett_conn_entry_sds_update() for why we append the new events
	 * and leave existing ones at their position. */
	sd = _storage_data_find_in_lst (&sett_conn_entry->dirty_sd_lst_head, storage);
	if (sd)
		nm_g_object_ref_set (&sd->connection, connection);
	else {
		sd = _storage_data_new_stale (storage, connection);
		c_list_link_tail (&sett_conn_entry->dirty_sd_lst_head, &sd->sd_lst);
	}

	if (prioritize) {
		StorageData *sd2;

		/* only one entry can be prioritized. */
		c_list_for_each_entry (sd2, &sett_conn_entry->dirty_sd_lst_head, sd_lst)
			sd2->prioritize = FALSE;
		sd->prioritize = TRUE;
	}

	nm_c_list_move_tail (&priv->sce_dirty_lst_head, &sett_conn_entry->sce_dirty_lst);

	return sett_conn_entry;
}

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

static void
_plugin_connections_reload_cb (NMSettingsPlugin *plugin,
                               NMSettingsStorage *storage,
                               NMConnection *connection,
                               gpointer user_data)
{
	_connection_changed_track (user_data, storage, connection, FALSE);
}

static void
_plugin_connections_reload (NMSettings *self)
{
	NMSettingsPrivate *priv = NM_SETTINGS_GET_PRIVATE (self);
	GSList *iter;

	for (iter = priv->plugins; iter; iter = iter->next) {
		nm_settings_plugin_reload_connections (iter->data,
		                                       _plugin_connections_reload_cb,
		                                       self);
	}

	_connection_changed_process_all_dirty (self,
	                                       FALSE,
	                                       NM_SETTINGS_CONNECTION_INT_FLAGS_NONE,
	                                       NM_SETTINGS_CONNECTION_INT_FLAGS_NONE,
	                                       TRUE,
	                                         NM_SETTINGS_CONNECTION_UPDATE_REASON_RESET_SYSTEM_SECRETS
	                                       | NM_SETTINGS_CONNECTION_UPDATE_REASON_RESET_AGENT_SECRETS);

	for (iter = priv->plugins; iter; iter = iter->next)
		nm_settings_plugin_load_connections_done (iter->data);
}

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

static gboolean
_add_connection_to_first_plugin (NMSettings *self,
                                 SettConnEntry *sett_conn_entry,
                                 NMConnection *new_connection,
                                 gboolean in_memory,
                                 NMSettingsConnectionIntFlags sett_flags,
                                 const char *shadowed_storage,
                                 gboolean shadowed_owned,
                                 NMSettingsStorage **out_new_storage,
                                 NMConnection **out_new_connection,
                                 GError **error)
{
	NMSettingsPrivate *priv = NM_SETTINGS_GET_PRIVATE (self);
	gs_free_error GError *first_error = NULL;
	GSList *iter;
	const char *uuid;

	uuid = nm_connection_get_uuid (new_connection);

	nm_assert (nm_utils_is_uuid (uuid));

	for (iter = priv->plugins; iter; iter = iter->next) {
		NMSettingsPlugin *plugin = NM_SETTINGS_PLUGIN (iter->data);
		gs_unref_object NMSettingsStorage *storage = NULL;
		gs_unref_object NMConnection *connection_to_add = NULL;
		gs_unref_object NMConnection *connection_to_add_cloned = NULL;
		NMConnection *connection_to_add_real = NULL;
		gs_unref_variant GVariant *agent_owned_secrets = NULL;
		gs_free_error GError *add_error = NULL;
		gboolean success;
		const char *filename;

		if (!in_memory) {
			NMSettingsStorage *conflicting_storage;

			conflicting_storage = _sett_conn_entry_storage_find_conflicting_storage (sett_conn_entry, plugin, NULL, priv->plugins);
			if (conflicting_storage) {
				/* we have a connection provided by a plugin with higher priority than the one
				 * we would want to add the connection. We cannot do that, because doing so
				 * would result in adding a connection that gets hidden by the existing profile.
				 * Also, since we test the plugins in order of priority, all following plugins
				 * are unsuitable.
				 *
				 * Multiple connection plugins are so cumbersome, especially if they are unable
				 * to add the connection. I suggest to disable all plugins except keyfile. */
				_LOGT ("add-connection: failed to add %s/'%s': there is an existing storage "NM_SETTINGS_STORAGE_PRINT_FMT" with higher priority",
				       nm_connection_get_uuid (new_connection),
				       nm_connection_get_id (new_connection),
				       NM_SETTINGS_STORAGE_PRINT_ARG (conflicting_storage));
				nm_assert (first_error);
				break;
			}
		}

		if (plugin == (NMSettingsPlugin *) priv->keyfile_plugin) {
			success = nms_keyfile_plugin_add_connection (priv->keyfile_plugin,
			                                             new_connection,
			                                             in_memory,
			                                             NM_FLAGS_HAS (sett_flags, NM_SETTINGS_CONNECTION_INT_FLAGS_NM_GENERATED),
			                                             NM_FLAGS_HAS (sett_flags, NM_SETTINGS_CONNECTION_INT_FLAGS_VOLATILE),
			                                             shadowed_storage,
			                                             shadowed_owned,
			                                             &storage,
			                                             &connection_to_add,
			                                             &add_error);
		} else {
			if (in_memory)
				continue;
			nm_assert (!NM_FLAGS_HAS (sett_flags, NM_SETTINGS_CONNECTION_INT_FLAGS_NM_GENERATED));
			nm_assert (!NM_FLAGS_HAS (sett_flags, NM_SETTINGS_CONNECTION_INT_FLAGS_VOLATILE));
			success = nm_settings_plugin_add_connection (plugin,
			                                             new_connection,
			                                             &storage,
			                                             &connection_to_add,
			                                             &add_error);
		}

		if (!success) {
			_LOGT ("add-connection: failed to add %s/'%s': %s",
			       nm_connection_get_uuid (new_connection),
			       nm_connection_get_id (new_connection),
			       add_error->message);
			if (!first_error)
				first_error = g_steal_pointer (&add_error);
			continue;
		}

		if (!nm_streq0 (nm_settings_storage_get_uuid (storage), uuid)) {
			nm_assert_not_reached ();
			continue;
		}

		agent_owned_secrets = nm_connection_to_dbus (new_connection,
		                                               NM_CONNECTION_SERIALIZE_ONLY_SECRETS
		                                             | NM_CONNECTION_SERIALIZE_WITH_SECRETS_AGENT_OWNED);
		connection_to_add_real = _connection_changed_normalize_connection (storage,
		                                                                   connection_to_add,
		                                                                   agent_owned_secrets,
		                                                                   &connection_to_add_cloned);
		if (!connection_to_add_real) {
			nm_assert_not_reached ();
			continue;
		}

		filename = nm_settings_storage_get_filename (storage);
		_LOGT ("add-connection: successfully added connection %s,'%s' ("NM_SETTINGS_STORAGE_PRINT_FMT"%s%s%s",
		       nm_settings_storage_get_uuid (storage),
		       nm_connection_get_id (new_connection),
		       NM_SETTINGS_STORAGE_PRINT_ARG (storage),
		       NM_PRINT_FMT_QUOTED (filename, ", \"", filename, "\")", ")"));

		*out_new_storage = g_steal_pointer (&storage);
		*out_new_connection =    g_steal_pointer (&connection_to_add_cloned)
		                      ?: g_steal_pointer (&connection_to_add);
		nm_assert (NM_IS_CONNECTION (*out_new_connection));
		return TRUE;
	}

	nm_assert (first_error);
	g_propagate_error (error, g_steal_pointer (&first_error));
	return FALSE;
}

static gboolean
_update_connection_to_plugin (NMSettings *self,
                              NMSettingsStorage *storage,
                              NMConnection *connection,
                              NMSettingsConnectionIntFlags sett_flags,
                              gboolean force_rename,
                              const char *shadowed_storage,
                              gboolean shadowed_owned,
                              NMSettingsStorage **out_new_storage,
                              NMConnection **out_new_connection,
                              GError **error)
{
	NMSettingsPrivate *priv = NM_SETTINGS_GET_PRIVATE (self);
	NMSettingsPlugin *plugin;
	gboolean success;

	plugin = nm_settings_storage_get_plugin (storage);

	if (plugin == (NMSettingsPlugin *) priv->keyfile_plugin) {
		success = nms_keyfile_plugin_update_connection (priv->keyfile_plugin,
		                                                storage,
		                                                connection,
		                                                NM_FLAGS_HAS (sett_flags, NM_SETTINGS_CONNECTION_INT_FLAGS_NM_GENERATED),
		                                                NM_FLAGS_HAS (sett_flags, NM_SETTINGS_CONNECTION_INT_FLAGS_VOLATILE),
		                                                shadowed_storage,
		                                                shadowed_owned,
		                                                force_rename,
		                                                out_new_storage,
		                                                out_new_connection,
		                                                error);
	} else {
		nm_assert (!shadowed_storage);
		nm_assert (!shadowed_owned);
		success = nm_settings_plugin_update_connection (plugin,
		                                                storage,
		                                                connection,
		                                                out_new_storage,
		                                                out_new_connection,
		                                                error);
	}

	return success;
}

static void
_set_nmmeta_tombstone (NMSettings *self,
                       const char *uuid,
                       gboolean tombstone_on_disk,
                       gboolean tombstone_in_memory,
                       const char *shadowed_storage)
{
	NMSettingsPrivate *priv = NM_SETTINGS_GET_PRIVATE (self);
	gs_unref_object NMSettingsStorage *tombstone_1_storage = NULL;
	gs_unref_object NMSettingsStorage *tombstone_2_storage = NULL;

	if (tombstone_on_disk) {
		if (!nms_keyfile_plugin_set_nmmeta_tombstone (priv->keyfile_plugin,
		                                              FALSE,
		                                              uuid,
		                                              FALSE,
		                                              TRUE,
		                                              NULL,
		                                              &tombstone_1_storage,
		                                              NULL))
			tombstone_in_memory = TRUE;
		if (tombstone_1_storage)
			_connection_changed_track (self, tombstone_1_storage, NULL, FALSE);
	}

	if (tombstone_in_memory) {
		if (!nms_keyfile_plugin_set_nmmeta_tombstone (priv->keyfile_plugin,
		                                              FALSE,
		                                              uuid,
		                                              TRUE,
		                                              TRUE,
		                                              shadowed_storage,
		                                              &tombstone_2_storage,
		                                              NULL)) {
			nms_keyfile_plugin_set_nmmeta_tombstone (priv->keyfile_plugin,
			                                         TRUE,
			                                         uuid,
			                                         TRUE,
			                                         TRUE,
			                                         shadowed_storage,
			                                         &tombstone_2_storage,
			                                         NULL);
		}
		_connection_changed_track (self, tombstone_2_storage, NULL, FALSE);
	}
}

/**
 * nm_settings_add_connection:
 * @self: the #NMSettings object
 * @connection: the source connection to create a new #NMSettingsConnection from
 * @persist_mode: the persist-mode for this profile.
 * @add_reason: the add-reason flags.
 * @sett_flags: the settings flags to set.
 * @out_sett_conn: (allow-none) (transfer none): the added settings connection on success.
 * @error: on return, a location to store any errors that may occur
 *
 * Creates a new #NMSettingsConnection for the given source @connection.
 * The returned object is owned by @self and the caller must reference
 * the object to continue using it.
 *
 * Returns: TRUE on success.
 */
gboolean
nm_settings_add_connection (NMSettings *self,
                            NMConnection *connection,
                            NMSettingsConnectionPersistMode persist_mode,
                            NMSettingsConnectionAddReason add_reason,
                            NMSettingsConnectionIntFlags sett_flags,
                            NMSettingsConnection **out_sett_conn,
                            GError **error)
{
	NMSettingsPrivate *priv;
	gs_unref_object NMConnection *connection_cloned_1 = NULL;
	gs_unref_object NMConnection *new_connection = NULL;
	gs_unref_object NMSettingsStorage *new_storage = NULL;
	gs_unref_object NMSettingsStorage *shadowed_storage = NULL;
	NMSettingsStorage *update_storage = NULL;
	gs_free_error GError *local = NULL;
	SettConnEntry *sett_conn_entry;
	const char *uuid;
	StorageData *sd;
	gboolean new_in_memory;
	gboolean success;
	const char *shadowed_storage_filename = NULL;

	priv = NM_SETTINGS_GET_PRIVATE (self);

	nm_assert (NM_IN_SET (persist_mode, NM_SETTINGS_CONNECTION_PERSIST_MODE_TO_DISK,
	                                    NM_SETTINGS_CONNECTION_PERSIST_MODE_IN_MEMORY_ONLY));

	new_in_memory = (persist_mode != NM_SETTINGS_CONNECTION_PERSIST_MODE_TO_DISK);

	nm_assert (!NM_FLAGS_ANY (sett_flags, ~_NM_SETTINGS_CONNECTION_INT_FLAGS_PERSISTENT_MASK));

	if (NM_FLAGS_ANY (sett_flags,   NM_SETTINGS_CONNECTION_INT_FLAGS_VOLATILE
	                              | NM_SETTINGS_CONNECTION_INT_FLAGS_NM_GENERATED)) {
		nm_assert (new_in_memory);
		new_in_memory = TRUE;
	}

	nm_assert (!NM_FLAGS_ANY (add_reason, ~NM_SETTINGS_CONNECTION_ADD_REASON_BLOCK_AUTOCONNECT));

	NM_SET_OUT (out_sett_conn, NULL);

	uuid = nm_connection_get_uuid (connection);

	sett_conn_entry = _sett_conn_entries_get (self, uuid);
	if (_sett_conn_entry_get_conn (sett_conn_entry)) {
		g_set_error_literal (error,
		                     NM_SETTINGS_ERROR,
		                     NM_SETTINGS_ERROR_UUID_EXISTS,
		                     "a connection with this UUID already exists");
		return FALSE;
	}

	if (!_nm_connection_ensure_normalized (connection,
	                                       FALSE,
	                                       NULL,
	                                       FALSE,
	                                       &connection_cloned_1,
	                                       &local)) {
		g_set_error (error,
		             NM_SETTINGS_ERROR,
		             NM_SETTINGS_ERROR_INVALID_CONNECTION,
		             "connection is invalid: %s",
		             local->message);
		return FALSE;
	}
	if (connection_cloned_1)
		connection = connection_cloned_1;

	if (sett_conn_entry) {
		c_list_for_each_entry (sd, &sett_conn_entry->sd_lst_head, sd_lst) {
			if (!nm_settings_storage_is_meta_data (sd->storage))
				continue;
			shadowed_storage = nm_g_object_ref (_sett_conn_entry_find_shadowed_storage (sett_conn_entry,
			                                                                            nm_settings_storage_get_shadowed_storage (sd->storage, NULL),
			                                                                            NULL));
			if (shadowed_storage) {
				/* We have a nmmeta tombstone that indicates that a storage is shadowed.
				 *
				 * This happens when deleting a in-memory profile that was decoupled from
				 * the persitant storage with NM_SETTINGS_CONNECTION_PERSIST_MODE_IN_MEMORY_DETACHED.
				 * We need to take over this storage again... */
				break;
			}
		}
	}

	if (   shadowed_storage
	    && !new_in_memory) {
		NMSettingsStorage *conflicting_storage;

		conflicting_storage = _sett_conn_entry_storage_find_conflicting_storage (sett_conn_entry,
		                                                                         nm_settings_storage_get_plugin (shadowed_storage),
		                                                                         shadowed_storage,
		                                                                         priv->plugins);
		if (conflicting_storage) {
			/* We cannot add the profile as @shadowed_storage, because there is another, existing storage
			 * that would hide it. Just add it as new storage. In general, this leads to duplication of profiles,
			 * but the circumstances where this happens are very exotic (you need at least one additional settings
			 * plugin, then going through the paths of making shadowed_storage in-memory-detached and delete it,
			 * and finally adding the conflicting storage outside of NM and restart/reload). */
			_LOGT ("ignore shadowed storage "NM_SETTINGS_STORAGE_PRINT_FMT" due to conflicting storage "NM_SETTINGS_STORAGE_PRINT_FMT,
			       NM_SETTINGS_STORAGE_PRINT_ARG (shadowed_storage),
			       NM_SETTINGS_STORAGE_PRINT_ARG (conflicting_storage));
		} else
			update_storage = shadowed_storage;
	}

	shadowed_storage_filename =   (   shadowed_storage
	                               && !update_storage)
	                            ? nm_settings_storage_get_filename_for_shadowed_storage (shadowed_storage)
	                            : NULL;

again_add_connection:

	if (!update_storage) {
		success = _add_connection_to_first_plugin (self,
		                                           sett_conn_entry,
		                                           connection,
		                                           new_in_memory,
		                                           sett_flags,
		                                           shadowed_storage_filename,
		                                           FALSE,
		                                           &new_storage,
		                                           &new_connection,
		                                           &local);
	} else {
		success = _update_connection_to_plugin (self,
		                                        update_storage,
		                                        connection,
		                                        sett_flags,
		                                        FALSE,
		                                        shadowed_storage_filename,
		                                        FALSE,
		                                        &new_storage,
		                                        &new_connection,
		                                        &local);
		if (!success) {
			if (!NMS_IS_KEYFILE_STORAGE (update_storage)) {
				/* hm, the intended storage is not keyfile (it's ifcfg-rh). This settings
				 * plugin may not support the new connection. So step back and retry adding
				 * the profile anew. */
				_LOGT ("failure to add profile as existing storage \"%s\": %s",
				       nm_settings_storage_get_filename (update_storage),
				       local->message);
				update_storage = NULL;
				g_clear_object (&shadowed_storage);
				shadowed_storage_filename = NULL;
				g_clear_error (&local);
				goto again_add_connection;
			}
		}
	}

	if (!success) {
		if (!update_storage) {
			g_set_error (error,
			             NM_SETTINGS_ERROR,
			             NM_SETTINGS_ERROR_FAILED,
			             "failure adding connection: %s",
			             local->message);
		} else {
			g_set_error (error,
			             NM_SETTINGS_ERROR,
			             NM_SETTINGS_ERROR_FAILED,
			             "failure writing connection to existing storage \"%s\": %s",
			             nm_settings_storage_get_filename (update_storage),
			             local->message);
		}
		return FALSE;
	}

	sett_conn_entry = _connection_changed_track (self, new_storage, new_connection, TRUE);

	c_list_for_each_entry (sd, &sett_conn_entry->sd_lst_head, sd_lst) {
		const NMSettingsMetaData *meta_data;
		gs_unref_object NMSettingsStorage *new_tombstone_storage = NULL;
		gboolean in_memory;
		gboolean simulate;

		meta_data = nm_settings_storage_is_meta_data_alive (sd->storage);
		if (   !meta_data
		    || !meta_data->is_tombstone)
			continue;

		if (nm_settings_storage_is_keyfile_run (sd->storage))
			in_memory = TRUE;
		else {
			if (nm_settings_storage_is_keyfile_run (new_storage)) {
				/* Don't remove the file from /etc if we just wrote an in-memory connection */
				continue;
			}
			in_memory = FALSE;
		}

		simulate = FALSE;
again_delete_tombstone:
		if (!nms_keyfile_plugin_set_nmmeta_tombstone (priv->keyfile_plugin,
		                                              simulate,
		                                              uuid,
		                                              in_memory,
		                                              FALSE,
		                                              NULL,
		                                              &new_tombstone_storage,
		                                              NULL)) {
			/* Ups, something went wrong. We really need to get rid of the tombstone. At least
			 * forget about it in-memory. Upong next restart/reload, this might be reverted
			 * however :( .*/
			if (!simulate) {
				simulate = TRUE;
				goto again_delete_tombstone;
			}
		}
		if (new_tombstone_storage)
			_connection_changed_track (self, new_tombstone_storage, NULL, FALSE);
	}

	_connection_changed_process_all_dirty (self,
	                                       FALSE,
	                                       sett_flags,
	                                       _NM_SETTINGS_CONNECTION_INT_FLAGS_PERSISTENT_MASK,
	                                       FALSE,
	                                         NM_SETTINGS_CONNECTION_UPDATE_REASON_RESET_SYSTEM_SECRETS
	                                       | NM_SETTINGS_CONNECTION_UPDATE_REASON_RESET_AGENT_SECRETS
	                                       | (  NM_FLAGS_HAS (add_reason, NM_SETTINGS_CONNECTION_ADD_REASON_BLOCK_AUTOCONNECT)
	                                          ? NM_SETTINGS_CONNECTION_UPDATE_REASON_BLOCK_AUTOCONNECT
	                                          : NM_SETTINGS_CONNECTION_UPDATE_REASON_NONE));

	nm_assert (sett_conn_entry == _sett_conn_entries_get (self, sett_conn_entry->uuid));
	nm_assert (NM_IS_SETTINGS_CONNECTION (sett_conn_entry->sett_conn));

	NM_SET_OUT (out_sett_conn, _sett_conn_entry_get_conn (sett_conn_entry));
	return TRUE;
}

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

gboolean
nm_settings_update_connection (NMSettings *self,
                               NMSettingsConnection *sett_conn,
                               NMConnection *connection,
                               NMSettingsConnectionPersistMode persist_mode,
                               NMSettingsConnectionIntFlags sett_flags,
                               NMSettingsConnectionIntFlags sett_mask,
                               NMSettingsConnectionUpdateReason update_reason,
                               const char *log_context_name,
                               GError **error)
{
	gs_unref_object NMConnection *connection_cloned_1 = NULL;
	gs_unref_object NMConnection *new_connection_cloned = NULL;
	gs_unref_object NMConnection *new_connection = NULL;
	NMConnection *new_connection_real;
	gs_unref_object NMSettingsStorage *cur_storage = NULL;
	gs_unref_object NMSettingsStorage *new_storage = NULL;
	NMSettingsStorage *drop_storage = NULL;
	SettConnEntry *sett_conn_entry;
	gboolean cur_in_memory;
	gboolean new_in_memory;
	const char *uuid;
	gboolean tombstone_in_memory = FALSE;
	gboolean tombstone_on_disk = FALSE;

	g_return_val_if_fail (NM_IS_SETTINGS (self), FALSE);
	g_return_val_if_fail (NM_IS_SETTINGS_CONNECTION (sett_conn), FALSE);
	g_return_val_if_fail (!connection || NM_IS_CONNECTION (connection), FALSE);

	nm_assert (!NM_FLAGS_ANY (sett_mask, ~_NM_SETTINGS_CONNECTION_INT_FLAGS_PERSISTENT_MASK));
	nm_assert (!NM_FLAGS_ANY (sett_flags, ~sett_mask));
	nm_assert (NM_IN_SET (persist_mode, NM_SETTINGS_CONNECTION_PERSIST_MODE_KEEP,
	                                    NM_SETTINGS_CONNECTION_PERSIST_MODE_NO_PERSIST,
	                                    NM_SETTINGS_CONNECTION_PERSIST_MODE_TO_DISK,
	                                    NM_SETTINGS_CONNECTION_PERSIST_MODE_IN_MEMORY,
	                                    NM_SETTINGS_CONNECTION_PERSIST_MODE_IN_MEMORY_DETACHED,
	                                    NM_SETTINGS_CONNECTION_PERSIST_MODE_IN_MEMORY_ONLY));

	cur_storage = g_object_ref (nm_settings_connection_get_storage (sett_conn));

	uuid = nm_settings_storage_get_uuid (cur_storage);

	nm_assert (NM_IS_SETTINGS_STORAGE (cur_storage));

	sett_conn_entry = _sett_conn_entries_get (self, uuid);

	nm_assert (_sett_conn_entry_get_conn (sett_conn_entry) == sett_conn);

	if (connection) {
		gs_free_error GError *local = NULL;

		if (!_nm_connection_ensure_normalized (connection,
		                                       FALSE,
		                                       uuid,
		                                       TRUE,
		                                       &connection_cloned_1,
		                                       &local)) {
			_LOGT ("update[%s]: %s: failed because profile is invalid: %s",
			       nm_settings_storage_get_uuid (cur_storage),
			       log_context_name,
			       local->message);
			g_set_error (error,
			             NM_SETTINGS_ERROR,
			             NM_SETTINGS_ERROR_INVALID_CONNECTION,
			             "connection is invalid: %s",
			             local->message);
			return FALSE;
		}
		if (connection_cloned_1)
			connection = connection_cloned_1;
	} else
		connection = nm_settings_connection_get_connection (sett_conn);

	cur_in_memory = nm_settings_storage_is_keyfile_run (cur_storage);

	if (persist_mode == NM_SETTINGS_CONNECTION_PERSIST_MODE_KEEP) {
		persist_mode =   cur_in_memory
		               ? NM_SETTINGS_CONNECTION_PERSIST_MODE_IN_MEMORY
		               : NM_SETTINGS_CONNECTION_PERSIST_MODE_TO_DISK;
	}

	if (   NM_FLAGS_HAS (sett_mask, NM_SETTINGS_CONNECTION_INT_FLAGS_NM_GENERATED)
	    && !NM_FLAGS_HAS (sett_flags, NM_SETTINGS_CONNECTION_INT_FLAGS_NM_GENERATED)) {
		NMDevice *device;

		/* The connection has been changed by the user, it should no longer be
		 * considered a default wired connection, and should no longer affect
		 * the no-auto-default configuration option.
		 */
		device = nm_settings_connection_default_wired_get_device (sett_conn);
		if (device) {
			nm_assert (cur_in_memory);
			nm_assert (!NM_FLAGS_ANY (nm_settings_connection_get_flags (sett_conn),
			                            NM_SETTINGS_CONNECTION_INT_FLAGS_NM_GENERATED
			                          | NM_SETTINGS_CONNECTION_INT_FLAGS_VOLATILE));

			default_wired_clear_tag (self, device, sett_conn, FALSE);

			if (NM_IN_SET (persist_mode, NM_SETTINGS_CONNECTION_PERSIST_MODE_NO_PERSIST)) {
				/* making a default-wired-connection a regular connection implies persisting
				 * it to disk (unless specified differently).
				 *
				 * Actually, this line is probably unreached, because we should not use
				 * NM_SETTINGS_CONNECTION_PERSIST_MODE_NO_PERSIST to toggle the nm-generated
				 * flag. */
				nm_assert_not_reached ();
				persist_mode = NM_SETTINGS_CONNECTION_PERSIST_MODE_TO_DISK;
			}
		}
	}

	if (   persist_mode == NM_SETTINGS_CONNECTION_PERSIST_MODE_NO_PERSIST
	    && NM_FLAGS_ANY (sett_mask,   NM_SETTINGS_CONNECTION_INT_FLAGS_NM_GENERATED
	                                | NM_SETTINGS_CONNECTION_INT_FLAGS_VOLATILE)
	    && NM_FLAGS_ANY ((sett_flags ^ nm_settings_connection_get_flags (sett_conn)) & sett_mask,
	                       NM_SETTINGS_CONNECTION_INT_FLAGS_NM_GENERATED
	                     | NM_SETTINGS_CONNECTION_INT_FLAGS_VOLATILE)) {
		/* we update the nm-generated/volatile setting of a profile (which is inherrently
		 * in-memory. The caller did not request to persist this to disk, however we need
		 * to store the flags in run. */
		nm_assert (cur_in_memory);
		persist_mode = NM_SETTINGS_CONNECTION_PERSIST_MODE_IN_MEMORY;
	}

	if (persist_mode == NM_SETTINGS_CONNECTION_PERSIST_MODE_TO_DISK)
		new_in_memory = FALSE;
	else if (NM_IN_SET (persist_mode, NM_SETTINGS_CONNECTION_PERSIST_MODE_IN_MEMORY,
	                                  NM_SETTINGS_CONNECTION_PERSIST_MODE_IN_MEMORY_DETACHED,
	                                  NM_SETTINGS_CONNECTION_PERSIST_MODE_IN_MEMORY_ONLY))
		new_in_memory = TRUE;
	else {
		nm_assert (persist_mode == NM_SETTINGS_CONNECTION_PERSIST_MODE_NO_PERSIST);
		new_in_memory = cur_in_memory;
	}

	if (!new_in_memory) {
		/* Persistent connections cannot be volatile nor nm-generated.
		 *
		 * That is obviously true for volatile, as it is enforced by Update2() API.
		 *
		 * For nm-generated profiles also, because the nm-generated flag is only stored
		 * for in-memory profiles. If we would persist the profile to /etc it would loose
		 * the nm-generated flag after restart/reload, and that cannot be right. If a profile
		 * ends up on disk, the information who created it gets lost. */
		nm_assert (!NM_FLAGS_ANY (sett_flags,   NM_SETTINGS_CONNECTION_INT_FLAGS_NM_GENERATED
		                                      | NM_SETTINGS_CONNECTION_INT_FLAGS_VOLATILE));
		sett_mask |=   NM_SETTINGS_CONNECTION_INT_FLAGS_NM_GENERATED
		             | NM_SETTINGS_CONNECTION_INT_FLAGS_VOLATILE;
		sett_flags &= ~(  NM_SETTINGS_CONNECTION_INT_FLAGS_NM_GENERATED
		                | NM_SETTINGS_CONNECTION_INT_FLAGS_VOLATILE);
	}

	if (persist_mode == NM_SETTINGS_CONNECTION_PERSIST_MODE_NO_PERSIST) {
		new_storage = g_object_ref (cur_storage);
		new_connection_real = connection;
		_LOGT ("update[%s]: %s: update profile \"%s\" (not persisted)",
		       nm_settings_storage_get_uuid (cur_storage),
		       log_context_name,
		       nm_connection_get_id (connection));
	} else {
		NMSettingsStorage *shadowed_storage;
		const char *cur_shadowed_storage_filename;
		const char *new_shadowed_storage_filename = NULL;
		gboolean cur_shadowed_owned;
		gboolean new_shadowed_owned = FALSE;
		NMSettingsStorage *update_storage = NULL;
		gs_free_error GError *local = NULL;
		gboolean success;

		cur_shadowed_storage_filename = nm_settings_storage_get_shadowed_storage (cur_storage, &cur_shadowed_owned);

		shadowed_storage = _sett_conn_entry_find_shadowed_storage (sett_conn_entry, cur_shadowed_storage_filename, cur_storage);
		if (!shadowed_storage) {
			cur_shadowed_storage_filename = NULL;
			cur_shadowed_owned = FALSE;
		}

		if (   new_in_memory
		    && persist_mode == NM_SETTINGS_CONNECTION_PERSIST_MODE_IN_MEMORY_ONLY) {
			if (cur_in_memory) {
				drop_storage = shadowed_storage;
				update_storage = cur_storage;
			} else
				drop_storage = cur_storage;
		} else if (   !new_in_memory
		           && cur_in_memory
		           && shadowed_storage) {
			drop_storage = cur_storage;
			update_storage = shadowed_storage;
		} else if (new_in_memory != cur_in_memory) {
			if (!new_in_memory)
				drop_storage = cur_storage;
			else if (persist_mode == NM_SETTINGS_CONNECTION_PERSIST_MODE_IN_MEMORY_ONLY)
				drop_storage = cur_storage;
			else {
				nm_assert (NM_IN_SET (persist_mode, NM_SETTINGS_CONNECTION_PERSIST_MODE_IN_MEMORY,
				                                    NM_SETTINGS_CONNECTION_PERSIST_MODE_IN_MEMORY_DETACHED));
			}
		} else if (nm_settings_storage_is_keyfile_lib (cur_storage)) {
			/* the profile is a keyfile in /usr/lib. It cannot be overwritten, we must migrate it
			 * from /usr/lib to /etc. */
		} else
			update_storage = cur_storage;

		if (new_in_memory) {
			if (persist_mode == NM_SETTINGS_CONNECTION_PERSIST_MODE_IN_MEMORY_ONLY) {
				/* pass */
			} else if (!cur_in_memory) {
				new_shadowed_storage_filename = nm_settings_storage_get_filename_for_shadowed_storage (cur_storage);
				if (   new_shadowed_storage_filename
				    && persist_mode != NM_SETTINGS_CONNECTION_PERSIST_MODE_IN_MEMORY_DETACHED)
					new_shadowed_owned = TRUE;
			} else {
				new_shadowed_storage_filename = cur_shadowed_storage_filename;
				if (   new_shadowed_storage_filename
				    && persist_mode == NM_SETTINGS_CONNECTION_PERSIST_MODE_IN_MEMORY)
					new_shadowed_owned = TRUE;
			}
		}

		if (!update_storage) {
			success = _add_connection_to_first_plugin (self,
			                                           sett_conn_entry,
			                                           connection,
			                                           new_in_memory,
			                                           sett_flags,
			                                           new_shadowed_storage_filename,
			                                           new_shadowed_owned,
			                                           &new_storage,
			                                           &new_connection,
			                                           &local);
		} else {
			success = _update_connection_to_plugin (self,
			                                        update_storage,
			                                        connection,
			                                        sett_flags,
			                                        update_reason,
			                                        new_shadowed_storage_filename,
			                                        new_shadowed_owned,
			                                        &new_storage,
			                                        &new_connection,
			                                        &local);
		}
		if (!success) {
			gboolean ignore_failure;

			ignore_failure = NM_FLAGS_ANY (update_reason, NM_SETTINGS_CONNECTION_UPDATE_REASON_IGNORE_PERSIST_FAILURE);

			_LOGT ("update[%s]: %s: %sfailure to %s connection \"%s\" on storage: %s",
			       nm_settings_storage_get_uuid (cur_storage),
			       log_context_name,
			       ignore_failure ? "ignore " : "",
			       update_storage ? "update" : "write",
			       nm_connection_get_id (connection),
			       local->message);
			if (!ignore_failure) {
				g_set_error (error,
				             NM_SETTINGS_ERROR,
				             NM_SETTINGS_ERROR_INVALID_CONNECTION,
				             "failed to %s connection: %s",
				             update_storage ? "update" : "write",
				             local->message);
				return FALSE;
			}

			new_storage = g_object_ref (cur_storage);
			new_connection_real = connection;
		} else {
			gs_unref_variant GVariant *agent_owned_secrets = NULL;

			_LOGT ("update[%s]: %s: %s profile \"%s\"",
			       nm_settings_storage_get_uuid (cur_storage),
			       log_context_name,
			       update_storage ? "update" : "write",
			       nm_connection_get_id (connection));

			nm_assert_valid_settings_storage (NULL, new_storage);
			nm_assert (NM_IS_CONNECTION (new_connection));
			nm_assert (nm_streq (uuid, nm_settings_storage_get_uuid (new_storage)));


			agent_owned_secrets = nm_connection_to_dbus (connection,
			                                               NM_CONNECTION_SERIALIZE_ONLY_SECRETS
			                                             | NM_CONNECTION_SERIALIZE_WITH_SECRETS_AGENT_OWNED);
			new_connection_real = _connection_changed_normalize_connection (new_storage,
			                                                                new_connection,
			                                                                agent_owned_secrets,
			                                                                &new_connection_cloned);
			if (!new_connection_real) {
				nm_assert_not_reached ();
				new_connection_real = new_connection;
			}
		}
	}

	nm_assert (NM_IS_SETTINGS_STORAGE (new_storage));
	nm_assert (NM_IS_CONNECTION (new_connection_real));

	_connection_changed_track (self, new_storage, new_connection_real, TRUE);

	if (   drop_storage
	    && drop_storage != new_storage) {
		gs_free_error GError *local = NULL;

		if (!nm_settings_plugin_delete_connection (nm_settings_storage_get_plugin (drop_storage),
		                                           drop_storage,
		                                           &local)) {
			const char *filename;

			filename = nm_settings_storage_get_filename (drop_storage);
			_LOGT ("update[%s]: failed to delete moved storage "NM_SETTINGS_STORAGE_PRINT_FMT"%s%s%s: %s",
			       nm_settings_storage_get_uuid (drop_storage),
			       NM_SETTINGS_STORAGE_PRINT_ARG (drop_storage),
			       NM_PRINT_FMT_QUOTED (filename, " (file \"", filename, "\")", ""),
			       local->message);
			/* there is no aborting back form this. We must get rid of the connection and
			 * cannot do better than log a message. Proceed, but remember to write tombstones. */
			if (nm_settings_storage_is_keyfile_run (cur_storage))
				tombstone_in_memory = TRUE;
			else
				tombstone_on_disk = TRUE;
		} else
			_connection_changed_track (self, drop_storage, NULL, FALSE);
	}

	_set_nmmeta_tombstone (self,
	                       uuid,
	                       tombstone_on_disk,
	                       tombstone_in_memory,
	                       NULL);

	_connection_changed_process_all_dirty (self,
	                                       FALSE,
	                                       sett_flags,
	                                       sett_mask,
	                                       FALSE,
	                                       update_reason);

	return TRUE;
}

void
nm_settings_delete_connection (NMSettings *self,
                               NMSettingsConnection *sett_conn,
                               gboolean allow_add_to_no_auto_default)
{
	NMSettingsStorage *cur_storage;
	NMSettingsStorage *shadowed_storage;
	NMSettingsStorage *shadowed_storage_unowned = NULL;
	NMSettingsStorage *drop_storages[2] = { };
	gs_free_error GError *local = NULL;
	SettConnEntry *sett_conn_entry;
	const char *cur_shadowed_storage_filename;
	const char *new_shadowed_storage_filename = NULL;
	gboolean cur_shadowed_owned;
	const char *uuid;
	gboolean tombstone_in_memory = FALSE;
	gboolean tombstone_on_disk = FALSE;
	int i;

	g_return_if_fail (NM_IS_SETTINGS (self));
	g_return_if_fail (NM_IS_SETTINGS_CONNECTION (sett_conn));
	g_return_if_fail (nm_settings_has_connection (self, sett_conn));

	cur_storage = nm_settings_connection_get_storage (sett_conn);

	nm_assert (NM_IS_SETTINGS_STORAGE (cur_storage));

	uuid = nm_settings_storage_get_uuid (cur_storage);
	nm_assert (nm_utils_is_uuid (uuid));

	sett_conn_entry = _sett_conn_entries_get (self, uuid);

	g_return_if_fail (sett_conn_entry);
	nm_assert (sett_conn_entry->sett_conn == sett_conn);
	g_return_if_fail (sett_conn_entry->storage == cur_storage);

	if (NMS_IS_KEYFILE_STORAGE (cur_storage)) {
		NMSKeyfileStorage *s = NMS_KEYFILE_STORAGE (cur_storage);

		if (NM_IN_SET (s->storage_type, NMS_KEYFILE_STORAGE_TYPE_RUN,
		                                NMS_KEYFILE_STORAGE_TYPE_ETC))
			drop_storages[0] = cur_storage;
		else
			tombstone_on_disk = TRUE;
	} else
		drop_storages[0] = cur_storage;

	cur_shadowed_storage_filename = nm_settings_storage_get_shadowed_storage (cur_storage, &cur_shadowed_owned);

	shadowed_storage = _sett_conn_entry_find_shadowed_storage (sett_conn_entry, cur_shadowed_storage_filename, cur_storage);
	if (shadowed_storage) {
		if (!cur_shadowed_owned)
			shadowed_storage_unowned = g_steal_pointer (&shadowed_storage);
	}
	drop_storages[1] = shadowed_storage;

	for (i = 0; i < (int) G_N_ELEMENTS (drop_storages); i++) {
		NMSettingsStorage *storage;
		StorageData *sd;

		storage = drop_storages[i];
		if (!storage)
			continue;

		if (!nm_settings_plugin_delete_connection (nm_settings_storage_get_plugin (storage),
		                                           storage,
		                                           &local)) {
			_LOGT ("delete-connection: failed to delete storage "NM_SETTINGS_STORAGE_PRINT_FMT": %s",
			       NM_SETTINGS_STORAGE_PRINT_ARG (storage),
			       local->message);
			g_clear_error (&local);
			/* there is no aborting back form this. We must get rid of the connection and
			 * cannot do better than log a message. Proceed, but remember to write tombstones. */
			if (nm_settings_storage_is_keyfile_run (cur_storage))
				tombstone_in_memory = TRUE;
			else
				tombstone_on_disk = TRUE;
			sett_conn_entry = _sett_conn_entries_get (self, uuid);
		} else
			sett_conn_entry = _connection_changed_track (self, storage, NULL, FALSE);

		c_list_for_each_entry (sd, &sett_conn_entry->sd_lst_head, sd_lst) {
			if (NM_IN_SET (sd->storage, drop_storages[0],
			                            drop_storages[1]))
				continue;
			if (!_storage_data_is_alive (sd))
				continue;
			if (nm_settings_storage_is_meta_data (sd->storage))
				continue;

			if (sd->storage == shadowed_storage_unowned) {
				/* this only happens if we leak a profile on disk after NM_SETTINGS_CONNECTION_PERSIST_MODE_IN_MEMORY_DETACHED.
				 * We need to write a tombstone and remember the shadowed-storage. */
				tombstone_in_memory = TRUE;
				new_shadowed_storage_filename = nm_settings_storage_get_filename (shadowed_storage_unowned);
				continue;
			}

			/* we have still conflicting storages. We need to hide them with tombstones. */
			if (nm_settings_storage_is_keyfile_run (sd->storage)) {
				tombstone_in_memory = TRUE;
				continue;
			}
			tombstone_on_disk = TRUE;
		}
	}

	_set_nmmeta_tombstone (self,
	                       uuid,
	                       tombstone_on_disk,
	                       tombstone_in_memory,
	                       new_shadowed_storage_filename);

	_connection_changed_process_all_dirty (self,
	                                       allow_add_to_no_auto_default,
	                                       NM_SETTINGS_CONNECTION_INT_FLAGS_NONE,
	                                       NM_SETTINGS_CONNECTION_INT_FLAGS_NONE,
	                                       FALSE,
	                                       NM_SETTINGS_CONNECTION_UPDATE_REASON_NONE);
}

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

static void
send_agent_owned_secrets (NMSettings *self,
                          NMSettingsConnection *sett_conn,
                          NMAuthSubject *subject)
{
	NMSettingsPrivate *priv = NM_SETTINGS_GET_PRIVATE (self);
	gs_unref_object NMConnection *for_agent = NULL;

	/* Dupe the connection so we can clear out non-agent-owned secrets,
	 * as agent-owned secrets are the only ones we send back to be saved.
	 * Only send secrets to agents of the same UID that called update too.
	 */
	for_agent = nm_simple_connection_new_clone (nm_settings_connection_get_connection (sett_conn));
	_nm_connection_clear_secrets_by_secret_flags (for_agent,
	                                              NM_SETTING_SECRET_FLAG_AGENT_OWNED);
	nm_agent_manager_save_secrets (priv->agent_mgr,
	                               nm_dbus_object_get_path (NM_DBUS_OBJECT (sett_conn)),
	                               for_agent,
	                               subject);
}

static void
pk_add_cb (NMAuthChain *chain,
           GDBusMethodInvocation *context,
           gpointer user_data)
{
	NMSettings *self = NM_SETTINGS (user_data);
	NMAuthCallResult result;
	gs_free_error GError *error = NULL;
	NMConnection *connection = NULL;
	gs_unref_object NMSettingsConnection *added = NULL;
	NMSettingsAddCallback callback;
	gpointer callback_data;
	NMAuthSubject *subject;
	const char *perm;

	nm_assert (G_IS_DBUS_METHOD_INVOCATION (context));

	c_list_unlink (nm_auth_chain_parent_lst_list (chain));

	perm = nm_auth_chain_get_data (chain, "perm");
	nm_assert (perm);

	result = nm_auth_chain_get_result (chain, perm);

	if (result != NM_AUTH_CALL_RESULT_YES) {
		error = g_error_new_literal (NM_SETTINGS_ERROR,
		                             NM_SETTINGS_ERROR_PERMISSION_DENIED,
		                             NM_UTILS_ERROR_MSG_INSUFF_PRIV);
	} else {
		/* Authorized */
		connection = nm_auth_chain_get_data (chain, "connection");
		nm_assert (NM_IS_CONNECTION (connection));

		nm_settings_add_connection (self,
		                            connection,
		                            GPOINTER_TO_UINT (nm_auth_chain_get_data (chain, "persist-mode")),
		                            GPOINTER_TO_UINT (nm_auth_chain_get_data (chain, "add-reason")),
		                            GPOINTER_TO_UINT (nm_auth_chain_get_data (chain, "sett-flags")),
		                            &added,
		                            &error);

		/* The callback may remove the connection from the settings manager (e.g.
		 * because it's found to be incompatible with the device on AddAndActivate).
		 * But we need to keep it alive for a bit longer, precisely to check wehther
		 * it's still known to the setting manager. */
		nm_g_object_ref (added);
	}

	callback = nm_auth_chain_get_data (chain, "callback");
	callback_data = nm_auth_chain_get_data (chain, "callback-data");
	subject = nm_auth_chain_get_data (chain, "subject");

	callback (self, added, error, context, subject, callback_data);

	/* Send agent-owned secrets to the agents */
	if (   added
	    && nm_settings_has_connection (self, added))
		send_agent_owned_secrets (self, added, subject);
}

void
nm_settings_add_connection_dbus (NMSettings *self,
                                 NMConnection *connection,
                                 NMSettingsConnectionPersistMode persist_mode,
                                 NMSettingsConnectionAddReason add_reason,
                                 NMSettingsConnectionIntFlags sett_flags,
                                 NMAuthSubject *subject,
                                 GDBusMethodInvocation *context,
                                 NMSettingsAddCallback callback,
                                 gpointer user_data)
{
	NMSettingsPrivate *priv = NM_SETTINGS_GET_PRIVATE (self);
	NMSettingConnection *s_con;
	NMAuthChain *chain;
	GError *error = NULL, *tmp_error = NULL;
	const char *perm;

	g_return_if_fail (NM_IS_CONNECTION (connection));
	g_return_if_fail (NM_IS_AUTH_SUBJECT (subject));
	g_return_if_fail (G_IS_DBUS_METHOD_INVOCATION (context));

	nm_assert (!NM_FLAGS_ANY (sett_flags, ~_NM_SETTINGS_CONNECTION_INT_FLAGS_PERSISTENT_MASK));

	/* Connection must be valid, of course */
	if (_nm_connection_verify (connection, &tmp_error) != NM_SETTING_VERIFY_SUCCESS) {
		error = g_error_new (NM_SETTINGS_ERROR,
		                     NM_SETTINGS_ERROR_INVALID_CONNECTION,
		                     "The connection was invalid: %s",
		                     tmp_error->message);
		g_error_free (tmp_error);
		goto done;
	}

	if (!nm_auth_is_subject_in_acl_set_error (connection,
	                                          subject,
	                                          NM_SETTINGS_ERROR,
	                                          NM_SETTINGS_ERROR_PERMISSION_DENIED,
	                                          &error))
		goto done;

	/* If the caller is the only user in the connection's permissions, then
	 * we use the 'modify.own' permission instead of 'modify.system'.  If the
	 * request affects more than just the caller, require 'modify.system'.
	 */
	s_con = nm_connection_get_setting_connection (connection);
	nm_assert (s_con);
	if (nm_setting_connection_get_num_permissions (s_con) == 1)
		perm = NM_AUTH_PERMISSION_SETTINGS_MODIFY_OWN;
	else
		perm = NM_AUTH_PERMISSION_SETTINGS_MODIFY_SYSTEM;

	/* Validate the user request */
	chain = nm_auth_chain_new_subject (subject, context, pk_add_cb, self);
	if (!chain) {
		error = g_error_new_literal (NM_SETTINGS_ERROR,
		                             NM_SETTINGS_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, "perm", (gpointer) perm, NULL);
	nm_auth_chain_set_data (chain, "connection", g_object_ref (connection), g_object_unref);
	nm_auth_chain_set_data (chain, "callback", callback, NULL);
	nm_auth_chain_set_data (chain, "callback-data", user_data, NULL);
	nm_auth_chain_set_data (chain, "subject", g_object_ref (subject), g_object_unref);
	nm_auth_chain_set_data (chain, "persist-mode", GUINT_TO_POINTER (persist_mode), NULL);
	nm_auth_chain_set_data (chain, "add-reason", GUINT_TO_POINTER (add_reason), NULL);
	nm_auth_chain_set_data (chain, "sett-flags", GUINT_TO_POINTER (sett_flags), NULL);
	nm_auth_chain_add_call_unsafe (chain, perm, TRUE);
	return;

done:
	nm_assert (error);
	callback (self, NULL, error, context, subject, user_data);
	g_error_free (error);
}

static void
settings_add_connection_add_cb (NMSettings *self,
                                NMSettingsConnection *connection,
                                GError *error,
                                GDBusMethodInvocation *context,
                                NMAuthSubject *subject,
                                gpointer user_data)
{
	gboolean is_add_connection_2 = GPOINTER_TO_INT (user_data);

	if (error) {
		g_dbus_method_invocation_return_gerror (context, error);
		nm_audit_log_connection_op (NM_AUDIT_OP_CONN_ADD, NULL, FALSE, NULL, subject, error->message);
		return;
	}

	if (is_add_connection_2) {
		GVariantBuilder builder;

		g_variant_builder_init (&builder, G_VARIANT_TYPE_VARDICT);
		g_dbus_method_invocation_return_value (context,
		                                       g_variant_new ("(oa{sv})",
		                                                      nm_dbus_object_get_path (NM_DBUS_OBJECT (connection)),
		                                                      &builder));
	} else {
		g_dbus_method_invocation_return_value (context,
		                                       g_variant_new ("(o)",
		                                                      nm_dbus_object_get_path (NM_DBUS_OBJECT (connection))));
	}
	nm_audit_log_connection_op (NM_AUDIT_OP_CONN_ADD, connection, TRUE, NULL,
	                            subject, NULL);
}

static void
settings_add_connection_helper (NMSettings *self,
                                GDBusMethodInvocation *context,
                                gboolean is_add_connection_2,
                                GVariant *settings,
                                NMSettingsAddConnection2Flags flags)
{
	gs_unref_object NMConnection *connection = NULL;
	GError *error = NULL;
	gs_unref_object NMAuthSubject *subject = NULL;
	NMSettingsConnectionPersistMode persist_mode;

	connection = _nm_simple_connection_new_from_dbus (settings,
	                                                    NM_SETTING_PARSE_FLAGS_STRICT
	                                                  | NM_SETTING_PARSE_FLAGS_NORMALIZE,
	                                                  &error);

	if (   !connection
	    || !nm_connection_verify_secrets (connection, &error)) {
		g_dbus_method_invocation_take_error (context, error);
		return;
	}

	subject = nm_dbus_manager_new_auth_subject_from_context (context);
	if (!subject) {
		g_dbus_method_invocation_return_error_literal (context,
		                                               NM_SETTINGS_ERROR,
		                                               NM_SETTINGS_ERROR_PERMISSION_DENIED,
		                                               NM_UTILS_ERROR_MSG_REQ_UID_UKNOWN);
		return;
	}

	if (NM_FLAGS_HAS (flags, NM_SETTINGS_ADD_CONNECTION2_FLAG_TO_DISK))
		persist_mode = NM_SETTINGS_CONNECTION_PERSIST_MODE_TO_DISK;
	else {
		nm_assert (NM_FLAGS_HAS (flags, NM_SETTINGS_ADD_CONNECTION2_FLAG_IN_MEMORY));
		persist_mode = NM_SETTINGS_CONNECTION_PERSIST_MODE_IN_MEMORY_ONLY;
	}

	nm_settings_add_connection_dbus (self,
	                                 connection,
	                                 persist_mode,
	                                   NM_FLAGS_HAS (flags, NM_SETTINGS_ADD_CONNECTION2_FLAG_BLOCK_AUTOCONNECT)
	                                 ? NM_SETTINGS_CONNECTION_ADD_REASON_BLOCK_AUTOCONNECT
	                                 : NM_SETTINGS_CONNECTION_ADD_REASON_NONE,
	                                 NM_SETTINGS_CONNECTION_INT_FLAGS_NONE,
	                                 subject,
	                                 context,
	                                 settings_add_connection_add_cb,
	                                 GINT_TO_POINTER (!!is_add_connection_2));
}

static void
impl_settings_add_connection (NMDBusObject *obj,
                              const NMDBusInterfaceInfoExtended *interface_info,
                              const NMDBusMethodInfoExtended *method_info,
                              GDBusConnection *connection,
                              const char *sender,
                              GDBusMethodInvocation *invocation,
                              GVariant *parameters)
{
	NMSettings *self = NM_SETTINGS (obj);
	gs_unref_variant GVariant *settings = NULL;

	g_variant_get (parameters, "(@a{sa{sv}})", &settings);
	settings_add_connection_helper (self, invocation, FALSE, settings, NM_SETTINGS_ADD_CONNECTION2_FLAG_TO_DISK);
}

static void
impl_settings_add_connection_unsaved (NMDBusObject *obj,
                                      const NMDBusInterfaceInfoExtended *interface_info,
                                      const NMDBusMethodInfoExtended *method_info,
                                      GDBusConnection *connection,
                                      const char *sender,
                                      GDBusMethodInvocation *invocation,
                                      GVariant *parameters)
{
	NMSettings *self = NM_SETTINGS (obj);
	gs_unref_variant GVariant *settings = NULL;

	g_variant_get (parameters, "(@a{sa{sv}})", &settings);
	settings_add_connection_helper (self, invocation, FALSE, settings, NM_SETTINGS_ADD_CONNECTION2_FLAG_IN_MEMORY);
}

static void
impl_settings_add_connection2 (NMDBusObject *obj,
                               const NMDBusInterfaceInfoExtended *interface_info,
                               const NMDBusMethodInfoExtended *method_info,
                               GDBusConnection *connection,
                               const char *sender,
                               GDBusMethodInvocation *invocation,
                               GVariant *parameters)
{
	NMSettings *self = NM_SETTINGS (obj);
	gs_unref_variant GVariant *settings = NULL;
	gs_unref_variant GVariant *args = NULL;
	NMSettingsAddConnection2Flags flags;
	const char *args_name;
	GVariantIter iter;
	guint32 flags_u;

	g_variant_get (parameters, "(@a{sa{sv}}u@a{sv})", &settings, &flags_u, &args);

	if (NM_FLAGS_ANY (flags_u, ~((guint32) (  NM_SETTINGS_ADD_CONNECTION2_FLAG_TO_DISK
	                                        | NM_SETTINGS_ADD_CONNECTION2_FLAG_IN_MEMORY
	                                        | NM_SETTINGS_ADD_CONNECTION2_FLAG_BLOCK_AUTOCONNECT)))) {
		g_dbus_method_invocation_take_error (invocation,
		                                     g_error_new_literal (NM_SETTINGS_ERROR,
		                                                          NM_SETTINGS_ERROR_INVALID_ARGUMENTS,
		                                                          "Unknown flags"));
		return;
	}

	flags = flags_u;

	if (!NM_FLAGS_ANY (flags,   NM_SETTINGS_ADD_CONNECTION2_FLAG_TO_DISK
	                          | NM_SETTINGS_ADD_CONNECTION2_FLAG_IN_MEMORY)) {
		g_dbus_method_invocation_take_error (invocation,
		                                     g_error_new_literal (NM_SETTINGS_ERROR,
		                                                          NM_SETTINGS_ERROR_INVALID_ARGUMENTS,
		                                                          "Requires either to-disk (0x1) or in-memory (0x2) flags"));
		return;
	}

	if (NM_FLAGS_ALL (flags,   NM_SETTINGS_ADD_CONNECTION2_FLAG_TO_DISK
	                         | NM_SETTINGS_ADD_CONNECTION2_FLAG_IN_MEMORY)) {
		g_dbus_method_invocation_take_error (invocation,
		                                     g_error_new_literal (NM_SETTINGS_ERROR,
		                                                          NM_SETTINGS_ERROR_INVALID_ARGUMENTS,
		                                                          "Cannot set to-disk (0x1) and in-memory (0x2) flags together"));
		return;
	}

	nm_assert (g_variant_is_of_type (args, G_VARIANT_TYPE ("a{sv}")));

	g_variant_iter_init (&iter, args);
	while (g_variant_iter_next (&iter, "{&sv}", &args_name, NULL)) {
		g_dbus_method_invocation_take_error (invocation,
		                                     g_error_new (NM_SETTINGS_ERROR,
		                                                  NM_SETTINGS_ERROR_INVALID_ARGUMENTS,
		                                                  "Unsupported argument '%s'", args_name));
		return;
	}

	settings_add_connection_helper (self, invocation, TRUE, settings, flags);
}

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

static void
impl_settings_load_connections (NMDBusObject *obj,
                                const NMDBusInterfaceInfoExtended *interface_info,
                                const NMDBusMethodInfoExtended *method_info,
                                GDBusConnection *dbus_connection,
                                const char *sender,
                                GDBusMethodInvocation *invocation,
                                GVariant *parameters)
{
	NMSettings *self = NM_SETTINGS (obj);
	NMSettingsPrivate *priv = NM_SETTINGS_GET_PRIVATE (self);
	gs_unref_ptrarray GPtrArray *failures = NULL;
	gs_free const char **filenames = NULL;
	gs_free char *op_result_str = NULL;

	g_variant_get (parameters, "(^a&s)", &filenames);

	/* 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 (obj),
	                                 invocation,
	                                 G_MAXULONG,
	                                 NM_SETTINGS_ERROR,
	                                 NM_SETTINGS_ERROR_PERMISSION_DENIED))
		return;

	if (   filenames
	    && filenames[0]) {
		NMSettingsPluginConnectionLoadEntry *entries;
		gsize n_entries;
		gsize i;
		GSList *iter;

		entries = nm_settings_plugin_create_connection_load_entries (filenames, &n_entries);

		for (iter = priv->plugins; iter; iter = iter->next) {
			NMSettingsPlugin *plugin = iter->data;

			nm_settings_plugin_load_connections (plugin,
			                                     entries,
			                                     n_entries,
			                                     _plugin_connections_reload_cb,
			                                     self);
		}

		for (i = 0; i < n_entries; i++) {
			NMSettingsPluginConnectionLoadEntry *entry = &entries[i];

			if (!entry->handled) {
				_LOGW ("load: no settings plugin could load \"%s\"", entry->filename);
				nm_assert (!entry->error);
			} else if (entry->error) {
				_LOGW ("load: failure to load \"%s\": %s", entry->filename, entry->error->message);
				g_clear_error (&entry->error);
			} else
				continue;

			if (!failures)
				failures = g_ptr_array_new ();
			g_ptr_array_add (failures, (char *) entry->filename);
		}

		nm_clear_g_free (&entries);

		_connection_changed_process_all_dirty (self,
		                                       TRUE,
		                                       NM_SETTINGS_CONNECTION_INT_FLAGS_NONE,
		                                       NM_SETTINGS_CONNECTION_INT_FLAGS_NONE,
		                                       TRUE,
		                                         NM_SETTINGS_CONNECTION_UPDATE_REASON_RESET_SYSTEM_SECRETS
		                                       | NM_SETTINGS_CONNECTION_UPDATE_REASON_RESET_AGENT_SECRETS);

		for (iter = priv->plugins; iter; iter = iter->next)
			nm_settings_plugin_load_connections_done (iter->data);
	}

	if (failures)
		g_ptr_array_add (failures, NULL);

	nm_audit_log_connection_op (NM_AUDIT_OP_CONNS_LOAD,
	                            NULL,
	                            !failures,
	                            (op_result_str = g_strjoinv (",", (char **) filenames)),
	                            invocation,
	                            NULL);

	g_dbus_method_invocation_return_value (invocation,
	                                       g_variant_new ("(b^as)",
	                                                      (gboolean) (!failures),
	                                                      failures
	                                                        ? (const char **) failures->pdata
	                                                        : NM_PTRARRAY_EMPTY (const char *)));
}

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

	/* 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 (obj),
	                                 invocation,
	                                 G_MAXULONG,
	                                 NM_SETTINGS_ERROR,
	                                 NM_SETTINGS_ERROR_PERMISSION_DENIED))
		return;

	_plugin_connections_reload (self);

	nm_audit_log_connection_op (NM_AUDIT_OP_CONNS_RELOAD, NULL, TRUE, NULL, invocation, NULL);

	/* We MUST return %TRUE here, otherwise older libnm versions might misbehave. */
	g_dbus_method_invocation_return_value (invocation, g_variant_new ("(b)", TRUE));
}

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

static void
_clear_connections_cached_list (NMSettingsPrivate *priv)
{
	if (!priv->connections_cached_list)
		return;

	nm_assert (priv->connections_len == NM_PTRARRAY_LEN (priv->connections_cached_list));

#if NM_MORE_ASSERTS
	/* set the pointer to a bogus value. This makes it more apparent
	 * if somebody has a reference to the cached list and still uses
	 * it. That is a bug, this code just tries to make it blow up
	 * more eagerly. */
	memset (priv->connections_cached_list,
	        0x43,
	        sizeof (NMSettingsConnection *) * (priv->connections_len + 1));
#endif

	nm_clear_g_free (&priv->connections_cached_list);
}

static void
impl_settings_list_connections (NMDBusObject *obj,
                                const NMDBusInterfaceInfoExtended *interface_info,
                                const NMDBusMethodInfoExtended *method_info,
                                GDBusConnection *dbus_connection,
                                const char *sender,
                                GDBusMethodInvocation *invocation,
                                GVariant *parameters)
{
	NMSettings *self = NM_SETTINGS (obj);
	NMSettingsPrivate *priv = NM_SETTINGS_GET_PRIVATE (self);
	gs_free const char **strv = NULL;

	strv = nm_dbus_utils_get_paths_for_clist (&priv->connections_lst_head,
	                                          priv->connections_len,
	                                          G_STRUCT_OFFSET (NMSettingsConnection, _connections_lst),
	                                          TRUE);
	g_dbus_method_invocation_return_value (invocation,
	                                       g_variant_new ("(^ao)", strv));
}

NMSettingsConnection *
nm_settings_get_connection_by_uuid (NMSettings *self, const char *uuid)
{
	g_return_val_if_fail (NM_IS_SETTINGS (self), NULL);
	g_return_val_if_fail (uuid != NULL, NULL);

	return _sett_conn_entry_get_conn (_sett_conn_entries_get (self, uuid));
}

const char *
nm_settings_get_dbus_path_for_uuid (NMSettings *self,
                                    const char *uuid)
{
	NMSettingsConnection *sett_conn;

	sett_conn = nm_settings_get_connection_by_uuid (self, uuid);

	if (!sett_conn)
		return NULL;

	return nm_dbus_object_get_path (NM_DBUS_OBJECT (sett_conn));
}

static void
impl_settings_get_connection_by_uuid (NMDBusObject *obj,
                                      const NMDBusInterfaceInfoExtended *interface_info,
                                      const NMDBusMethodInfoExtended *method_info,
                                      GDBusConnection *dbus_connection,
                                      const char *sender,
                                      GDBusMethodInvocation *invocation,
                                      GVariant *parameters)
{
	NMSettings *self = NM_SETTINGS (obj);
	NMSettingsConnection *sett_conn;
	gs_unref_object NMAuthSubject *subject = NULL;
	GError *error = NULL;
	const char *uuid;

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

	sett_conn = nm_settings_get_connection_by_uuid (self, uuid);
	if (!sett_conn) {
		error = g_error_new_literal (NM_SETTINGS_ERROR,
		                             NM_SETTINGS_ERROR_INVALID_CONNECTION,
		                             "No connection with the UUID was found.");
		goto error;
	}

	subject = nm_dbus_manager_new_auth_subject_from_context (invocation);
	if (!subject) {
		error = g_error_new_literal (NM_SETTINGS_ERROR,
		                             NM_SETTINGS_ERROR_PERMISSION_DENIED,
		                             NM_UTILS_ERROR_MSG_REQ_UID_UKNOWN);
		goto error;
	}

	if (!nm_auth_is_subject_in_acl_set_error (nm_settings_connection_get_connection (sett_conn),
	                                          subject,
	                                          NM_SETTINGS_ERROR,
	                                          NM_SETTINGS_ERROR_PERMISSION_DENIED,
	                                          &error))
		goto error;

	g_dbus_method_invocation_return_value (invocation,
	                                       g_variant_new ("(o)",
	                                                      nm_dbus_object_get_path (NM_DBUS_OBJECT (sett_conn))));
	return;

error:
	g_dbus_method_invocation_take_error (invocation, error);
}

/**
 * nm_settings_get_connections:
 * @self: the #NMSettings
 * @out_len: (out) (allow-none): returns the number of returned
 *   connections.
 *
 * Returns: (transfer none): a list of NMSettingsConnections. The list is
 * unsorted and NULL terminated. The result is never %NULL, in case of no
 * connections, it returns an empty list.
 * The returned list is cached internally, only valid until the next
 * NMSettings operation.
 */
NMSettingsConnection *const*
nm_settings_get_connections (NMSettings *self, guint *out_len)
{
	NMSettingsPrivate *priv;
	NMSettingsConnection **v;
	NMSettingsConnection *con;
	guint i;

	g_return_val_if_fail (NM_IS_SETTINGS (self), NULL);

	priv = NM_SETTINGS_GET_PRIVATE (self);

	nm_assert (priv->connections_len == c_list_length (&priv->connections_lst_head));

	if (G_UNLIKELY (!priv->connections_cached_list)) {
		v = g_new (NMSettingsConnection *, priv->connections_len + 1);

		i = 0;
		c_list_for_each_entry (con, &priv->connections_lst_head, _connections_lst) {
			nm_assert (i < priv->connections_len);
			v[i++] = con;
		}
		nm_assert (i == priv->connections_len);
		v[i] = NULL;

		priv->connections_cached_list = v;
	}

	NM_SET_OUT (out_len, priv->connections_len);
	return priv->connections_cached_list;
}

/**
 * nm_settings_get_connections_clone:
 * @self: the #NMSetting
 * @out_len: (allow-none): optional output argument
 * @func: caller-supplied function for filtering connections
 * @func_data: caller-supplied data passed to @func
 * @sort_compare_func: (allow-none): optional function pointer for
 *   sorting the returned list.
 * @sort_data: user data for @sort_compare_func.
 *
 * Returns: (transfer container) (element-type NMSettingsConnection):
 *   an NULL terminated array of #NMSettingsConnection objects that were
 *   filtered by @func (or all connections if no filter was specified).
 *   The order is arbitrary.
 *   Caller is responsible for freeing the returned array with free(),
 *   the contained values do not need to be unrefed.
 */
NMSettingsConnection **
nm_settings_get_connections_clone (NMSettings *self,
                                   guint *out_len,
                                   NMSettingsConnectionFilterFunc func,
                                   gpointer func_data,
                                   GCompareDataFunc sort_compare_func,
                                   gpointer sort_data)
{
	NMSettingsConnection *const*list_cached;
	NMSettingsConnection **list;
	guint len, i, j;

	g_return_val_if_fail (NM_IS_SETTINGS (self), NULL);

	list_cached = nm_settings_get_connections (self, &len);

#if NM_MORE_ASSERTS
	nm_assert (list_cached);
	for (i = 0; i < len; i++)
		nm_assert (NM_IS_SETTINGS_CONNECTION (list_cached[i]));
	nm_assert (!list_cached[i]);
#endif

	list = g_new (NMSettingsConnection *, ((gsize) len + 1));
	if (func) {
		for (i = 0, j = 0; i < len; i++) {
			if (func (self, list_cached[i], func_data))
				list[j++] = list_cached[i];
		}
		list[j] = NULL;
		len = j;
	} else
		memcpy (list, list_cached, sizeof (list[0]) * ((gsize) len + 1));

	if (   len > 1
	    && sort_compare_func) {
		g_qsort_with_data (list, len, sizeof (NMSettingsConnection *),
		                   sort_compare_func, sort_data);
	}
	NM_SET_OUT (out_len, len);
	return list;
}

NMSettingsConnection *
nm_settings_get_connection_by_path (NMSettings *self, const char *path)
{
	NMSettingsPrivate *priv;
	NMSettingsConnection *connection;

	g_return_val_if_fail (NM_IS_SETTINGS (self), NULL);
	g_return_val_if_fail (path, NULL);

	priv = NM_SETTINGS_GET_PRIVATE (self);

	connection = nm_dbus_manager_lookup_object (nm_dbus_object_get_manager (NM_DBUS_OBJECT (self)),
	                                            path);
	if (   !connection
	    || !NM_IS_SETTINGS_CONNECTION (connection))
		return NULL;

	nm_assert (c_list_contains (&priv->connections_lst_head, &connection->_connections_lst));
	return connection;
}

gboolean
nm_settings_has_connection (NMSettings *self, NMSettingsConnection *connection)
{
	gboolean has;

	g_return_val_if_fail (NM_IS_SETTINGS (self), FALSE);
	g_return_val_if_fail (NM_IS_SETTINGS_CONNECTION (connection), FALSE);

	has = !c_list_is_empty (&connection->_connections_lst);

	nm_assert (has == nm_c_list_contains_entry (&NM_SETTINGS_GET_PRIVATE (self)->connections_lst_head,
                                                connection,
                                                _connections_lst));
	nm_assert (({
		NMSettingsConnection *candidate = NULL;
		const char *path;

		path = nm_dbus_object_get_path (NM_DBUS_OBJECT (connection));
		if (path)
			candidate = nm_settings_get_connection_by_path (self, path);

		(has == (connection == candidate));
	}));

	return has;
}

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

static void
add_plugin (NMSettings *self,
            NMSettingsPlugin *plugin,
            const char *pname,
            const char *path)
{
	NMSettingsPrivate *priv;

	nm_assert (NM_IS_SETTINGS (self));
	nm_assert (NM_IS_SETTINGS_PLUGIN (plugin));

	nm_assert (pname);
	nm_assert (nm_streq0 (pname, nm_settings_plugin_get_plugin_name (plugin)));

	priv = NM_SETTINGS_GET_PRIVATE (self);

	nm_assert (!g_slist_find (priv->plugins, plugin));

	priv->plugins = g_slist_append (priv->plugins, g_object_ref (plugin));

	nm_shutdown_wait_obj_register_object_full (plugin,
	                                           g_strdup_printf ("%s-settings-plugin", pname),
	                                           TRUE);

	_LOGI ("Loaded settings plugin: %s (%s%s%s)",
	       pname,
	       NM_PRINT_FMT_QUOTED (path, "\"", path, "\"", "internal"));
}

static gboolean
add_plugin_load_file (NMSettings *self, const char *pname, GError **error)
{
	gs_free char *full_name = NULL;
	gs_free char *path = NULL;
	gs_unref_object NMSettingsPlugin *plugin = NULL;
	GModule *module;
	NMSettingsPluginFactoryFunc factory_func;
	struct stat st;
	int errsv;

	full_name = g_strdup_printf ("nm-settings-plugin-%s", pname);
	path = g_module_build_path (NMPLUGINDIR, full_name);

	if (stat (path, &st) != 0) {
		errsv = errno;
		_LOGW ("could not load plugin '%s' from file '%s': %s", pname, path, nm_strerror_native (errsv));
		return TRUE;
	}
	if (!S_ISREG (st.st_mode)) {
		_LOGW ("could not load plugin '%s' from file '%s': not a file", pname, path);
		return TRUE;
	}
	if (st.st_uid != 0) {
		_LOGW ("could not load plugin '%s' from file '%s': file must be owned by root", pname, path);
		return TRUE;
	}
	if (st.st_mode & (S_IWGRP | S_IWOTH | S_ISUID)) {
		_LOGW ("could not load plugin '%s' from file '%s': invalid file permissions", pname, path);
		return TRUE;
	}

	module = g_module_open (path, G_MODULE_BIND_LOCAL);
	if (!module) {
		_LOGW ("could not load plugin '%s' from file '%s': %s",
		     pname, path, g_module_error ());
		return TRUE;
	}

	/* errors after this point are fatal, because we loaded the shared library already. */

	if (!g_module_symbol (module, "nm_settings_plugin_factory", (gpointer) (&factory_func))) {
		g_set_error (error, NM_SETTINGS_ERROR, NM_SETTINGS_ERROR_FAILED,
		             "Could not find plugin '%s' factory function.",
		             pname);
		g_module_close (module);
		return FALSE;
	}

	/* after accessing the plugin we cannot unload it anymore, because the glib
	 * types cannot be properly unregistered. */
	g_module_make_resident (module);

	plugin = (*factory_func) ();
	if (!NM_IS_SETTINGS_PLUGIN (plugin)) {
		g_set_error (error, NM_SETTINGS_ERROR, NM_SETTINGS_ERROR_FAILED,
		             "plugin '%s' returned invalid settings plugin",
		             pname);
		return FALSE;
	}

	add_plugin (self, NM_SETTINGS_PLUGIN (plugin), pname, path);
	return TRUE;
}

static void
add_plugin_keyfile (NMSettings *self)
{
	NMSettingsPrivate *priv = NM_SETTINGS_GET_PRIVATE (self);

	if (priv->keyfile_plugin)
		return;
	priv->keyfile_plugin = nms_keyfile_plugin_new ();
	add_plugin (self, NM_SETTINGS_PLUGIN (priv->keyfile_plugin), "keyfile", NULL);
}

static gboolean
load_plugins (NMSettings *self, const char *const*plugins, GError **error)
{
	const char *const*iter;
	gboolean success = TRUE;

	for (iter = plugins; iter && *iter; iter++) {
		const char *pname = *iter;

		if (!*pname || strchr (pname, '/')) {
			_LOGW ("ignore invalid plugin \"%s\"", pname);
			continue;
		}

		if (NM_IN_STRSET (pname, "ifcfg-suse", "ifnet", "ibft", "no-ibft")) {
			_LOGW ("skipping deprecated plugin %s", pname);
			continue;
		}

		/* keyfile plugin is built-in now */
		if (nm_streq (pname, "keyfile")) {
			add_plugin_keyfile (self);
			continue;
		}

		if (nm_utils_strv_find_first ((char **) plugins,
		                              iter - plugins,
		                              pname) >= 0) {
			/* the plugin is already mentioned in the list previously.
			 * Don't load a duplicate. */
			continue;
		}

		success = add_plugin_load_file (self, pname, error);
		if (!success)
			break;
	}

	/* If keyfile plugin was not among configured plugins, add it as the last one */
	if (success)
		add_plugin_keyfile (self);

	return success;
}

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

static void
pk_hostname_cb (NMAuthChain *chain,
                GDBusMethodInvocation *context,
                gpointer user_data)
{
	NMSettings *self = NM_SETTINGS (user_data);
	NMSettingsPrivate *priv = NM_SETTINGS_GET_PRIVATE (self);
	NMAuthCallResult result;
	GError *error = NULL;
	const char *hostname;

	nm_assert (G_IS_DBUS_METHOD_INVOCATION (context));

	c_list_unlink (nm_auth_chain_parent_lst_list (chain));

	result = nm_auth_chain_get_result (chain, NM_AUTH_PERMISSION_SETTINGS_MODIFY_HOSTNAME);
	hostname = nm_auth_chain_get_data (chain, "hostname");

	/* If our NMSettingsConnection is already gone, do nothing */
	if (result != NM_AUTH_CALL_RESULT_YES) {
		error = g_error_new_literal (NM_SETTINGS_ERROR,
		                             NM_SETTINGS_ERROR_PERMISSION_DENIED,
		                             NM_UTILS_ERROR_MSG_INSUFF_PRIV);
	} else {
		if (!nm_hostname_manager_write_hostname (priv->hostname_manager, hostname)) {
			error = g_error_new_literal (NM_SETTINGS_ERROR,
			                             NM_SETTINGS_ERROR_FAILED,
			                             "Saving the hostname failed.");
		}
	}

	nm_audit_log_control_op (NM_AUDIT_OP_HOSTNAME_SAVE,
	                         hostname,
	                         !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, NULL);
}

static void
impl_settings_save_hostname (NMDBusObject *obj,
                             const NMDBusInterfaceInfoExtended *interface_info,
                             const NMDBusMethodInfoExtended *method_info,
                             GDBusConnection *connection,
                             const char *sender,
                             GDBusMethodInvocation *invocation,
                             GVariant *parameters)
{
	NMSettings *self = NM_SETTINGS (obj);
	NMSettingsPrivate *priv = NM_SETTINGS_GET_PRIVATE (self);
	NMAuthChain *chain;
	const char *hostname;
	const char *error_reason;
	int error_code;

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

	/* Minimal validation of the hostname */
	if (!nm_hostname_manager_validate_hostname (hostname)) {
		error_code = NM_SETTINGS_ERROR_INVALID_HOSTNAME;
		error_reason = "The hostname was too long or contained invalid characters";
		goto err;
	}

	chain = nm_auth_chain_new_context (invocation, pk_hostname_cb, self);
	if (!chain) {
		error_code = NM_SETTINGS_ERROR_PERMISSION_DENIED;
		error_reason = NM_UTILS_ERROR_MSG_REQ_AUTH_FAILED;
		goto err;
	}

	c_list_link_tail (&priv->auth_lst_head, nm_auth_chain_parent_lst_list (chain));
	nm_auth_chain_add_call (chain, NM_AUTH_PERMISSION_SETTINGS_MODIFY_HOSTNAME, TRUE);
	nm_auth_chain_set_data (chain, "hostname", g_strdup (hostname), g_free);
	return;
err:
	nm_audit_log_control_op (NM_AUDIT_OP_HOSTNAME_SAVE,
	                         hostname,
	                         FALSE,
	                         invocation,
	                         error_reason);
	g_dbus_method_invocation_return_error_literal (invocation,
	                                               NM_SETTINGS_ERROR,
	                                               error_code,
	                                               error_reason);
}

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

static void
_hostname_changed_cb (NMHostnameManager *hostname_manager,
                      GParamSpec *pspec,
                      gpointer user_data)
{
	_notify (user_data, PROP_HOSTNAME);
}

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

static gboolean
have_connection_for_device (NMSettings *self, NMDevice *device)
{
	NMSettingsPrivate *priv = NM_SETTINGS_GET_PRIVATE (self);
	NMSettingsConnection *sett_conn;

	g_return_val_if_fail (NM_IS_SETTINGS (self), FALSE);

	/* Find a wired connection matching for the device, if any */
	c_list_for_each_entry (sett_conn, &priv->connections_lst_head, _connections_lst) {
		NMConnection *connection = nm_settings_connection_get_connection (sett_conn);

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

		if (nm_settings_connection_default_wired_get_device (sett_conn))
			continue;

		if (NM_FLAGS_ANY (nm_settings_connection_get_flags (sett_conn),
		                  NM_SETTINGS_CONNECTION_INT_FLAGS_VOLATILE))
			continue;

		return TRUE;
	}

	/* See if there's a known non-NetworkManager configuration for the device */
	if (nm_device_spec_match_list (device, priv->unrecognized_specs))
		return TRUE;

	return FALSE;
}

static void
default_wired_clear_tag (NMSettings *self,
                         NMDevice *device,
                         NMSettingsConnection *sett_conn,
                         gboolean add_to_no_auto_default)
{
	nm_assert (NM_IS_SETTINGS (self));
	nm_assert (NM_IS_DEVICE (device));
	nm_assert (NM_IS_SETTINGS_CONNECTION (sett_conn));
	nm_assert (device == nm_settings_connection_default_wired_get_device (sett_conn));
	nm_assert (sett_conn == g_object_get_qdata (G_OBJECT (device), _default_wired_connection_quark ()));

	_LOGT ("auto-default: forget association between %s (%s) and device %s (%s)",
	       nm_settings_connection_get_uuid (sett_conn),
	       nm_settings_connection_get_id (sett_conn),
	       nm_device_get_iface (device),
	       add_to_no_auto_default ? "persisted" : "temporary");

	nm_settings_connection_default_wired_set_device (sett_conn, NULL);

	g_object_set_qdata (G_OBJECT (device), _default_wired_connection_quark (), NULL);

	if (add_to_no_auto_default)
		nm_config_set_no_auto_default_for_device (NM_SETTINGS_GET_PRIVATE (self)->config, device);
}

static void
device_realized (NMDevice *device, GParamSpec *pspec, NMSettings *self)
{
	gs_unref_object NMConnection *connection = NULL;
	NMSettingsPrivate *priv;
	NMSettingsConnection *added;
	GError *error = NULL;

	if (!nm_device_is_real (device))
		return;

	g_signal_handlers_disconnect_by_func (device,
	                                      G_CALLBACK (device_realized),
	                                      self);

	priv = NM_SETTINGS_GET_PRIVATE (self);

	/* If the device isn't managed or it already has a default wired connection,
	 * ignore it.
	 */
	if (   !NM_DEVICE_GET_CLASS (device)->new_default_connection
	    || !nm_device_get_managed (device, FALSE)
	    || g_object_get_qdata (G_OBJECT (device), _default_wired_connection_quark ()))
		return;

	if (nm_config_get_no_auto_default_for_device (priv->config, device)) {
		_LOGT ("auto-default: cannot create auto-default connection for device %s: disabled by \"no-auto-default\"",
		       nm_device_get_iface (device));
		return;
	}

	if (have_connection_for_device (self, device)) {
		_LOGT ("auto-default: cannot create auto-default connection for device %s: already has a profile",
		       nm_device_get_iface (device));
		return;
	}

	connection = nm_device_new_default_connection (device);
	if (!connection) {
		_LOGT ("auto-default: cannot create auto-default connection for device %s",
		       nm_device_get_iface (device));
		return;
	}

	_LOGT ("auto-default: creating in-memory connection %s (%s) for device %s",
	       nm_connection_get_uuid (connection),
	       nm_connection_get_id (connection),
	       nm_device_get_iface (device));

	nm_settings_add_connection (self,
	                            connection,
	                            NM_SETTINGS_CONNECTION_PERSIST_MODE_IN_MEMORY_ONLY,
	                            NM_SETTINGS_CONNECTION_ADD_REASON_NONE,
	                            NM_SETTINGS_CONNECTION_INT_FLAGS_NM_GENERATED,
	                            &added,
	                            &error);
	if (!added) {
		if (!g_error_matches (error, NM_SETTINGS_ERROR, NM_SETTINGS_ERROR_UUID_EXISTS)) {
			_LOGW ("(%s) couldn't create default wired connection: %s",
			       nm_device_get_iface (device),
			       error->message);
		}
		g_clear_error (&error);
		return;
	}

	nm_settings_connection_default_wired_set_device (added, device);

	g_object_set_qdata (G_OBJECT (device), _default_wired_connection_quark (), added);

	_LOGI ("(%s): created default wired connection '%s'",
	       nm_device_get_iface (device),
	       nm_settings_connection_get_id (added));
}

void
nm_settings_device_added (NMSettings *self, NMDevice *device)
{
	if (nm_device_is_real (device))
		device_realized (device, NULL, self);
	else {
		/* FIXME(shutdown): we need to disconnect this signal handler during
		 *   shutdown. */
		g_signal_connect_after (device, "notify::" NM_DEVICE_REAL,
		                        G_CALLBACK (device_realized),
		                        self);
	}
}

void
nm_settings_device_removed (NMSettings *self, NMDevice *device, gboolean quitting)
{
	NMSettingsConnection *connection;

	g_signal_handlers_disconnect_by_func (device,
	                                      G_CALLBACK (device_realized),
	                                      self);

	connection = g_object_get_qdata (G_OBJECT (device), _default_wired_connection_quark ());
	if (connection) {
		default_wired_clear_tag (self, device, connection, FALSE);

		/* Don't delete the default wired connection on shutdown, so that it
		 * remains up and can be assumed if NM starts again.
		 */
		if (quitting == FALSE)
			nm_settings_connection_delete (connection, TRUE);
	}
}

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

static void
session_monitor_changed_cb (NMSessionMonitor *session_monitor,
                            NMSettings *self)
{
	NMSettingsPrivate *priv = NM_SETTINGS_GET_PRIVATE (self);
	NMSettingsConnection *const*list;
	guint i, len;
	guint generation;

again:
	list = nm_settings_get_connections (self, &len);
	generation = priv->connections_generation;
	for (i = 0; i < len; i++) {
		gboolean is_visible;

		is_visible = nm_settings_connection_check_visibility (list[i],
		                                                      session_monitor);
		nm_settings_connection_set_flags (list[i],
		                                  NM_SETTINGS_CONNECTION_INT_FLAGS_VISIBLE,
		                                  is_visible);
		if (generation != priv->connections_generation) {
			/* the cached list was invalidated. Start again.
			 *
			 * Note that nm_settings_connection_recheck_visibility() will do nothing
			 * if the visibility didn't change (including emitting no signals,
			 * and not invalidating the list).
			 *
			 * Hence, for this to be an endless loop, the settings would have
			 * to constantly change the visibility flag and also invalidate the list. */
			goto again;
		}
	}
}

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

G_GNUC_PRINTF (4, 5)
static void
_kf_db_log_fcn (NMKeyFileDB *kf_db,
                int syslog_level,
                gpointer user_data,
                const char *fmt,
                ...)
{
	NMSettings *self = user_data;
	NMLogLevel level = nm_log_level_from_syslog (syslog_level);

	if (_NMLOG_ENABLED (level)) {
		NMSettingsPrivate *priv = NM_SETTINGS_GET_PRIVATE (self);
		gs_free char *msg = NULL;
		va_list ap;
		const char *prefix;

		va_start (ap, fmt);
		msg = g_strdup_vprintf (fmt, ap);
		va_end (ap);

		if (priv->kf_db_timestamps == kf_db)
			prefix = "timestamps";
		else if (priv->kf_db_seen_bssids == kf_db)
			prefix = "seen-bssids";
		else {
			nm_assert_not_reached ();
			prefix = "???";
		}

		_NMLOG (level, "[%s-keyfile]: %s", prefix, msg);
	}
}

static gboolean
_kf_db_got_dirty_flush (NMSettings *self,
                        gboolean is_timestamps)
{
	NMSettingsPrivate *priv = NM_SETTINGS_GET_PRIVATE (self);
	const char *prefix;
	NMKeyFileDB *kf_db;

	if (is_timestamps) {
		prefix = "timestamps";
		kf_db = priv->kf_db_timestamps;
		priv->kf_db_flush_idle_id_timestamps = 0;
	} else {
		prefix = "seen-bssids";
		kf_db = priv->kf_db_seen_bssids;
		priv->kf_db_flush_idle_id_seen_bssids = 0;
	}

	if (nm_key_file_db_is_dirty (kf_db))
		nm_key_file_db_to_file (kf_db, FALSE);
	else {
		_LOGT ("[%s-keyfile]: skip saving changes to \"%s\"",
		       prefix,
		       nm_key_file_db_get_filename (kf_db));
	}

	return G_SOURCE_REMOVE;
}

static gboolean
_kf_db_got_dirty_flush_timestamps_cb (gpointer user_data)
{
	return _kf_db_got_dirty_flush (user_data,
	                               TRUE);
}

static gboolean
_kf_db_got_dirty_flush_seen_bssids_cb (gpointer user_data)
{
	return _kf_db_got_dirty_flush (user_data,
	                               FALSE);
}

static void
_kf_db_got_dirty_fcn (NMKeyFileDB *kf_db,
                      gpointer user_data)
{
	NMSettings *self = user_data;
	NMSettingsPrivate *priv = NM_SETTINGS_GET_PRIVATE (self);
	GSourceFunc idle_func;
	guint *p_id;
	const char *prefix;

	if (priv->kf_db_timestamps == kf_db) {
		prefix = "timestamps";
		p_id = &priv->kf_db_flush_idle_id_timestamps;
		idle_func = _kf_db_got_dirty_flush_timestamps_cb;
	} else if (priv->kf_db_seen_bssids == kf_db) {
		prefix = "seen-bssids";
		p_id = &priv->kf_db_flush_idle_id_seen_bssids;
		idle_func = _kf_db_got_dirty_flush_seen_bssids_cb;
	} else {
		nm_assert_not_reached ();
		return;
	}

	if (*p_id != 0)
		return;
	_LOGT ("[%s-keyfile]: schedule flushing changes to disk", prefix);
	*p_id = g_idle_add_full (G_PRIORITY_LOW, idle_func, self, NULL);
}

void
nm_settings_kf_db_write (NMSettings *self)
{
	NMSettingsPrivate *priv;

	g_return_if_fail (NM_IS_SETTINGS (self));

	priv = NM_SETTINGS_GET_PRIVATE (self);
	if (priv->kf_db_timestamps)
		nm_key_file_db_to_file (priv->kf_db_timestamps, TRUE);
	if (priv->kf_db_seen_bssids)
		nm_key_file_db_to_file (priv->kf_db_seen_bssids, TRUE);
}

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

gboolean
nm_settings_start (NMSettings *self, GError **error)
{
	NMSettingsPrivate *priv;
	gs_strfreev char **plugins = NULL;
	GSList *iter;

	priv = NM_SETTINGS_GET_PRIVATE (self);

	nm_assert (!priv->started);

	priv->hostname_manager = g_object_ref (nm_hostname_manager_get ());

	priv->kf_db_timestamps = nm_key_file_db_new (NMSTATEDIR "/timestamps",
	                                             "timestamps",
	                                             _kf_db_log_fcn,
	                                             _kf_db_got_dirty_fcn,
	                                             self);
	priv->kf_db_seen_bssids = nm_key_file_db_new (NMSTATEDIR "/seen-bssids",
	                                              "seen-bssids",
	                                              _kf_db_log_fcn,
	                                              _kf_db_got_dirty_fcn,
	                                              self);
	nm_key_file_db_start (priv->kf_db_timestamps);
	nm_key_file_db_start (priv->kf_db_seen_bssids);

	/* Load the plugins; fail if a plugin is not found. */
	plugins = nm_config_data_get_plugins (nm_config_get_data_orig (priv->config), TRUE);

	if (!load_plugins (self, (const char *const*) plugins, error))
		return FALSE;

	for (iter = priv->plugins; iter; iter = iter->next) {
		NMSettingsPlugin *plugin = NM_SETTINGS_PLUGIN (iter->data);

		g_signal_connect (plugin, NM_SETTINGS_PLUGIN_UNMANAGED_SPECS_CHANGED,
		                  G_CALLBACK (_plugin_unmanaged_specs_changed), self);
		g_signal_connect (plugin, NM_SETTINGS_PLUGIN_UNRECOGNIZED_SPECS_CHANGED,
		                  G_CALLBACK (_plugin_unrecognized_specs_changed), self);
	}

	_plugin_unmanaged_specs_changed (NULL, self);
	_plugin_unrecognized_specs_changed (NULL, self);

	_plugin_connections_reload (self);

	g_signal_connect (priv->hostname_manager,
	                  "notify::"NM_HOSTNAME_MANAGER_HOSTNAME,
	                  G_CALLBACK (_hostname_changed_cb),
	                  self);
	if (nm_hostname_manager_get_hostname (priv->hostname_manager))
		_notify (self, PROP_HOSTNAME);

	priv->started = TRUE;
	_startup_complete_check (self, 0);

	/* FIXME(shutdown): we also need a nm_settings_stop() during shutdown.
	 *
	 * In particular, we need to remove all in-memory keyfiles from /run that are nm-generated.
	 * alternatively, the nm-generated flag must also be persisted and loaded to /run. */

	return TRUE;
}

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

static void
get_property (GObject *object, guint prop_id,
              GValue *value, GParamSpec *pspec)
{
	NMSettings *self = NM_SETTINGS (object);
	NMSettingsPrivate *priv = NM_SETTINGS_GET_PRIVATE (self);
	const char **strv;

	switch (prop_id) {
	case PROP_UNMANAGED_SPECS:
		g_value_take_boxed (value,
		                    _nm_utils_slist_to_strv (nm_settings_get_unmanaged_specs (self),
		                                             TRUE));
		break;
	case PROP_HOSTNAME:
		g_value_set_string (value,
		                      priv->hostname_manager
		                    ? nm_hostname_manager_get_hostname (priv->hostname_manager)
		                    : NULL);
		break;
	case PROP_CAN_MODIFY:
		g_value_set_boolean (value, TRUE);
		break;
	case PROP_CONNECTIONS:
		strv = nm_dbus_utils_get_paths_for_clist (&priv->connections_lst_head,
		                                          priv->connections_len,
		                                          G_STRUCT_OFFSET (NMSettingsConnection, _connections_lst),
		                                          TRUE);
		g_value_take_boxed (value, nm_utils_strv_make_deep_copied (strv));
		break;
	case PROP_STARTUP_COMPLETE:
		g_value_set_boolean (value, !nm_settings_get_startup_complete_blocked_reason (self));
		break;
	default:
		G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
		break;
	}
}

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

static void
nm_settings_init (NMSettings *self)
{
	NMSettingsPrivate *priv = NM_SETTINGS_GET_PRIVATE (self);

	c_list_init (&priv->auth_lst_head);
	c_list_init (&priv->connections_lst_head);

	c_list_init (&priv->sce_dirty_lst_head);
	priv->sce_idx = g_hash_table_new_full (nm_pstr_hash, nm_pstr_equal,
	                                       NULL, (GDestroyNotify) _sett_conn_entry_free);

	priv->config = g_object_ref (nm_config_get ());

	priv->agent_mgr = g_object_ref (nm_agent_manager_get ());

	priv->platform = g_object_ref (NM_PLATFORM_GET);

	priv->session_monitor = g_object_ref (nm_session_monitor_get ());
	g_signal_connect (priv->session_monitor,
	                  NM_SESSION_MONITOR_CHANGED,
	                  G_CALLBACK (session_monitor_changed_cb),
	                  self);
}

NMSettings *
nm_settings_new (void)
{
	return g_object_new (NM_TYPE_SETTINGS, NULL);
}

static void
dispose (GObject *object)
{
	NMSettings *self = NM_SETTINGS (object);
	NMSettingsPrivate *priv = NM_SETTINGS_GET_PRIVATE (self);
	CList *iter;

	nm_assert (c_list_is_empty (&priv->sce_dirty_lst_head));
	nm_assert (g_hash_table_size (priv->sce_idx) == 0);

	nm_clear_g_source (&priv->startup_complete_timeout_id);
	nm_clear_g_signal_handler (priv->platform, &priv->startup_complete_platform_change_id);
	nm_clear_pointer (&priv->startup_complete_idx, g_hash_table_destroy);
	g_clear_object (&priv->startup_complete_blocked_by);

	while ((iter = c_list_first (&priv->auth_lst_head)))
		nm_auth_chain_destroy (nm_auth_chain_parent_lst_entry (iter));

	if (priv->hostname_manager) {
		g_signal_handlers_disconnect_by_func (priv->hostname_manager,
		                                      G_CALLBACK (_hostname_changed_cb),
		                                      self);
		g_clear_object (&priv->hostname_manager);
	}

	if (priv->session_monitor) {
		g_signal_handlers_disconnect_by_func (priv->session_monitor,
		                                      G_CALLBACK (session_monitor_changed_cb),
		                                      self);
		g_clear_object (&priv->session_monitor);
	}

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

static void
finalize (GObject *object)
{
	NMSettings *self = NM_SETTINGS (object);
	NMSettingsPrivate *priv = NM_SETTINGS_GET_PRIVATE (self);
	GSList *iter;

	_clear_connections_cached_list (priv);

	nm_assert (c_list_is_empty (&priv->connections_lst_head));

	nm_assert (c_list_is_empty (&priv->sce_dirty_lst_head));
	nm_assert (g_hash_table_size (priv->sce_idx) == 0);

	nm_clear_pointer (&priv->sce_idx, g_hash_table_destroy);

	g_slist_free_full (priv->unmanaged_specs, g_free);
	g_slist_free_full (priv->unrecognized_specs, g_free);

	while ((iter = priv->plugins)) {
		gs_unref_object NMSettingsPlugin *plugin = iter->data;

		priv->plugins = g_slist_delete_link (priv->plugins, iter);
		g_signal_handlers_disconnect_by_data (plugin, self);
	}

	g_clear_object (&priv->keyfile_plugin);

	g_clear_object (&priv->agent_mgr);

	nm_clear_g_source (&priv->kf_db_flush_idle_id_timestamps);
	nm_clear_g_source (&priv->kf_db_flush_idle_id_seen_bssids);
	nm_key_file_db_to_file (priv->kf_db_timestamps, FALSE);
	nm_key_file_db_to_file (priv->kf_db_seen_bssids, FALSE);
	nm_key_file_db_destroy (priv->kf_db_timestamps);
	nm_key_file_db_destroy (priv->kf_db_seen_bssids);

	G_OBJECT_CLASS (nm_settings_parent_class)->finalize (object);

	g_clear_object (&priv->config);

	g_clear_object (&priv->platform);
}

static const GDBusSignalInfo signal_info_new_connection = NM_DEFINE_GDBUS_SIGNAL_INFO_INIT (
	"NewConnection",
	.args = NM_DEFINE_GDBUS_ARG_INFOS (
		NM_DEFINE_GDBUS_ARG_INFO ("connection", "o"),
	),
);

static const GDBusSignalInfo signal_info_connection_removed = NM_DEFINE_GDBUS_SIGNAL_INFO_INIT (
	"ConnectionRemoved",
	.args = NM_DEFINE_GDBUS_ARG_INFOS (
		NM_DEFINE_GDBUS_ARG_INFO ("connection", "o"),
	),
);

static const NMDBusInterfaceInfoExtended interface_info_settings = {
	.parent = NM_DEFINE_GDBUS_INTERFACE_INFO_INIT (
		NM_DBUS_INTERFACE_SETTINGS,
		.methods = NM_DEFINE_GDBUS_METHOD_INFOS (
			NM_DEFINE_DBUS_METHOD_INFO_EXTENDED (
				NM_DEFINE_GDBUS_METHOD_INFO_INIT (
					"ListConnections",
					.out_args = NM_DEFINE_GDBUS_ARG_INFOS (
						NM_DEFINE_GDBUS_ARG_INFO ("connections", "ao"),
					),
				),
				.handle = impl_settings_list_connections,
			),
			NM_DEFINE_DBUS_METHOD_INFO_EXTENDED (
				NM_DEFINE_GDBUS_METHOD_INFO_INIT (
					"GetConnectionByUuid",
					.in_args = NM_DEFINE_GDBUS_ARG_INFOS (
						NM_DEFINE_GDBUS_ARG_INFO ("uuid", "s"),
					),
					.out_args = NM_DEFINE_GDBUS_ARG_INFOS (
						NM_DEFINE_GDBUS_ARG_INFO ("connection", "o"),
					),
				),
				.handle = impl_settings_get_connection_by_uuid,
			),
			NM_DEFINE_DBUS_METHOD_INFO_EXTENDED (
				NM_DEFINE_GDBUS_METHOD_INFO_INIT (
					"AddConnection",
					.in_args = NM_DEFINE_GDBUS_ARG_INFOS (
						NM_DEFINE_GDBUS_ARG_INFO ("connection", "a{sa{sv}}"),
					),
					.out_args = NM_DEFINE_GDBUS_ARG_INFOS (
						NM_DEFINE_GDBUS_ARG_INFO ("path", "o"),
					),
				),
				.handle = impl_settings_add_connection,
			),
			NM_DEFINE_DBUS_METHOD_INFO_EXTENDED (
				NM_DEFINE_GDBUS_METHOD_INFO_INIT (
					"AddConnectionUnsaved",
					.in_args = NM_DEFINE_GDBUS_ARG_INFOS (
						NM_DEFINE_GDBUS_ARG_INFO ("connection", "a{sa{sv}}"),
					),
					.out_args = NM_DEFINE_GDBUS_ARG_INFOS (
						NM_DEFINE_GDBUS_ARG_INFO ("path", "o"),
					),
				),
				.handle = impl_settings_add_connection_unsaved,
			),
			NM_DEFINE_DBUS_METHOD_INFO_EXTENDED (
				NM_DEFINE_GDBUS_METHOD_INFO_INIT (
					"AddConnection2",
					.in_args = NM_DEFINE_GDBUS_ARG_INFOS (
						NM_DEFINE_GDBUS_ARG_INFO ("settings", "a{sa{sv}}"),
						NM_DEFINE_GDBUS_ARG_INFO ("flags",    "u"),
						NM_DEFINE_GDBUS_ARG_INFO ("args",     "a{sv}"),
					),
					.out_args = NM_DEFINE_GDBUS_ARG_INFOS (
						NM_DEFINE_GDBUS_ARG_INFO ("path", "o"),
						NM_DEFINE_GDBUS_ARG_INFO ("result", "a{sv}"),
					),
				),
				.handle = impl_settings_add_connection2,
			),
			NM_DEFINE_DBUS_METHOD_INFO_EXTENDED (
				NM_DEFINE_GDBUS_METHOD_INFO_INIT (
					"LoadConnections",
					.in_args = NM_DEFINE_GDBUS_ARG_INFOS (
						NM_DEFINE_GDBUS_ARG_INFO ("filenames", "as"),
					),
					.out_args = NM_DEFINE_GDBUS_ARG_INFOS (
						NM_DEFINE_GDBUS_ARG_INFO ("status", "b"),
						NM_DEFINE_GDBUS_ARG_INFO ("failures", "as"),
					),
				),
				.handle = impl_settings_load_connections,
			),
			NM_DEFINE_DBUS_METHOD_INFO_EXTENDED (
				NM_DEFINE_GDBUS_METHOD_INFO_INIT (
					"ReloadConnections",
					.out_args = NM_DEFINE_GDBUS_ARG_INFOS (
						NM_DEFINE_GDBUS_ARG_INFO ("status", "b"),
					),
				),
				.handle = impl_settings_reload_connections,
			),
			NM_DEFINE_DBUS_METHOD_INFO_EXTENDED (
				NM_DEFINE_GDBUS_METHOD_INFO_INIT (
					"SaveHostname",
					.in_args = NM_DEFINE_GDBUS_ARG_INFOS (
						NM_DEFINE_GDBUS_ARG_INFO ("hostname", "s"),
					),
				),
				.handle = impl_settings_save_hostname,
			),
		),
		.signals = NM_DEFINE_GDBUS_SIGNAL_INFOS (
			&nm_signal_info_property_changed_legacy,
			&signal_info_new_connection,
			&signal_info_connection_removed,
		),
		.properties = NM_DEFINE_GDBUS_PROPERTY_INFOS (
			NM_DEFINE_DBUS_PROPERTY_INFO_EXTENDED_READABLE_L ("Connections", "ao", NM_SETTINGS_CONNECTIONS),
			NM_DEFINE_DBUS_PROPERTY_INFO_EXTENDED_READABLE_L ("Hostname",    "s",  NM_SETTINGS_HOSTNAME),
			NM_DEFINE_DBUS_PROPERTY_INFO_EXTENDED_READABLE_L ("CanModify",   "b",  NM_SETTINGS_CAN_MODIFY),
		),
	),
	.legacy_property_changed = TRUE,
};

static void
nm_settings_class_init (NMSettingsClass *class)
{
	GObjectClass *object_class = G_OBJECT_CLASS (class);
	NMDBusObjectClass *dbus_object_class = NM_DBUS_OBJECT_CLASS (class);

	dbus_object_class->export_path = NM_DBUS_EXPORT_PATH_STATIC (NM_DBUS_PATH_SETTINGS);
	dbus_object_class->interface_infos = NM_DBUS_INTERFACE_INFOS (&interface_info_settings);

	object_class->get_property = get_property;
	object_class->dispose = dispose;
	object_class->finalize = finalize;

	obj_properties[PROP_UNMANAGED_SPECS] =
	    g_param_spec_boxed (NM_SETTINGS_UNMANAGED_SPECS, "", "",
	                        G_TYPE_STRV,
	                        G_PARAM_READABLE |
	                        G_PARAM_STATIC_STRINGS);

	obj_properties[PROP_HOSTNAME] =
	    g_param_spec_string (NM_SETTINGS_HOSTNAME, "", "",
	                         NULL,
	                         G_PARAM_READABLE |
	                         G_PARAM_STATIC_STRINGS);

	obj_properties[PROP_CAN_MODIFY] =
	    g_param_spec_boolean (NM_SETTINGS_CAN_MODIFY, "", "",
	                          FALSE,
	                          G_PARAM_READABLE |
	                          G_PARAM_STATIC_STRINGS);

	obj_properties[PROP_CONNECTIONS] =
	    g_param_spec_boxed (NM_SETTINGS_CONNECTIONS, "", "",
	                        G_TYPE_STRV,
	                        G_PARAM_READABLE |
	                        G_PARAM_STATIC_STRINGS);

	obj_properties[PROP_STARTUP_COMPLETE] =
	    g_param_spec_boolean (NM_SETTINGS_STARTUP_COMPLETE, "", "",
	                          FALSE,
	                          G_PARAM_READABLE |
	                          G_PARAM_STATIC_STRINGS);

	g_object_class_install_properties (object_class, _PROPERTY_ENUMS_LAST, obj_properties);

	signals[CONNECTION_ADDED] =
	    g_signal_new (NM_SETTINGS_SIGNAL_CONNECTION_ADDED,
	                  G_OBJECT_CLASS_TYPE (object_class),
	                  G_SIGNAL_RUN_FIRST,
	                  0, NULL, NULL,
	                  g_cclosure_marshal_VOID__OBJECT,
	                  G_TYPE_NONE, 1, NM_TYPE_SETTINGS_CONNECTION);

	signals[CONNECTION_UPDATED] =
	    g_signal_new (NM_SETTINGS_SIGNAL_CONNECTION_UPDATED,
	                  G_OBJECT_CLASS_TYPE (object_class),
	                  G_SIGNAL_RUN_FIRST,
	                  0, NULL, NULL,
	                  NULL,
	                  G_TYPE_NONE, 2, NM_TYPE_SETTINGS_CONNECTION, G_TYPE_UINT);

	signals[CONNECTION_REMOVED] =
	    g_signal_new (NM_SETTINGS_SIGNAL_CONNECTION_REMOVED,
	                  G_OBJECT_CLASS_TYPE (object_class),
	                  G_SIGNAL_RUN_FIRST,
	                  0, NULL, NULL,
	                  g_cclosure_marshal_VOID__OBJECT,
	                  G_TYPE_NONE, 1, NM_TYPE_SETTINGS_CONNECTION);

	signals[CONNECTION_FLAGS_CHANGED] =
	    g_signal_new (NM_SETTINGS_SIGNAL_CONNECTION_FLAGS_CHANGED,
	                  G_OBJECT_CLASS_TYPE (object_class),
	                  G_SIGNAL_RUN_FIRST,
	                  0, NULL, NULL,
	                  g_cclosure_marshal_VOID__OBJECT,
	                  G_TYPE_NONE, 1, NM_TYPE_SETTINGS_CONNECTION);
}