File: pam_cgfs.c

package info (click to toggle)
lxcfs 2.0.7-1%2Bdeb9u1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 2,160 kB
  • sloc: ansic: 6,678; sh: 4,630; makefile: 159
file content (2587 lines) | stat: -rw-r--r-- 65,140 bytes parent folder | download
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
/* pam-cgfs
 *
 * Copyright © 2016 Canonical, Inc
 * Author: Serge Hallyn <serge.hallyn@ubuntu.com>
 * Author: Christian Brauner <christian.brauner@ubuntu.com>
 *
 * When a user logs in, this pam module will create cgroups which the user may
 * administer. It handles both pure cgroupfs v1 and pure cgroupfs v2, as well as
 * mixed mounts, where some controllers are mounted in a standard cgroupfs v1
 * hierarchy location (/sys/fs/cgroup/<controller>) and others are in the
 * cgroupfs v2 hierarchy.
 * Writeable cgroups are either created for all controllers or, if specified,
 * for any controllers listed on the command line.
 * The cgroup created will be "user/$user/0" for the first session,
 * "user/$user/1" for the second, etc.
 *
 * Systems with a systemd init system are treated specially, both with respect
 * to cgroupfs v1 and cgroupfs v2. For both, cgroupfs v1 and cgroupfs v2, We
 * check whether systemd already placed us in a cgroup it created:
 *
 *	user.slice/user-uid.slice/session-n.scope
 *
 * by checking whether uid == our uid. If it did, we simply chown the last
 * part (session-n.scope). If it did not we create a cgroup as outlined above
 * (user/$user/n) and chown it to our uid.
 * The same holds for cgroupfs v2 where this assumptions becomes crucial:
 * We __have to__ be placed in our under the cgroup systemd created for us on
 * login, otherwise things like starting an xserver or similar will not work.
 *
 * All requested cgroups must be mounted under /sys/fs/cgroup/$controller,
 * no messing around with finding mountpoints.
 *
 * See COPYING file for details.
 */

#include <ctype.h>
#include <dirent.h>
#include <errno.h>
#include <fcntl.h>
#include <pwd.h>
#include <stdarg.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <syslog.h>
#include <unistd.h>
#include <linux/unistd.h>
#include <sys/mount.h>
#include <sys/param.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/vfs.h>

#define PAM_SM_SESSION
#include <security/_pam_macros.h>
#include <security/pam_modules.h>

#include "macro.h"

#ifndef CGROUP_SUPER_MAGIC
#define CGROUP_SUPER_MAGIC 0x27e0eb
#endif

#ifndef CGROUP2_SUPER_MAGIC
#define CGROUP2_SUPER_MAGIC 0x63677270
#endif

/* Taken over modified from the kernel sources. */
#define NBITS 32 /* bits in uint32_t */
#define DIV_ROUND_UP(n, d) (((n) + (d)-1) / (d))
#define BITS_TO_LONGS(nr) DIV_ROUND_UP(nr, NBITS)

static enum cg_mount_mode {
	CGROUP_UNKNOWN = -1,
	CGROUP_MIXED = 0,
	CGROUP_PURE_V1 = 1,
	CGROUP_PURE_V2 = 2,
	CGROUP_UNINITIALIZED = 3,
} cg_mount_mode = CGROUP_UNINITIALIZED;

/* Common helper functions. Most of these have been taken from LXC. */
static void append_line(char **dest, size_t oldlen, char *new, size_t newlen);
static int append_null_to_list(void ***list);
static void batch_realloc(char **mem, size_t oldlen, size_t newlen);
static inline void clear_bit(unsigned bit, uint32_t *bitarr)
{
	bitarr[bit / NBITS] &= ~(1 << (bit % NBITS));
}
static char *copy_to_eol(char *s);
static bool file_exists(const char *f);
static void free_string_list(char **list);
static char *get_mountpoint(char *line);
static bool get_uid_gid(const char *user, uid_t *uid, gid_t *gid);
static int handle_login(const char *user, uid_t uid, gid_t gid);
static inline bool is_set(unsigned bit, uint32_t *bitarr)
{
	return (bitarr[bit / NBITS] & (1 << (bit % NBITS))) != 0;
}
/* __typeof__ should be safe to use with all compilers. */
typedef __typeof__(((struct statfs *)NULL)->f_type) fs_type_magic;
static bool has_fs_type(const struct statfs *fs, fs_type_magic magic_val);
static bool is_lxcfs(const char *line);
static bool is_cgv1(char *line);
static bool is_cgv2(char *line);
static bool mkdir_p(const char *root, char *path);
static void *must_alloc(size_t sz);
static void must_add_to_list(char ***clist, char *entry);
static void must_append_controller(char **klist, char **nlist, char ***clist,
				   char *entry);
static void must_append_string(char ***list, char *entry);
static char *must_copy_string(const char *entry);
static char *must_make_path(const char *first, ...) __attribute__((sentinel));
static void *must_realloc(void *orig, size_t sz);
static void mysyslog(int err, const char *format, ...) __attribute__((sentinel));
static char *read_file(char *fnam);
static int read_from_file(const char *filename, void* buf, size_t count);
static int recursive_rmdir(char *dirname);
static inline void set_bit(unsigned bit, uint32_t *bitarr)
{
	bitarr[bit / NBITS] |= (1 << (bit % NBITS));
}
static bool string_in_list(char **list, const char *entry);
static char *string_join(const char *sep, const char **parts, bool use_as_prefix);
static void trim(char *s);
static bool write_int(char *path, int v);
static ssize_t write_nointr(int fd, const void* buf, size_t count);
static int write_to_file(const char *filename, const void *buf, size_t count,
			 bool add_newline);

/* cgroupfs prototypes. */
static bool cg_belongs_to_uid_gid(const char *path, uid_t uid, gid_t gid);
static uint32_t *cg_cpumask(char *buf, size_t nbits);
static bool cg_copy_parent_file(char *path, char *file);
static char *cg_cpumask_to_cpulist(uint32_t *bitarr, size_t nbits);
static bool cg_enter(const char *cgroup);
static void cg_escape(void);
static bool cg_filter_and_set_cpus(char *path, bool am_initialized);
static ssize_t cg_get_max_cpus(char *cpulist);
static int cg_get_version_of_mntpt(const char *path);
static bool cg_init(uid_t uid, gid_t gid);
static void cg_mark_to_make_rw(const char *cstring);
static void cg_prune_empty_cgroups(const char *user);
static bool cg_systemd_created_user_slice(const char *base_cgroup,
					  const char *init_cgroup,
					  const char *in, uid_t uid);
static bool cg_systemd_chown_existing_cgroup(const char *mountpoint,
					     const char *base_cgroup, uid_t uid,
					     gid_t gid,
					     bool systemd_user_slice);
static bool cg_systemd_under_user_slice_1(const char *in, uid_t uid);
static bool cg_systemd_under_user_slice_2(const char *base_cgroup,
					  const char *init_cgroup, uid_t uid);
static void cg_systemd_prune_init_scope(char *cg);
static bool is_lxcfs(const char *line);

/* cgroupfs v1 prototypes. */
struct cgv1_hierarchy {
	char **controllers;
	char *mountpoint;
	char *base_cgroup;
	char *fullcgpath;
	char *init_cgroup;
	bool create_rw_cgroup;
	bool systemd_user_slice;
};

static struct cgv1_hierarchy **cgv1_hierarchies;

static void cgv1_add_controller(char **clist, char *mountpoint,
				char *base_cgroup, char *init_cgroup);
static bool cgv1_controller_in_clist(char *cgline, char *c);
static bool cgv1_controller_lists_intersect(char **l1, char **l2);
static bool cgv1_controller_list_is_dup(struct cgv1_hierarchy **hlist,
					char **clist);
static bool cgv1_create(const char *cgroup, uid_t uid, gid_t gid,
			bool *existed);
static bool cgv1_create_one(struct cgv1_hierarchy *h, const char *cgroup,
			    uid_t uid, gid_t gid, bool *existed);
static bool cgv1_enter(const char *cgroup);
static void cgv1_escape(void);
static bool cgv1_get_controllers(char ***klist, char ***nlist);
static char *cgv1_get_current_cgroup(char *basecginfo, char *controller);
static char **cgv1_get_proc_mountinfo_controllers(char **klist, char **nlist,
						  char *line);
static bool cgv1_handle_cpuset_hierarchy(struct cgv1_hierarchy *h,
					 const char *cgroup);
static bool cgv1_handle_root_cpuset_hierarchy(struct cgv1_hierarchy *h);
static bool cgv1_init(uid_t uid, gid_t gid);
static void cgv1_mark_to_make_rw(char **clist);
static char *cgv1_must_prefix_named(char *entry);
static bool cgv1_prune_empty_cgroups(const char *user);
static bool cgv1_remove_one(struct cgv1_hierarchy *h, const char *cgroup);
static bool is_cgv1(char *line);

/* cgroupfs v2 prototypes. */
struct cgv2_hierarchy {
	char **controllers;
	char *mountpoint;
	char *base_cgroup;
	char *fullcgpath;
	char *init_cgroup;
	bool create_rw_cgroup;
	bool systemd_user_slice;
};

/* Actually this should only be a single hierarchy. But for the sake of
 * parallelism and because the layout of the cgroupfs v2 is still somewhat
 * changing, we'll leave it as an array of structs.
 */
static struct cgv2_hierarchy **cgv2_hierarchies;

static void cgv2_add_controller(char **clist, char *mountpoint,
				char *base_cgroup, char *init_cgroup,
				bool systemd_user_slice);
static bool cgv2_create(const char *cgroup, uid_t uid, gid_t gid,
			bool *existed);
static bool cgv2_enter(const char *cgroup);
static void cgv2_escape(void);
static char *cgv2_get_current_cgroup(int pid);
static bool cgv2_init(uid_t uid, gid_t gid);
static void cgv2_mark_to_make_rw(char **clist);
static bool cgv2_prune_empty_cgroups(const char *user);
static bool cgv2_remove(const char *cgroup);
static bool is_cgv2(char *line);

