1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
|
/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
/***
This file is part of systemd.
Copyright 2010 Lennart Poettering
systemd is free software; you can redistribute it and/or modify it
under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.
systemd is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with systemd; If not, see <http://www.gnu.org/licenses/>.
***/
#include <ctype.h>
#include <dirent.h>
#include <errno.h>
#include <fcntl.h>
#include <glob.h>
#include <grp.h>
#include <langinfo.h>
#include <libintl.h>
#include <limits.h>
#include <linux/magic.h>
#include <linux/oom.h>
#include <linux/sched.h>
#include <locale.h>
#include <poll.h>
#include <pwd.h>
#include <sched.h>
#include <signal.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/file.h>
#include <sys/ioctl.h>
#include <sys/mman.h>
#include <sys/mount.h>
#include <sys/personality.h>
#include <sys/prctl.h>
#include <sys/resource.h>
#include <sys/stat.h>
#include <sys/statvfs.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/utsname.h>
#include <sys/vfs.h>
#include <sys/wait.h>
#include <sys/xattr.h>
#include <syslog.h>
#include <unistd.h>
/* When we include libgen.h because we need dirname() we immediately
* undefine basename() since libgen.h defines it as a macro to the
* POSIX version which is really broken. We prefer GNU basename(). */
#include <libgen.h>
#undef basename
#ifdef HAVE_SYS_AUXV_H
#include <sys/auxv.h>
#endif
/* We include linux/fs.h as last of the system headers, as it
* otherwise conflicts with sys/mount.h. Yay, Linux is great! */
#include <linux/fs.h>
#include "build.h"
#include "def.h"
#include "device-nodes.h"
#include "env-util.h"
#include "escape.h"
#include "exit-status.h"
#include "fd-util.h"
#include "fileio.h"
#include "formats-util.h"
#include "gunicode.h"
#include "hashmap.h"
#include "hostname-util.h"
#include "ioprio.h"
#include "log.h"
#include "macro.h"
#include "missing.h"
#include "mkdir.h"
#include "hexdecoct.h"
#include "parse-util.h"
#include "path-util.h"
#include "process-util.h"
#include "random-util.h"
#include "signal-util.h"
#include "sparse-endian.h"
#include "string-util.h"
#include "strv.h"
#include "terminal-util.h"
#include "user-util.h"
#include "utf8.h"
#include "util.h"
#include "virt.h"
/* Put this test here for a lack of better place */
assert_cc(EAGAIN == EWOULDBLOCK);
int saved_argc = 0;
char **saved_argv = NULL;
size_t page_size(void) {
static thread_local size_t pgsz = 0;
long r;
if (_likely_(pgsz > 0))
return pgsz;
r = sysconf(_SC_PAGESIZE);
assert(r > 0);
pgsz = (size_t) r;
return pgsz;
}
int unlink_noerrno(const char *path) {
PROTECT_ERRNO;
int r;
r = unlink(path);
if (r < 0)
return -errno;
return 0;
}
int fchmod_umask(int fd, mode_t m) {
mode_t u;
int r;
u = umask(0777);
r = fchmod(fd, m & (~u)) < 0 ? -errno : 0;
umask(u);
return r;
}
int readlinkat_malloc(int fd, const char *p, char **ret) {
size_t l = 100;
int r;
assert(p);
assert(ret);
for (;;) {
char *c;
ssize_t n;
c = new(char, l);
if (!c)
return -ENOMEM;
n = readlinkat(fd, p, c, l-1);
if (n < 0) {
r = -errno;
free(c);
return r;
}
if ((size_t) n < l-1) {
c[n] = 0;
*ret = c;
return 0;
}
free(c);
l *= 2;
}
}
int readlink_malloc(const char *p, char **ret) {
return readlinkat_malloc(AT_FDCWD, p, ret);
}
int readlink_value(const char *p, char **ret) {
_cleanup_free_ char *link = NULL;
char *value;
int r;
r = readlink_malloc(p, &link);
if (r < 0)
return r;
value = basename(link);
if (!value)
return -ENOENT;
value = strdup(value);
if (!value)
return -ENOMEM;
*ret = value;
return 0;
}
int readlink_and_make_absolute(const char *p, char **r) {
_cleanup_free_ char *target = NULL;
char *k;
int j;
assert(p);
assert(r);
j = readlink_malloc(p, &target);
if (j < 0)
return j;
k = file_in_same_dir(p, target);
if (!k)
return -ENOMEM;
*r = k;
return 0;
}
int readlink_and_canonicalize(const char *p, char **r) {
char *t, *s;
int j;
assert(p);
assert(r);
j = readlink_and_make_absolute(p, &t);
if (j < 0)
return j;
s = canonicalize_file_name(t);
if (s) {
free(t);
*r = s;
} else
*r = t;
path_kill_slashes(*r);
return 0;
}
char *file_in_same_dir(const char *path, const char *filename) {
char *e, *ret;
size_t k;
assert(path);
assert(filename);
/* This removes the last component of path and appends
* filename, unless the latter is absolute anyway or the
* former isn't */
if (path_is_absolute(filename))
return strdup(filename);
e = strrchr(path, '/');
if (!e)
return strdup(filename);
k = strlen(filename);
ret = new(char, (e + 1 - path) + k + 1);
if (!ret)
return NULL;
memcpy(mempcpy(ret, path, e + 1 - path), filename, k + 1);
return ret;
}
int rmdir_parents(const char *path, const char *stop) {
size_t l;
int r = 0;
assert(path);
assert(stop);
l = strlen(path);
/* Skip trailing slashes */
while (l > 0 && path[l-1] == '/')
l--;
while (l > 0) {
char *t;
/* Skip last component */
while (l > 0 && path[l-1] != '/')
l--;
/* Skip trailing slashes */
while (l > 0 && path[l-1] == '/')
l--;
if (l <= 0)
break;
if (!(t = strndup(path, l)))
return -ENOMEM;
if (path_startswith(stop, t)) {
free(t);
return 0;
}
r = rmdir(t);
free(t);
if (r < 0)
if (errno != ENOENT)
return -errno;
}
return 0;
}
_pure_ static bool hidden_file_allow_backup(const char *filename) {
assert(filename);
return
filename[0] == '.' ||
streq(filename, "lost+found") ||
streq(filename, "aquota.user") ||
streq(filename, "aquota.group") ||
endswith(filename, ".rpmnew") ||
endswith(filename, ".rpmsave") ||
endswith(filename, ".rpmorig") ||
endswith(filename, ".dpkg-old") ||
endswith(filename, ".dpkg-new") ||
endswith(filename, ".dpkg-tmp") ||
endswith(filename, ".dpkg-dist") ||
endswith(filename, ".dpkg-bak") ||
endswith(filename, ".dpkg-backup") ||
endswith(filename, ".dpkg-remove") ||
endswith(filename, ".swp");
}
bool hidden_file(const char *filename) {
assert(filename);
if (endswith(filename, "~"))
return true;
return hidden_file_allow_backup(filename);
}
bool fstype_is_network(const char *fstype) {
static const char table[] =
"afs\0"
"cifs\0"
"smbfs\0"
"sshfs\0"
"ncpfs\0"
"ncp\0"
"nfs\0"
"nfs4\0"
"gfs\0"
"gfs2\0"
"glusterfs\0";
const char *x;
x = startswith(fstype, "fuse.");
if (x)
fstype = x;
return nulstr_contains(table, fstype);
}
bool is_device_path(const char *path) {
/* Returns true on paths that refer to a device, either in
* sysfs or in /dev */
return
path_startswith(path, "/dev/") ||
path_startswith(path, "/sys/");
}
int dir_is_empty(const char *path) {
_cleanup_closedir_ DIR *d;
struct dirent *de;
d = opendir(path);
if (!d)
return -errno;
FOREACH_DIRENT(de, d, return -errno)
return 0;
return 1;
}
char* dirname_malloc(const char *path) {
char *d, *dir, *dir2;
d = strdup(path);
if (!d)
return NULL;
dir = dirname(d);
assert(dir);
if (dir != d) {
dir2 = strdup(dir);
free(d);
return dir2;
}
return dir;
}
void rename_process(const char name[8]) {
assert(name);
/* This is a like a poor man's setproctitle(). It changes the
* comm field, argv[0], and also the glibc's internally used
* name of the process. For the first one a limit of 16 chars
* applies, to the second one usually one of 10 (i.e. length
* of "/sbin/init"), to the third one one of 7 (i.e. length of
* "systemd"). If you pass a longer string it will be
* truncated */
prctl(PR_SET_NAME, name);
if (program_invocation_name)
strncpy(program_invocation_name, name, strlen(program_invocation_name));
if (saved_argc > 0) {
int i;
if (saved_argv[0])
strncpy(saved_argv[0], name, strlen(saved_argv[0]));
for (i = 1; i < saved_argc; i++) {
if (!saved_argv[i])
break;
memzero(saved_argv[i], strlen(saved_argv[i]));
}
}
}
bool is_fs_type(const struct statfs *s, statfs_f_type_t magic_value) {
assert(s);
assert_cc(sizeof(statfs_f_type_t) >= sizeof(s->f_type));
return F_TYPE_EQUAL(s->f_type, magic_value);
}
int fd_check_fstype(int fd, statfs_f_type_t magic_value) {
struct statfs s;
if (fstatfs(fd, &s) < 0)
return -errno;
return is_fs_type(&s, magic_value);
}
int path_check_fstype(const char *path, statfs_f_type_t magic_value) {
_cleanup_close_ int fd = -1;
fd = open(path, O_RDONLY);
if (fd < 0)
return -errno;
return fd_check_fstype(fd, magic_value);
}
bool is_temporary_fs(const struct statfs *s) {
return is_fs_type(s, TMPFS_MAGIC) ||
is_fs_type(s, RAMFS_MAGIC);
}
int fd_is_temporary_fs(int fd) {
struct statfs s;
if (fstatfs(fd, &s) < 0)
return -errno;
return is_temporary_fs(&s);
}
int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid) {
assert(path);
/* Under the assumption that we are running privileged we
* first change the access mode and only then hand out
* ownership to avoid a window where access is too open. */
if (mode != MODE_INVALID)
if (chmod(path, mode) < 0)
return -errno;
if (uid != UID_INVALID || gid != GID_INVALID)
if (chown(path, uid, gid) < 0)
return -errno;
return 0;
}
int fchmod_and_fchown(int fd, mode_t mode, uid_t uid, gid_t gid) {
assert(fd >= 0);
/* Under the assumption that we are running privileged we
* first change the access mode and only then hand out
* ownership to avoid a window where access is too open. */
if (mode != MODE_INVALID)
if (fchmod(fd, mode) < 0)
return -errno;
if (uid != UID_INVALID || gid != GID_INVALID)
if (fchown(fd, uid, gid) < 0)
return -errno;
return 0;
}
int files_same(const char *filea, const char *fileb) {
struct stat a, b;
if (stat(filea, &a) < 0)
return -errno;
if (stat(fileb, &b) < 0)
return -errno;
return a.st_dev == b.st_dev &&
a.st_ino == b.st_ino;
}
int running_in_chroot(void) {
int ret;
ret = files_same("/proc/1/root", "/");
if (ret < 0)
return ret;
return ret == 0;
}
int touch_file(const char *path, bool parents, usec_t stamp, uid_t uid, gid_t gid, mode_t mode) {
_cleanup_close_ int fd;
int r;
assert(path);
if (parents)
mkdir_parents(path, 0755);
fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY, mode > 0 ? mode : 0644);
if (fd < 0)
return -errno;
if (mode > 0) {
r = fchmod(fd, mode);
if (r < 0)
return -errno;
}
if (uid != UID_INVALID || gid != GID_INVALID) {
r = fchown(fd, uid, gid);
if (r < 0)
return -errno;
}
if (stamp != USEC_INFINITY) {
struct timespec ts[2];
timespec_store(&ts[0], stamp);
ts[1] = ts[0];
r = futimens(fd, ts);
} else
r = futimens(fd, NULL);
if (r < 0)
return -errno;
return 0;
}
int touch(const char *path) {
return touch_file(path, false, USEC_INFINITY, UID_INVALID, GID_INVALID, 0);
}
static char *unquote(const char *s, const char* quotes) {
size_t l;
assert(s);
/* This is rather stupid, simply removes the heading and
* trailing quotes if there is one. Doesn't care about
* escaping or anything.
*
* DON'T USE THIS FOR NEW CODE ANYMORE!*/
l = strlen(s);
if (l < 2)
return strdup(s);
if (strchr(quotes, s[0]) && s[l-1] == s[0])
return strndup(s+1, l-2);
return strdup(s);
}
noreturn void freeze(void) {
/* Make sure nobody waits for us on a socket anymore */
close_all_fds(NULL, 0);
sync();
for (;;)
pause();
}
bool null_or_empty(struct stat *st) {
assert(st);
if (S_ISREG(st->st_mode) && st->st_size <= 0)
return true;
if (S_ISCHR(st->st_mode) || S_ISBLK(st->st_mode))
return true;
return false;
}
int null_or_empty_path(const char *fn) {
struct stat st;
assert(fn);
if (stat(fn, &st) < 0)
return -errno;
return null_or_empty(&st);
}
int null_or_empty_fd(int fd) {
struct stat st;
assert(fd >= 0);
if (fstat(fd, &st) < 0)
return -errno;
return null_or_empty(&st);
}
DIR *xopendirat(int fd, const char *name, int flags) {
int nfd;
DIR *d;
assert(!(flags & O_CREAT));
nfd = openat(fd, name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|flags, 0);
if (nfd < 0)
return NULL;
d = fdopendir(nfd);
if (!d) {
safe_close(nfd);
return NULL;
}
return d;
}
static char *tag_to_udev_node(const char *tagvalue, const char *by) {
_cleanup_free_ char *t = NULL, *u = NULL;
size_t enc_len;
u = unquote(tagvalue, QUOTES);
if (!u)
return NULL;
enc_len = strlen(u) * 4 + 1;
t = new(char, enc_len);
if (!t)
return NULL;
if (encode_devnode_name(u, t, enc_len) < 0)
return NULL;
return strjoin("/dev/disk/by-", by, "/", t, NULL);
}
char *fstab_node_to_udev_node(const char *p) {
assert(p);
if (startswith(p, "LABEL="))
return tag_to_udev_node(p+6, "label");
if (startswith(p, "UUID="))
return tag_to_udev_node(p+5, "uuid");
if (startswith(p, "PARTUUID="))
return tag_to_udev_node(p+9, "partuuid");
if (startswith(p, "PARTLABEL="))
return tag_to_udev_node(p+10, "partlabel");
return strdup(p);
}
bool dirent_is_file(const struct dirent *de) {
assert(de);
if (hidden_file(de->d_name))
return false;
if (de->d_type != DT_REG &&
de->d_type != DT_LNK &&
de->d_type != DT_UNKNOWN)
return false;
return true;
}
bool dirent_is_file_with_suffix(const struct dirent *de, const char *suffix) {
assert(de);
if (de->d_type != DT_REG &&
de->d_type != DT_LNK &&
de->d_type != DT_UNKNOWN)
return false;
if (hidden_file_allow_backup(de->d_name))
return false;
return endswith(de->d_name, suffix);
}
static int do_execute(char **directories, usec_t timeout, char *argv[]) {
_cleanup_hashmap_free_free_ Hashmap *pids = NULL;
_cleanup_set_free_free_ Set *seen = NULL;
char **directory;
/* We fork this all off from a child process so that we can
* somewhat cleanly make use of SIGALRM to set a time limit */
(void) reset_all_signal_handlers();
(void) reset_signal_mask();
assert_se(prctl(PR_SET_PDEATHSIG, SIGTERM) == 0);
pids = hashmap_new(NULL);
if (!pids)
return log_oom();
seen = set_new(&string_hash_ops);
if (!seen)
return log_oom();
STRV_FOREACH(directory, directories) {
_cleanup_closedir_ DIR *d;
struct dirent *de;
d = opendir(*directory);
if (!d) {
if (errno == ENOENT)
continue;
return log_error_errno(errno, "Failed to open directory %s: %m", *directory);
}
FOREACH_DIRENT(de, d, break) {
_cleanup_free_ char *path = NULL;
pid_t pid;
int r;
if (!dirent_is_file(de))
continue;
if (set_contains(seen, de->d_name)) {
log_debug("%1$s/%2$s skipped (%2$s was already seen).", *directory, de->d_name);
continue;
}
r = set_put_strdup(seen, de->d_name);
if (r < 0)
return log_oom();
path = strjoin(*directory, "/", de->d_name, NULL);
if (!path)
return log_oom();
if (null_or_empty_path(path)) {
log_debug("%s is empty (a mask).", path);
continue;
}
pid = fork();
if (pid < 0) {
log_error_errno(errno, "Failed to fork: %m");
continue;
} else if (pid == 0) {
char *_argv[2];
assert_se(prctl(PR_SET_PDEATHSIG, SIGTERM) == 0);
if (!argv) {
_argv[0] = path;
_argv[1] = NULL;
argv = _argv;
} else
argv[0] = path;
execv(path, argv);
return log_error_errno(errno, "Failed to execute %s: %m", path);
}
log_debug("Spawned %s as " PID_FMT ".", path, pid);
r = hashmap_put(pids, UINT_TO_PTR(pid), path);
if (r < 0)
return log_oom();
path = NULL;
}
}
/* Abort execution of this process after the timout. We simply
* rely on SIGALRM as default action terminating the process,
* and turn on alarm(). */
if (timeout != USEC_INFINITY)
alarm((timeout + USEC_PER_SEC - 1) / USEC_PER_SEC);
while (!hashmap_isempty(pids)) {
_cleanup_free_ char *path = NULL;
pid_t pid;
pid = PTR_TO_UINT(hashmap_first_key(pids));
assert(pid > 0);
path = hashmap_remove(pids, UINT_TO_PTR(pid));
assert(path);
wait_for_terminate_and_warn(path, pid, true);
}
return 0;
}
void execute_directories(const char* const* directories, usec_t timeout, char *argv[]) {
pid_t executor_pid;
int r;
char *name;
char **dirs = (char**) directories;
assert(!strv_isempty(dirs));
name = basename(dirs[0]);
assert(!isempty(name));
/* Executes all binaries in the directories in parallel and waits
* for them to finish. Optionally a timeout is applied. If a file
* with the same name exists in more than one directory, the
* earliest one wins. */
executor_pid = fork();
if (executor_pid < 0) {
log_error_errno(errno, "Failed to fork: %m");
return;
} else if (executor_pid == 0) {
r = do_execute(dirs, timeout, argv);
_exit(r < 0 ? EXIT_FAILURE : EXIT_SUCCESS);
}
wait_for_terminate_and_warn(name, executor_pid, true);
}
bool plymouth_running(void) {
return access("/run/plymouth/pid", F_OK) >= 0;
}
int fopen_temporary(const char *path, FILE **_f, char **_temp_path) {
FILE *f;
char *t;
int r, fd;
assert(path);
assert(_f);
assert(_temp_path);
r = tempfn_xxxxxx(path, NULL, &t);
if (r < 0)
return r;
fd = mkostemp_safe(t, O_WRONLY|O_CLOEXEC);
if (fd < 0) {
free(t);
return -errno;
}
f = fdopen(fd, "we");
if (!f) {
unlink_noerrno(t);
free(t);
safe_close(fd);
return -errno;
}
*_f = f;
*_temp_path = t;
return 0;
}
int symlink_atomic(const char *from, const char *to) {
_cleanup_free_ char *t = NULL;
int r;
assert(from);
assert(to);
r = tempfn_random(to, NULL, &t);
if (r < 0)
return r;
if (symlink(from, t) < 0)
return -errno;
if (rename(t, to) < 0) {
unlink_noerrno(t);
return -errno;
}
return 0;
}
int symlink_idempotent(const char *from, const char *to) {
_cleanup_free_ char *p = NULL;
int r;
assert(from);
assert(to);
if (symlink(from, to) < 0) {
if (errno != EEXIST)
return -errno;
r = readlink_malloc(to, &p);
if (r < 0)
return r;
if (!streq(p, from))
return -EINVAL;
}
return 0;
}
int mknod_atomic(const char *path, mode_t mode, dev_t dev) {
_cleanup_free_ char *t = NULL;
int r;
assert(path);
r = tempfn_random(path, NULL, &t);
if (r < 0)
return r;
if (mknod(t, mode, dev) < 0)
return -errno;
if (rename(t, path) < 0) {
unlink_noerrno(t);
return -errno;
}
return 0;
}
int mkfifo_atomic(const char *path, mode_t mode) {
_cleanup_free_ char *t = NULL;
int r;
assert(path);
r = tempfn_random(path, NULL, &t);
if (r < 0)
return r;
if (mkfifo(t, mode) < 0)
return -errno;
if (rename(t, path) < 0) {
unlink_noerrno(t);
return -errno;
}
return 0;
}
bool display_is_local(const char *display) {
assert(display);
return
display[0] == ':' &&
display[1] >= '0' &&
display[1] <= '9';
}
int socket_from_display(const char *display, char **path) {
size_t k;
char *f, *c;
assert(display);
assert(path);
if (!display_is_local(display))
return -EINVAL;
k = strspn(display+1, "0123456789");
f = new(char, strlen("/tmp/.X11-unix/X") + k + 1);
if (!f)
return -ENOMEM;
c = stpcpy(f, "/tmp/.X11-unix/X");
memcpy(c, display+1, k);
c[k] = 0;
*path = f;
return 0;
}
int glob_exists(const char *path) {
_cleanup_globfree_ glob_t g = {};
int k;
assert(path);
errno = 0;
k = glob(path, GLOB_NOSORT|GLOB_BRACE, NULL, &g);
if (k == GLOB_NOMATCH)
return 0;
else if (k == GLOB_NOSPACE)
return -ENOMEM;
else if (k == 0)
return !strv_isempty(g.gl_pathv);
else
return errno ? -errno : -EIO;
}
int glob_extend(char ***strv, const char *path) {
_cleanup_globfree_ glob_t g = {};
int k;
char **p;
errno = 0;
k = glob(path, GLOB_NOSORT|GLOB_BRACE, NULL, &g);
if (k == GLOB_NOMATCH)
return -ENOENT;
else if (k == GLOB_NOSPACE)
return -ENOMEM;
else if (k != 0 || strv_isempty(g.gl_pathv))
return errno ? -errno : -EIO;
STRV_FOREACH(p, g.gl_pathv) {
k = strv_extend(strv, *p);
if (k < 0)
break;
}
return k;
}
int dirent_ensure_type(DIR *d, struct dirent *de) {
struct stat st;
assert(d);
assert(de);
if (de->d_type != DT_UNKNOWN)
return 0;
if (fstatat(dirfd(d), de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0)
return -errno;
de->d_type =
S_ISREG(st.st_mode) ? DT_REG :
S_ISDIR(st.st_mode) ? DT_DIR :
S_ISLNK(st.st_mode) ? DT_LNK :
S_ISFIFO(st.st_mode) ? DT_FIFO :
S_ISSOCK(st.st_mode) ? DT_SOCK :
S_ISCHR(st.st_mode) ? DT_CHR :
S_ISBLK(st.st_mode) ? DT_BLK :
DT_UNKNOWN;
return 0;
}
int get_files_in_directory(const char *path, char ***list) {
_cleanup_closedir_ DIR *d = NULL;
size_t bufsize = 0, n = 0;
_cleanup_strv_free_ char **l = NULL;
assert(path);
/* Returns all files in a directory in *list, and the number
* of files as return value. If list is NULL returns only the
* number. */
d = opendir(path);
if (!d)
return -errno;
for (;;) {
struct dirent *de;
errno = 0;
de = readdir(d);
if (!de && errno != 0)
return -errno;
if (!de)
break;
dirent_ensure_type(d, de);
if (!dirent_is_file(de))
continue;
if (list) {
/* one extra slot is needed for the terminating NULL */
if (!GREEDY_REALLOC(l, bufsize, n + 2))
return -ENOMEM;
l[n] = strdup(de->d_name);
if (!l[n])
return -ENOMEM;
l[++n] = NULL;
} else
n++;
}
if (list) {
*list = l;
l = NULL; /* avoid freeing */
}
return n;
}
bool is_main_thread(void) {
static thread_local int cached = 0;
if (_unlikely_(cached == 0))
cached = getpid() == gettid() ? 1 : -1;
return cached > 0;
}
int block_get_whole_disk(dev_t d, dev_t *ret) {
char *p, *s;
int r;
unsigned n, m;
assert(ret);
/* If it has a queue this is good enough for us */
if (asprintf(&p, "/sys/dev/block/%u:%u/queue", major(d), minor(d)) < 0)
return -ENOMEM;
r = access(p, F_OK);
free(p);
if (r >= 0) {
*ret = d;
return 0;
}
/* If it is a partition find the originating device */
if (asprintf(&p, "/sys/dev/block/%u:%u/partition", major(d), minor(d)) < 0)
return -ENOMEM;
r = access(p, F_OK);
free(p);
if (r < 0)
return -ENOENT;
/* Get parent dev_t */
if (asprintf(&p, "/sys/dev/block/%u:%u/../dev", major(d), minor(d)) < 0)
return -ENOMEM;
r = read_one_line_file(p, &s);
free(p);
if (r < 0)
return r;
r = sscanf(s, "%u:%u", &m, &n);
free(s);
if (r != 2)
return -EINVAL;
/* Only return this if it is really good enough for us. */
if (asprintf(&p, "/sys/dev/block/%u:%u/queue", m, n) < 0)
return -ENOMEM;
r = access(p, F_OK);
free(p);
if (r >= 0) {
*ret = makedev(m, n);
return 0;
}
return -ENOENT;
}
static const char *const ioprio_class_table[] = {
[IOPRIO_CLASS_NONE] = "none",
[IOPRIO_CLASS_RT] = "realtime",
[IOPRIO_CLASS_BE] = "best-effort",
[IOPRIO_CLASS_IDLE] = "idle"
};
DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ioprio_class, int, INT_MAX);
static const char *const sigchld_code_table[] = {
[CLD_EXITED] = "exited",
[CLD_KILLED] = "killed",
[CLD_DUMPED] = "dumped",
[CLD_TRAPPED] = "trapped",
[CLD_STOPPED] = "stopped",
[CLD_CONTINUED] = "continued",
};
DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
static const char *const log_facility_unshifted_table[LOG_NFACILITIES] = {
[LOG_FAC(LOG_KERN)] = "kern",
[LOG_FAC(LOG_USER)] = "user",
[LOG_FAC(LOG_MAIL)] = "mail",
[LOG_FAC(LOG_DAEMON)] = "daemon",
[LOG_FAC(LOG_AUTH)] = "auth",
[LOG_FAC(LOG_SYSLOG)] = "syslog",
[LOG_FAC(LOG_LPR)] = "lpr",
[LOG_FAC(LOG_NEWS)] = "news",
[LOG_FAC(LOG_UUCP)] = "uucp",
[LOG_FAC(LOG_CRON)] = "cron",
[LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
[LOG_FAC(LOG_FTP)] = "ftp",
[LOG_FAC(LOG_LOCAL0)] = "local0",
[LOG_FAC(LOG_LOCAL1)] = "local1",
[LOG_FAC(LOG_LOCAL2)] = "local2",
[LOG_FAC(LOG_LOCAL3)] = "local3",
[LOG_FAC(LOG_LOCAL4)] = "local4",
[LOG_FAC(LOG_LOCAL5)] = "local5",
[LOG_FAC(LOG_LOCAL6)] = "local6",
[LOG_FAC(LOG_LOCAL7)] = "local7"
};
DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_facility_unshifted, int, LOG_FAC(~0));
bool log_facility_unshifted_is_valid(int facility) {
return facility >= 0 && facility <= LOG_FAC(~0);
}
static const char *const log_level_table[] = {
[LOG_EMERG] = "emerg",
[LOG_ALERT] = "alert",
[LOG_CRIT] = "crit",
[LOG_ERR] = "err",
[LOG_WARNING] = "warning",
[LOG_NOTICE] = "notice",
[LOG_INFO] = "info",
[LOG_DEBUG] = "debug"
};
DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_level, int, LOG_DEBUG);
bool log_level_is_valid(int level) {
return level >= 0 && level <= LOG_DEBUG;
}
static const char* const sched_policy_table[] = {
[SCHED_OTHER] = "other",
[SCHED_BATCH] = "batch",
[SCHED_IDLE] = "idle",
[SCHED_FIFO] = "fifo",
[SCHED_RR] = "rr"
};
DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(sched_policy, int, INT_MAX);
static const char* const rlimit_table[_RLIMIT_MAX] = {
[RLIMIT_CPU] = "LimitCPU",
[RLIMIT_FSIZE] = "LimitFSIZE",
[RLIMIT_DATA] = "LimitDATA",
[RLIMIT_STACK] = "LimitSTACK",
[RLIMIT_CORE] = "LimitCORE",
[RLIMIT_RSS] = "LimitRSS",
[RLIMIT_NOFILE] = "LimitNOFILE",
[RLIMIT_AS] = "LimitAS",
[RLIMIT_NPROC] = "LimitNPROC",
[RLIMIT_MEMLOCK] = "LimitMEMLOCK",
[RLIMIT_LOCKS] = "LimitLOCKS",
[RLIMIT_SIGPENDING] = "LimitSIGPENDING",
[RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
[RLIMIT_NICE] = "LimitNICE",
[RLIMIT_RTPRIO] = "LimitRTPRIO",
[RLIMIT_RTTIME] = "LimitRTTIME"
};
DEFINE_STRING_TABLE_LOOKUP(rlimit, int);
bool kexec_loaded(void) {
bool loaded = false;
char *s;
if (read_one_line_file("/sys/kernel/kexec_loaded", &s) >= 0) {
if (s[0] == '1')
loaded = true;
free(s);
}
return loaded;
}
int prot_from_flags(int flags) {
switch (flags & O_ACCMODE) {
case O_RDONLY:
return PROT_READ;
case O_WRONLY:
return PROT_WRITE;
case O_RDWR:
return PROT_READ|PROT_WRITE;
default:
return -EINVAL;
}
}
void* memdup(const void *p, size_t l) {
void *r;
assert(p);
r = malloc(l);
if (!r)
return NULL;
memcpy(r, p, l);
return r;
}
int fork_agent(pid_t *pid, const int except[], unsigned n_except, const char *path, ...) {
bool stdout_is_tty, stderr_is_tty;
pid_t parent_pid, agent_pid;
sigset_t ss, saved_ss;
unsigned n, i;
va_list ap;
char **l;
assert(pid);
assert(path);
/* Spawns a temporary TTY agent, making sure it goes away when
* we go away */
parent_pid = getpid();
/* First we temporarily block all signals, so that the new
* child has them blocked initially. This way, we can be sure
* that SIGTERMs are not lost we might send to the agent. */
assert_se(sigfillset(&ss) >= 0);
assert_se(sigprocmask(SIG_SETMASK, &ss, &saved_ss) >= 0);
agent_pid = fork();
if (agent_pid < 0) {
assert_se(sigprocmask(SIG_SETMASK, &saved_ss, NULL) >= 0);
return -errno;
}
if (agent_pid != 0) {
assert_se(sigprocmask(SIG_SETMASK, &saved_ss, NULL) >= 0);
*pid = agent_pid;
return 0;
}
/* In the child:
*
* Make sure the agent goes away when the parent dies */
if (prctl(PR_SET_PDEATHSIG, SIGTERM) < 0)
_exit(EXIT_FAILURE);
/* Make sure we actually can kill the agent, if we need to, in
* case somebody invoked us from a shell script that trapped
* SIGTERM or so... */
(void) reset_all_signal_handlers();
(void) reset_signal_mask();
/* Check whether our parent died before we were able
* to set the death signal and unblock the signals */
if (getppid() != parent_pid)
_exit(EXIT_SUCCESS);
/* Don't leak fds to the agent */
close_all_fds(except, n_except);
stdout_is_tty = isatty(STDOUT_FILENO);
stderr_is_tty = isatty(STDERR_FILENO);
if (!stdout_is_tty || !stderr_is_tty) {
int fd;
/* Detach from stdout/stderr. and reopen
* /dev/tty for them. This is important to
* ensure that when systemctl is started via
* popen() or a similar call that expects to
* read EOF we actually do generate EOF and
* not delay this indefinitely by because we
* keep an unused copy of stdin around. */
fd = open("/dev/tty", O_WRONLY);
if (fd < 0) {
log_error_errno(errno, "Failed to open /dev/tty: %m");
_exit(EXIT_FAILURE);
}
if (!stdout_is_tty)
dup2(fd, STDOUT_FILENO);
if (!stderr_is_tty)
dup2(fd, STDERR_FILENO);
if (fd > 2)
close(fd);
}
/* Count arguments */
va_start(ap, path);
for (n = 0; va_arg(ap, char*); n++)
;
va_end(ap);
/* Allocate strv */
l = alloca(sizeof(char *) * (n + 1));
/* Fill in arguments */
va_start(ap, path);
for (i = 0; i <= n; i++)
l[i] = va_arg(ap, char*);
va_end(ap);
execv(path, l);
_exit(EXIT_FAILURE);
}
int setrlimit_closest(int resource, const struct rlimit *rlim) {
struct rlimit highest, fixed;
assert(rlim);
if (setrlimit(resource, rlim) >= 0)
return 0;
if (errno != EPERM)
return -errno;
/* So we failed to set the desired setrlimit, then let's try
* to get as close as we can */
assert_se(getrlimit(resource, &highest) == 0);
fixed.rlim_cur = MIN(rlim->rlim_cur, highest.rlim_max);
fixed.rlim_max = MIN(rlim->rlim_max, highest.rlim_max);
if (setrlimit(resource, &fixed) < 0)
return -errno;
return 0;
}
bool http_etag_is_valid(const char *etag) {
if (isempty(etag))
return false;
if (!endswith(etag, "\""))
return false;
if (!startswith(etag, "\"") && !startswith(etag, "W/\""))
return false;
return true;
}
bool http_url_is_valid(const char *url) {
const char *p;
if (isempty(url))
return false;
p = startswith(url, "http://");
if (!p)
p = startswith(url, "https://");
if (!p)
return false;
if (isempty(p))
return false;
return ascii_is_valid(p);
}
bool documentation_url_is_valid(const char *url) {
const char *p;
if (isempty(url))
return false;
if (http_url_is_valid(url))
return true;
p = startswith(url, "file:/");
if (!p)
p = startswith(url, "info:");
if (!p)
p = startswith(url, "man:");
if (isempty(p))
return false;
return ascii_is_valid(p);
}
bool in_initrd(void) {
static int saved = -1;
struct statfs s;
if (saved >= 0)
return saved;
/* We make two checks here:
*
* 1. the flag file /etc/initrd-release must exist
* 2. the root file system must be a memory file system
*
* The second check is extra paranoia, since misdetecting an
* initrd can have bad bad consequences due the initrd
* emptying when transititioning to the main systemd.
*/
saved = access("/etc/initrd-release", F_OK) >= 0 &&
statfs("/", &s) >= 0 &&
is_temporary_fs(&s);
return saved;
}
bool filename_is_valid(const char *p) {
if (isempty(p))
return false;
if (strchr(p, '/'))
return false;
if (streq(p, "."))
return false;
if (streq(p, ".."))
return false;
if (strlen(p) > FILENAME_MAX)
return false;
return true;
}
bool string_is_safe(const char *p) {
const char *t;
if (!p)
return false;
for (t = p; *t; t++) {
if (*t > 0 && *t < ' ')
return false;
if (strchr("\\\"\'\x7f", *t))
return false;
}
return true;
}
bool path_is_safe(const char *p) {
if (isempty(p))
return false;
if (streq(p, "..") || startswith(p, "../") || endswith(p, "/..") || strstr(p, "/../"))
return false;
if (strlen(p)+1 > PATH_MAX)
return false;
/* The following two checks are not really dangerous, but hey, they still are confusing */
if (streq(p, ".") || startswith(p, "./") || endswith(p, "/.") || strstr(p, "/./"))
return false;
if (strstr(p, "//"))
return false;
return true;
}
/* hey glibc, APIs with callbacks without a user pointer are so useless */
void *xbsearch_r(const void *key, const void *base, size_t nmemb, size_t size,
int (*compar) (const void *, const void *, void *), void *arg) {
size_t l, u, idx;
const void *p;
int comparison;
l = 0;
u = nmemb;
while (l < u) {
idx = (l + u) / 2;
p = (void *)(((const char *) base) + (idx * size));
comparison = compar(key, p, arg);
if (comparison < 0)
u = idx;
else if (comparison > 0)
l = idx + 1;
else
return (void *)p;
}
return NULL;
}
void init_gettext(void) {
setlocale(LC_ALL, "");
textdomain(GETTEXT_PACKAGE);
}
bool is_locale_utf8(void) {
const char *set;
static int cached_answer = -1;
if (cached_answer >= 0)
goto out;
if (!setlocale(LC_ALL, "")) {
cached_answer = true;
goto out;
}
set = nl_langinfo(CODESET);
if (!set) {
cached_answer = true;
goto out;
}
if (streq(set, "UTF-8")) {
cached_answer = true;
goto out;
}
/* For LC_CTYPE=="C" return true, because CTYPE is effectly
* unset and everything can do to UTF-8 nowadays. */
set = setlocale(LC_CTYPE, NULL);
if (!set) {
cached_answer = true;
goto out;
}
/* Check result, but ignore the result if C was set
* explicitly. */
cached_answer =
STR_IN_SET(set, "C", "POSIX") &&
!getenv("LC_ALL") &&
!getenv("LC_CTYPE") &&
!getenv("LANG");
out:
return (bool) cached_answer;
}
const char *draw_special_char(DrawSpecialChar ch) {
static const char *draw_table[2][_DRAW_SPECIAL_CHAR_MAX] = {
/* UTF-8 */ {
[DRAW_TREE_VERTICAL] = "\342\224\202 ", /* │ */
[DRAW_TREE_BRANCH] = "\342\224\234\342\224\200", /* ├─ */
[DRAW_TREE_RIGHT] = "\342\224\224\342\224\200", /* └─ */
[DRAW_TREE_SPACE] = " ", /* */
[DRAW_TRIANGULAR_BULLET] = "\342\200\243", /* ‣ */
[DRAW_BLACK_CIRCLE] = "\342\227\217", /* ● */
[DRAW_ARROW] = "\342\206\222", /* → */
[DRAW_DASH] = "\342\200\223", /* – */
},
/* ASCII fallback */ {
[DRAW_TREE_VERTICAL] = "| ",
[DRAW_TREE_BRANCH] = "|-",
[DRAW_TREE_RIGHT] = "`-",
[DRAW_TREE_SPACE] = " ",
[DRAW_TRIANGULAR_BULLET] = ">",
[DRAW_BLACK_CIRCLE] = "*",
[DRAW_ARROW] = "->",
[DRAW_DASH] = "-",
}
};
return draw_table[!is_locale_utf8()][ch];
}
int on_ac_power(void) {
bool found_offline = false, found_online = false;
_cleanup_closedir_ DIR *d = NULL;
d = opendir("/sys/class/power_supply");
if (!d)
return errno == ENOENT ? true : -errno;
for (;;) {
struct dirent *de;
_cleanup_close_ int fd = -1, device = -1;
char contents[6];
ssize_t n;
errno = 0;
de = readdir(d);
if (!de && errno != 0)
return -errno;
if (!de)
break;
if (hidden_file(de->d_name))
continue;
device = openat(dirfd(d), de->d_name, O_DIRECTORY|O_RDONLY|O_CLOEXEC|O_NOCTTY);
if (device < 0) {
if (errno == ENOENT || errno == ENOTDIR)
continue;
return -errno;
}
fd = openat(device, "type", O_RDONLY|O_CLOEXEC|O_NOCTTY);
if (fd < 0) {
if (errno == ENOENT)
continue;
return -errno;
}
n = read(fd, contents, sizeof(contents));
if (n < 0)
return -errno;
if (n != 6 || memcmp(contents, "Mains\n", 6))
continue;
safe_close(fd);
fd = openat(device, "online", O_RDONLY|O_CLOEXEC|O_NOCTTY);
if (fd < 0) {
if (errno == ENOENT)
continue;
return -errno;
}
n = read(fd, contents, sizeof(contents));
if (n < 0)
return -errno;
if (n != 2 || contents[1] != '\n')
return -EIO;
if (contents[0] == '1') {
found_online = true;
break;
} else if (contents[0] == '0')
found_offline = true;
else
return -EIO;
}
return found_online || !found_offline;
}
static int search_and_fopen_internal(const char *path, const char *mode, const char *root, char **search, FILE **_f) {
char **i;
assert(path);
assert(mode);
assert(_f);
if (!path_strv_resolve_uniq(search, root))
return -ENOMEM;
STRV_FOREACH(i, search) {
_cleanup_free_ char *p = NULL;
FILE *f;
if (root)
p = strjoin(root, *i, "/", path, NULL);
else
p = strjoin(*i, "/", path, NULL);
if (!p)
return -ENOMEM;
f = fopen(p, mode);
if (f) {
*_f = f;
return 0;
}
if (errno != ENOENT)
return -errno;
}
return -ENOENT;
}
int search_and_fopen(const char *path, const char *mode, const char *root, const char **search, FILE **_f) {
_cleanup_strv_free_ char **copy = NULL;
assert(path);
assert(mode);
assert(_f);
if (path_is_absolute(path)) {
FILE *f;
f = fopen(path, mode);
if (f) {
*_f = f;
return 0;
}
return -errno;
}
copy = strv_copy((char**) search);
if (!copy)
return -ENOMEM;
return search_and_fopen_internal(path, mode, root, copy, _f);
}
int search_and_fopen_nulstr(const char *path, const char *mode, const char *root, const char *search, FILE **_f) {
_cleanup_strv_free_ char **s = NULL;
if (path_is_absolute(path)) {
FILE *f;
f = fopen(path, mode);
if (f) {
*_f = f;
return 0;
}
return -errno;
}
s = strv_split_nulstr(search);
if (!s)
return -ENOMEM;
return search_and_fopen_internal(path, mode, root, s, _f);
}
void* greedy_realloc(void **p, size_t *allocated, size_t need, size_t size) {
size_t a, newalloc;
void *q;
assert(p);
assert(allocated);
if (*allocated >= need)
return *p;
newalloc = MAX(need * 2, 64u / size);
a = newalloc * size;
/* check for overflows */
if (a < size * need)
return NULL;
q = realloc(*p, a);
if (!q)
return NULL;
*p = q;
*allocated = newalloc;
return q;
}
void* greedy_realloc0(void **p, size_t *allocated, size_t need, size_t size) {
size_t prev;
uint8_t *q;
assert(p);
assert(allocated);
prev = *allocated;
q = greedy_realloc(p, allocated, need, size);
if (!q)
return NULL;
if (*allocated > prev)
memzero(q + prev * size, (*allocated - prev) * size);
return q;
}
bool id128_is_valid(const char *s) {
size_t i, l;
l = strlen(s);
if (l == 32) {
/* Simple formatted 128bit hex string */
for (i = 0; i < l; i++) {
char c = s[i];
if (!(c >= '0' && c <= '9') &&
!(c >= 'a' && c <= 'z') &&
!(c >= 'A' && c <= 'Z'))
return false;
}
} else if (l == 36) {
/* Formatted UUID */
for (i = 0; i < l; i++) {
char c = s[i];
if ((i == 8 || i == 13 || i == 18 || i == 23)) {
if (c != '-')
return false;
} else {
if (!(c >= '0' && c <= '9') &&
!(c >= 'a' && c <= 'z') &&
!(c >= 'A' && c <= 'Z'))
return false;
}
}
} else
return false;
return true;
}
int shall_restore_state(void) {
_cleanup_free_ char *value = NULL;
int r;
r = get_proc_cmdline_key("systemd.restore_state=", &value);
if (r < 0)
return r;
if (r == 0)
return true;
return parse_boolean(value) != 0;
}
int proc_cmdline(char **ret) {
assert(ret);
if (detect_container() > 0)
return get_process_cmdline(1, 0, false, ret);
else
return read_one_line_file("/proc/cmdline", ret);
}
int parse_proc_cmdline(int (*parse_item)(const char *key, const char *value)) {
_cleanup_free_ char *line = NULL;
const char *p;
int r;
assert(parse_item);
r = proc_cmdline(&line);
if (r < 0)
return r;
p = line;
for (;;) {
_cleanup_free_ char *word = NULL;
char *value = NULL;
r = extract_first_word(&p, &word, NULL, EXTRACT_QUOTES|EXTRACT_RELAX);
if (r < 0)
return r;
if (r == 0)
break;
/* Filter out arguments that are intended only for the
* initrd */
if (!in_initrd() && startswith(word, "rd."))
continue;
value = strchr(word, '=');
if (value)
*(value++) = 0;
r = parse_item(word, value);
if (r < 0)
return r;
}
return 0;
}
int get_proc_cmdline_key(const char *key, char **value) {
_cleanup_free_ char *line = NULL, *ret = NULL;
bool found = false;
const char *p;
int r;
assert(key);
r = proc_cmdline(&line);
if (r < 0)
return r;
p = line;
for (;;) {
_cleanup_free_ char *word = NULL;
const char *e;
r = extract_first_word(&p, &word, NULL, EXTRACT_QUOTES|EXTRACT_RELAX);
if (r < 0)
return r;
if (r == 0)
break;
/* Filter out arguments that are intended only for the
* initrd */
if (!in_initrd() && startswith(word, "rd."))
continue;
if (value) {
e = startswith(word, key);
if (!e)
continue;
r = free_and_strdup(&ret, e);
if (r < 0)
return r;
found = true;
} else {
if (streq(word, key))
found = true;
}
}
if (value) {
*value = ret;
ret = NULL;
}
return found;
}
int container_get_leader(const char *machine, pid_t *pid) {
_cleanup_free_ char *s = NULL, *class = NULL;
const char *p;
pid_t leader;
int r;
assert(machine);
assert(pid);
if (!machine_name_is_valid(machine))
return -EINVAL;
p = strjoina("/run/systemd/machines/", machine);
r = parse_env_file(p, NEWLINE, "LEADER", &s, "CLASS", &class, NULL);
if (r == -ENOENT)
return -EHOSTDOWN;
if (r < 0)
return r;
if (!s)
return -EIO;
if (!streq_ptr(class, "container"))
return -EIO;
r = parse_pid(s, &leader);
if (r < 0)
return r;
if (leader <= 1)
return -EIO;
*pid = leader;
return 0;
}
int namespace_open(pid_t pid, int *pidns_fd, int *mntns_fd, int *netns_fd, int *userns_fd, int *root_fd) {
_cleanup_close_ int pidnsfd = -1, mntnsfd = -1, netnsfd = -1, usernsfd = -1;
int rfd = -1;
assert(pid >= 0);
if (mntns_fd) {
const char *mntns;
mntns = procfs_file_alloca(pid, "ns/mnt");
mntnsfd = open(mntns, O_RDONLY|O_NOCTTY|O_CLOEXEC);
if (mntnsfd < 0)
return -errno;
}
if (pidns_fd) {
const char *pidns;
pidns = procfs_file_alloca(pid, "ns/pid");
pidnsfd = open(pidns, O_RDONLY|O_NOCTTY|O_CLOEXEC);
if (pidnsfd < 0)
return -errno;
}
if (netns_fd) {
const char *netns;
netns = procfs_file_alloca(pid, "ns/net");
netnsfd = open(netns, O_RDONLY|O_NOCTTY|O_CLOEXEC);
if (netnsfd < 0)
return -errno;
}
if (userns_fd) {
const char *userns;
userns = procfs_file_alloca(pid, "ns/user");
usernsfd = open(userns, O_RDONLY|O_NOCTTY|O_CLOEXEC);
if (usernsfd < 0 && errno != ENOENT)
return -errno;
}
if (root_fd) {
const char *root;
root = procfs_file_alloca(pid, "root");
rfd = open(root, O_RDONLY|O_NOCTTY|O_CLOEXEC|O_DIRECTORY);
if (rfd < 0)
return -errno;
}
if (pidns_fd)
*pidns_fd = pidnsfd;
if (mntns_fd)
*mntns_fd = mntnsfd;
if (netns_fd)
*netns_fd = netnsfd;
if (userns_fd)
*userns_fd = usernsfd;
if (root_fd)
*root_fd = rfd;
pidnsfd = mntnsfd = netnsfd = usernsfd = -1;
return 0;
}
int namespace_enter(int pidns_fd, int mntns_fd, int netns_fd, int userns_fd, int root_fd) {
if (userns_fd >= 0) {
/* Can't setns to your own userns, since then you could
* escalate from non-root to root in your own namespace, so
* check if namespaces equal before attempting to enter. */
_cleanup_free_ char *userns_fd_path = NULL;
int r;
if (asprintf(&userns_fd_path, "/proc/self/fd/%d", userns_fd) < 0)
return -ENOMEM;
r = files_same(userns_fd_path, "/proc/self/ns/user");
if (r < 0)
return r;
if (r)
userns_fd = -1;
}
if (pidns_fd >= 0)
if (setns(pidns_fd, CLONE_NEWPID) < 0)
return -errno;
if (mntns_fd >= 0)
if (setns(mntns_fd, CLONE_NEWNS) < 0)
return -errno;
if (netns_fd >= 0)
if (setns(netns_fd, CLONE_NEWNET) < 0)
return -errno;
if (userns_fd >= 0)
if (setns(userns_fd, CLONE_NEWUSER) < 0)
return -errno;
if (root_fd >= 0) {
if (fchdir(root_fd) < 0)
return -errno;
if (chroot(".") < 0)
return -errno;
}
return reset_uid_gid();
}
/* This is much like like mkostemp() but is subject to umask(). */
int mkostemp_safe(char *pattern, int flags) {
_cleanup_umask_ mode_t u;
int fd;
assert(pattern);
u = umask(077);
fd = mkostemp(pattern, flags);
if (fd < 0)
return -errno;
return fd;
}
int open_tmpfile(const char *path, int flags) {
char *p;
int fd;
assert(path);
#ifdef O_TMPFILE
/* Try O_TMPFILE first, if it is supported */
fd = open(path, flags|O_TMPFILE|O_EXCL, S_IRUSR|S_IWUSR);
if (fd >= 0)
return fd;
#endif
/* Fall back to unguessable name + unlinking */
p = strjoina(path, "/systemd-tmp-XXXXXX");
fd = mkostemp_safe(p, flags);
if (fd < 0)
return fd;
unlink(p);
return fd;
}
int fd_warn_permissions(const char *path, int fd) {
struct stat st;
if (fstat(fd, &st) < 0)
return -errno;
if (st.st_mode & 0111)
log_warning("Configuration file %s is marked executable. Please remove executable permission bits. Proceeding anyway.", path);
if (st.st_mode & 0002)
log_warning("Configuration file %s is marked world-writable. Please remove world writability permission bits. Proceeding anyway.", path);
if (getpid() == 1 && (st.st_mode & 0044) != 0044)
log_warning("Configuration file %s is marked world-inaccessible. This has no effect as configuration data is accessible via APIs without restrictions. Proceeding anyway.", path);
return 0;
}
unsigned long personality_from_string(const char *p) {
/* Parse a personality specifier. We introduce our own
* identifiers that indicate specific ABIs, rather than just
* hints regarding the register size, since we want to keep
* things open for multiple locally supported ABIs for the
* same register size. We try to reuse the ABI identifiers
* used by libseccomp. */
#if defined(__x86_64__)
if (streq(p, "x86"))
return PER_LINUX32;
if (streq(p, "x86-64"))
return PER_LINUX;
#elif defined(__i386__)
if (streq(p, "x86"))
return PER_LINUX;
#elif defined(__s390x__)
if (streq(p, "s390"))
return PER_LINUX32;
if (streq(p, "s390x"))
return PER_LINUX;
#elif defined(__s390__)
if (streq(p, "s390"))
return PER_LINUX;
#endif
return PERSONALITY_INVALID;
}
const char* personality_to_string(unsigned long p) {
#if defined(__x86_64__)
if (p == PER_LINUX32)
return "x86";
if (p == PER_LINUX)
return "x86-64";
#elif defined(__i386__)
if (p == PER_LINUX)
return "x86";
#elif defined(__s390x__)
if (p == PER_LINUX)
return "s390x";
if (p == PER_LINUX32)
return "s390";
#elif defined(__s390__)
if (p == PER_LINUX)
return "s390";
#endif
return NULL;
}
uint64_t physical_memory(void) {
long mem;
/* We return this as uint64_t in case we are running as 32bit
* process on a 64bit kernel with huge amounts of memory */
mem = sysconf(_SC_PHYS_PAGES);
assert(mem > 0);
return (uint64_t) mem * (uint64_t) page_size();
}
int update_reboot_param_file(const char *param) {
int r = 0;
if (param) {
r = write_string_file(REBOOT_PARAM_FILE, param, WRITE_STRING_FILE_CREATE);
if (r < 0)
return log_error_errno(r, "Failed to write reboot param to "REBOOT_PARAM_FILE": %m");
} else
(void) unlink(REBOOT_PARAM_FILE);
return 0;
}
int umount_recursive(const char *prefix, int flags) {
bool again;
int n = 0, r;
/* Try to umount everything recursively below a
* directory. Also, take care of stacked mounts, and keep
* unmounting them until they are gone. */
do {
_cleanup_fclose_ FILE *proc_self_mountinfo = NULL;
again = false;
r = 0;
proc_self_mountinfo = fopen("/proc/self/mountinfo", "re");
if (!proc_self_mountinfo)
return -errno;
for (;;) {
_cleanup_free_ char *path = NULL, *p = NULL;
int k;
k = fscanf(proc_self_mountinfo,
"%*s " /* (1) mount id */
"%*s " /* (2) parent id */
"%*s " /* (3) major:minor */
"%*s " /* (4) root */
"%ms " /* (5) mount point */
"%*s" /* (6) mount options */
"%*[^-]" /* (7) optional fields */
"- " /* (8) separator */
"%*s " /* (9) file system type */
"%*s" /* (10) mount source */
"%*s" /* (11) mount options 2 */
"%*[^\n]", /* some rubbish at the end */
&path);
if (k != 1) {
if (k == EOF)
break;
continue;
}
r = cunescape(path, UNESCAPE_RELAX, &p);
if (r < 0)
return r;
if (!path_startswith(p, prefix))
continue;
if (umount2(p, flags) < 0) {
r = -errno;
continue;
}
again = true;
n++;
break;
}
} while (again);
return r ? r : n;
}
static int get_mount_flags(const char *path, unsigned long *flags) {
struct statvfs buf;
if (statvfs(path, &buf) < 0)
return -errno;
*flags = buf.f_flag;
return 0;
}
int bind_remount_recursive(const char *prefix, bool ro) {
_cleanup_set_free_free_ Set *done = NULL;
_cleanup_free_ char *cleaned = NULL;
int r;
/* Recursively remount a directory (and all its submounts)
* read-only or read-write. If the directory is already
* mounted, we reuse the mount and simply mark it
* MS_BIND|MS_RDONLY (or remove the MS_RDONLY for read-write
* operation). If it isn't we first make it one. Afterwards we
* apply MS_BIND|MS_RDONLY (or remove MS_RDONLY) to all
* submounts we can access, too. When mounts are stacked on
* the same mount point we only care for each individual
* "top-level" mount on each point, as we cannot
* influence/access the underlying mounts anyway. We do not
* have any effect on future submounts that might get
* propagated, they migt be writable. This includes future
* submounts that have been triggered via autofs. */
cleaned = strdup(prefix);
if (!cleaned)
return -ENOMEM;
path_kill_slashes(cleaned);
done = set_new(&string_hash_ops);
if (!done)
return -ENOMEM;
for (;;) {
_cleanup_fclose_ FILE *proc_self_mountinfo = NULL;
_cleanup_set_free_free_ Set *todo = NULL;
bool top_autofs = false;
char *x;
unsigned long orig_flags;
todo = set_new(&string_hash_ops);
if (!todo)
return -ENOMEM;
proc_self_mountinfo = fopen("/proc/self/mountinfo", "re");
if (!proc_self_mountinfo)
return -errno;
for (;;) {
_cleanup_free_ char *path = NULL, *p = NULL, *type = NULL;
int k;
k = fscanf(proc_self_mountinfo,
"%*s " /* (1) mount id */
"%*s " /* (2) parent id */
"%*s " /* (3) major:minor */
"%*s " /* (4) root */
"%ms " /* (5) mount point */
"%*s" /* (6) mount options (superblock) */
"%*[^-]" /* (7) optional fields */
"- " /* (8) separator */
"%ms " /* (9) file system type */
"%*s" /* (10) mount source */
"%*s" /* (11) mount options (bind mount) */
"%*[^\n]", /* some rubbish at the end */
&path,
&type);
if (k != 2) {
if (k == EOF)
break;
continue;
}
r = cunescape(path, UNESCAPE_RELAX, &p);
if (r < 0)
return r;
/* Let's ignore autofs mounts. If they aren't
* triggered yet, we want to avoid triggering
* them, as we don't make any guarantees for
* future submounts anyway. If they are
* already triggered, then we will find
* another entry for this. */
if (streq(type, "autofs")) {
top_autofs = top_autofs || path_equal(cleaned, p);
continue;
}
if (path_startswith(p, cleaned) &&
!set_contains(done, p)) {
r = set_consume(todo, p);
p = NULL;
if (r == -EEXIST)
continue;
if (r < 0)
return r;
}
}
/* If we have no submounts to process anymore and if
* the root is either already done, or an autofs, we
* are done */
if (set_isempty(todo) &&
(top_autofs || set_contains(done, cleaned)))
return 0;
if (!set_contains(done, cleaned) &&
!set_contains(todo, cleaned)) {
/* The prefix directory itself is not yet a
* mount, make it one. */
if (mount(cleaned, cleaned, NULL, MS_BIND|MS_REC, NULL) < 0)
return -errno;
orig_flags = 0;
(void) get_mount_flags(cleaned, &orig_flags);
orig_flags &= ~MS_RDONLY;
if (mount(NULL, prefix, NULL, orig_flags|MS_BIND|MS_REMOUNT|(ro ? MS_RDONLY : 0), NULL) < 0)
return -errno;
x = strdup(cleaned);
if (!x)
return -ENOMEM;
r = set_consume(done, x);
if (r < 0)
return r;
}
while ((x = set_steal_first(todo))) {
r = set_consume(done, x);
if (r == -EEXIST || r == 0)
continue;
if (r < 0)
return r;
/* Try to reuse the original flag set, but
* don't care for errors, in case of
* obstructed mounts */
orig_flags = 0;
(void) get_mount_flags(x, &orig_flags);
orig_flags &= ~MS_RDONLY;
if (mount(NULL, x, NULL, orig_flags|MS_BIND|MS_REMOUNT|(ro ? MS_RDONLY : 0), NULL) < 0) {
/* Deal with mount points that are
* obstructed by a later mount */
if (errno != ENOENT)
return -errno;
}
}
}
}
int fflush_and_check(FILE *f) {
assert(f);
errno = 0;
fflush(f);
if (ferror(f))
return errno ? -errno : -EIO;
return 0;
}
int tempfn_xxxxxx(const char *p, const char *extra, char **ret) {
const char *fn;
char *t;
assert(p);
assert(ret);
/*
* Turns this:
* /foo/bar/waldo
*
* Into this:
* /foo/bar/.#<extra>waldoXXXXXX
*/
fn = basename(p);
if (!filename_is_valid(fn))
return -EINVAL;
if (extra == NULL)
extra = "";
t = new(char, strlen(p) + 2 + strlen(extra) + 6 + 1);
if (!t)
return -ENOMEM;
strcpy(stpcpy(stpcpy(stpcpy(mempcpy(t, p, fn - p), ".#"), extra), fn), "XXXXXX");
*ret = path_kill_slashes(t);
return 0;
}
int tempfn_random(const char *p, const char *extra, char **ret) {
const char *fn;
char *t, *x;
uint64_t u;
unsigned i;
assert(p);
assert(ret);
/*
* Turns this:
* /foo/bar/waldo
*
* Into this:
* /foo/bar/.#<extra>waldobaa2a261115984a9
*/
fn = basename(p);
if (!filename_is_valid(fn))
return -EINVAL;
if (!extra)
extra = "";
t = new(char, strlen(p) + 2 + strlen(extra) + 16 + 1);
if (!t)
return -ENOMEM;
x = stpcpy(stpcpy(stpcpy(mempcpy(t, p, fn - p), ".#"), extra), fn);
u = random_u64();
for (i = 0; i < 16; i++) {
*(x++) = hexchar(u & 0xF);
u >>= 4;
}
*x = 0;
*ret = path_kill_slashes(t);
return 0;
}
int tempfn_random_child(const char *p, const char *extra, char **ret) {
char *t, *x;
uint64_t u;
unsigned i;
assert(p);
assert(ret);
/* Turns this:
* /foo/bar/waldo
* Into this:
* /foo/bar/waldo/.#<extra>3c2b6219aa75d7d0
*/
if (!extra)
extra = "";
t = new(char, strlen(p) + 3 + strlen(extra) + 16 + 1);
if (!t)
return -ENOMEM;
x = stpcpy(stpcpy(stpcpy(t, p), "/.#"), extra);
u = random_u64();
for (i = 0; i < 16; i++) {
*(x++) = hexchar(u & 0xF);
u >>= 4;
}
*x = 0;
*ret = path_kill_slashes(t);
return 0;
}
int take_password_lock(const char *root) {
struct flock flock = {
.l_type = F_WRLCK,
.l_whence = SEEK_SET,
.l_start = 0,
.l_len = 0,
};
const char *path;
int fd, r;
/* This is roughly the same as lckpwdf(), but not as awful. We
* don't want to use alarm() and signals, hence we implement
* our own trivial version of this.
*
* Note that shadow-utils also takes per-database locks in
* addition to lckpwdf(). However, we don't given that they
* are redundant as they they invoke lckpwdf() first and keep
* it during everything they do. The per-database locks are
* awfully racy, and thus we just won't do them. */
if (root)
path = strjoina(root, "/etc/.pwd.lock");
else
path = "/etc/.pwd.lock";
fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW, 0600);
if (fd < 0)
return -errno;
r = fcntl(fd, F_SETLKW, &flock);
if (r < 0) {
safe_close(fd);
return -errno;
}
return fd;
}
int is_symlink(const char *path) {
struct stat info;
if (lstat(path, &info) < 0)
return -errno;
return !!S_ISLNK(info.st_mode);
}
int is_dir(const char* path, bool follow) {
struct stat st;
int r;
if (follow)
r = stat(path, &st);
else
r = lstat(path, &st);
if (r < 0)
return -errno;
return !!S_ISDIR(st.st_mode);
}
int is_device_node(const char *path) {
struct stat info;
if (lstat(path, &info) < 0)
return -errno;
return !!(S_ISBLK(info.st_mode) || S_ISCHR(info.st_mode));
}
ssize_t fgetxattrat_fake(int dirfd, const char *filename, const char *attribute, void *value, size_t size, int flags) {
char fn[strlen("/proc/self/fd/") + DECIMAL_STR_MAX(int) + 1];
_cleanup_close_ int fd = -1;
ssize_t l;
/* The kernel doesn't have a fgetxattrat() command, hence let's emulate one */
fd = openat(dirfd, filename, O_RDONLY|O_CLOEXEC|O_NOCTTY|O_PATH|(flags & AT_SYMLINK_NOFOLLOW ? O_NOFOLLOW : 0));
if (fd < 0)
return -errno;
xsprintf(fn, "/proc/self/fd/%i", fd);
l = getxattr(fn, attribute, value, size);
if (l < 0)
return -errno;
return l;
}
static int parse_crtime(le64_t le, usec_t *usec) {
uint64_t u;
assert(usec);
u = le64toh(le);
if (u == 0 || u == (uint64_t) -1)
return -EIO;
*usec = (usec_t) u;
return 0;
}
int fd_getcrtime(int fd, usec_t *usec) {
le64_t le;
ssize_t n;
assert(fd >= 0);
assert(usec);
/* Until Linux gets a real concept of birthtime/creation time,
* let's fake one with xattrs */
n = fgetxattr(fd, "user.crtime_usec", &le, sizeof(le));
if (n < 0)
return -errno;
if (n != sizeof(le))
return -EIO;
return parse_crtime(le, usec);
}
int fd_getcrtime_at(int dirfd, const char *name, usec_t *usec, int flags) {
le64_t le;
ssize_t n;
n = fgetxattrat_fake(dirfd, name, "user.crtime_usec", &le, sizeof(le), flags);
if (n < 0)
return -errno;
if (n != sizeof(le))
return -EIO;
return parse_crtime(le, usec);
}
int path_getcrtime(const char *p, usec_t *usec) {
le64_t le;
ssize_t n;
assert(p);
assert(usec);
n = getxattr(p, "user.crtime_usec", &le, sizeof(le));
if (n < 0)
return -errno;
if (n != sizeof(le))
return -EIO;
return parse_crtime(le, usec);
}
int fd_setcrtime(int fd, usec_t usec) {
le64_t le;
assert(fd >= 0);
if (usec <= 0)
usec = now(CLOCK_REALTIME);
le = htole64((uint64_t) usec);
if (fsetxattr(fd, "user.crtime_usec", &le, sizeof(le), 0) < 0)
return -errno;
return 0;
}
int chattr_fd(int fd, unsigned value, unsigned mask) {
unsigned old_attr, new_attr;
struct stat st;
assert(fd >= 0);
if (fstat(fd, &st) < 0)
return -errno;
/* Explicitly check whether this is a regular file or
* directory. If it is anything else (such as a device node or
* fifo), then the ioctl will not hit the file systems but
* possibly drivers, where the ioctl might have different
* effects. Notably, DRM is using the same ioctl() number. */
if (!S_ISDIR(st.st_mode) && !S_ISREG(st.st_mode))
return -ENOTTY;
if (mask == 0)
return 0;
if (ioctl(fd, FS_IOC_GETFLAGS, &old_attr) < 0)
return -errno;
new_attr = (old_attr & ~mask) | (value & mask);
if (new_attr == old_attr)
return 0;
if (ioctl(fd, FS_IOC_SETFLAGS, &new_attr) < 0)
return -errno;
return 1;
}
int chattr_path(const char *p, unsigned value, unsigned mask) {
_cleanup_close_ int fd = -1;
assert(p);
if (mask == 0)
return 0;
fd = open(p, O_RDONLY|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW);
if (fd < 0)
return -errno;
return chattr_fd(fd, value, mask);
}
int read_attr_fd(int fd, unsigned *ret) {
struct stat st;
assert(fd >= 0);
if (fstat(fd, &st) < 0)
return -errno;
if (!S_ISDIR(st.st_mode) && !S_ISREG(st.st_mode))
return -ENOTTY;
if (ioctl(fd, FS_IOC_GETFLAGS, ret) < 0)
return -errno;
return 0;
}
int read_attr_path(const char *p, unsigned *ret) {
_cleanup_close_ int fd = -1;
assert(p);
assert(ret);
fd = open(p, O_RDONLY|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW);
if (fd < 0)
return -errno;
return read_attr_fd(fd, ret);
}
int syslog_parse_priority(const char **p, int *priority, bool with_facility) {
int a = 0, b = 0, c = 0;
int k;
assert(p);
assert(*p);
assert(priority);
if ((*p)[0] != '<')
return 0;
if (!strchr(*p, '>'))
return 0;
if ((*p)[2] == '>') {
c = undecchar((*p)[1]);
k = 3;
} else if ((*p)[3] == '>') {
b = undecchar((*p)[1]);
c = undecchar((*p)[2]);
k = 4;
} else if ((*p)[4] == '>') {
a = undecchar((*p)[1]);
b = undecchar((*p)[2]);
c = undecchar((*p)[3]);
k = 5;
} else
return 0;
if (a < 0 || b < 0 || c < 0 ||
(!with_facility && (a || b || c > 7)))
return 0;
if (with_facility)
*priority = a*100 + b*10 + c;
else
*priority = (*priority & LOG_FACMASK) | c;
*p += k;
return 1;
}
ssize_t string_table_lookup(const char * const *table, size_t len, const char *key) {
size_t i;
if (!key)
return -1;
for (i = 0; i < len; ++i)
if (streq_ptr(table[i], key))
return (ssize_t) i;
return -1;
}
int rename_noreplace(int olddirfd, const char *oldpath, int newdirfd, const char *newpath) {
struct stat buf;
int ret;
ret = renameat2(olddirfd, oldpath, newdirfd, newpath, RENAME_NOREPLACE);
if (ret >= 0)
return 0;
/* renameat2() exists since Linux 3.15, btrfs added support for it later.
* If it is not implemented, fallback to another method. */
if (!IN_SET(errno, EINVAL, ENOSYS))
return -errno;
/* The link()/unlink() fallback does not work on directories. But
* renameat() without RENAME_NOREPLACE gives the same semantics on
* directories, except when newpath is an *empty* directory. This is
* good enough. */
ret = fstatat(olddirfd, oldpath, &buf, AT_SYMLINK_NOFOLLOW);
if (ret >= 0 && S_ISDIR(buf.st_mode)) {
ret = renameat(olddirfd, oldpath, newdirfd, newpath);
return ret >= 0 ? 0 : -errno;
}
/* If it is not a directory, use the link()/unlink() fallback. */
ret = linkat(olddirfd, oldpath, newdirfd, newpath, 0);
if (ret < 0)
return -errno;
ret = unlinkat(olddirfd, oldpath, 0);
if (ret < 0) {
/* backup errno before the following unlinkat() alters it */
ret = errno;
(void) unlinkat(newdirfd, newpath, 0);
errno = ret;
return -errno;
}
return 0;
}
int mount_move_root(const char *path) {
assert(path);
if (chdir(path) < 0)
return -errno;
if (mount(path, "/", NULL, MS_MOVE, NULL) < 0)
return -errno;
if (chroot(".") < 0)
return -errno;
if (chdir("/") < 0)
return -errno;
return 0;
}
int getxattr_malloc(const char *path, const char *name, char **value, bool allow_symlink) {
char *v;
size_t l;
ssize_t n;
assert(path);
assert(name);
assert(value);
for (l = 100; ; l = (size_t) n + 1) {
v = new0(char, l);
if (!v)
return -ENOMEM;
if (allow_symlink)
n = lgetxattr(path, name, v, l);
else
n = getxattr(path, name, v, l);
if (n >= 0 && (size_t) n < l) {
*value = v;
return n;
}
free(v);
if (n < 0 && errno != ERANGE)
return -errno;
if (allow_symlink)
n = lgetxattr(path, name, NULL, 0);
else
n = getxattr(path, name, NULL, 0);
if (n < 0)
return -errno;
}
}
int fgetxattr_malloc(int fd, const char *name, char **value) {
char *v;
size_t l;
ssize_t n;
assert(fd >= 0);
assert(name);
assert(value);
for (l = 100; ; l = (size_t) n + 1) {
v = new0(char, l);
if (!v)
return -ENOMEM;
n = fgetxattr(fd, name, v, l);
if (n >= 0 && (size_t) n < l) {
*value = v;
return n;
}
free(v);
if (n < 0 && errno != ERANGE)
return -errno;
n = fgetxattr(fd, name, NULL, 0);
if (n < 0)
return -errno;
}
}
int version(void) {
puts(PACKAGE_STRING "\n"
SYSTEMD_FEATURES);
return 0;
}
bool fdname_is_valid(const char *s) {
const char *p;
/* Validates a name for $LISTEN_FDNAMES. We basically allow
* everything ASCII that's not a control character. Also, as
* special exception the ":" character is not allowed, as we
* use that as field separator in $LISTEN_FDNAMES.
*
* Note that the empty string is explicitly allowed
* here. However, we limit the length of the names to 255
* characters. */
if (!s)
return false;
for (p = s; *p; p++) {
if (*p < ' ')
return false;
if (*p >= 127)
return false;
if (*p == ':')
return false;
}
return p - s < 256;
}
bool oom_score_adjust_is_valid(int oa) {
return oa >= OOM_SCORE_ADJ_MIN && oa <= OOM_SCORE_ADJ_MAX;
}
|