summaryrefslogtreecommitdiff
path: root/src/platform/tests/test-common.c
blob: a7fe59056725c7016677cbbb458c0af76847e6e7 (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
/* SPDX-License-Identifier: GPL-2.0+ */
/*
 * Copyright (C) 2016 - 2017 Red Hat, Inc.
 */

#include "nm-default.h"

#include <sys/mount.h>
#include <sched.h>
#include <sys/wait.h>
#include <fcntl.h>
#include <linux/if_tun.h>

#include "test-common.h"

#define SIGNAL_DATA_FMT "'%s-%s' ifindex %d%s%s%s (%d times received)"
#define SIGNAL_DATA_ARG(data)                                                                     \
    (data)->name, nm_platform_signal_change_type_to_string((data)->change_type), (data)->ifindex, \
        (data)->ifname ? " ifname '" : "", (data)->ifname ?: "", (data)->ifname ? "'" : "",       \
        (data)->received_count

int NMTSTP_ENV1_IFINDEX = -1;
int NMTSTP_ENV1_EX      = -1;

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

void
nmtstp_setup_platform(void)
{
    g_assert(_nmtstp_setup_platform_func);
    _nmtstp_setup_platform_func();
}

gboolean
nmtstp_is_root_test(void)
{
    g_assert(_nmtstp_setup_platform_func);
    return _nmtstp_setup_platform_func == nm_linux_platform_setup;
}

gboolean
nmtstp_is_sysfs_writable(void)
{
    return !nmtstp_is_root_test() || (access("/sys/devices", W_OK) == 0);
}

static void
_init_platform(NMPlatform **platform, gboolean external_command)
{
    g_assert(platform);
    if (!*platform)
        *platform = NM_PLATFORM_GET;
    g_assert(NM_IS_PLATFORM(*platform));

    if (external_command)
        g_assert(NM_IS_LINUX_PLATFORM(*platform));
}

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

static GArray *
_ipx_address_get_all(NMPlatform *self, int ifindex, NMPObjectType obj_type)
{
    NMPLookup lookup;

    g_assert(NM_IS_PLATFORM(self));
    g_assert(ifindex > 0);
    g_assert(NM_IN_SET(obj_type, NMP_OBJECT_TYPE_IP4_ADDRESS, NMP_OBJECT_TYPE_IP6_ADDRESS));
    nmp_lookup_init_object(&lookup, obj_type, ifindex);
    return nmp_cache_lookup_to_array(nm_platform_lookup(self, &lookup),
                                     obj_type,
                                     FALSE /*addresses are always visible. */);
}

GArray *
nmtstp_platform_ip4_address_get_all(NMPlatform *self, int ifindex)
{
    return _ipx_address_get_all(self, ifindex, NMP_OBJECT_TYPE_IP4_ADDRESS);
}

GArray *
nmtstp_platform_ip6_address_get_all(NMPlatform *self, int ifindex)
{
    return _ipx_address_get_all(self, ifindex, NMP_OBJECT_TYPE_IP6_ADDRESS);
}

const NMPlatformIPAddress *
nmtstp_platform_ip_address_find(NMPlatform *self, int ifindex, int addr_family, gconstpointer addr)
{
    const gboolean             IS_IPv4 = NM_IS_IPv4(addr_family);
    const NMPlatformIPAddress *found   = NULL;
    NMDedupMultiIter           iter;
    const NMPObject *          obj;
    NMPLookup                  lookup;

    g_assert(NM_IS_PLATFORM(self));
    nm_assert(ifindex >= 0);
    nm_assert_addr_family(addr_family);
    nm_assert(addr);

    nmp_lookup_init_object(&lookup, NMP_OBJECT_TYPE_IP_ADDRESS(IS_IPv4), ifindex);
    nm_platform_iter_obj_for_each (&iter, self, &lookup, &obj) {
        const NMPlatformIPAddress *a = NMP_OBJECT_CAST_IP_ADDRESS(obj);

        g_assert(NMP_OBJECT_GET_ADDR_FAMILY(obj) == addr_family);
        g_assert(ifindex <= 0 || a->ifindex == ifindex);

        if (memcmp(addr, a->address_ptr, nm_utils_addr_family_to_size(addr_family)) != 0)
            continue;

        g_assert(!found);
        found = a;
    }

    if (!IS_IPv4 && ifindex > 0)
        g_assert(found
                 == (const NMPlatformIPAddress *) nm_platform_ip6_address_get(self, ifindex, addr));

    return found;
}

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

typedef struct {
    NMIPAddr addr;
    int      addr_family;
    bool     found : 1;
} IPAddressesAssertData;

void
_nmtstp_platform_ip_addresses_assert(const char *       filename,
                                     int                lineno,
                                     NMPlatform *       self,
                                     int                ifindex,
                                     gboolean           force_exact_4,
                                     gboolean           force_exact_6,
                                     gboolean           ignore_ll6,
                                     guint              addrs_len,
                                     const char *const *addrs)
{
    gs_free IPAddressesAssertData *addrs_bin = NULL;
    int                            IS_IPv4;
    guint                          i;

    g_assert(filename);
    g_assert(lineno >= 0);
    g_assert(NM_IS_PLATFORM(self));
    g_assert(ifindex >= 0);

    addrs_bin = g_new(IPAddressesAssertData, addrs_len);

    for (i = 0; i < addrs_len; i++) {
        const char *addrstr = addrs[i];
        int         addr_family;
        NMIPAddr    a;

        if (!addrstr) {
            addr_family = AF_UNSPEC;
            a           = nm_ip_addr_zero;
        } else if (inet_pton(AF_INET, addrstr, &a) == 1)
            addr_family = AF_INET;
        else if (inet_pton(AF_INET6, addrstr, &a) == 1)
            addr_family = AF_INET6;
        else
            g_error("%s:%d: invalid IP address in argument: %s", filename, lineno, addrstr);

        addrs_bin[i] = (IPAddressesAssertData){
            .addr_family = addr_family,
            .addr        = a,
            .found       = FALSE,
        };
    }

    for (IS_IPv4 = 1; IS_IPv4 >= 0; IS_IPv4--) {
        const int         addr_family           = IS_IPv4 ? AF_INET : AF_INET6;
        gs_unref_ptrarray GPtrArray *plat_addrs = NULL;
        NMPLookup                    lookup;
        guint                        j;

        plat_addrs = nm_platform_lookup_clone(
            self,
            nmp_lookup_init_object(&lookup, NMP_OBJECT_TYPE_IP_ADDRESS(IS_IPv4), ifindex),
            NULL,
            NULL);

        for (i = 0; i < addrs_len; i++) {
            IPAddressesAssertData *addr_bin = &addrs_bin[i];

            if (addr_bin->addr_family != addr_family)
                continue;

            g_assert(!addr_bin->found);
            for (j = 0; j < nm_g_ptr_array_len(plat_addrs);) {
                const NMPlatformIPAddress *a = NMP_OBJECT_CAST_IP_ADDRESS(plat_addrs->pdata[j]);

                if (memcmp(&addr_bin->addr,
                           a->address_ptr,
                           nm_utils_addr_family_to_size(addr_family))
                    != 0) {
                    j++;
                    continue;
                }

                g_assert(!addr_bin->found);
                addr_bin->found = TRUE;
                g_ptr_array_remove_index_fast(plat_addrs, j);
            }

            if (!addr_bin->found) {
                char sbuf[NM_UTILS_INET_ADDRSTRLEN];

                g_error("%s:%d: IPv%c address %s was not found on ifindex %d",
                        filename,
                        lineno,
                        nm_utils_addr_family_to_char(addr_bin->addr_family),
                        nm_utils_inet_ntop(addr_bin->addr_family, &addr_bin->addr, sbuf),
                        ifindex);
            }
        }
        if (!IS_IPv4 && ignore_ll6 && nm_g_ptr_array_len(plat_addrs) > 0) {
            /* we prune all remaining, non-matching IPv6 link local addresses. */
            for (j = 0; j < nm_g_ptr_array_len(plat_addrs);) {
                const NMPlatformIPAddress *a = NMP_OBJECT_CAST_IP_ADDRESS(plat_addrs->pdata[j]);

                if (!IN6_IS_ADDR_LINKLOCAL(a->address_ptr)) {
                    j++;
                    continue;
                }

                g_ptr_array_remove_index_fast(plat_addrs, j);
            }
        }
        if ((IS_IPv4 ? force_exact_4 : force_exact_6) && nm_g_ptr_array_len(plat_addrs) > 0) {
            char sbuf[sizeof(_nm_utils_to_string_buffer)];

            g_error("%s:%d: %u IPv%c addresses found on ifindex %d that should not be there (one "
                    "is %s)",
                    filename,
                    lineno,
                    plat_addrs->len,
                    nm_utils_addr_family_to_char(addr_family),
                    ifindex,
                    nmp_object_to_string(plat_addrs->pdata[0],
                                         NMP_OBJECT_TO_STRING_PUBLIC,
                                         sbuf,
                                         sizeof(sbuf)));
        }
    }
}

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

gboolean
nmtstp_platform_ip4_route_delete(NMPlatform *platform,
                                 int         ifindex,
                                 in_addr_t   network,
                                 guint8      plen,
                                 guint32     metric)
{
    NMDedupMultiIter iter;

    nm_platform_process_events(platform);

    nm_dedup_multi_iter_for_each (
        &iter,
        nm_platform_lookup_object(platform, NMP_OBJECT_TYPE_IP4_ROUTE, ifindex)) {
        const NMPlatformIP4Route *r = NMP_OBJECT_CAST_IP4_ROUTE(iter.current->obj);

        if (r->ifindex != ifindex || r->network != network || r->plen != plen
            || r->metric != metric) {
            continue;
        }

        return nm_platform_object_delete(platform, NMP_OBJECT_UP_CAST(r));
    }

    return TRUE;
}

gboolean
nmtstp_platform_ip6_route_delete(NMPlatform *    platform,
                                 int             ifindex,
                                 struct in6_addr network,
                                 guint8          plen,
                                 guint32         metric)
{
    NMDedupMultiIter iter;

    nm_platform_process_events(platform);

    nm_dedup_multi_iter_for_each (
        &iter,
        nm_platform_lookup_object(platform, NMP_OBJECT_TYPE_IP6_ROUTE, ifindex)) {
        const NMPlatformIP6Route *r = NMP_OBJECT_CAST_IP6_ROUTE(iter.current->obj);

        if (r->ifindex != ifindex || !IN6_ARE_ADDR_EQUAL(&r->network, &network) || r->plen != plen
            || r->metric != metric) {
            continue;
        }

        return nm_platform_object_delete(platform, NMP_OBJECT_UP_CAST(r));
    }

    return TRUE;
}

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

SignalData *
add_signal_full(const char *               name,
                NMPlatformSignalChangeType change_type,
                GCallback                  callback,
                int                        ifindex,
                const char *               ifname)
{
    SignalData *data = g_new0(SignalData, 1);

    data->name           = name;
    data->change_type    = change_type;
    data->received_count = 0;
    data->handler_id     = g_signal_connect(NM_PLATFORM_GET, name, callback, data);
    data->ifindex        = ifindex;
    data->ifname         = ifname;

    g_assert(data->handler_id > 0);

    return data;
}

void
_accept_signal(const char *file, int line, const char *func, SignalData *data)
{
    _LOGD("NMPlatformSignalAssert: %s:%d, %s(): Accepting signal one time: " SIGNAL_DATA_FMT,
          file,
          line,
          func,
          SIGNAL_DATA_ARG(data));
    if (data->received_count != 1)
        g_error("NMPlatformSignalAssert: %s:%d, %s(): failure to accept signal one "
                "time: " SIGNAL_DATA_FMT,
                file,
                line,
                func,
                SIGNAL_DATA_ARG(data));
    data->received_count = 0;
}

void
_accept_signals(const char *file, int line, const char *func, SignalData *data, int min, int max)
{
    _LOGD("NMPlatformSignalAssert: %s:%d, %s(): Accepting signal [%d,%d] times: " SIGNAL_DATA_FMT,
          file,
          line,
          func,
          min,
          max,
          SIGNAL_DATA_ARG(data));
    if (data->received_count < min || data->received_count > max)
        g_error("NMPlatformSignalAssert: %s:%d, %s(): failure to accept signal [%d,%d] "
                "times: " SIGNAL_DATA_FMT,
                file,
                line,
                func,
                min,
                max,
                SIGNAL_DATA_ARG(data));
    data->received_count = 0;
}

void
_ensure_no_signal(const char *file, int line, const char *func, SignalData *data)
{
    _LOGD("NMPlatformSignalAssert: %s:%d, %s(): Accepting signal 0 times: " SIGNAL_DATA_FMT,
          file,
          line,
          func,
          SIGNAL_DATA_ARG(data));
    if (data->received_count > 0)
        g_error("NMPlatformSignalAssert: %s:%d, %s(): failure to accept signal 0 "
                "times: " SIGNAL_DATA_FMT,
                file,
                line,
                func,
                SIGNAL_DATA_ARG(data));
}

void
_accept_or_wait_signal(const char *file, int line, const char *func, SignalData *data)
{
    _LOGD("NMPlatformSignalAssert: %s:%d, %s(): accept-or-wait signal: " SIGNAL_DATA_FMT,
          file,
          line,
          func,
          SIGNAL_DATA_ARG(data));
    if (data->received_count == 0) {
        data->loop = g_main_loop_new(NULL, FALSE);
        g_main_loop_run(data->loop);
        nm_clear_pointer(&data->loop, g_main_loop_unref);
    }

    _accept_signal(file, line, func, data);
}

void
_wait_signal(const char *file, int line, const char *func, SignalData *data)
{
    _LOGD("NMPlatformSignalAssert: %s:%d, %s(): wait signal: " SIGNAL_DATA_FMT,
          file,
          line,
          func,
          SIGNAL_DATA_ARG(data));
    if (data->received_count)
        g_error("NMPlatformSignalAssert: %s:%d, %s(): failure to wait for signal: " SIGNAL_DATA_FMT,
                file,
                line,
                func,
                SIGNAL_DATA_ARG(data));

    data->loop = g_main_loop_new(NULL, FALSE);
    g_main_loop_run(data->loop);
    nm_clear_pointer(&data->loop, g_main_loop_unref);

    _accept_signal(file, line, func, data);
}

void
_free_signal(const char *file, int line, const char *func, SignalData *data)
{
    _LOGD("NMPlatformSignalAssert: %s:%d, %s(): free signal: " SIGNAL_DATA_FMT,
          file,
          line,
          func,
          SIGNAL_DATA_ARG(data));
    if (data->received_count != 0)
        g_error("NMPlatformSignalAssert: %s:%d, %s(): failure to free non-accepted "
                "signal: " SIGNAL_DATA_FMT,
                file,
                line,
                func,
                SIGNAL_DATA_ARG(data));

    g_signal_handler_disconnect(NM_PLATFORM_GET, data->handler_id);
    g_free(data);
}

void
link_callback(NMPlatform *    platform,
              int             obj_type_i,
              int             ifindex,
              NMPlatformLink *received,
              int             change_type_i,
              SignalData *    data)
{
    const NMPObjectType              obj_type    = obj_type_i;
    const NMPlatformSignalChangeType change_type = change_type_i;
    NMPLookup                        lookup;
    NMDedupMultiIter                 iter;
    const NMPlatformLink *           cached;

    g_assert_cmpint(obj_type, ==, NMP_OBJECT_TYPE_LINK);
    g_assert(received);
    g_assert_cmpint(received->ifindex, ==, ifindex);
    g_assert(data && data->name);
    g_assert_cmpstr(data->name, ==, NM_PLATFORM_SIGNAL_LINK_CHANGED);

    if (data->ifindex && data->ifindex != received->ifindex)
        return;
    if (data->ifname
        && g_strcmp0(data->ifname, nm_platform_link_get_name(NM_PLATFORM_GET, ifindex)) != 0)
        return;
    if (change_type != data->change_type)
        return;

    if (data->loop) {
        _LOGD("Quitting main loop.");
        g_main_loop_quit(data->loop);
    }

    data->received_count++;
    _LOGD("Received signal '%s-%s' ifindex %d ifname '%s' %dth time.",
          data->name,
          nm_platform_signal_change_type_to_string(data->change_type),
          ifindex,
          received->name,
          data->received_count);

    if (change_type == NM_PLATFORM_SIGNAL_REMOVED)
        g_assert(!nm_platform_link_get_name(NM_PLATFORM_GET, ifindex));
    else
        g_assert(nm_platform_link_get_name(NM_PLATFORM_GET, ifindex));

    /* Check the data */
    g_assert(received->ifindex > 0);

    nmp_lookup_init_obj_type(&lookup, NMP_OBJECT_TYPE_LINK);
    nmp_cache_iter_for_each_link (&iter, nm_platform_lookup(platform, &lookup), &cached) {
        if (!nmp_object_is_visible(NMP_OBJECT_UP_CAST(cached)))
            continue;
        if (cached->ifindex == received->ifindex) {
            g_assert_cmpint(nm_platform_link_cmp(cached, received), ==, 0);
            g_assert(!memcmp(cached, received, sizeof(*cached)));
            if (data->change_type == NM_PLATFORM_SIGNAL_REMOVED)
                g_error("Deleted link still found in the local cache.");
            return;
        }
    }

    if (data->change_type != NM_PLATFORM_SIGNAL_REMOVED)
        g_error("Added/changed link not found in the local cache.");
}

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

static const NMPlatformIP4Route *
_ip4_route_get(NMPlatform *platform,
               int         ifindex,
               guint32     network,
               int         plen,
               guint32     metric,
               guint8      tos,
               guint *     out_c_exists)
{
    NMDedupMultiIter          iter;
    NMPLookup                 lookup;
    const NMPObject *         o = NULL;
    guint                     c;
    const NMPlatformIP4Route *r = NULL;

    _init_platform(&platform, FALSE);

    nmp_lookup_init_ip4_route_by_weak_id(&lookup, network, plen, metric, tos);

    c = 0;
    nmp_cache_iter_for_each (&iter, nm_platform_lookup(platform, &lookup), &o) {
        if (NMP_OBJECT_CAST_IP4_ROUTE(o)->ifindex != ifindex && ifindex > 0)
            continue;
        if (!r)
            r = NMP_OBJECT_CAST_IP4_ROUTE(o);
        c++;
    }

    NM_SET_OUT(out_c_exists, c);
    return r;
}

const NMPlatformIP4Route *
_nmtstp_assert_ip4_route_exists(const char *file,
                                guint       line,
                                const char *func,
                                NMPlatform *platform,
                                int         c_exists,
                                const char *ifname,
                                guint32     network,
                                int         plen,
                                guint32     metric,
                                guint8      tos)
{
    int                       ifindex;
    guint                     c;
    const NMPlatformIP4Route *r = NULL;

    _init_platform(&platform, FALSE);

    ifindex = -1;
    if (ifname) {
        ifindex = nm_platform_link_get_ifindex(platform, ifname);
        g_assert(ifindex > 0);
    }

    r = _ip4_route_get(platform, ifindex, network, plen, metric, tos, &c);

    if (c != c_exists && c_exists != -1) {
        char sbuf[NM_UTILS_INET_ADDRSTRLEN];

        g_error("[%s:%u] %s(): The ip4 route %s/%d metric %u tos %u shall exist %u times, but "
                "platform has it %u times",
                file,
                line,
                func,
                _nm_utils_inet4_ntop(network, sbuf),
                plen,
                metric,
                tos,
                c_exists,
                c);
    }

    return r;
}

const NMPlatformIP4Route *
nmtstp_ip4_route_get(NMPlatform *platform,
                     int         ifindex,
                     guint32     network,
                     int         plen,
                     guint32     metric,
                     guint8      tos)
{
    return _ip4_route_get(platform, ifindex, network, plen, metric, tos, NULL);
}

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

static const NMPlatformIP6Route *
_ip6_route_get(NMPlatform *           platform,
               int                    ifindex,
               const struct in6_addr *network,
               guint                  plen,
               guint32                metric,
               const struct in6_addr *src,
               guint8                 src_plen,
               guint *                out_c_exists)
{
    NMDedupMultiIter          iter;
    NMPLookup                 lookup;
    const NMPObject *         o = NULL;
    guint                     c;
    const NMPlatformIP6Route *r = NULL;

    _init_platform(&platform, FALSE);

    nmp_lookup_init_ip6_route_by_weak_id(&lookup, network, plen, metric, src, src_plen);

    c = 0;
    nmp_cache_iter_for_each (&iter, nm_platform_lookup(platform, &lookup), &o) {
        if (NMP_OBJECT_CAST_IP6_ROUTE(o)->ifindex != ifindex && ifindex > 0)
            continue;
        if (!r)
            r = NMP_OBJECT_CAST_IP6_ROUTE(o);
        c++;
    }

    NM_SET_OUT(out_c_exists, c);
    return r;
}

const NMPlatformIP6Route *
_nmtstp_assert_ip6_route_exists(const char *           file,
                                guint                  line,
                                const char *           func,
                                NMPlatform *           platform,
                                int                    c_exists,
                                const char *           ifname,
                                const struct in6_addr *network,
                                guint                  plen,
                                guint32                metric,
                                const struct in6_addr *src,
                                guint8                 src_plen)
{
    int                       ifindex;
    guint                     c;
    const NMPlatformIP6Route *r = NULL;

    _init_platform(&platform, FALSE);

    ifindex = -1;
    if (ifname) {
        ifindex = nm_platform_link_get_ifindex(platform, ifname);
        g_assert(ifindex > 0);
    }

    r = _ip6_route_get(platform, ifindex, network, plen, metric, src, src_plen, &c);

    if (c != c_exists && c_exists != -1) {
        char s_src[NM_UTILS_INET_ADDRSTRLEN];
        char s_network[NM_UTILS_INET_ADDRSTRLEN];

        g_error("[%s:%u] %s(): The ip6 route %s/%d metric %u src %s/%d shall exist %u times, but "
                "platform has it %u times",
                file,
                line,
                func,
                _nm_utils_inet6_ntop(network, s_network),
                plen,
                metric,
                _nm_utils_inet6_ntop(src, s_src),
                src_plen,
                c_exists,
                c);
    }

    return r;
}

const NMPlatformIP6Route *
nmtstp_ip6_route_get(NMPlatform *           platform,
                     int                    ifindex,
                     const struct in6_addr *network,
                     guint                  plen,
                     guint32                metric,
                     const struct in6_addr *src,
                     guint8                 src_plen)
{
    return _ip6_route_get(platform, ifindex, network, plen, metric, src, src_plen, NULL);
}

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

int
nmtstp_run_command(const char *format, ...)
{
    int           result;
    gs_free char *command = NULL;
    va_list       ap;

    va_start(ap, format);
    command = g_strdup_vprintf(format, ap);
    va_end(ap);

    _LOGD("Running command: %s", command);
    result = system(command);
    _LOGD("Command finished: result=%d", result);

    return result;
}

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

typedef struct {
    GMainLoop *loop;
    guint      signal_counts;
    guint      id;
} WaitForSignalData;

static void
_wait_for_signal_cb(NMPlatform *    platform,
                    int             obj_type_i,
                    int             ifindex,
                    NMPlatformLink *plink,
                    int             change_type_i,
                    gpointer        user_data)
{
    WaitForSignalData *data = user_data;

    data->signal_counts++;
    nm_clear_g_source(&data->id);
    g_main_loop_quit(data->loop);
}

static gboolean
_wait_for_signal_timeout(gpointer user_data)
{
    WaitForSignalData *data = user_data;

    g_assert(data->id);
    data->id = 0;
    g_main_loop_quit(data->loop);
    return G_SOURCE_REMOVE;
}

guint
nmtstp_wait_for_signal(NMPlatform *platform, gint64 timeout_msec)
{
    WaitForSignalData data = {0};
    gulong            id_link, id_ip4_address, id_ip6_address, id_ip4_route, id_ip6_route;
    gulong            id_qdisc, id_tfilter;

    _init_platform(&platform, FALSE);

    data.loop = g_main_loop_new(NULL, FALSE);

    id_link        = g_signal_connect(platform,
                               NM_PLATFORM_SIGNAL_LINK_CHANGED,
                               G_CALLBACK(_wait_for_signal_cb),
                               &data);
    id_ip4_address = g_signal_connect(platform,
                                      NM_PLATFORM_SIGNAL_IP4_ADDRESS_CHANGED,
                                      G_CALLBACK(_wait_for_signal_cb),
                                      &data);
    id_ip6_address = g_signal_connect(platform,
                                      NM_PLATFORM_SIGNAL_IP6_ADDRESS_CHANGED,
                                      G_CALLBACK(_wait_for_signal_cb),
                                      &data);
    id_ip4_route   = g_signal_connect(platform,
                                    NM_PLATFORM_SIGNAL_IP4_ROUTE_CHANGED,
                                    G_CALLBACK(_wait_for_signal_cb),
                                    &data);
    id_ip6_route   = g_signal_connect(platform,
                                    NM_PLATFORM_SIGNAL_IP6_ROUTE_CHANGED,
                                    G_CALLBACK(_wait_for_signal_cb),
                                    &data);
    id_qdisc       = g_signal_connect(platform,
                                NM_PLATFORM_SIGNAL_QDISC_CHANGED,
                                G_CALLBACK(_wait_for_signal_cb),
                                &data);
    id_tfilter     = g_signal_connect(platform,
                                  NM_PLATFORM_SIGNAL_TFILTER_CHANGED,
                                  G_CALLBACK(_wait_for_signal_cb),
                                  &data);

    /* if timeout_msec is negative, it means the wait-time already expired.
     * Maybe, we should do nothing and return right away, without even
     * processing events from platform. However, that inconsistency (of not
     * processing events from mainloop) is inconvenient.
     *
     * It's better that on the return of nmtstp_wait_for_signal(), we always
     * have no events pending. So, a negative timeout is treated the same as
     * a zero timeout: we check whether there are any events pending in platform,
     * and quite the mainloop immediately afterwards. But we always check. */

    data.id = g_timeout_add(CLAMP(timeout_msec, 0, G_MAXUINT32), _wait_for_signal_timeout, &data);

    g_main_loop_run(data.loop);

    g_assert(!data.id);
    g_assert(nm_clear_g_signal_handler(platform, &id_link));
    g_assert(nm_clear_g_signal_handler(platform, &id_ip4_address));
    g_assert(nm_clear_g_signal_handler(platform, &id_ip6_address));
    g_assert(nm_clear_g_signal_handler(platform, &id_ip4_route));
    g_assert(nm_clear_g_signal_handler(platform, &id_ip6_route));
    g_assert(nm_clear_g_signal_handler(platform, &id_tfilter));
    g_assert(nm_clear_g_signal_handler(platform, &id_qdisc));

    nm_clear_pointer(&data.loop, g_main_loop_unref);

    /* return the number of signals, or 0 if timeout was reached .*/
    return data.signal_counts;
}

guint
nmtstp_wait_for_signal_until(NMPlatform *platform, gint64 until_ms)
{
    gint64 now;
    guint  signal_counts;

    while (TRUE) {
        now = nm_utils_get_monotonic_timestamp_msec();

        if (until_ms < now)
            return 0;

        signal_counts = nmtstp_wait_for_signal(platform, until_ms - now);
        if (signal_counts)
            return signal_counts;
    }
}

const NMPlatformLink *
nmtstp_wait_for_link(NMPlatform *platform,
                     const char *ifname,
                     NMLinkType  expected_link_type,
                     gint64      timeout_msec)
{
    return nmtstp_wait_for_link_until(
        platform,
        ifname,
        expected_link_type,
        timeout_msec ? nm_utils_get_monotonic_timestamp_msec() + timeout_msec : 0);
}

const NMPlatformLink *
nmtstp_wait_for_link_until(NMPlatform *platform,
                           const char *ifname,
                           NMLinkType  expected_link_type,
                           gint64      until_ms)
{
    const NMPlatformLink *plink;
    gint64                now;
    gboolean              waited_once = FALSE;

    _init_platform(&platform, FALSE);

    while (TRUE) {
        now = nm_utils_get_monotonic_timestamp_msec();

        plink = nm_platform_link_get_by_ifname(platform, ifname);
        if (plink && (expected_link_type == NM_LINK_TYPE_NONE || plink->type == expected_link_type))
            return plink;

        if (until_ms == 0) {
            /* don't wait, don't even poll the socket. */
            return NULL;
        }

        if (waited_once && until_ms < now) {
            /* timeout reached (+ we already waited for a signal at least once). */
            return NULL;
        }

        waited_once = TRUE;
        /* regardless of whether timeout is already reached, we poll the netlink
         * socket a bit. */
        nmtstp_wait_for_signal(platform, until_ms - now);
    }
}

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

int
nmtstp_run_command_check_external_global(void)
{
    if (!nmtstp_is_root_test())
        return FALSE;
    switch (nmtst_get_rand_uint32() % 3) {
    case 0:
        return -1;
    case 1:
        return FALSE;
    default:
        return TRUE;
    }
}

gboolean
nmtstp_run_command_check_external(int external_command)
{
    if (external_command != -1) {
        g_assert(NM_IN_SET(external_command, FALSE, TRUE));
        g_assert(!external_command || nmtstp_is_root_test());
        return !!external_command;
    }
    if (!nmtstp_is_root_test())
        return FALSE;
    return (nmtst_get_rand_uint32() % 2) == 0;
}

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

#define CHECK_LIFETIME_MAX_DIFF 2

gboolean
nmtstp_ip_address_check_lifetime(const NMPlatformIPAddress *addr,
                                 gint64                     now,
                                 guint32                    expected_lifetime,
                                 guint32                    expected_preferred)
{
    gint64 offset;
    int    i;

    g_assert(addr);

    if (now == -1)
        now = nm_utils_get_monotonic_timestamp_sec();
    g_assert(now > 0);

    g_assert(expected_preferred <= expected_lifetime);

    if (expected_lifetime == NM_PLATFORM_LIFETIME_PERMANENT
        && expected_preferred == NM_PLATFORM_LIFETIME_PERMANENT) {
        return addr->timestamp == 0 && addr->lifetime == NM_PLATFORM_LIFETIME_PERMANENT
               && addr->preferred == NM_PLATFORM_LIFETIME_PERMANENT;
    }

    if (addr->timestamp == 0)
        return FALSE;

    offset = (gint64) now - addr->timestamp;

    for (i = 0; i < 2; i++) {
        guint32 lft = i ? expected_lifetime : expected_preferred;
        guint32 adr = i ? addr->lifetime : addr->preferred;

        if (lft == NM_PLATFORM_LIFETIME_PERMANENT) {
            if (adr != NM_PLATFORM_LIFETIME_PERMANENT)
                return FALSE;
        } else {
            if (((gint64) adr) - offset <= ((gint64) lft) - CHECK_LIFETIME_MAX_DIFF
                || ((gint64) adr) - offset >= ((gint64) lft) + CHECK_LIFETIME_MAX_DIFF)
                return FALSE;
        }
    }
    return TRUE;
}

void
nmtstp_ip_address_assert_lifetime(const NMPlatformIPAddress *addr,
                                  gint64                     now,
                                  guint32                    expected_lifetime,
                                  guint32                    expected_preferred)
{
    gint64 n = now;
    gint64 offset;
    int    i;

    g_assert(addr);

    if (now == -1)
        now = nm_utils_get_monotonic_timestamp_sec();
    g_assert(now > 0);

    g_assert(expected_preferred <= expected_lifetime);

    if (expected_lifetime == NM_PLATFORM_LIFETIME_PERMANENT
        && expected_preferred == NM_PLATFORM_LIFETIME_PERMANENT) {
        g_assert_cmpint(addr->timestamp, ==, 0);
        g_assert_cmpint(addr->lifetime, ==, NM_PLATFORM_LIFETIME_PERMANENT);
        g_assert_cmpint(addr->preferred, ==, NM_PLATFORM_LIFETIME_PERMANENT);
        return;
    }

    g_assert_cmpint(addr->timestamp, >, 0);
    g_assert_cmpint(addr->timestamp, <=, now);

    offset = (gint64) now - addr->timestamp;
    g_assert_cmpint(offset, >=, 0);

    for (i = 0; i < 2; i++) {
        guint32 lft = i ? expected_lifetime : expected_preferred;
        guint32 adr = i ? addr->lifetime : addr->preferred;

        if (lft == NM_PLATFORM_LIFETIME_PERMANENT)
            g_assert_cmpint(adr, ==, NM_PLATFORM_LIFETIME_PERMANENT);
        else {
            g_assert_cmpint(adr - offset, <=, lft + CHECK_LIFETIME_MAX_DIFF);
            g_assert_cmpint(adr - offset, >=, lft - CHECK_LIFETIME_MAX_DIFF);
        }
    }

    g_assert(nmtstp_ip_address_check_lifetime(addr, n, expected_lifetime, expected_preferred));
}

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

static void
_ip_address_add(NMPlatform *    platform,
                gboolean        external_command,
                gboolean        is_v4,
                int             ifindex,
                const NMIPAddr *address,
                int             plen,
                const NMIPAddr *peer_address,
                guint32         lifetime,
                guint32         preferred,
                guint32         flags,
                const char *    label)
{
    gint64 end_time;

    external_command = nmtstp_run_command_check_external(external_command);

    _init_platform(&platform, external_command);

    if (external_command) {
        const char *  ifname;
        gs_free char *s_valid     = NULL;
        gs_free char *s_preferred = NULL;
        gs_free char *s_label     = NULL;
        char          b1[NM_UTILS_INET_ADDRSTRLEN];
        char          b2[NM_UTILS_INET_ADDRSTRLEN];

        ifname = nm_platform_link_get_name(platform, ifindex);
        g_assert(ifname);

        if (lifetime != NM_PLATFORM_LIFETIME_PERMANENT)
            s_valid = g_strdup_printf(" valid_lft %d", lifetime);
        if (preferred != NM_PLATFORM_LIFETIME_PERMANENT)
            s_preferred = g_strdup_printf(" preferred_lft %d", preferred);
        if (label)
            s_label = g_strdup_printf("%s:%s", ifname, label);

        if (is_v4) {
            char s_peer[NM_UTILS_INET_ADDRSTRLEN + 50];

            g_assert(flags == 0);

            if (peer_address->addr4 != address->addr4 || nmtst_get_rand_uint32() % 2) {
                /* If the peer is the same as the local address, we can omit it. The result should be identical */
                nm_sprintf_buf(s_peer, " peer %s", _nm_utils_inet4_ntop(peer_address->addr4, b2));
            } else
                s_peer[0] = '\0';

            nmtstp_run_command_check("ip address change %s%s/%d dev %s%s%s%s",
                                     _nm_utils_inet4_ntop(address->addr4, b1),
                                     s_peer,
                                     plen,
                                     ifname,
                                     s_valid ?: "",
                                     s_preferred ?: "",
                                     s_label ?: "");
        } else {
            g_assert(label == NULL);

            /* flags not implemented (yet) */
            g_assert(flags == 0);
            nmtstp_run_command_check("ip address change %s%s%s/%d dev %s%s%s%s",
                                     _nm_utils_inet6_ntop(&address->addr6, b1),
                                     !IN6_IS_ADDR_UNSPECIFIED(&peer_address->addr6) ? " peer " : "",
                                     !IN6_IS_ADDR_UNSPECIFIED(&peer_address->addr6)
                                         ? _nm_utils_inet6_ntop(&peer_address->addr6, b2)
                                         : "",
                                     plen,
                                     ifname,
                                     s_valid ?: "",
                                     s_preferred ?: "",
                                     s_label ?: "");
        }
    } else {
        gboolean success;

        if (is_v4) {
            success = nm_platform_ip4_address_add(platform,
                                                  ifindex,
                                                  address->addr4,
                                                  plen,
                                                  peer_address->addr4,
                                                  0u,
                                                  lifetime,
                                                  preferred,
                                                  flags,
                                                  label);
        } else {
            g_assert(label == NULL);
            success = nm_platform_ip6_address_add(platform,
                                                  ifindex,
                                                  address->addr6,
                                                  plen,
                                                  peer_address->addr6,
                                                  lifetime,
                                                  preferred,
                                                  flags);
        }
        g_assert(success);
    }

    /* Let's wait until we see the address. */
    end_time = nm_utils_get_monotonic_timestamp_msec() + 500;
    do {
        if (external_command)
            nm_platform_process_events(platform);

        /* let's wait until we see the address as we added it. */
        if (is_v4) {
            const NMPlatformIP4Address *a;

            g_assert(flags == 0);
            a = nm_platform_ip4_address_get(platform,
                                            ifindex,
                                            address->addr4,
                                            plen,
                                            peer_address->addr4);
            if (a && a->peer_address == peer_address->addr4
                && nmtstp_ip_address_check_lifetime((NMPlatformIPAddress *) a,
                                                    -1,
                                                    lifetime,
                                                    preferred)
                && strcmp(a->label, label ?: "") == 0)
                break;
        } else {
            const NMPlatformIP6Address *a;

            g_assert(label == NULL);
            g_assert(flags == 0);

            a = nm_platform_ip6_address_get(platform, ifindex, &address->addr6);
            if (a
                && !memcmp(nm_platform_ip6_address_get_peer(a),
                           (IN6_IS_ADDR_UNSPECIFIED(&peer_address->addr6)
                            || IN6_ARE_ADDR_EQUAL(&address->addr6, &peer_address->addr6))
                               ? &address->addr6
                               : &peer_address->addr6,
                           sizeof(struct in6_addr))
                && nmtstp_ip_address_check_lifetime((NMPlatformIPAddress *) a,
                                                    -1,
                                                    lifetime,
                                                    preferred))
                break;
        }

        /* for internal command, we expect not to reach this line.*/
        g_assert(external_command);

        nmtstp_assert_wait_for_signal_until(platform, end_time);
    } while (TRUE);
}

void
nmtstp_ip4_address_add(NMPlatform *platform,
                       gboolean    external_command,
                       int         ifindex,
                       in_addr_t   address,
                       int         plen,
                       in_addr_t   peer_address,
                       guint32     lifetime,
                       guint32     preferred,
                       guint32     flags,
                       const char *label)
{
    _ip_address_add(platform,
                    external_command,
                    TRUE,
                    ifindex,
                    (NMIPAddr *) &address,
                    plen,
                    (NMIPAddr *) &peer_address,
                    lifetime,
                    preferred,
                    flags,
                    label);
}

void
nmtstp_ip6_address_add(NMPlatform *    platform,
                       gboolean        external_command,
                       int             ifindex,
                       struct in6_addr address,
                       int             plen,
                       struct in6_addr peer_address,
                       guint32         lifetime,
                       guint32         preferred,
                       guint32         flags)
{
    _ip_address_add(platform,
                    external_command,
                    FALSE,
                    ifindex,
                    (NMIPAddr *) &address,
                    plen,
                    (NMIPAddr *) &peer_address,
                    lifetime,
                    preferred,
                    flags,
                    NULL);
}

void
nmtstp_ip4_route_add(NMPlatform *     platform,
                     int              ifindex,
                     NMIPConfigSource source,
                     in_addr_t        network,
                     guint8           plen,
                     in_addr_t        gateway,
                     in_addr_t        pref_src,
                     guint32          metric,
                     guint32          mss)
{
    NMPlatformIP4Route route = {};

    route.ifindex   = ifindex;
    route.rt_source = source;
    route.network   = network;
    route.plen      = plen;
    route.gateway   = gateway;
    route.pref_src  = pref_src;
    route.metric    = metric;
    route.mss       = mss;

    g_assert(
        NMTST_NM_ERR_SUCCESS(nm_platform_ip4_route_add(platform, NMP_NLM_FLAG_REPLACE, &route)));
}

void
nmtstp_ip6_route_add(NMPlatform *     platform,
                     int              ifindex,
                     NMIPConfigSource source,
                     struct in6_addr  network,
                     guint8           plen,
                     struct in6_addr  gateway,
                     struct in6_addr  pref_src,
                     guint32          metric,
                     guint32          mss)
{
    NMPlatformIP6Route route = {};

    route.ifindex   = ifindex;
    route.rt_source = source;
    route.network   = network;
    route.plen      = plen;
    route.gateway   = gateway;
    route.pref_src  = pref_src;
    route.metric    = metric;
    route.mss       = mss;

    g_assert(
        NMTST_NM_ERR_SUCCESS(nm_platform_ip6_route_add(platform, NMP_NLM_FLAG_REPLACE, &route)));
}

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

static void
_ip_address_del(NMPlatform *    platform,
                gboolean        external_command,
                gboolean        is_v4,
                int             ifindex,
                const NMIPAddr *address,
                int             plen,
                const NMIPAddr *peer_address)
{
    gint64 end_time;

    external_command = nmtstp_run_command_check_external(external_command);

    _init_platform(&platform, external_command);

    if (external_command) {
        const char *ifname;
        char        b1[NM_UTILS_INET_ADDRSTRLEN];
        char        b2[NM_UTILS_INET_ADDRSTRLEN];
        int         success;
        gboolean    had_address;

        ifname = nm_platform_link_get_name(platform, ifindex);
        g_assert(ifname);

        /* let's wait until we see the address as we added it. */
        if (is_v4)
            had_address = !!nm_platform_ip4_address_get(platform,
                                                        ifindex,
                                                        address->addr4,
                                                        plen,
                                                        peer_address->addr4);
        else
            had_address = !!nm_platform_ip6_address_get(platform, ifindex, &address->addr6);

        if (is_v4) {
            success = nmtstp_run_command("ip address delete %s%s%s/%d dev %s",
                                         _nm_utils_inet4_ntop(address->addr4, b1),
                                         peer_address->addr4 != address->addr4 ? " peer " : "",
                                         peer_address->addr4 != address->addr4
                                             ? _nm_utils_inet4_ntop(peer_address->addr4, b2)
                                             : "",
                                         plen,
                                         ifname);
        } else {
            g_assert(!peer_address);
            success = nmtstp_run_command("ip address delete %s/%d dev %s",
                                         _nm_utils_inet6_ntop(&address->addr6, b1),
                                         plen,
                                         ifname);
        }
        g_assert(success == 0 || !had_address);
    } else {
        gboolean success;

        if (is_v4) {
            success = nm_platform_ip4_address_delete(platform,
                                                     ifindex,
                                                     address->addr4,
                                                     plen,
                                                     peer_address->addr4);
        } else {
            g_assert(!peer_address);
            success = nm_platform_ip6_address_delete(platform, ifindex, address->addr6, plen);
        }
        g_assert(success);
    }

    /* Let's wait until we get the result */
    end_time = nm_utils_get_monotonic_timestamp_msec() + 250;
    do {
        if (external_command)
            nm_platform_process_events(platform);

        /* let's wait until we see the address as we added it. */
        if (is_v4) {
            const NMPlatformIP4Address *a;

            a = nm_platform_ip4_address_get(platform,
                                            ifindex,
                                            address->addr4,
                                            plen,
                                            peer_address->addr4);
            if (!a)
                break;
        } else {
            const NMPlatformIP6Address *a;

            a = nm_platform_ip6_address_get(platform, ifindex, &address->addr6);
            if (!a)
                break;
        }

        /* for internal command, we expect not to reach this line.*/
        g_assert(external_command);

        nmtstp_assert_wait_for_signal_until(platform, end_time);
    } while (TRUE);
}

void
nmtstp_ip4_address_del(NMPlatform *platform,
                       gboolean    external_command,
                       int         ifindex,
                       in_addr_t   address,
                       int         plen,
                       in_addr_t   peer_address)
{
    _ip_address_del(platform,
                    external_command,
                    TRUE,
                    ifindex,
                    (NMIPAddr *) &address,
                    plen,
                    (NMIPAddr *) &peer_address);
}

void
nmtstp_ip6_address_del(NMPlatform *    platform,
                       gboolean        external_command,
                       int             ifindex,
                       struct in6_addr address,
                       int             plen)
{
    _ip_address_del(platform, external_command, FALSE, ifindex, (NMIPAddr *) &address, plen, NULL);
}

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

#define _assert_pllink(platform, success, pllink, name, type)                               \
    G_STMT_START                                                                            \
    {                                                                                       \
        const NMPlatformLink *_pllink = (pllink);                                           \
                                                                                            \
        if ((success)) {                                                                    \
            g_assert(_pllink);                                                              \
            g_assert(_pllink                                                                \
                     == nmtstp_link_get_typed(platform, _pllink->ifindex, (name), (type))); \
        } else {                                                                            \
            g_assert(!_pllink);                                                             \
            g_assert(!nmtstp_link_get(platform, 0, (name)));                                \
        }                                                                                   \
    }                                                                                       \
    G_STMT_END

const NMPlatformLink *
nmtstp_link_bridge_add(NMPlatform *               platform,
                       gboolean                   external_command,
                       const char *               name,
                       const NMPlatformLnkBridge *lnk)
{
    const NMPlatformLink *     pllink = NULL;
    const NMPlatformLnkBridge *ll     = NULL;
    int                        r      = 0;

    g_assert(nm_utils_ifname_valid_kernel(name, NULL));

    external_command = nmtstp_run_command_check_external(external_command);

    _init_platform(&platform, external_command);

    if (external_command) {
        char sbuf_gfw[100];
        char sbuf_mhm[100];
        char sbuf_mlmc[100];
        char sbuf_mlmi[100];
        char sbuf_mmi[100];
        char sbuf_mqi[100];
        char sbuf_mqii[100];
        char sbuf_msqc[100];
        char sbuf_msqi[100];
        char sbuf_mqri[100];

        r = nmtstp_run_command(
            "ip link add %s type bridge "
            "forward_delay %u "
            "hello_time %u "
            "max_age %u "
            "ageing_time %u "
            "stp_state %d "
            "priority %u "
            "vlan_protocol %u "
            "vlan_stats_enabled %d "
            "%s" /* group_fwd_mask */
            "group_address " NM_ETHER_ADDR_FORMAT_STR " "
            "mcast_snooping %d "
            "mcast_router %u "
            "mcast_query_use_ifaddr %d "
            "mcast_querier %d "
            "%s" /* mcast_hash_max */
            "%s" /* mcast_last_member_count */
            "%s" /* mcast_startup_query_count */
            "%s" /* mcast_last_member_interval */
            "%s" /* mcast_membership_interval */
            "%s" /* mcast_querier_interval */
            "%s" /* mcast_query_interval */
            "%s" /* mcast_query_response_interval */
            "%s" /* mcast_startup_query_interval */
            "",
            name,
            lnk->forward_delay,
            lnk->hello_time,
            lnk->max_age,
            lnk->ageing_time,
            (int) lnk->stp_state,
            lnk->priority,
            lnk->vlan_protocol,
            (int) lnk->vlan_stats_enabled,
            lnk->group_fwd_mask != 0
                ? nm_sprintf_buf(sbuf_gfw, "group_fwd_mask %#x ", lnk->group_fwd_mask)
                : "",
            NM_ETHER_ADDR_FORMAT_VAL(&lnk->group_addr),
            (int) lnk->mcast_snooping,
            lnk->mcast_router,
            (int) lnk->mcast_query_use_ifaddr,
            (int) lnk->mcast_querier,
            lnk->mcast_hash_max != NM_BRIDGE_MULTICAST_HASH_MAX_DEF
                ? nm_sprintf_buf(sbuf_mhm, "mcast_hash_max %u ", lnk->mcast_hash_max)
                : "",
            lnk->mcast_last_member_count != NM_BRIDGE_MULTICAST_LAST_MEMBER_COUNT_DEF
                ? nm_sprintf_buf(sbuf_mlmc,
                                 "mcast_last_member_count %u ",
                                 lnk->mcast_last_member_count)
                : "",
            lnk->mcast_startup_query_count != NM_BRIDGE_MULTICAST_STARTUP_QUERY_COUNT_DEF
                ? nm_sprintf_buf(sbuf_msqc,
                                 "mcast_startup_query_count %u ",
                                 lnk->mcast_startup_query_count)
                : "",
            lnk->mcast_last_member_interval != NM_BRIDGE_MULTICAST_LAST_MEMBER_INTERVAL_DEF
                ? nm_sprintf_buf(sbuf_mlmi,
                                 "mcast_last_member_interval %" G_GUINT64_FORMAT " ",
                                 lnk->mcast_last_member_interval)
                : "",
            lnk->mcast_membership_interval != NM_BRIDGE_MULTICAST_MEMBERSHIP_INTERVAL_DEF
                ? nm_sprintf_buf(sbuf_mmi,
                                 "mcast_membership_interval %" G_GUINT64_FORMAT " ",
                                 lnk->mcast_membership_interval)
                : "",
            lnk->mcast_querier_interval != NM_BRIDGE_MULTICAST_QUERIER_INTERVAL_DEF
                ? nm_sprintf_buf(sbuf_mqi,
                                 "mcast_querier_interval %" G_GUINT64_FORMAT " ",
                                 lnk->mcast_querier_interval)
                : "",
            lnk->mcast_query_interval != NM_BRIDGE_MULTICAST_QUERY_INTERVAL_DEF
                ? nm_sprintf_buf(sbuf_mqii,
                                 "mcast_query_interval %" G_GUINT64_FORMAT " ",
                                 lnk->mcast_query_interval)
                : "",
            lnk->mcast_query_response_interval != NM_BRIDGE_MULTICAST_QUERY_RESPONSE_INTERVAL_DEF
                ? nm_sprintf_buf(sbuf_mqri,
                                 "mcast_query_response_interval %" G_GUINT64_FORMAT " ",
                                 lnk->mcast_query_response_interval)
                : "",
            lnk->mcast_startup_query_interval != NM_BRIDGE_MULTICAST_STARTUP_QUERY_INTERVAL_DEF
                ? nm_sprintf_buf(sbuf_msqi,
                                 "mcast_startup_query_interval %" G_GUINT64_FORMAT " ",
                                 lnk->mcast_startup_query_interval)
                : "");
        if (r == 0)
            pllink = nmtstp_assert_wait_for_link(platform, name, NM_LINK_TYPE_BRIDGE, 100);
        else
            _LOGI(
                "Adding bridge device via iproute2 failed. Assume iproute2 is not up to the task.");
    }

    if (!pllink) {
        r = nm_platform_link_bridge_add(platform, name, NULL, 0, lnk, &pllink);
    }

    _assert_pllink(platform, r == 0, pllink, name, NM_LINK_TYPE_BRIDGE);

    ll = NMP_OBJECT_CAST_LNK_BRIDGE(NMP_OBJECT_UP_CAST(pllink)->_link.netlink.lnk);

    g_assert_cmpint(lnk->forward_delay, ==, ll->forward_delay);
    g_assert_cmpint(lnk->hello_time, ==, ll->hello_time);
    g_assert_cmpint(lnk->max_age, ==, ll->max_age);
    g_assert_cmpint(lnk->ageing_time, ==, ll->ageing_time);
    g_assert_cmpint(lnk->stp_state, ==, ll->stp_state);
    g_assert_cmpint(lnk->priority, ==, ll->priority);
    g_assert_cmpint(lnk->vlan_stats_enabled, ==, ll->vlan_stats_enabled);
    g_assert_cmpint(lnk->group_fwd_mask, ==, ll->group_fwd_mask);
    g_assert_cmpint(lnk->mcast_snooping, ==, ll->mcast_snooping);
    g_assert_cmpint(lnk->mcast_router, ==, ll->mcast_router);
    g_assert_cmpint(lnk->mcast_query_use_ifaddr, ==, ll->mcast_query_use_ifaddr);
    g_assert_cmpint(lnk->mcast_querier, ==, ll->mcast_querier);
    g_assert_cmpint(lnk->mcast_hash_max, ==, ll->mcast_hash_max);
    g_assert_cmpint(lnk->mcast_last_member_count, ==, ll->mcast_last_member_count);
    g_assert_cmpint(lnk->mcast_startup_query_count, ==, ll->mcast_startup_query_count);
    g_assert_cmpint(lnk->mcast_last_member_interval, ==, ll->mcast_last_member_interval);
    g_assert_cmpint(lnk->mcast_membership_interval, ==, ll->mcast_membership_interval);
    g_assert_cmpint(lnk->mcast_querier_interval, ==, ll->mcast_querier_interval);
    g_assert_cmpint(lnk->mcast_query_interval, ==, ll->mcast_query_interval);
    g_assert_cmpint(lnk->mcast_query_response_interval, ==, ll->mcast_query_response_interval);
    g_assert_cmpint(lnk->mcast_startup_query_interval, ==, ll->mcast_startup_query_interval);

    return pllink;
}
const NMPlatformLink *
nmtstp_link_veth_add(NMPlatform *platform,
                     gboolean    external_command,
                     const char *name,
                     const char *peer)
{
    const NMPlatformLink *pllink = NULL;
    gboolean              success;

    g_assert(nm_utils_ifname_valid_kernel(name, NULL));

    external_command = nmtstp_run_command_check_external(external_command);

    _init_platform(&platform, external_command);

    if (external_command) {
        success = !nmtstp_run_command("ip link add dev %s type veth peer name %s", name, peer);
        if (success) {
            pllink = nmtstp_assert_wait_for_link(platform, name, NM_LINK_TYPE_VETH, 100);
            nmtstp_assert_wait_for_link(platform, peer, NM_LINK_TYPE_VETH, 10);
        }
    } else
        success = NMTST_NM_ERR_SUCCESS(nm_platform_link_veth_add(platform, name, peer, &pllink));

    g_assert(success);
    _assert_pllink(platform, success, pllink, name, NM_LINK_TYPE_VETH);
    return pllink;
}

const NMPlatformLink *
nmtstp_link_dummy_add(NMPlatform *platform, gboolean external_command, const char *name)
{
    const NMPlatformLink *pllink = NULL;
    gboolean              success;

    g_assert(nm_utils_ifname_valid_kernel(name, NULL));

    external_command = nmtstp_run_command_check_external(external_command);

    _init_platform(&platform, external_command);

    if (external_command) {
        success = !nmtstp_run_command("ip link add %s type dummy", name);
        if (success)
            pllink = nmtstp_assert_wait_for_link(platform, name, NM_LINK_TYPE_DUMMY, 100);
    } else
        success = NMTST_NM_ERR_SUCCESS(nm_platform_link_dummy_add(platform, name, &pllink));

    g_assert(success);
    _assert_pllink(platform, success, pllink, name, NM_LINK_TYPE_DUMMY);
    return pllink;
}

const NMPlatformLink *
nmtstp_link_gre_add(NMPlatform *            platform,
                    gboolean                external_command,
                    const char *            name,
                    const NMPlatformLnkGre *lnk)
{
    const NMPlatformLink *pllink = NULL;
    gboolean              success;
    char                  b1[INET_ADDRSTRLEN];
    char                  b2[INET_ADDRSTRLEN];
    NMLinkType            link_type;

    g_assert(nm_utils_ifname_valid_kernel(name, NULL));

    external_command = nmtstp_run_command_check_external(external_command);
    link_type        = lnk->is_tap ? NM_LINK_TYPE_GRETAP : NM_LINK_TYPE_GRE;

    _init_platform(&platform, external_command);

    if (external_command) {
        gs_free char *dev = NULL;
        char *        obj, *type;

        if (lnk->parent_ifindex)
            dev =
                g_strdup_printf("dev %s", nm_platform_link_get_name(platform, lnk->parent_ifindex));

        obj  = lnk->is_tap ? "link" : "tunnel";
        type = lnk->is_tap ? "type gretap" : "mode gre";

        success = !nmtstp_run_command("ip %s add %s %s %s local %s remote %s ttl %u tos %02x %s",
                                      obj,
                                      name,
                                      type,
                                      dev ?: "",
                                      _nm_utils_inet4_ntop(lnk->local, b1),
                                      _nm_utils_inet4_ntop(lnk->remote, b2),
                                      lnk->ttl,
                                      lnk->tos,
                                      lnk->path_mtu_discovery ? "pmtudisc" : "nopmtudisc");
        if (success)
            pllink = nmtstp_assert_wait_for_link(platform, name, link_type, 100);
    } else
        success =
            NMTST_NM_ERR_SUCCESS(nm_platform_link_gre_add(platform, name, NULL, 0, lnk, &pllink));

    _assert_pllink(platform, success, pllink, name, link_type);

    return pllink;
}

const NMPlatformLink *
nmtstp_link_ip6tnl_add(NMPlatform *               platform,
                       gboolean                   external_command,
                       const char *               name,
                       const NMPlatformLnkIp6Tnl *lnk)
{
    const NMPlatformLink *pllink = NULL;
    gboolean              success;
    char                  b1[NM_UTILS_INET_ADDRSTRLEN];
    char                  b2[NM_UTILS_INET_ADDRSTRLEN];
    char                  encap[20];
    char                  tclass[20];
    gboolean              encap_ignore;
    gboolean              tclass_inherit;

    g_assert(nm_utils_ifname_valid_kernel(name, NULL));
    g_assert(!lnk->is_gre);

    external_command = nmtstp_run_command_check_external(external_command);

    _init_platform(&platform, external_command);

    if (external_command) {
        gs_free char *dev = NULL;
        const char *  mode;

        if (lnk->parent_ifindex)
            dev =
                g_strdup_printf("dev %s", nm_platform_link_get_name(platform, lnk->parent_ifindex));

        switch (lnk->proto) {
        case IPPROTO_IPIP:
            mode = "ipip6";
            break;
        case IPPROTO_IPV6:
            mode = "ip6ip6";
            break;
        default:
            g_assert_not_reached();
        }

        encap_ignore   = NM_FLAGS_HAS(lnk->flags, IP6_TNL_F_IGN_ENCAP_LIMIT);
        tclass_inherit = NM_FLAGS_HAS(lnk->flags, IP6_TNL_F_USE_ORIG_TCLASS);

        success = !nmtstp_run_command(
            "ip -6 tunnel add %s mode %s %s local %s remote %s ttl %u tclass %s encaplimit %s "
            "flowlabel %x",
            name,
            mode,
            dev,
            _nm_utils_inet6_ntop(&lnk->local, b1),
            _nm_utils_inet6_ntop(&lnk->remote, b2),
            lnk->ttl,
            tclass_inherit ? "inherit" : nm_sprintf_buf(tclass, "%02x", lnk->tclass),
            encap_ignore ? "none" : nm_sprintf_buf(encap, "%u", lnk->encap_limit),
            lnk->flow_label);
        if (success)
            pllink = nmtstp_assert_wait_for_link(platform, name, NM_LINK_TYPE_IP6TNL, 100);
    } else
        success = NMTST_NM_ERR_SUCCESS(nm_platform_link_ip6tnl_add(platform, name, lnk, &pllink));

    _assert_pllink(platform, success, pllink, name, NM_LINK_TYPE_IP6TNL);

    return pllink;
}

const NMPlatformLink *
nmtstp_link_ip6gre_add(NMPlatform *               platform,
                       gboolean                   external_command,
                       const char *               name,
                       const NMPlatformLnkIp6Tnl *lnk)
{
    const NMPlatformLink *pllink = NULL;
    gboolean              success;
    char                  b1[NM_UTILS_INET_ADDRSTRLEN];
    char                  b2[NM_UTILS_INET_ADDRSTRLEN];
    char                  tclass[20];
    gboolean              tclass_inherit;

    g_assert(nm_utils_ifname_valid_kernel(name, NULL));
    g_assert(lnk->is_gre);

    external_command = nmtstp_run_command_check_external(external_command);

    _init_platform(&platform, external_command);

    if (external_command) {
        gs_free char *dev = NULL;

        if (lnk->parent_ifindex)
            dev =
                g_strdup_printf("dev %s", nm_platform_link_get_name(platform, lnk->parent_ifindex));

        tclass_inherit = NM_FLAGS_HAS(lnk->flags, IP6_TNL_F_USE_ORIG_TCLASS);

        success = !nmtstp_run_command(
            "ip link add %s type %s %s local %s remote %s ttl %u tclass %s flowlabel %x",
            name,
            lnk->is_tap ? "ip6gretap" : "ip6gre",
            dev,
            _nm_utils_inet6_ntop(&lnk->local, b1),
            _nm_utils_inet6_ntop(&lnk->remote, b2),
            lnk->ttl,
            tclass_inherit ? "inherit" : nm_sprintf_buf(tclass, "%02x", lnk->tclass),
            lnk->flow_label);
        if (success) {
            pllink = nmtstp_assert_wait_for_link(platform,
                                                 name,
                                                 lnk->is_tap ? NM_LINK_TYPE_IP6GRETAP
                                                             : NM_LINK_TYPE_IP6GRE,
                                                 100);
        }
    } else
        success = NMTST_NM_ERR_SUCCESS(
            nm_platform_link_ip6gre_add(platform, name, NULL, 0, lnk, &pllink));

    _assert_pllink(platform,
                   success,
                   pllink,
                   name,
                   lnk->is_tap ? NM_LINK_TYPE_IP6GRETAP : NM_LINK_TYPE_IP6GRE);

    return pllink;
}

const NMPlatformLink *
nmtstp_link_ipip_add(NMPlatform *             platform,
                     gboolean                 external_command,
                     const char *             name,
                     const NMPlatformLnkIpIp *lnk)
{
    const NMPlatformLink *pllink = NULL;
    gboolean              success;
    char                  b1[INET_ADDRSTRLEN];
    char                  b2[INET_ADDRSTRLEN];

    g_assert(nm_utils_ifname_valid_kernel(name, NULL));

    external_command = nmtstp_run_command_check_external(external_command);

    _init_platform(&platform, external_command);

    if (external_command) {
        gs_free char *dev = NULL;

        if (lnk->parent_ifindex)
            dev =
                g_strdup_printf("dev %s", nm_platform_link_get_name(platform, lnk->parent_ifindex));

        success = !nmtstp_run_command(
            "ip tunnel add %s mode ipip %s local %s remote %s ttl %u tos %02x %s",
            name,
            dev,
            _nm_utils_inet4_ntop(lnk->local, b1),
            _nm_utils_inet4_ntop(lnk->remote, b2),
            lnk->ttl,
            lnk->tos,
            lnk->path_mtu_discovery ? "pmtudisc" : "nopmtudisc");
        if (success)
            pllink = nmtstp_assert_wait_for_link(platform, name, NM_LINK_TYPE_IPIP, 100);
    } else
        success = NMTST_NM_ERR_SUCCESS(nm_platform_link_ipip_add(platform, name, lnk, &pllink));

    _assert_pllink(platform, success, pllink, name, NM_LINK_TYPE_IPIP);

    return pllink;
}

const NMPlatformLink *
nmtstp_link_macvlan_add(NMPlatform *                platform,
                        gboolean                    external_command,
                        const char *                name,
                        int                         parent,
                        const NMPlatformLnkMacvlan *lnk)
{
    const NMPlatformLink *pllink = NULL;
    gboolean              success;
    NMLinkType            link_type;

    g_assert(nm_utils_ifname_valid_kernel(name, NULL));

    external_command = nmtstp_run_command_check_external(external_command);

    _init_platform(&platform, external_command);

    link_type = lnk->tap ? NM_LINK_TYPE_MACVTAP : NM_LINK_TYPE_MACVLAN;

    if (external_command) {
        const char *dev;
        char *      modes[] = {
            [MACVLAN_MODE_BRIDGE]   = "bridge",
            [MACVLAN_MODE_VEPA]     = "vepa",
            [MACVLAN_MODE_PRIVATE]  = "private",
            [MACVLAN_MODE_PASSTHRU] = "passthru",
        };

        dev = nm_platform_link_get_name(platform, parent);
        g_assert(dev);
        g_assert_cmpint(lnk->mode, <, G_N_ELEMENTS(modes));

        success = !nmtstp_run_command("ip link add name %s link %s type %s mode %s %s",
                                      name,
                                      dev,
                                      lnk->tap ? "macvtap" : "macvlan",
                                      modes[lnk->mode],
                                      lnk->no_promisc ? "nopromisc" : "");
        if (success)
            pllink = nmtstp_assert_wait_for_link(platform, name, link_type, 100);
    } else
        success = NMTST_NM_ERR_SUCCESS(
            nm_platform_link_macvlan_add(platform, name, parent, lnk, &pllink));

    _assert_pllink(platform, success, pllink, name, link_type);

    return pllink;
}

const NMPlatformLink *
nmtstp_link_sit_add(NMPlatform *            platform,
                    gboolean                external_command,
                    const char *            name,
                    const NMPlatformLnkSit *lnk)
{
    const NMPlatformLink *pllink = NULL;
    gboolean              success;
    char                  b1[INET_ADDRSTRLEN];
    char                  b2[INET_ADDRSTRLEN];

    g_assert(nm_utils_ifname_valid_kernel(name, NULL));

    external_command = nmtstp_run_command_check_external(external_command);

    _init_platform(&platform, external_command);

    if (external_command) {
        const char *dev = "";

        if (lnk->parent_ifindex) {
            const char *parent_name;

            parent_name = nm_platform_link_get_name(platform, lnk->parent_ifindex);
            g_assert(parent_name);
            dev = nm_sprintf_bufa(100, " dev %s", parent_name);
        }

        success =
            !nmtstp_run_command("ip tunnel add %s mode sit%s local %s remote %s ttl %u tos %02x %s",
                                name,
                                dev,
                                _nm_utils_inet4_ntop(lnk->local, b1),
                                _nm_utils_inet4_ntop(lnk->remote, b2),
                                lnk->ttl,
                                lnk->tos,
                                lnk->path_mtu_discovery ? "pmtudisc" : "nopmtudisc");
        if (success)
            pllink = nmtstp_assert_wait_for_link(platform, name, NM_LINK_TYPE_SIT, 100);
    } else
        success = NMTST_NM_ERR_SUCCESS(nm_platform_link_sit_add(platform, name, lnk, &pllink));

    _assert_pllink(platform, success, pllink, name, NM_LINK_TYPE_SIT);

    return pllink;
}

const NMPlatformLink *
nmtstp_link_tun_add(NMPlatform *            platform,
                    gboolean                external_command,
                    const char *            name,
                    const NMPlatformLnkTun *lnk,
                    int *                   out_fd)
{
    const NMPlatformLink *pllink = NULL;
    int                   err;
    int                   r;

    g_assert(nm_utils_ifname_valid_kernel(name, NULL));
    g_assert(lnk);
    g_assert(NM_IN_SET(lnk->type, IFF_TUN, IFF_TAP));
    g_assert(!out_fd || *out_fd == -1);

    if (!lnk->persist) {
        /* ip tuntap does not support non-persistent devices.
         *
         * Add this device only via NMPlatform. */
        if (external_command == -1)
            external_command = FALSE;
    }

    external_command = nmtstp_run_command_check_external(external_command);

    _init_platform(&platform, external_command);

    if (external_command) {
        g_assert(lnk->persist);

        err = nmtstp_run_command(
            "ip tuntap add"
            " mode %s"
            "%s" /* user */
            "%s" /* group */
            "%s" /* pi */
            "%s" /* vnet_hdr */
            "%s" /* multi_queue */
            " name %s",
            lnk->type == IFF_TUN ? "tun" : "tap",
            lnk->owner_valid ? nm_sprintf_bufa(100, " user %u", (guint) lnk->owner) : "",
            lnk->group_valid ? nm_sprintf_bufa(100, " group %u", (guint) lnk->group) : "",
            lnk->pi ? " pi" : "",
            lnk->vnet_hdr ? " vnet_hdr" : "",
            lnk->multi_queue ? " multi_queue" : "",
            name);
        /* Older versions of iproute2 don't support adding  devices.
         * On failure, fallback to using platform code. */
        if (err == 0)
            pllink = nmtstp_assert_wait_for_link(platform, name, NM_LINK_TYPE_TUN, 100);
        else
            g_error("failure to add tun/tap device via ip-route");
    } else {
        g_assert(lnk->persist || out_fd);
        r = nm_platform_link_tun_add(platform, name, lnk, &pllink, out_fd);
        g_assert_cmpint(r, ==, 0);
    }

    g_assert(pllink);
    g_assert_cmpint(pllink->type, ==, NM_LINK_TYPE_TUN);
    g_assert_cmpstr(pllink->name, ==, name);
    return pllink;
}

const NMPlatformLink *
nmtstp_link_vrf_add(NMPlatform *            platform,
                    gboolean                external_command,
                    const char *            name,
                    const NMPlatformLnkVrf *lnk,
                    gboolean *              out_not_supported)
{
    const NMPlatformLink *pllink = NULL;
    int                   r      = 0;

    g_assert(nm_utils_ifname_valid_kernel(name, NULL));

    NM_SET_OUT(out_not_supported, FALSE);
    external_command = nmtstp_run_command_check_external(external_command);

    _init_platform(&platform, external_command);

    if (external_command) {
        r = nmtstp_run_command("ip link add %s type vrf table %u", name, lnk->table);

        if (r == 0)
            pllink = nmtstp_assert_wait_for_link(platform, name, NM_LINK_TYPE_VRF, 100);
        else
            _LOGI("Adding vrf device via iproute2 failed. Assume iproute2 is not up to the task.");
    }

    if (!pllink) {
        r = nm_platform_link_vrf_add(platform, name, lnk, &pllink);
        if (r == -EOPNOTSUPP)
            NM_SET_OUT(out_not_supported, TRUE);
    }

    _assert_pllink(platform, r == 0, pllink, name, NM_LINK_TYPE_VRF);

    return pllink;
}

const NMPlatformLink *
nmtstp_link_vxlan_add(NMPlatform *              platform,
                      gboolean                  external_command,
                      const char *              name,
                      const NMPlatformLnkVxlan *lnk)
{
    const NMPlatformLink *pllink = NULL;
    int                   err;
    int                   r;

    g_assert(nm_utils_ifname_valid_kernel(name, NULL));

    external_command = nmtstp_run_command_check_external(external_command);

    _init_platform(&platform, external_command);

    if (external_command) {
        gs_free char *dev = NULL;
        char          local[NM_UTILS_INET_ADDRSTRLEN];
        char          group[NM_UTILS_INET_ADDRSTRLEN];

        if (lnk->parent_ifindex)
            dev =
                g_strdup_printf("dev %s", nm_platform_link_get_name(platform, lnk->parent_ifindex));

        if (lnk->local)
            _nm_utils_inet4_ntop(lnk->local, local);
        else if (memcmp(&lnk->local6, &in6addr_any, sizeof(in6addr_any)))
            _nm_utils_inet6_ntop(&lnk->local6, local);
        else
            local[0] = '\0';

        if (lnk->group)
            _nm_utils_inet4_ntop(lnk->group, group);
        else if (memcmp(&lnk->group6, &in6addr_any, sizeof(in6addr_any)))
            _nm_utils_inet6_ntop(&lnk->group6, group);
        else
            group[0] = '\0';

        err = nmtstp_run_command("ip link add %s type vxlan id %u %s local %s group %s ttl %u tos "
                                 "%02x dstport %u srcport %u %u ageing %u",
                                 name,
                                 lnk->id,
                                 dev ?: "",
                                 local,
                                 group,
                                 lnk->ttl,
                                 lnk->tos,
                                 lnk->dst_port,
                                 lnk->src_port_min,
                                 lnk->src_port_max,
                                 lnk->ageing);
        /* Older versions of iproute2 don't support adding vxlan devices.
         * On failure, fallback to using platform code. */
        if (err == 0)
            pllink = nmtstp_assert_wait_for_link(platform, name, NM_LINK_TYPE_VXLAN, 100);
        else
            _LOGI(
                "Adding vxlan device via iproute2 failed. Assume iproute2 is not up to the task.");
    }
    if (!pllink) {
        r = nm_platform_link_vxlan_add(platform, name, lnk, &pllink);
        g_assert(NMTST_NM_ERR_SUCCESS(r));
        g_assert(pllink);
    }

    g_assert_cmpint(pllink->type, ==, NM_LINK_TYPE_VXLAN);
    g_assert_cmpstr(pllink->name, ==, name);
    return pllink;
}

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

const NMPlatformLink *
nmtstp_link_get_typed(NMPlatform *platform, int ifindex, const char *name, NMLinkType link_type)
{
    const NMPlatformLink *pllink = NULL;

    _init_platform(&platform, FALSE);

    if (ifindex > 0) {
        pllink = nm_platform_link_get(platform, ifindex);

        if (pllink) {
            g_assert_cmpint(pllink->ifindex, ==, ifindex);
            if (name)
                g_assert_cmpstr(name, ==, pllink->name);
        } else {
            if (name)
                g_assert(!nm_platform_link_get_by_ifname(platform, name));
        }
    } else {
        g_assert(name);

        pllink = nm_platform_link_get_by_ifname(platform, name);

        if (pllink)
            g_assert_cmpstr(name, ==, pllink->name);
    }

    g_assert(!name || nm_utils_ifname_valid_kernel(name, NULL));

    if (pllink && link_type != NM_LINK_TYPE_NONE)
        g_assert_cmpint(pllink->type, ==, link_type);

    return pllink;
}

const NMPlatformLink *
nmtstp_link_get(NMPlatform *platform, int ifindex, const char *name)
{
    return nmtstp_link_get_typed(platform, ifindex, name, NM_LINK_TYPE_NONE);
}

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

void
nmtstp_link_delete(NMPlatform *platform,
                   gboolean    external_command,
                   int         ifindex,
                   const char *name,
                   gboolean    require_exist)
{
    gint64                end_time;
    const NMPlatformLink *pllink;
    gboolean              success;
    gs_free char *        name_copy = NULL;

    external_command = nmtstp_run_command_check_external(external_command);

    _init_platform(&platform, external_command);

    pllink = nmtstp_link_get(platform, ifindex, name);

    if (!pllink) {
        g_assert(!require_exist);
        return;
    }

    name = name_copy = g_strdup(pllink->name);
    ifindex          = pllink->ifindex;

    if (external_command) {
        nmtstp_run_command_check("ip link delete %s", name);
    } else {
        success = nm_platform_link_delete(platform, ifindex);
        g_assert(success);
    }

    /* Let's wait until we get the result */
    end_time = nm_utils_get_monotonic_timestamp_msec() + 250;
    do {
        if (external_command)
            nm_platform_process_events(platform);

        if (!nm_platform_link_get(platform, ifindex)) {
            g_assert(!nm_platform_link_get_by_ifname(platform, name));
            break;
        }

        /* for internal command, we expect not to reach this line.*/
        g_assert(external_command);

        nmtstp_assert_wait_for_signal_until(platform, end_time);
    } while (TRUE);
}

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

void
nmtstp_link_set_updown(NMPlatform *platform, gboolean external_command, int ifindex, gboolean up)
{
    const NMPlatformLink *plink;
    gint64                end_time;

    external_command = nmtstp_run_command_check_external(external_command);

    _init_platform(&platform, external_command);

    if (external_command) {
        const char *ifname;

        ifname = nm_platform_link_get_name(platform, ifindex);
        g_assert(ifname);

        nmtstp_run_command_check("ip link set %s %s", ifname, up ? "up" : "down");
    } else {
        if (up)
            g_assert(nm_platform_link_set_up(platform, ifindex, NULL));
        else
            g_assert(nm_platform_link_set_down(platform, ifindex));
    }

    /* Let's wait until we get the result */
    end_time = nm_utils_get_monotonic_timestamp_msec() + 250;
    do {
        if (external_command)
            nm_platform_process_events(platform);

        /* let's wait until we see the address as we added it. */
        plink = nm_platform_link_get(platform, ifindex);
        g_assert(plink);

        if (NM_FLAGS_HAS(plink->n_ifi_flags, IFF_UP) == !!up)
            break;

        /* for internal command, we expect not to reach this line.*/
        g_assert(external_command);

        nmtstp_assert_wait_for_signal_until(platform, end_time);
    } while (TRUE);
}

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

gboolean
nmtstp_kernel_support_get(NMPlatformKernelSupportType type)
{
    const NMPlatformLink *pllink;
    NMTernary             v;

    v = nm_platform_kernel_support_get_full(type, FALSE);
    if (v != NM_TERNARY_DEFAULT)
        return v != NM_TERNARY_FALSE;

    switch (type) {
    case NM_PLATFORM_KERNEL_SUPPORT_TYPE_IFLA_BR_VLAN_STATS_ENABLED:
        pllink = nmtstp_link_bridge_add(NULL, -1, "br-test-11", &nm_platform_lnk_bridge_default);
        nmtstp_link_delete(NULL, -1, pllink->ifindex, NULL, TRUE);
        v = nm_platform_kernel_support_get_full(type, FALSE);
        g_assert(v != NM_TERNARY_DEFAULT);
        return v;
    default:
        g_assert_not_reached();
    }
}

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

struct _NMTstpNamespaceHandle {
    pid_t pid;
    int   pipe_fd;
};

NMTstpNamespaceHandle *
nmtstp_namespace_create(int unshare_flags, GError **error)
{
    NMTstpNamespaceHandle *ns_handle;
    int                    e;
    int                    errsv;
    pid_t                  pid, pid2;
    int                    pipefd_c2p[2];
    int                    pipefd_p2c[2];
    ssize_t                r;

    e = pipe2(pipefd_c2p, O_CLOEXEC);
    if (e != 0) {
        errsv = errno;
        g_set_error(error,
                    NM_UTILS_ERROR,
                    NM_UTILS_ERROR_UNKNOWN,
                    "pipe() failed with %d (%s)",
                    errsv,
                    nm_strerror_native(errsv));
        return FALSE;
    }

    e = pipe2(pipefd_p2c, O_CLOEXEC);
    if (e != 0) {
        errsv = errno;
        g_set_error(error,
                    NM_UTILS_ERROR,
                    NM_UTILS_ERROR_UNKNOWN,
                    "pipe() failed with %d (%s)",
                    errsv,
                    nm_strerror_native(errsv));
        nm_close(pipefd_c2p[0]);
        nm_close(pipefd_c2p[1]);
        return FALSE;
    }

    pid = fork();
    if (pid < 0) {
        errsv = errno;
        g_set_error(error,
                    NM_UTILS_ERROR,
                    NM_UTILS_ERROR_UNKNOWN,
                    "fork() failed with %d (%s)",
                    errsv,
                    nm_strerror_native(errsv));
        nm_close(pipefd_c2p[0]);
        nm_close(pipefd_c2p[1]);
        nm_close(pipefd_p2c[0]);
        nm_close(pipefd_p2c[1]);
        return FALSE;
    }

    if (pid == 0) {
        char read_buf[1];

        nm_close(pipefd_c2p[0]); /* close read-end */
        nm_close(pipefd_p2c[1]); /* close write-end */

        if (unshare(unshare_flags) != 0) {
            errsv = errno;
            if (errsv == 0)
                errsv = -1;
        } else
            errsv = 0;

        /* sync with parent process and send result. */
        do {
            r = write(pipefd_c2p[1], &errsv, sizeof(errsv));
        } while (r < 0 && errno == EINTR);
        if (r != sizeof(errsv)) {
            errsv = errno;
            if (errsv == 0)
                errsv = -2;
        }
        nm_close(pipefd_c2p[1]);

        /* wait until parent process terminates (or kills us). */
        if (errsv == 0) {
            do {
                r = read(pipefd_p2c[0], read_buf, sizeof(read_buf));
            } while (r < 0 && errno == EINTR);
        }
        nm_close(pipefd_p2c[0]);
        _exit(0);
    }

    nm_close(pipefd_c2p[1]); /* close write-end */
    nm_close(pipefd_p2c[0]); /* close read-end */

    /* sync with child process. */
    do {
        r = read(pipefd_c2p[0], &errsv, sizeof(errsv));
    } while (r < 0 && errno == EINTR);

    nm_close(pipefd_c2p[0]);

    if (r != sizeof(errsv) || errsv != 0) {
        int status;

        if (r != sizeof(errsv)) {
            g_set_error(error,
                        NM_UTILS_ERROR,
                        NM_UTILS_ERROR_UNKNOWN,
                        "child process failed for unknown reason");
        } else {
            g_set_error(error,
                        NM_UTILS_ERROR,
                        NM_UTILS_ERROR_UNKNOWN,
                        "child process signaled failure %d (%s)",
                        errsv,
                        nm_strerror_native(errsv));
        }
        nm_close(pipefd_p2c[1]);
        kill(pid, SIGKILL);
        do {
            pid2 = waitpid(pid, &status, 0);
        } while (pid2 == -1 && errno == EINTR);
        return FALSE;
    }

    ns_handle          = g_new0(NMTstpNamespaceHandle, 1);
    ns_handle->pid     = pid;
    ns_handle->pipe_fd = pipefd_p2c[1];
    return ns_handle;
}

pid_t
nmtstp_namespace_handle_get_pid(NMTstpNamespaceHandle *ns_handle)
{
    g_return_val_if_fail(ns_handle, 0);
    g_return_val_if_fail(ns_handle->pid > 0, 0);

    return ns_handle->pid;
}

void
nmtstp_namespace_handle_release(NMTstpNamespaceHandle *ns_handle)
{
    pid_t pid;
    int   status;

    if (!ns_handle)
        return;

    g_return_if_fail(ns_handle->pid > 0);

    nm_close(ns_handle->pipe_fd);
    ns_handle->pipe_fd = 0;

    kill(ns_handle->pid, SIGKILL);

    do {
        pid = waitpid(ns_handle->pid, &status, 0);
    } while (pid == -1 && errno == EINTR);
    ns_handle->pid = 0;

    g_free(ns_handle);
}

int
nmtstp_namespace_get_fd_for_process(pid_t pid, const char *ns_name)
{
    char p[1000];

    g_return_val_if_fail(pid > 0, 0);
    g_return_val_if_fail(ns_name && ns_name[0] && strlen(ns_name) < 50, 0);

    nm_sprintf_buf(p, "/proc/%lu/ns/%s", (unsigned long) pid, ns_name);

    return open(p, O_RDONLY | O_CLOEXEC);
}

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

void
nmtstp_netns_select_random(NMPlatform **platforms, gsize n_platforms, NMPNetns **netns)
{
    int i;

    g_assert(platforms);
    g_assert(n_platforms && n_platforms <= G_MAXINT32);
    g_assert(netns && !*netns);
    for (i = 0; i < n_platforms; i++)
        g_assert(NM_IS_PLATFORM(platforms[i]));

    i = nmtst_get_rand_uint32() % (n_platforms + 1);
    if (i == 0)
        return;
    g_assert(nm_platform_netns_push(platforms[i - 1], netns));
}

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

NMTST_DEFINE();

static gboolean
unshare_user(void)
{
    FILE *f;
    uid_t uid = geteuid();
    gid_t gid = getegid();

    /* Already a root? */
    if (gid == 0 && uid == 0)
        return TRUE;

    /* Become a root in new user NS. */
    if (unshare(CLONE_NEWUSER) != 0)
        return FALSE;

    /* Since Linux 3.19 we have to disable setgroups() in order to map users.
     * Just proceed if the file is not there. */
    f = fopen("/proc/self/setgroups", "we");
    if (f) {
        fprintf(f, "deny");
        fclose(f);
    }

    /* Map current UID to root in NS to be created. */
    f = fopen("/proc/self/uid_map", "we");
    if (!f)
        return FALSE;
    fprintf(f, "0 %d 1", uid);
    fclose(f);

    /* Map current GID to root in NS to be created. */
    f = fopen("/proc/self/gid_map", "we");
    if (!f)
        return FALSE;
    fprintf(f, "0 %d 1", gid);
    fclose(f);

    return TRUE;
}

int
main(int argc, char **argv)
{
    int         result;
    const char *program = *argv;

    _nmtstp_init_tests(&argc, &argv);

    if (nmtstp_is_root_test() && (geteuid() != 0 || getegid() != 0)) {
        if (g_getenv("NMTST_FORCE_REAL_ROOT") || !unshare_user()) {
            /* Try to exec as sudo, this function does not return, if a sudo-cmd is set. */
            nmtst_reexec_sudo();

#ifdef REQUIRE_ROOT_TESTS
            g_print("Fail test: requires root privileges (%s)\n", program);
            return EXIT_FAILURE;
#else
            g_print("Skipping test: requires root privileges (%s)\n", program);
            return g_test_run();
#endif
        }
    }

    if (nmtstp_is_root_test() && !g_getenv("NMTST_NO_UNSHARE")) {
        int errsv;

        if (unshare(CLONE_NEWNET | CLONE_NEWNS) != 0) {
            errsv = errno;
            g_error("unshare(CLONE_NEWNET|CLONE_NEWNS) failed with %s (%d)",
                    nm_strerror_native(errsv),
                    errsv);
        }

        /* We need a read-only /sys so that the platform knows there's no udev. */
        mount(NULL, "/sys", "sysfs", MS_SLAVE, NULL);
        if (mount("sys", "/sys", "sysfs", MS_RDONLY, NULL) != 0) {
            errsv = errno;
            g_error("mount(\"/sys\") failed with %s (%d)", nm_strerror_native(errsv), errsv);
        }
    }

    nmtstp_setup_platform();

    _nmtstp_setup_tests();

    result = g_test_run();

    nmtstp_link_delete(NM_PLATFORM_GET, -1, -1, DEVICE_NAME, FALSE);

    g_object_unref(NM_PLATFORM_GET);
    return result;
}