/* Common helper functions. Most of these have been taken from LXC. */
static void mysyslog(int err, const char *format, ...)
{
	va_list args;

	va_start(args, format);
	openlog("PAM-CGFS", LOG_CONS | LOG_PID, LOG_AUTH);
	vsyslog(err, format, args);
	va_end(args);
	closelog();
}

/* realloc() pointer; do not fail. */
static void *must_realloc(void *orig, size_t sz)
{
	void *ret;

	do {
		ret = realloc(orig, sz);
	} while (!ret);

	return ret;
}

/* realloc() pointer in batch sizes; do not fail. */
#define BATCH_SIZE 50
static void batch_realloc(char **mem, size_t oldlen, size_t newlen)
{
	int newbatches = (newlen / BATCH_SIZE) + 1;
	int oldbatches = (oldlen / BATCH_SIZE) + 1;

	if (!*mem || newbatches > oldbatches)
		*mem = must_realloc(*mem, newbatches * BATCH_SIZE);
}

/* Append lines as is to pointer; do not fail. */
static void append_line(char **dest, size_t oldlen, char *new, size_t newlen)
{
	size_t full = oldlen + newlen;

	batch_realloc(dest, oldlen, full + 1);

	memcpy(*dest + oldlen, new, newlen + 1);
}

/* Read in whole file and return allocated pointer. */
static char *read_file(char *fnam)
{
	FILE *f;
	int linelen;
	char *line = NULL, *buf = NULL;
	size_t len = 0, fulllen = 0;

	f = fopen(fnam, "r");
	if (!f)
		return NULL;

	while ((linelen = getline(&line, &len, f)) != -1) {
		append_line(&buf, fulllen, line, linelen);
		fulllen += linelen;
	}

	fclose(f);
	free(line);

	return buf;
}

/* Given a pointer to a null-terminated array of pointers, realloc to add one
 * entry, and point the new entry to NULL. Do not fail. Return the index to the
 * second-to-last entry - that is, the one which is now available for use
 * (keeping the list null-terminated).
 */
static int append_null_to_list(void ***list)
{
	int newentry = 0;

	if (*list)
		for (; (*list)[newentry]; newentry++) {
			;
		}

	*list = must_realloc(*list, (newentry + 2) * sizeof(void **));
	(*list)[newentry + 1] = NULL;

	return newentry;
}

/* Make allocated copy of string; do not fail. */
static char *must_copy_string(const char *entry)
{
	char *ret;

	if (!entry)
		return NULL;

	do {
		ret = strdup(entry);
	} while (!ret);

	return ret;
}

/* Append new entry to null-terminated array of pointer; make sure that array of
 * pointers will still be null-terminated.
 */
static void must_append_string(char ***list, char *entry)
{
	int newentry;
	char *copy;

	newentry = append_null_to_list((void ***)list);
	copy = must_copy_string(entry);
	(*list)[newentry] = copy;
}

/* Remove newlines from string. */
static void trim(char *s)
{
	size_t len = strlen(s);

	while ((len > 0) && s[len - 1] == '\n')
		s[--len] = '\0';
}

/* Allocate pointer; do not fail. */
static void *must_alloc(size_t sz)
{
	return must_realloc(NULL, sz);
}

/* Make allocated copy of string. End of string is taken to be '\n'. */
static char *copy_to_eol(char *s)
{
	char *newline, *sret;
	size_t len;

	newline = strchr(s, '\n');
	if (!newline)
		return NULL;

	len = newline - s;
	sret = must_alloc(len + 1);
	memcpy(sret, s, len);
	sret[len] = '\0';

	return sret;
}

/* Check if given entry under /proc/<pid>/mountinfo is a fuse.lxcfs mount. */
static bool is_lxcfs(const char *line)
{
	char *p = strstr(line, " - ");
	if (!p)
		return false;

	return strncmp(p, " - fuse.lxcfs ", 14) == 0;
}

/* Check if given entry under /proc/<pid>/mountinfo is a cgroupfs v1 mount. */
static bool is_cgv1(char *line)
{
	char *p = strstr(line, " - ");
	if (!p)
		return false;

	return strncmp(p, " - cgroup ", 10) == 0;
}

/* Check if given entry under /proc/<pid>/mountinfo is a cgroupfs v2 mount. */
static bool is_cgv2(char *line)
{
	char *p = strstr(line, " - ");
	if (!p)
		return false;

	return strncmp(p, " - cgroup2 ", 11) == 0;
}

/* Given a null-terminated array of strings, check whether @entry is one of the
 * strings
 */
static bool string_in_list(char **list, const char *entry)
{
	char **it;

	for (it = list; it && *it; it++)
		if (strcmp(*it, entry) == 0)
			return true;

	return false;
}

/* Free null-terminated array of strings. */
static void free_string_list(char **list)
{
	char **it;

	for (it = list; it && *it; it++)
		free(*it);
	free(list);
}

/* Concatenate all passed-in strings into one path. Do not fail. If any piece
 * is not prefixed with '/', add a '/'. Does not remove duplicate '///' from the
 * created path.
 */
static char *must_make_path(const char *first, ...)
{
	va_list args;
	char *cur, *dest;
	size_t full_len;

	full_len = strlen(first);

	dest = must_copy_string(first);

	va_start(args, first);
	while ((cur = va_arg(args, char *)) != NULL) {
		full_len += strlen(cur);

		if (cur[0] != '/')
			full_len++;

		dest = must_realloc(dest, full_len + 1);

		if (cur[0] != '/')
			strcat(dest, "/");

		strcat(dest, cur);
	}
	va_end(args);

	return dest;
}

/* Write single integer to file. */
static bool write_int(char *path, int v)
{
	FILE *f;
	bool ret = true;

	f = fopen(path, "w");
	if (!f)
		return false;

	if (fprintf(f, "%d\n", v) < 0)
		ret = false;

	if (fclose(f) != 0)
		ret = false;

	return ret;
}

/* Check if a given file exists. */
static bool file_exists(const char *f)
{
	struct stat statbuf;

	return stat(f, &statbuf) == 0;
}

/* Create directory and (if necessary) its parents. */
static bool mkdir_p(const char *root, char *path)
{
	char *b, orig, *e;

	if (strlen(path) < strlen(root))
		return false;

	if (strlen(path) == strlen(root))
		return true;

	b = path + strlen(root) + 1;
	while (true) {
		while (*b && (*b == '/'))
			b++;
		if (!*b)
			return true;

		e = b + 1;
		while (*e && *e != '/')
			e++;

		orig = *e;
		if (orig)
			*e = '\0';

		if (file_exists(path))
			goto next;

		if (mkdir(path, 0755) < 0) {
			lxcfs_debug("Failed to create %s: %s.\n", path, strerror(errno));
			return false;
		}

	next:
		if (!orig)
			return true;

		*e = orig;
		b = e + 1;
	}

	return false;
}

/* Recursively remove directory and its parents. */
static int recursive_rmdir(char *dirname)
{
	struct dirent *direntp;
	DIR *dir;
	int r = 0;

	dir = opendir(dirname);
	if (!dir)
		return -ENOENT;

	while ((direntp = readdir(dir))) {
		struct stat st;
		char *pathname;

		if (!direntp)
			break;

		if (!strcmp(direntp->d_name, ".") ||
		    !strcmp(direntp->d_name, ".."))
			continue;

		pathname = must_make_path(dirname, direntp->d_name, NULL);

		if (lstat(pathname, &st)) {
			if (!r)
				lxcfs_debug("Failed to stat %s.\n", pathname);
			r = -1;
			goto next;
		}

		if (!S_ISDIR(st.st_mode))
			goto next;

		if (recursive_rmdir(pathname) < 0)
			r = -1;
next:
		free(pathname);
	}

	if (rmdir(dirname) < 0) {
		if (!r)
			lxcfs_debug("Failed to delete %s: %s.\n", dirname, strerror(errno));
		r = -1;
	}

	if (closedir(dir) < 0) {
		if (!r)
			lxcfs_debug("Failed to delete %s: %s.\n", dirname, strerror(errno));
		r = -1;
	}

	return r;
}

/* Add new entry to null-terminated array of pointers. Make sure array is still
 * null-terminated.
 */
static void must_add_to_list(char ***clist, char *entry)
{
	int newentry;

	newentry = append_null_to_list((void ***)clist);
	(*clist)[newentry] = must_copy_string(entry);
}

/* Get mountpoint from a /proc/<pid>/mountinfo line. */
static char *get_mountpoint(char *line)
{
	int i;
	char *p, *sret, *p2;
	size_t len;

	p = line;

	for (i = 0; i < 4; i++) {
		p = strchr(p, ' ');
		if (!p)
			return NULL;
		p++;
	}

	p2 = strchr(p, ' ');
	if (p2)
		*p2 = '\0';

	len = strlen(p);
	sret = must_alloc(len + 1);
	memcpy(sret, p, len);
	sret[len] = '\0';

	return sret;
}

/* Create list of cgroupfs v1 controller found under /proc/self/cgroup. Skips
 * the 0::/some/path cgroupfs v2 hierarchy listed. Splits controllers into
 * kernel controllers (@klist) and named controllers (@nlist).
 */
static bool cgv1_get_controllers(char ***klist, char ***nlist)
{
	FILE *f;
	char *line = NULL;
	size_t len = 0;

	f = fopen("/proc/self/cgroup", "r");
	if (!f)
		return false;

	while (getline(&line, &len, f) != -1) {
		char *p, *p2, *tok;
		char *saveptr = NULL;

		p = strchr(line, ':');
		if (!p)
			continue;
		p++;

		p2 = strchr(p, ':');
		if (!p2)
			continue;
		*p2 = '\0';

		/* Skip the v2 hierarchy. */
		if ((p2 - p) == 0)
			continue;

		for (tok = strtok_r(p, ",", &saveptr); tok;
				tok = strtok_r(NULL, ",", &saveptr)) {
			if (strncmp(tok, "name=", 5) == 0)
				must_append_string(nlist, tok);
			else
				must_append_string(klist, tok);
		}
	}

	free(line);
	fclose(f);

	return true;
}

/* Get list of controllers for cgroupfs v2 hierarchy by looking at
 * cgroup.controllers and/or cgroup.subtree_control of a given (parent) cgroup.
static bool cgv2_get_controllers(char ***klist)
{
	return -ENOSYS;
}
*/

/* Get current cgroup from /proc/self/cgroup for the cgroupfs v2 hierarchy. */
static char *cgv2_get_current_cgroup(int pid)
{
	int ret;
	char *cgroups_v2;
	char *current_cgroup;
	char *copy = NULL;
	/* The largest integer that can fit into long int is 2^64. This is a
	 * 20-digit number. */
#define __PIDLEN /* /proc */ 5 + /* /pid-to-str */ 21 + /* /cgroup */ 7 + /* \0 */ 1
	char path[__PIDLEN];

	ret = snprintf(path, __PIDLEN, "/proc/%d/cgroup", pid);
	if (ret < 0 || ret >= __PIDLEN)
		return NULL;

	cgroups_v2 = read_file(path);
	if (!cgroups_v2)
		return NULL;

	current_cgroup = strstr(cgroups_v2, "0::/");
	if (!current_cgroup)
		goto cleanup_on_err;

	current_cgroup = current_cgroup + 3;
	copy = copy_to_eol(current_cgroup);
	if (!copy)
		goto cleanup_on_err;

cleanup_on_err:
	free(cgroups_v2);
	if (copy)
		trim(copy);

	return copy;
}

/* Given two null-terminated lists of strings, return true if any string is in
 * both.
 */
static bool cgv1_controller_lists_intersect(char **l1, char **l2)
{
	char **it;

	if (!l2)
		return false;

	for (it = l1; it && *it; it++)
		if (string_in_list(l2, *it))
			return true;

	return false;
}

/* For a null-terminated list of controllers @clist, return true if any of those
 * controllers is already listed the null-terminated list of hierarchies @hlist.
 * Realistically, if one is present, all must be present.
 */
static bool cgv1_controller_list_is_dup(struct cgv1_hierarchy **hlist, char **clist)
{
	struct cgv1_hierarchy **it;

	for (it = hlist; it && *it; it++)
		if ((*it)->controllers)
			if (cgv1_controller_lists_intersect((*it)->controllers, clist))
				return true;
	return false;

}

/* Set boolean to mark controllers under which we are supposed create a
 * writeable cgroup.
 */
static void cgv1_mark_to_make_rw(char **clist)
{
	struct cgv1_hierarchy **it;

	for (it = cgv1_hierarchies; it && *it; it++)
		if ((*it)->controllers)
			if (cgv1_controller_lists_intersect((*it)->controllers, clist))
				(*it)->create_rw_cgroup = true;
}

/* Set boolean to mark whether we are supposed to create a writeable cgroup in
 * the cgroupfs v2 hierarchy.
 */
static void cgv2_mark_to_make_rw(char **clist)
{
	if (string_in_list(clist, "unified"))
		if (cgv2_hierarchies)
			(*cgv2_hierarchies)->create_rw_cgroup = true;
}

/* Wrapper around cgv{1,2}_mark_to_make_rw(). */
static void cg_mark_to_make_rw(const char *cstring)
{
	char *copy, *tok;
	char *saveptr = NULL;
	char **clist = NULL;

	copy = must_copy_string(cstring);

	for (tok = strtok_r(copy, ",", &saveptr); tok;
	     tok = strtok_r(NULL, ",", &saveptr))
		must_add_to_list(&clist, tok);

	free(copy);

	cgv1_mark_to_make_rw(clist);
	cgv2_mark_to_make_rw(clist);

	free_string_list(clist);
}

/* Prefix any named controllers with "name=", e.g. "name=systemd". */
static char *cgv1_must_prefix_named(char *entry)
{
	char *s;
	int ret;
	size_t len;

	len = strlen(entry);
	s = must_alloc(len + 6);

	ret = snprintf(s, len + 6, "name=%s", entry);
	if (ret < 0 || (size_t)ret >= (len + 6))
		return NULL;

	return s;
}

/* Append kernel controller in @klist or named controller in @nlist to @clist */
static void must_append_controller(char **klist, char **nlist, char ***clist, char *entry)
{
	int newentry;
	char *copy;

	if (string_in_list(klist, entry) && string_in_list(nlist, entry))
		return;

	newentry = append_null_to_list((void ***)clist);

	if (strncmp(entry, "name=", 5) == 0)
		copy = must_copy_string(entry);
	else if (string_in_list(klist, entry))
		copy = must_copy_string(entry);
	else
		copy = cgv1_must_prefix_named(entry);

	(*clist)[newentry] = copy;
}

/* Get the controllers from a mountinfo line. There are other ways we could get
 * this info. For lxcfs, field 3 is /cgroup/controller-list. For cgroupfs, we
 * could parse the mount options. But we simply assume that the mountpoint must
 * be /sys/fs/cgroup/controller-list
 */
static char **cgv1_get_proc_mountinfo_controllers(char **klist, char **nlist, char *line)
{
	int i;
	char *p, *p2, *tok;
	char *saveptr = NULL;
	char **aret = NULL;

	p = line;

	for (i = 0; i < 4; i++) {
		p = strchr(p, ' ');
		if (!p)
			return NULL;
		p++;
	}
	if (!p)
		return NULL;

	if (strncmp(p, "/sys/fs/cgroup/", 15) != 0)
		return NULL;

	p += 15;

	p2 = strchr(p, ' ');
	if (!p2)
		return NULL;
	*p2 = '\0';

	for (tok = strtok_r(p, ",", &saveptr); tok;
	     tok = strtok_r(NULL, ",", &saveptr))
		must_append_controller(klist, nlist, &aret, tok);

	return aret;
}

/* Check if a cgroupfs v2 controller is present in the string @cgline. */
static bool cgv1_controller_in_clist(char *cgline, char *c)
{
	size_t len;
	char *tok, *eol, *tmp;
	char *saveptr = NULL;

	eol = strchr(cgline, ':');
	if (!eol)
		return false;

	len = eol - cgline;
	tmp = alloca(len + 1);
	memcpy(tmp, cgline, len);
	tmp[len] = '\0';

	for (tok = strtok_r(tmp, ",", &saveptr); tok;
	     tok = strtok_r(NULL, ",", &saveptr)) {
		if (strcmp(tok, c) == 0)
			return true;
	}
	return false;
}

/* Get current cgroup from the /proc/<pid>/cgroup file passed in via @basecginfo
 * of a given cgv1 controller passed in via @controller.
 */
static char *cgv1_get_current_cgroup(char *basecginfo, char *controller)
{
	char *p;

	p = basecginfo;

	while (true) {
		p = strchr(p, ':');
		if (!p)
			return NULL;
		p++;

		if (cgv1_controller_in_clist(p, controller)) {
			p = strchr(p, ':');
			if (!p)
				return NULL;
			p++;

			return copy_to_eol(p);
		}

		p = strchr(p, '\n');
		if (!p)
			return NULL;
		p++;
	}

	return NULL;
}

/* Remove /init.scope from string @cg. This will mostly affect systemd-based
 * systems.
 */
#define INIT_SCOPE "/init.scope"
static void cg_systemd_prune_init_scope(char *cg)
{
	char *point;

	if (!cg)
		return;

	point = cg + strlen(cg) - strlen(INIT_SCOPE);
	if (point < cg)
		return;

	if (strcmp(point, INIT_SCOPE) == 0) {
		if (point == cg)
			*(point + 1) = '\0';
		else
			*point = '\0';
	}
}

/* Add new info about a mounted cgroupfs v1 hierarchy. Includes the controllers
 * mounted into that hierarchy (e.g. cpu,cpuacct), the mountpoint of that
 * hierarchy (/sys/fs/cgroup/<controller>, the base cgroup of the current
 * process gathered from /proc/self/cgroup, and the init cgroup of PID1 gathered
 * from /proc/1/cgroup.
 */
static void cgv1_add_controller(char **clist, char *mountpoint, char *base_cgroup, char *init_cgroup)
{
	struct cgv1_hierarchy *new;
	int newentry;

	new = must_alloc(sizeof(*new));
	new->controllers = clist;
	new->mountpoint = mountpoint;
	new->base_cgroup = base_cgroup;
	new->fullcgpath = NULL;
	new->create_rw_cgroup = false;
	new->init_cgroup = init_cgroup;
	new->systemd_user_slice = false;

	newentry = append_null_to_list((void ***)&cgv1_hierarchies);
	cgv1_hierarchies[newentry] = new;
}

/* Add new info about the mounted cgroupfs v2 hierarchy. Can (but doesn't
 * currently) include the controllers mounted into the hierarchy (e.g.  memory,
 * pids, blkio), the mountpoint of that hierarchy (Should usually be
 * /sys/fs/cgroup but some init systems seems to think it might be a good idea
 * to also mount empty cgroupfs v2 hierarchies at /sys/fs/cgroup/systemd.), the
 * base cgroup of the current process gathered from /proc/self/cgroup, and the
 * init cgroup of PID1 gathered from /proc/1/cgroup.
 */
static void cgv2_add_controller(char **clist, char *mountpoint, char *base_cgroup, char *init_cgroup, bool systemd_user_slice)
{
	struct cgv2_hierarchy *new;
	int newentry;

	new = must_alloc(sizeof(*new));
	new->controllers = clist;
	new->mountpoint = mountpoint;
	new->base_cgroup = base_cgroup;
	new->fullcgpath = NULL;
	new->create_rw_cgroup = false;
	new->init_cgroup = init_cgroup;
	new->systemd_user_slice = systemd_user_slice;

	newentry = append_null_to_list((void ***)&cgv2_hierarchies);
	cgv2_hierarchies[newentry] = new;
}

/* In Ubuntu 14.04, the paths created for us were
 * '/user/$uid.user/$something.session' This can be merged better with
 * systemd_created_slice_for_us(), but keeping it separate makes it easier to
 * reason about the correctness.
 */
static bool cg_systemd_under_user_slice_1(const char *in, uid_t uid)
{
	char *p;
	size_t len;
	int id;
	char *copy = NULL;
	bool bret = false;

	copy = must_copy_string(in);
	if (strlen(copy) < strlen("/user/1.user/1.session"))
		goto cleanup;
	p = copy + strlen(copy) - 1;

	/* skip any trailing '/' (shouldn't be any, but be sure) */
	while (p >= copy && *p == '/')
		*(p--) = '\0';
	if (p < copy)
		goto cleanup;

	/* Get last path element */
	while (p >= copy && *p != '/')
		p--;
	if (p < copy)
		goto cleanup;
	/* make sure it is something.session */
	len = strlen(p + 1);
	if (len < strlen("1.session") ||
	    strncmp(p + 1 + len - 8, ".session", 8) != 0)
		goto cleanup;

	/* ok last path piece checks out, now check the second to last */
	*(p + 1) = '\0';
	while (p >= copy && *(--p) != '/')
		;
	if (sscanf(p + 1, "%d.user/", &id) != 1)
		goto cleanup;

	if (id != (int)uid)
		goto cleanup;

	bret = true;

cleanup:
	free(copy);
	return bret;
}

/* So long as our path relative to init starts with /user.slice/user-$uid.slice,
 * assume it belongs to $uid and chown it
 */
static bool cg_systemd_under_user_slice_2(const char *base_cgroup,
					  const char *init_cgroup, uid_t uid)
{
	int ret;
	char buf[100];
	size_t curlen, initlen;

	curlen = strlen(base_cgroup);
	initlen = strlen(init_cgroup);
	if (curlen <= initlen)
		return false;

	if (strncmp(base_cgroup, init_cgroup, initlen) != 0)
		return false;

	ret = snprintf(buf, 100, "/user.slice/user-%d.slice/", (int)uid);
	if (ret < 0 || ret >= 100)
		return false;

	if (initlen == 1)
		initlen = 0; // skip the '/'

	return strncmp(base_cgroup + initlen, buf, strlen(buf)) == 0;
}

/* The systemd-created path is: user-$uid.slice/session-c$session.scope. If that
 * is not the end of our systemd path, then we're not part of the PAM call that
 * created that path.
 *
 * The last piece is chowned to $uid, the user- part not.
 * Note: If the user creates paths that look like what we're looking for to
 * 'fool' us, either
 *  - they fool us, we create new cgroups, and they get auto-logged-out.
 *  - they fool a root sudo, systemd cgroup is not changed but chowned, and they
 *    lose ownership of their cgroups
 */
static bool cg_systemd_created_user_slice(const char *base_cgroup,
					  const char *init_cgroup,
					  const char *in, uid_t uid)
{
	char *p;
	size_t len;
	int id;
	char *copy = NULL;
	bool bret = false;

	copy = must_copy_string(in);

	/* An old version of systemd has already created a cgroup for us. */
	if (cg_systemd_under_user_slice_1(in, uid))
		goto succeed;

	/* A new version of systemd has already created a cgroup for us. */
	if (cg_systemd_under_user_slice_2(base_cgroup, init_cgroup, uid))
		goto succeed;

	if (strlen(copy) < strlen("/user-0.slice/session-0.scope"))
		goto cleanup;

	p = copy + strlen(copy) - 1;
	/* Skip any trailing '/' (shouldn't be any, but be sure). */
	while (p >= copy && *p == '/')
		*(p--) = '\0';

	if (p < copy)
		goto cleanup;

	/* Get last path element */
	while (p >= copy && *p != '/')
		p--;

	if (p < copy)
		goto cleanup;

	/* Make sure it is session-something.scope. */
	len = strlen(p + 1);
	if (strncmp(p + 1, "session-", strlen("session-")) != 0 ||
	    strncmp(p + 1 + len - 6, ".scope", 6) != 0)
		goto cleanup;

	/* Ok last path piece checks out, now check the second to last. */
	*(p + 1) = '\0';
	while (p >= copy && *(--p) != '/')
		;

	if (sscanf(p + 1, "user-%d.slice/", &id) != 1)
		goto cleanup;

	if (id != (int)uid)
		goto cleanup;

succeed:
	bret = true;
cleanup:
	free(copy);
	return bret;
}

/* Chown existing cgroup that systemd has already created for us. */
static bool cg_systemd_chown_existing_cgroup(const char *mountpoint,
					     const char *base_cgroup, uid_t uid,
					     gid_t gid, bool systemd_user_slice)
{
	char *path;

	if (!systemd_user_slice)
		return false;

	path = must_make_path(mountpoint, base_cgroup, NULL);

	/* A cgroup within name=systemd has already been created. So we only
	 * need to chown it.
	 */
	if (chown(path, uid, gid) < 0)
		mysyslog(LOG_WARNING, "Failed to chown %s to %d:%d: %s.\n",
			 path, (int)uid, (int)gid, strerror(errno), NULL);
	lxcfs_debug("Chowned %s to %d:%d.\n", path, (int)uid, (int)gid);

	free(path);
	return true;
}

/* Detect and store information about cgroupfs v1 hierarchies. */
static bool cgv1_init(uid_t uid, gid_t gid)
{
	FILE *f;
	struct cgv1_hierarchy **it;
	char *basecginfo;
	char *line = NULL;
	char **klist = NULL, **nlist = NULL;
	size_t len = 0;

	basecginfo = read_file("/proc/self/cgroup");
	if (!basecginfo)
		return false;

	f = fopen("/proc/self/mountinfo", "r");
	if (!f) {
		free(basecginfo);
		return false;
	}

	cgv1_get_controllers(&klist, &nlist);

	while (getline(&line, &len, f) != -1) {
		char **controller_list = NULL;
		char *mountpoint, *base_cgroup;

		if (is_lxcfs(line) || !is_cgv1(line))
			continue;

		controller_list = cgv1_get_proc_mountinfo_controllers(klist, nlist, line);
		if (!controller_list)
			continue;

		if (cgv1_controller_list_is_dup(cgv1_hierarchies,
						controller_list)) {
			free(controller_list);
			continue;
		}

		mountpoint = get_mountpoint(line);
		if (!mountpoint) {
			free_string_list(controller_list);
			continue;
		}

		base_cgroup = cgv1_get_current_cgroup(basecginfo, controller_list[0]);
		if (!base_cgroup) {
			free_string_list(controller_list);
			free(mountpoint);
			continue;
		}
		trim(base_cgroup);
		lxcfs_debug("Detected cgroupfs v1 controller \"%s\" with "
			    "mountpoint \"%s\" and cgroup \"%s\".\n",
			    controller_list[0], mountpoint, base_cgroup);
		cgv1_add_controller(controller_list, mountpoint, base_cgroup,
				    NULL);
	}
	free_string_list(klist);
	free_string_list(nlist);
	free(basecginfo);
	fclose(f);
	free(line);

	/* Retrieve init cgroup path for all controllers. */
	basecginfo = read_file("/proc/1/cgroup");
	if (!basecginfo)
		return false;

	for (it = cgv1_hierarchies; it && *it; it++) {
		if ((*it)->controllers) {
			char *init_cgroup, *user_slice;
			/* We've already stored the controller and received its
			 * current cgroup. If we now fail to retrieve its init
			 * cgroup, we should probably fail.
			 */
			init_cgroup = cgv1_get_current_cgroup(basecginfo, (*it)->controllers[0]);
			if (!init_cgroup) {
				free(basecginfo);
				return false;
			}
			cg_systemd_prune_init_scope(init_cgroup);
			(*it)->init_cgroup = init_cgroup;
			lxcfs_debug("cgroupfs v1 controller \"%s\" has init "
				    "cgroup \"%s\".\n",
				    (*(*it)->controllers), init_cgroup);
			/* Check whether systemd has already created a cgroup
			 * for us.
			 */
			user_slice = must_make_path((*it)->mountpoint, (*it)->base_cgroup, NULL);
			if (cg_systemd_created_user_slice((*it)->base_cgroup, (*it)->init_cgroup, user_slice, uid))
				(*it)->systemd_user_slice = true;
		}
	}
	free(basecginfo);

	return true;
}

/* __typeof__ should be safe to use with all compilers. */
typedef __typeof__(((struct statfs *)NULL)->f_type) fs_type_magic;
/* Check whether given mountpoint has mount type specified via @magic_val. */
static bool has_fs_type(const struct statfs *fs, fs_type_magic magic_val)
{
	return (fs->f_type == (fs_type_magic)magic_val);
}

/* Check whether @path is a cgroupfs v1 or cgroupfs v2 mount. Returns -1 if
 * statfs fails. If @path is null /sys/fs/cgroup is checked.
 */
static int cg_get_version_of_mntpt(const char *path)
{
	int ret;
	struct statfs sb;

	if (path)
		ret = statfs(path, &sb);
	else
		ret = statfs("/sys/fs/cgroup", &sb);

	if (ret < 0)
		return -1;

	if (has_fs_type(&sb, CGROUP_SUPER_MAGIC))
		return 1;
	else if (has_fs_type(&sb, CGROUP2_SUPER_MAGIC))
		return 2;

	return 0;
}

/* Detect and store information about the cgroupfs v2 hierarchy. Currently only
 * deals with the empty v2 hierachy as we do not retrieve enabled controllers.
 */
static bool cgv2_init(uid_t uid, gid_t gid)
{
	char *mountpoint;
	FILE *f = NULL;
	char *current_cgroup = NULL, *init_cgroup = NULL;
	char * line = NULL;
	size_t len = 0;
	int ret = false;

	current_cgroup = cgv2_get_current_cgroup(getpid());
	if (!current_cgroup) {
		/* No v2 hierarchy present. We're done. */
		ret = true;
		goto cleanup;
	}

	init_cgroup = cgv2_get_current_cgroup(1);
	if (!init_cgroup) {
		/* If we're here and didn't fail already above, then something's
		 * certainly wrong, so error this time.
		 */
		goto cleanup;
	}
	cg_systemd_prune_init_scope(init_cgroup);

	/* Check if the v2 hierarchy is mounted at its standard location.
	 * If so we can skip the rest of the work here. Although the unified
	 * hierarchy can be mounted multiple times, each of those mountpoints
	 * will expose identical information.
	 */
	if (cg_get_version_of_mntpt("/sys/fs/cgroup") == 2) {
		char *user_slice;
		bool has_user_slice = false;

		mountpoint = must_copy_string("/sys/fs/cgroup");
		if (!mountpoint)
			goto cleanup;

		user_slice = must_make_path(mountpoint, current_cgroup, NULL);
		if (cg_systemd_created_user_slice(current_cgroup, init_cgroup, user_slice, uid))
			has_user_slice = true;
		free(user_slice);

		cgv2_add_controller(NULL, mountpoint, current_cgroup, init_cgroup, has_user_slice);

		ret = true;
		goto cleanup;
	}

	f = fopen("/proc/self/mountinfo", "r");
	if (!f)
		goto cleanup;

	/* we support simple cgroup mounts and lxcfs mounts */
	while (getline(&line, &len, f) != -1) {
		char *user_slice;
		bool has_user_slice = false;
		if (!is_cgv2(line))
			continue;

		mountpoint = get_mountpoint(line);
		if (!mountpoint)
			continue;

		user_slice = must_make_path(mountpoint, current_cgroup, NULL);
		if (cg_systemd_created_user_slice(current_cgroup, init_cgroup, user_slice, uid))
			has_user_slice = true;
		free(user_slice);

		cgv2_add_controller(NULL, mountpoint, current_cgroup, init_cgroup, has_user_slice);
		/* Although the unified hierarchy can be mounted multiple times,
		 * each of those mountpoints will expose identical information.
		 * So let the first mountpoint we find, win.
		 */
		break;
	}

	lxcfs_debug("Detected cgroupfs v2 hierarchy at mountpoint \"%s\" with "
		    "current cgroup \"%s\" and init cgroup \"%s\".\n",
		    mountpoint, current_cgroup, init_cgroup);

cleanup:
	if (f)
		fclose(f);
	free(line);

	return ret;
}

/* Detect and store information about mounted cgroupfs v1 hierarchies and the
 * cgroupfs v2 hierarchy.
 * Detect whether we are on a pure cgroupfs v1, cgroupfs v2, or mixed system,
 * where some controllers are mounted into their standard cgroupfs v1 locations
 * (/sys/fs/cgroup/<controller>) and others are mounted into the cgroupfs v2
 * hierarchy (/sys/fs/cgroup).
 */
static bool cg_init(uid_t uid, gid_t gid)
{
	if (!cgv1_init(uid, gid))
		return false;

	if (!cgv2_init(uid, gid))
		return false;

	if (cgv1_hierarchies && cgv2_hierarchies) {
		cg_mount_mode = CGROUP_MIXED;
		lxcfs_debug("%s\n", "Detected cgroupfs v1 and v2 hierarchies.");
	} else if (cgv1_hierarchies && !cgv2_hierarchies) {
		cg_mount_mode = CGROUP_PURE_V1;
		lxcfs_debug("%s\n", "Detected cgroupfs v1 hierarchies.");
	} else if (cgv2_hierarchies && !cgv1_hierarchies) {
		cg_mount_mode = CGROUP_PURE_V2;
		lxcfs_debug("%s\n", "Detected cgroupfs v2 hierarchies.");
	} else {
		cg_mount_mode = CGROUP_UNKNOWN;
		mysyslog(LOG_ERR, "Could not detect cgroupfs hierarchy.\n", NULL);
	}

	if (cg_mount_mode == CGROUP_UNKNOWN)
		return false;

	return true;
}

/* Try to move/migrate us into @cgroup in a cgroupfs v1 hierarchy. */
static bool cgv1_enter(const char *cgroup)
{
	struct cgv1_hierarchy **it;

	for (it = cgv1_hierarchies; it && *it; it++) {
		char **controller;
		bool entered = false;

		if (!(*it)->controllers || !(*it)->mountpoint ||
		    !(*it)->init_cgroup || !(*it)->create_rw_cgroup)
			continue;

		for (controller = (*it)->controllers; controller && *controller;
		     controller++) {
			char *path;

			/* We've already been placed in a user slice, so we
			 * don't need to enter the cgroup again.
			 */
			if ((*it)->systemd_user_slice) {
				entered = true;
				break;
			}

			path = must_make_path((*it)->mountpoint,
					      (*it)->init_cgroup,
					      cgroup,
					      "/cgroup.procs",
					      NULL);
			if (!file_exists(path)) {
				free(path);
				path = must_make_path((*it)->mountpoint,
						      (*it)->init_cgroup,
						      cgroup,
						      "/tasks",
						      NULL);
			}
			lxcfs_debug("Attempting to enter cgroupfs v1 hierarchy in \"%s\" cgroup.\n", path);
			entered = write_int(path, (int)getpid());
			if (entered) {
				free(path);
				break;
			}
			lxcfs_debug("Failed to enter cgroupfs v1 hierarchy in \"%s\" cgroup.\n", path);
			free(path);
		}
		if (!entered)
			return false;
	}

	return true;
}

/* Try to move/migrate us into @cgroup in the cgroupfs v2 hierarchy. */
static bool cgv2_enter(const char *cgroup)
{
	struct cgv2_hierarchy *v2;
	char *path;
	bool entered = false;

	if (!cgv2_hierarchies)
		return true;

	v2 = *cgv2_hierarchies;

	if (!v2->mountpoint || !v2->base_cgroup)
		return false;

	if (!v2->create_rw_cgroup || v2->systemd_user_slice)
		return true;

	path = must_make_path(v2->mountpoint, v2->base_cgroup, cgroup,
			      "/cgroup.procs", NULL);
	lxcfs_debug("Attempting to enter cgroupfs v2 hierarchy in cgroup \"%s\".\n", path);
	entered = write_int(path, (int)getpid());
	if (!entered) {
		lxcfs_debug("Failed to enter cgroupfs v2 hierarchy in cgroup \"%s\".\n", path);
		free(path);
		return false;
	}

	free(path);

	return true;
}

/* Wrapper around cgv{1,2}_enter(). */
static bool cg_enter(const char *cgroup)
{
	if (!cgv1_enter(cgroup)) {
		mysyslog(LOG_WARNING, "cgroupfs v1: Failed to enter cgroups.\n", NULL);
		return false;
	}

	if (!cgv2_enter(cgroup)) {
		mysyslog(LOG_WARNING, "cgroupfs v2: Failed to enter cgroups.\n", NULL);
		return false;
	}

	return true;
}

/* Escape to root cgroup in all detected cgroupfs v1 hierarchies. */
static void cgv1_escape(void)
{
	struct cgv1_hierarchy **it;

	/* In case systemd hasn't already placed us in a user slice for the
	 * cpuset v1 controller we will reside in the root cgroup. This means
	 * that cgroup.clone_children will not have been initialized for us so
	 * we need to do it.
	 */
	for (it = cgv1_hierarchies; it && *it; it++)
		if (!cgv1_handle_root_cpuset_hierarchy(*it))
			mysyslog(LOG_WARNING, "cgroupfs v1: Failed to initialize cpuset.\n", NULL);

	if (!cgv1_enter("/"))
		mysyslog(LOG_WARNING, "cgroupfs v1: Failed to escape to init's cgroup.\n", NULL);
}

/* Escape to root cgroup in the cgroupfs v2 hierarchy. */
static void cgv2_escape(void)
{
	if (!cgv2_enter("/"))
		mysyslog(LOG_WARNING, "cgroupfs v2: Failed to escape to init's cgroup.\n", NULL);
}

/* Wrapper around cgv{1,2}_escape(). */
static void cg_escape(void)
{
	cgv1_escape();
	cgv2_escape();
}

/* Get uid and gid for @user. */
static bool get_uid_gid(const char *user, uid_t *uid, gid_t *gid)
{
	struct passwd *pwent;

	pwent = getpwnam(user);
	if (!pwent)
		return false;

	*uid = pwent->pw_uid;
	*gid = pwent->pw_gid;

	return true;
}

/* Check if cgroup belongs to our uid and gid. If so, reuse it. */
static bool cg_belongs_to_uid_gid(const char *path, uid_t uid, gid_t gid)
{
	struct stat statbuf;

	if (stat(path, &statbuf) < 0)
		return false;

	if (!(statbuf.st_uid == uid) || !(statbuf.st_gid == gid))
		return false;

	return true;
}

/* Create cpumask from cpulist aka turn:
 *
 *	0,2-3
 *
 *  into bit array
 *
 *	1 0 1 1
 */
static uint32_t *cg_cpumask(char *buf, size_t nbits)
{
	char *token;
	char *saveptr = NULL;
	size_t arrlen = BITS_TO_LONGS(nbits);
	uint32_t *bitarr = calloc(arrlen, sizeof(uint32_t));
	if (!bitarr)
		return NULL;

	for (; (token = strtok_r(buf, ",", &saveptr)); buf = NULL) {
		errno = 0;
		unsigned start = strtoul(token, NULL, 0);
		unsigned end = start;

		char *range = strchr(token, '-');
		if (range)
			end = strtoul(range + 1, NULL, 0);
		if (!(start <= end)) {
			free(bitarr);
			return NULL;
		}

		if (end >= nbits) {
			free(bitarr);
			return NULL;
		}

		while (start <= end)
			set_bit(start++, bitarr);
	}

	return bitarr;
}

static char *string_join(const char *sep, const char **parts, bool use_as_prefix)
{
	char *result;
	char **p;
	size_t sep_len = strlen(sep);
	size_t result_len = use_as_prefix * sep_len;

	if (!parts)
		return NULL;

	/* calculate new string length */
	for (p = (char **)parts; *p; p++)
		result_len += (p > (char **)parts) * sep_len + strlen(*p);

	result = calloc(result_len + 1, sizeof(char));
	if (!result)
		return NULL;

	if (use_as_prefix)
		strcpy(result, sep);
	for (p = (char **)parts; *p; p++) {
		if (p > (char **)parts)
			strcat(result, sep);
		strcat(result, *p);
	}

	return result;
}

/* The largest integer that can fit into long int is 2^64. This is a
 * 20-digit number.
 */
#define __IN_TO_STR_LEN 21
/* Turn cpumask into simple, comma-separated cpulist. */
static char *cg_cpumask_to_cpulist(uint32_t *bitarr, size_t nbits)
{
	size_t i;
	int ret;
	char numstr[__IN_TO_STR_LEN] = {0};
	char **cpulist = NULL;

	for (i = 0; i <= nbits; i++) {
		if (is_set(i, bitarr)) {
			ret = snprintf(numstr, __IN_TO_STR_LEN, "%zu", i);
			if (ret < 0 || (size_t)ret >= __IN_TO_STR_LEN) {
				free_string_list(cpulist);
				return NULL;
			}
			must_append_string(&cpulist, numstr);
		}
	}
	return string_join(",", (const char **)cpulist, false);
}

static ssize_t cg_get_max_cpus(char *cpulist)
{
	char *c1, *c2;
	char *maxcpus = cpulist;
	size_t cpus = 0;

	c1 = strrchr(maxcpus, ',');
	if (c1)
		c1++;

	c2 = strrchr(maxcpus, '-');
	if (c2)
		c2++;

	if (!c1 && !c2)
		c1 = maxcpus;
	else if (c1 < c2)
		c1 = c2;

	/* If the above logic is correct, c1 should always hold a valid string
	 * here.
	 */

	errno = 0;
	cpus = strtoul(c1, NULL, 0);
	if (errno != 0)
		return -1;

	return cpus;
}

static ssize_t write_nointr(int fd, const void* buf, size_t count)
{
	ssize_t ret;
again:
	ret = write(fd, buf, count);
	if (ret < 0 && errno == EINTR)
		goto again;
	return ret;
}

static int write_to_file(const char *filename, const void* buf, size_t count, bool add_newline)
{
	int fd, saved_errno;
	ssize_t ret;

	fd = open(filename, O_WRONLY | O_TRUNC | O_CREAT | O_CLOEXEC, 0666);
	if (fd < 0)
		return -1;
	ret = write_nointr(fd, buf, count);
	if (ret < 0)
		goto out_error;
	if ((size_t)ret != count)
		goto out_error;
	if (add_newline) {
		ret = write_nointr(fd, "\n", 1);
		if (ret != 1)
			goto out_error;
	}
	close(fd);
	return 0;

out_error:
	saved_errno = errno;
	close(fd);
	errno = saved_errno;
	return -1;
}

#define __ISOL_CPUS "/sys/devices/system/cpu/isolated"
static bool cg_filter_and_set_cpus(char *path, bool am_initialized)
{
	char *lastslash, *fpath, oldv;
	int ret;
	ssize_t i;

	ssize_t maxposs = 0, maxisol = 0;
	char *cpulist = NULL, *posscpus = NULL, *isolcpus = NULL;
	uint32_t *possmask = NULL, *isolmask = NULL;
	bool bret = false, flipped_bit = false;

	lastslash = strrchr(path, '/');
	if (!lastslash) { // bug...  this shouldn't be possible
		lxcfs_debug("Invalid path: %s.\n", path);
		return bret;
	}
	oldv = *lastslash;
	*lastslash = '\0';
	fpath = must_make_path(path, "cpuset.cpus", NULL);
	posscpus = read_file(fpath);
	if (!posscpus) {
		lxcfs_debug("Could not read file: %s.\n", fpath);
		goto on_error;
	}

	/* Get maximum number of cpus found in possible cpuset. */
	maxposs = cg_get_max_cpus(posscpus);
	if (maxposs < 0)
		goto on_error;

	if (!file_exists(__ISOL_CPUS)) {
		/* This system doesn't expose isolated cpus. */
		lxcfs_debug("%s", "Path: "__ISOL_CPUS" to read isolated cpus from does not exist.\n");
		cpulist = posscpus;
		/* No isolated cpus but we weren't already initialized by
		 * someone. We should simply copy the parents cpuset.cpus
		 * values.
		 */
		if (!am_initialized) {
			lxcfs_debug("%s", "Copying cpuset of parent cgroup.\n");
			goto copy_parent;
		}
		/* No isolated cpus but we were already initialized by someone.
		 * Nothing more to do for us.
		 */
		goto on_success;
	}

	isolcpus = read_file(__ISOL_CPUS);
	if (!isolcpus) {
		lxcfs_debug("%s", "Could not read file "__ISOL_CPUS"\n");
		goto on_error;
	}
	if (!isdigit(isolcpus[0])) {
		lxcfs_debug("%s", "No isolated cpus detected.\n");
		cpulist = posscpus;
		/* No isolated cpus but we weren't already initialized by
		 * someone. We should simply copy the parents cpuset.cpus
		 * values.
		 */
		if (!am_initialized) {
			lxcfs_debug("%s", "Copying cpuset of parent cgroup.\n");
			goto copy_parent;
		}
		/* No isolated cpus but we were already initialized by someone.
		 * Nothing more to do for us.
		 */
		goto on_success;
	}

	/* Get maximum number of cpus found in isolated cpuset. */
	maxisol = cg_get_max_cpus(isolcpus);
	if (maxisol < 0)
		goto on_error;

	if (maxposs < maxisol)
		maxposs = maxisol;
	maxposs++;

	possmask = cg_cpumask(posscpus, maxposs);
	if (!possmask) {
		lxcfs_debug("%s", "Could not create cpumask for all possible cpus.\n");
		goto on_error;
	}

	isolmask = cg_cpumask(isolcpus, maxposs);
	if (!isolmask) {
		lxcfs_debug("%s", "Could not create cpumask for all isolated cpus.\n");
		goto on_error;
	}

	for (i = 0; i <= maxposs; i++) {
		if (is_set(i, isolmask) && is_set(i, possmask)) {
			flipped_bit = true;
			clear_bit(i, possmask);
		}
	}

	if (!flipped_bit) {
		lxcfs_debug("%s", "No isolated cpus present in cpuset.\n");
		goto on_success;
	}
	lxcfs_debug("%s", "Removed isolated cpus from cpuset.\n");

	cpulist = cg_cpumask_to_cpulist(possmask, maxposs);
	if (!cpulist) {
		lxcfs_debug("%s", "Could not create cpu list.\n");
		goto on_error;
	}

copy_parent:
	*lastslash = oldv;
	fpath = must_make_path(path, "cpuset.cpus", NULL);
	ret = write_to_file(fpath, cpulist, strlen(cpulist), false);
	if (ret < 0) {
		lxcfs_debug("Could not write cpu list to: %s.\n", fpath);
		goto on_error;
	}

on_success:
	bret = true;

on_error:
	free(fpath);

	free(isolcpus);
	free(isolmask);

	if (posscpus != cpulist)
		free(posscpus);
	free(possmask);

	free(cpulist);
	return bret;
}

int read_from_file(const char *filename, void* buf, size_t count)
{
	int fd = -1, saved_errno;
	ssize_t ret;

	fd = open(filename, O_RDONLY | O_CLOEXEC);
	if (fd < 0)
		return -1;

	if (!buf || !count) {
		char buf2[100];
		size_t count2 = 0;
		while ((ret = read(fd, buf2, 100)) > 0)
			count2 += ret;
		if (ret >= 0)
			ret = count2;
	} else {
		memset(buf, 0, count);
		ret = read(fd, buf, count);
	}

	if (ret < 0)
		lxcfs_debug("read %s: %s", filename, strerror(errno));

	saved_errno = errno;
	close(fd);
	errno = saved_errno;
	return ret;
}

/* Copy contents of parent(@path)/@file to @path/@file */
static bool cg_copy_parent_file(char *path, char *file)
{
	char *lastslash, *value = NULL, *fpath, oldv;
	int len = 0;
	int ret;

	lastslash = strrchr(path, '/');
	if (!lastslash) { // bug...  this shouldn't be possible
		lxcfs_debug("cgfsng:copy_parent_file: bad path %s", path);
		return false;
	}
	oldv = *lastslash;
	*lastslash = '\0';
	fpath = must_make_path(path, file, NULL);
	len = read_from_file(fpath, NULL, 0);
	if (len <= 0)
		goto bad;
	value = must_alloc(len + 1);
	if (read_from_file(fpath, value, len) != len)
		goto bad;
	free(fpath);
	*lastslash = oldv;
	fpath = must_make_path(path, file, NULL);
	ret = write_to_file(fpath, value, len, false);
	if (ret < 0)
		lxcfs_debug("Unable to write %s to %s", value, fpath);
	free(fpath);
	free(value);
	return ret >= 0;

bad:
	lxcfs_debug("Error reading '%s'", fpath);
	free(fpath);
	free(value);
	return false;
}

/* In case systemd hasn't already placed us in a user slice for the cpuset v1
 * controller we will reside in the root cgroup. This means that
 * cgroup.clone_children will not have been initialized for us so we need to do
 * it.
 */
static bool cgv1_handle_root_cpuset_hierarchy(struct cgv1_hierarchy *h)
{
	char *clonechildrenpath, v;

	if (!string_in_list(h->controllers, "cpuset"))
		return true;

	clonechildrenpath = must_make_path(h->mountpoint, "cgroup.clone_children", NULL);

	if (read_from_file(clonechildrenpath, &v, 1) < 0) {
		lxcfs_debug("Failed to read '%s'", clonechildrenpath);
		free(clonechildrenpath);
		return false;
	}

	if (v == '1') {  /* already set for us by someone else */
		free(clonechildrenpath);
		return true;
	}

	if (write_to_file(clonechildrenpath, "1", 1, false) < 0) {
		/* Set clone_children so children inherit our settings */
		lxcfs_debug("Failed to write 1 to %s", clonechildrenpath);
		free(clonechildrenpath);
		return false;
	}
	free(clonechildrenpath);
	return true;
}

/*
 * Initialize the cpuset hierarchy in first directory of @gname and
 * set cgroup.clone_children so that children inherit settings.
 * Since the h->base_path is populated by init or ourselves, we know
 * it is already initialized.
 */
static bool cgv1_handle_cpuset_hierarchy(struct cgv1_hierarchy *h,
					 const char *cgroup)
{
	char *cgpath, *clonechildrenpath, v, *slash;

	if (!string_in_list(h->controllers, "cpuset"))
		return true;

	if (*cgroup == '/')
		cgroup++;
	slash = strchr(cgroup, '/');
	if (slash)
		*slash = '\0';

	cgpath = must_make_path(h->mountpoint, h->base_cgroup, cgroup, NULL);
	if (slash)
		*slash = '/';
	if (mkdir(cgpath, 0755) < 0 && errno != EEXIST) {
		lxcfs_debug("Failed to create '%s'", cgpath);
		free(cgpath);
		return false;
	}
	clonechildrenpath = must_make_path(cgpath, "cgroup.clone_children", NULL);
	if (!file_exists(clonechildrenpath)) { /* unified hierarchy doesn't have clone_children */
		free(clonechildrenpath);
		free(cgpath);
		return true;
	}
	if (read_from_file(clonechildrenpath, &v, 1) < 0) {
		lxcfs_debug("Failed to read '%s'", clonechildrenpath);
		free(clonechildrenpath);
		free(cgpath);
		return false;
	}

	/* Make sure any isolated cpus are removed from cpuset.cpus. */
	if (!cg_filter_and_set_cpus(cgpath, v == '1')) {
		lxcfs_debug("%s", "Failed to remove isolated cpus.\n");
		free(clonechildrenpath);
		free(cgpath);
		return false;
	}

	if (v == '1') {  /* already set for us by someone else */
		lxcfs_debug("%s", "\"cgroup.clone_children\" was already set to \"1\".\n");
		free(clonechildrenpath);
		free(cgpath);
		return true;
	}

	/* copy parent's settings */
	if (!cg_copy_parent_file(cgpath, "cpuset.mems")) {
		lxcfs_debug("%s", "Failed to copy \"cpuset.mems\" settings.\n");
		free(cgpath);
		free(clonechildrenpath);
		return false;
	}
	free(cgpath);

	if (write_to_file(clonechildrenpath, "1", 1, false) < 0) {
		/* Set clone_children so children inherit our settings */
		lxcfs_debug("Failed to write 1 to %s", clonechildrenpath);
		free(clonechildrenpath);
		return false;
	}
	free(clonechildrenpath);
	return true;
}

/* Create and chown @cgroup for all given controllers in a cgroupfs v1 hierarchy
 * (For example, create @cgroup for the cpu and cpuacct controller mounted into
 * /sys/fs/cgroup/cpu,cpuacct). Check if the path already exists and report back
 * to the caller in @existed.
 */
#define __PAM_CGFS_USER "/user/"
#define __PAM_CGFS_USER_LEN 6
static bool cgv1_create_one(struct cgv1_hierarchy *h, const char *cgroup, uid_t uid, gid_t gid, bool *existed)
{
	char *clean_base_cgroup, *path;
	char **controller;
	struct cgv1_hierarchy *it;
	bool created = false;

	*existed = false;
	it = h;
	for (controller = it->controllers; controller && *controller;
	     controller++) {
		if (!cgv1_handle_cpuset_hierarchy(it, cgroup))
			return false;

		/* If systemd has already created a cgroup for us, keep using
		 * it.
		 */
		if (cg_systemd_chown_existing_cgroup(it->mountpoint,
						     it->base_cgroup, uid, gid,
						     it->systemd_user_slice)) {
			return true;
		}

		/* We need to make sure that we do not create an endless chain
		 * of sub-cgroups. So we check if we have already logged in
		 * somehow (sudo -i, su, etc.) and have created a
		 * /user/PAM_user/idx cgroup. If so, we skip that part. For most
		 * cgroups this is unnecessary since we use the init_cgroup
		 * anyway, but for controllers which have an existing systemd
		 * cgroup that does not match the current uid, this is pretty
		 * useful.
		 */
		if (strncmp(it->base_cgroup, __PAM_CGFS_USER, __PAM_CGFS_USER_LEN) == 0) {
			free(it->base_cgroup);
			it->base_cgroup = must_copy_string("/");
		} else {
			clean_base_cgroup =
				strstr(it->base_cgroup, __PAM_CGFS_USER);
			if (clean_base_cgroup)
				*clean_base_cgroup = '\0';
		}

		path = must_make_path(it->mountpoint, it->init_cgroup, cgroup, NULL);
		lxcfs_debug("Constructing path: %s.\n", path);
		if (file_exists(path)) {
			bool our_cg = cg_belongs_to_uid_gid(path, uid, gid);
			lxcfs_debug("%s existed and does %shave our uid: %d and gid: %d.\n", path, our_cg ? "" : "not ", uid, gid);
			free(path);
			if (our_cg)
				*existed = false;
			else
				*existed = true;
			return our_cg;
		}
		created = mkdir_p(it->mountpoint, path);
		if (!created) {
			free(path);
			continue;
		}
		if (chown(path, uid, gid) < 0)
			mysyslog(LOG_WARNING,
				 "Failed to chown %s to %d:%d: %s.\n", path,
				 (int)uid, (int)gid, strerror(errno), NULL);
		lxcfs_debug("Chowned %s to %d:%d.\n", path, (int)uid, (int)gid);
		free(path);
		break;
	}

	return created;
}

/* Try to remove @cgroup for all given controllers in a cgroupfs v1 hierarchy
 * (For example, try to remove @cgroup for the cpu and cpuacct controller
 * mounted into /sys/fs/cgroup/cpu,cpuacct). Ignores failures.
 */
static bool cgv1_remove_one(struct cgv1_hierarchy *h, const char *cgroup)
{

	char *path;

	/* Better safe than sorry. */
	if (!h->controllers)
		return true;

	/* Cgroups created by systemd for us which we re-use won't be removed
	 * here, since we're using init_cgroup + cgroup as path instead of
	 * base_cgroup + cgroup.
	 */
	path = must_make_path(h->mountpoint, h->init_cgroup, cgroup, NULL);
	(void)recursive_rmdir(path);
	free(path);

	return true;
}

/* Try to remove @cgroup the cgroupfs v2 hierarchy. */
static bool cgv2_remove(const char *cgroup)
{
	struct cgv2_hierarchy *v2;
	char *path;

	if (!cgv2_hierarchies)
		return true;

	v2 = *cgv2_hierarchies;

	/* If we reused an already existing cgroup, don't bother trying to
	 * remove (a potentially wrong)/the path.
	 * Cgroups created by systemd for us which we re-use would be removed
	 * here, since we're using base_cgroup + cgroup as path.
	 */
	if (v2->systemd_user_slice)
		return true;

	path = must_make_path(v2->mountpoint, v2->base_cgroup, cgroup, NULL);
	(void)recursive_rmdir(path);
	free(path);

	return true;
}

/* Create @cgroup in all detected cgroupfs v1 hierarchy. If the creation fails
 * for any cgroupfs v1 hierarchy, remove all we have created so far. Report
 * back, to the caller if the creation failed due to @cgroup already existing
 * via @existed.
 */
static bool cgv1_create(const char *cgroup, uid_t uid, gid_t gid, bool *existed)
{
	struct cgv1_hierarchy **it, **rev_it;
	bool all_created = true;

	for (it = cgv1_hierarchies; it && *it; it++) {
		if (!(*it)->controllers || !(*it)->mountpoint ||
		    !(*it)->init_cgroup || !(*it)->create_rw_cgroup)
			continue;

		if (!cgv1_create_one(*it, cgroup, uid, gid, existed)) {
			all_created = false;
			break;
		}
	}

	if (all_created)
		return true;

	for (rev_it = cgv1_hierarchies; rev_it && *rev_it && (*rev_it != *it);
	     rev_it++)
		cgv1_remove_one(*rev_it, cgroup);

	return false;
}

/* Create @cgroup in the cgroupfs v2 hierarchy. Report back, to the caller if
 * the creation failed due to @cgroup already existing via @existed.
 */
static bool cgv2_create(const char *cgroup, uid_t uid, gid_t gid, bool *existed)
{
	char *clean_base_cgroup;
	char *path;
	struct cgv2_hierarchy *v2;
	bool created = false;

	*existed = false;

	if (!cgv2_hierarchies || !(*cgv2_hierarchies)->create_rw_cgroup)
		return true;

	v2 = *cgv2_hierarchies;

	/* We can't be placed under init's cgroup for the v2 hierarchy. We need
	 * to be placed under our current cgroup.
	 */
	if (cg_systemd_chown_existing_cgroup(v2->mountpoint,
				v2->base_cgroup, uid, gid,
				v2->systemd_user_slice))
		return true;

	/* We need to make sure that we do not create an endless chaing of
	 * sub-cgroups. So we check if we have already logged in somehow (sudo
	 * -i, su, etc.) and have created a /user/PAM_user/idx cgroup. If so, we
	 * skip that part.
	 */
	if (strncmp(v2->base_cgroup, __PAM_CGFS_USER, __PAM_CGFS_USER_LEN) == 0) {
		free(v2->base_cgroup);
		v2->base_cgroup = must_copy_string("/");
	} else {
		clean_base_cgroup = strstr(v2->base_cgroup, __PAM_CGFS_USER);
		if (clean_base_cgroup)
			*clean_base_cgroup = '\0';
	}

	path = must_make_path(v2->mountpoint, v2->base_cgroup, cgroup, NULL);
	lxcfs_debug("Constructing path \"%s\".\n", path);
	if (file_exists(path)) {
		bool our_cg = cg_belongs_to_uid_gid(path, uid, gid);
		lxcfs_debug("%s existed and does %shave our uid: %d and gid: %d.\n", path, our_cg ? "" : "not ", uid, gid);
		free(path);
		if (our_cg)
			*existed = false;
		else
			*existed = true;
		return our_cg;
	}

	created = mkdir_p(v2->mountpoint, path);
	if (!created) {
		free(path);
		return false;
	}

	if (chown(path, uid, gid) < 0)
		mysyslog(LOG_WARNING, "Failed to chown %s to %d:%d: %s.\n",
			 path, (int)uid, (int)gid, strerror(errno), NULL);
	lxcfs_debug("Chowned %s to %d:%d.\n", path, (int)uid, (int)gid);
	free(path);

	return true;
}

/* Create writeable cgroups for @user at login. Details can be found in the
 * preamble/license at the top of this file.
 */
static int handle_login(const char *user, uid_t uid, gid_t gid)
{
	int idx = 0, ret;
	bool existed;
	char cg[MAXPATHLEN];

	cg_escape();

	while (idx >= 0) {
		ret = snprintf(cg, MAXPATHLEN, "/user/%s/%d", user, idx);
		if (ret < 0 || ret >= MAXPATHLEN) {
			mysyslog(LOG_ERR, "Username too long.\n", NULL);
			return PAM_SESSION_ERR;
		}

		existed = false;
		if (!cgv2_create(cg, uid, gid, &existed)) {
			if (existed) {
				cgv2_remove(cg);
				idx++;
				continue;
			}
			mysyslog(LOG_ERR, "Failed to create a cgroup for user %s.\n", user, NULL);
			return PAM_SESSION_ERR;
		}

		existed = false;
		if (!cgv1_create(cg, uid, gid, &existed)) {
			if (existed) {
				cgv2_remove(cg);
				idx++;
				continue;
			}
			mysyslog(LOG_ERR, "Failed to create a cgroup for user %s.\n", user, NULL);
			return PAM_SESSION_ERR;
		}

		if (!cg_enter(cg)) {
			mysyslog( LOG_ERR, "Failed to enter user cgroup %s for user %s.\n", cg, user, NULL);
			return PAM_SESSION_ERR;
		}
		break;
	}

	return PAM_SUCCESS;
}

/* Try to prune cgroups we created and that now are empty from all cgroupfs v1
 * hierarchies.
 */
static bool cgv1_prune_empty_cgroups(const char *user)
{
	bool controller_removed = true;
	bool all_removed = true;
	struct cgv1_hierarchy **it;

	for (it = cgv1_hierarchies; it && *it; it++) {
		int ret;
		char *path_base, *path_init;
		char **controller;

		if (!(*it)->controllers || !(*it)->mountpoint ||
		    !(*it)->init_cgroup || !(*it)->create_rw_cgroup)
			continue;

		for (controller = (*it)->controllers; controller && *controller;
		     controller++) {
			bool path_base_rm, path_init_rm;

			path_base = must_make_path((*it)->mountpoint, (*it)->base_cgroup, "/user", user, NULL);
			lxcfs_debug("cgroupfs v1: Trying to prune \"%s\".\n", path_base);
			ret = recursive_rmdir(path_base);
			if (ret == -ENOENT || ret >= 0)
				path_base_rm = true;
			else
				path_base_rm = false;
			free(path_base);

			path_init = must_make_path((*it)->mountpoint, (*it)->init_cgroup, "/user", user, NULL);
			lxcfs_debug("cgroupfs v1: Trying to prune \"%s\".\n", path_init);
			ret = recursive_rmdir(path_init);
			if (ret == -ENOENT || ret >= 0)
				path_init_rm = true;
			else
				path_init_rm = false;
			free(path_init);

			if (!path_base_rm && !path_init_rm) {
				controller_removed = false;
				continue;
			}

			controller_removed = true;
			break;
		}
		if (!controller_removed)
			all_removed = false;
	}

	return all_removed;
}

/* Try to prune cgroup we created and that now is empty from the cgroupfs v2
 * hierarchy.
 */
static bool cgv2_prune_empty_cgroups(const char *user)
{
	int ret;
	struct cgv2_hierarchy *v2;
	char *path_base, *path_init;
	bool path_base_rm, path_init_rm;

	if (!cgv2_hierarchies)
		return true;

	v2 = *cgv2_hierarchies;

	path_base = must_make_path(v2->mountpoint, v2->base_cgroup, "/user", user, NULL);
	lxcfs_debug("cgroupfs v2: Trying to prune \"%s\".\n", path_base);
	ret = recursive_rmdir(path_base);
	if (ret == -ENOENT || ret >= 0)
		path_base_rm = true;
	else
		path_base_rm = false;
	free(path_base);

	path_init = must_make_path(v2->mountpoint, v2->init_cgroup, "/user", user, NULL);
	lxcfs_debug("cgroupfs v2: Trying to prune \"%s\".\n", path_init);
	ret = recursive_rmdir(path_init);
	if (ret == -ENOENT || ret >= 0)
		path_init_rm = true;
	else
		path_init_rm = false;
	free(path_init);

	if (!path_base_rm && !path_init_rm)
		return false;

	return true;
}

/* Wrapper around cgv{1,2}_prune_empty_cgroups(). */
static void cg_prune_empty_cgroups(const char *user)
{
	(void)cgv1_prune_empty_cgroups(user);
	(void)cgv2_prune_empty_cgroups(user);
}

/* Free allocated information for detected cgroupfs v1 hierarchies. */
static void cgv1_free_hierarchies(void)
{
	struct cgv1_hierarchy **it;

	if (!cgv1_hierarchies)
		return;

	for (it = cgv1_hierarchies; it && *it; it++) {
		if ((*it)->controllers) {
			char **tmp;
			for (tmp = (*it)->controllers; tmp && *tmp; tmp++)
				free(*tmp);

			free((*it)->controllers);
		}
		free((*it)->mountpoint);
		free((*it)->base_cgroup);
		free((*it)->fullcgpath);
		free((*it)->init_cgroup);
	}
	free(cgv1_hierarchies);
}

/* Free allocated information for the detected cgroupfs v2 hierarchy. */
static void cgv2_free_hierarchies(void)
{
	struct cgv2_hierarchy **it;

	if (!cgv2_hierarchies)
		return;

	for (it = cgv2_hierarchies; it && *it; it++) {
		if ((*it)->controllers) {
			char **tmp;
			for (tmp = (*it)->controllers; tmp && *tmp; tmp++)
				free(*tmp);

			free((*it)->controllers);
		}
		free((*it)->mountpoint);
		free((*it)->base_cgroup);
		free((*it)->fullcgpath);
		free((*it)->init_cgroup);
	}
	free(cgv2_hierarchies);
}

/* Wrapper around cgv{1,2}_free_hierarchies(). */
static void cg_exit(void)
{
	cgv1_free_hierarchies();
	cgv2_free_hierarchies();
}

int pam_sm_open_session(pam_handle_t *pamh, int flags, int argc,
		const char **argv)
{
	int ret;
	uid_t uid = 0;
	gid_t gid = 0;
	const char *PAM_user = NULL;

	ret = pam_get_user(pamh, &PAM_user, NULL);
	if (ret != PAM_SUCCESS) {
		mysyslog(LOG_ERR, "PAM-CGFS: couldn't get user\n", NULL);
		return PAM_SESSION_ERR;
	}

	if (!get_uid_gid(PAM_user, &uid, &gid)) {
		mysyslog(LOG_ERR, "Failed to get uid and gid for %s.\n", PAM_user, NULL);
		return PAM_SESSION_ERR;
	}

	if (!cg_init(uid, gid)) {
		mysyslog(LOG_ERR, "Failed to get list of controllers\n", NULL);
		return PAM_SESSION_ERR;
	}

	/* Try to prune cgroups, that are actually empty but were still marked
	 * as busy by the kernel so we couldn't remove them on session close.
	 */
	cg_prune_empty_cgroups(PAM_user);

	if (cg_mount_mode == CGROUP_UNKNOWN)
		return PAM_SESSION_ERR;

	if (argc > 1 && strcmp(argv[0], "-c") == 0)
		cg_mark_to_make_rw(argv[1]);

	return handle_login(PAM_user, uid, gid);
}

int pam_sm_close_session(pam_handle_t *pamh, int flags, int argc,
		const char **argv)
{
	int ret;
	uid_t uid = 0;
	gid_t gid = 0;
	const char *PAM_user = NULL;

	ret = pam_get_user(pamh, &PAM_user, NULL);
	if (ret != PAM_SUCCESS) {
		mysyslog(LOG_ERR, "PAM-CGFS: couldn't get user\n", NULL);
		return PAM_SESSION_ERR;
	}

	if (!get_uid_gid(PAM_user, &uid, &gid)) {
		mysyslog(LOG_ERR, "Failed to get uid and gid for %s.\n", PAM_user, NULL);
		return PAM_SESSION_ERR;
	}

	if (cg_mount_mode == CGROUP_UNINITIALIZED) {
		if (!cg_init(uid, gid))
			mysyslog(LOG_ERR, "Failed to get list of controllers\n", NULL);

		if (argc > 1 && strcmp(argv[0], "-c") == 0)
			cg_mark_to_make_rw(argv[1]);
	}

	cg_prune_empty_cgroups(PAM_user);
	cg_exit();

	return PAM_SUCCESS;
}