agentcell 0.2.1

Unprivileged Linux sandbox for AI agents — namespaces, Landlock, seccomp, cgroups
Documentation
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
/*
 * sand.c — a from-scratch agent sandbox using raw Linux primitives.
 *
 * Layers of defense (applied per child process):
 *   1. cgroup v2 resource limits (cpu.max / memory.max / pids.max)
 *   2. namespaces via clone(2): user mount pid net ipc uts cgroup
 *   3. minimal root: tmpfs root + pivot_root(2), read-only bind mounts for
 *      /usr /etc /opt, rw tmpfs for /tmp /run /var/tmp, fresh /proc, fresh
 *      /dev with 5 bound device nodes
 *   4. Landlock LSM: path-based allowlist (what may be read / written / exec'd)
 *   5. Seccomp-BPF: hand-built sock_filter deny-list (module loads, ptrace,
 *      bpf, new mount API, io_uring, keyring, time-setting, ...)
 *      --ask turns the deny-list into SECCOMP_RET_USER_NOTIF: blocked
 *      syscalls park in-kernel and the supervisor approves them on /dev/tty
 *
 * Runs 100% unprivileged — user namespaces give the child "root" that maps
 * to your normal uid outside, so a breakout gains nothing.
 *
 * Build:  cc -O2 -o sand sand.c
 * Usage:  ./sand [--mem 2G] [--cpu 2] [--pids 256] [--net none|host]
 *                [--workdir DIR] [--ro DIR]... [--rw DIR]... -- CMD [ARGS]
 */
#define _GNU_SOURCE
#include <ctype.h>
#include <dirent.h>
#include <errno.h>
#include <fcntl.h>
#include <getopt.h>
#include <limits.h>
#include <linux/audit.h>
#include <linux/filter.h>
#include <linux/landlock.h>
#include <linux/seccomp.h>

#include "arch/syscalls.h"   /* AC_SYS_*: per-arch syscall numbers */
#include <net/if.h>
#include <net/route.h>
#include <arpa/inet.h>
#include <poll.h>
#include <signal.h>
#include <stdint.h>
#include <sys/ioctl.h>
#include <sys/mount.h>
#include <sys/prctl.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/sysmacros.h>
#include <sys/syscall.h>
#include <sys/types.h>
#include <sys/un.h>
#include <sys/wait.h>
#include <sched.h>
#include <setjmp.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>

#define MAXBIND 32
#define MAX_EGRESS 16
#define MAX_RESOLV 4
#define MAX_ENV 64
#define MAX_SECRET 8

static int write_full(int fd, const void *buf, size_t n);

/* ------------------------------------------------------------------ */
/* helpers                                                             */
/* ------------------------------------------------------------------ */

/* library mode (libagentcell): a fatal setup error returns to the
 * caller instead of exiting the hosting process */
static jmp_buf *g_die_jmp;

static void die(const char *msg)
{
    fprintf(stderr, "sand: %s: %s\n", msg, strerror(errno));
    if (g_die_jmp)
        longjmp(*g_die_jmp, errno > 0 ? errno : 1);
    exit(1);
}

static void warn2(const char *msg)
{
    fprintf(stderr, "sand: %s: %s (continuing)\n", msg, strerror(errno));
}

static const char *basename_of(const char *p)
{
    const char *r = strrchr(p, '/');
    return r ? r + 1 : p;
}

static void write_file(const char *path, const char *val)
{
    int fd = open(path, O_WRONLY);
    if (fd < 0) { warn2(path); return; }
    if (write(fd, val, strlen(val)) < 0) warn2(path);
    close(fd);
}

static void mmkdir(const char *p, mode_t m)
{
    if (mkdir(p, m) < 0 && errno != EEXIST)
        die(p);
}

static void mmkdir_p(const char *path, mode_t m)
{
    char tmp[PATH_MAX];
    snprintf(tmp, sizeof tmp, "%s", path);
    for (char *p = tmp + 1; *p; p++)
        if (*p == '/') { *p = 0; mmkdir(tmp, m); *p = '/'; }
    mmkdir(tmp, m);
}

/* textual absolute-path normalizer: collapses "." and ".." segments
 * (no symlink resolution — the host's paths are about to vanish) */
static void normalize_path(char *path)
{
    char *seg[128], out[PATH_MAX] = "";
    int n = 0;
    for (char *tok = strtok(path, "/"); tok && n < 128; tok = strtok(NULL, "/")) {
        if (!strcmp(tok, ".")) continue;
        if (!strcmp(tok, "..")) { if (n) n--; continue; }
        seg[n++] = tok;
    }
    for (int i = 0; i < n; i++) { strcat(out, "/"); strcat(out, seg[i]); }
    if (!n) strcpy(out, "/");
    strcpy(path, out);          /* never longer than the input */
}

static void bind_mount(const char *src, const char *dst, int ro, int rec)
{
    unsigned long fl = MS_BIND | (rec ? MS_REC : 0);
    if (mount(src, dst, NULL, fl, NULL) < 0) {
        char msg[PATH_MAX * 2];
        snprintf(msg, sizeof msg, "bind %s -> %s", src, dst);
        die(msg);
    }
    if (ro)
        if (mount(NULL, dst, NULL, MS_BIND | MS_REMOUNT | MS_RDONLY |
                  (rec ? MS_REC : 0), NULL) < 0) {
            char msg[PATH_MAX * 2];
            snprintf(msg, sizeof msg, "remount ro %s", dst);
            warn2(msg);   /* EPERM if src sb is init-userns (tmpfs); Landlock still RO */
        }
}

static void tmpfs_mount(const char *dst, const char *opts)
{
    if (mount("tmpfs", dst, "tmpfs", MS_NOSUID | MS_NODEV, opts) < 0)
        die(dst);
}

/* ------------------------------------------------------------------ */
/* config                                                              */
/* ------------------------------------------------------------------ */

enum { NET_NONE, NET_HOST, NET_VETH };

struct cfg {
    long mem_bytes;
    char cpu_max[64];
    int  pids;
    int  netmode;                   /* NET_NONE | NET_HOST | NET_VETH */
    char veth_if[64], veth_ip[64], veth_gw[64];   /* --net veth */
    char workdir[PATH_MAX];
    char rootfs[PATH_MAX];          /* --rootfs DIR; empty = host /usr /etc */
    char sock[PATH_MAX];            /* --sock PATH for serve; empty = auto */
    char *ro[MAXBIND]; int n_ro;
    char *rw[MAXBIND]; int n_rw;
    struct bind { char src[PATH_MAX]; char dst[PATH_MAX]; int ro; }
         binds[MAXBIND]; int n_binds;
    int  no_landlock;
    int  no_seccomp;
    int  ask;                       /* user-notify: ask before denied syscalls */
    int  secure;                    /* register with agentlsm daemon */
    char deny[MAXBIND][256];        /* extra LSM deny prefixes */
    int  n_deny;
    char *ov[MAXBIND]; int n_ov;      /* --overlay DIR: copy-on-write binds */
    long io_rbps, io_wbps;          /* io.max on the workspace device (0=off) */
    char egress_host[MAX_EGRESS][128];  /* --egress HOST[:PORT] allowlist */
    char egress_port[MAX_EGRESS][8];
    int  n_egress;
    char resolv[MAX_RESOLV][64];      /* cell's nameservers (veth) */
    int  n_resolv;
    char *env[MAX_ENV]; int n_env;    /* --env / --env-file K=V */
    char secret_dst[MAX_SECRET][PATH_MAX];  /* --secret DST=SRC on tmpfs */
    char *secret_data[MAX_SECRET];
    size_t secret_len[MAX_SECRET];
    int  n_secrets;
    long workdir_size;                /* --workdir-size: tmpfs workspace */
    int  timeout;
    char *const *argv;
};

static struct cfg C = {
    .mem_bytes = 2L << 30,
    .cpu_max   = "200000 100000",
    .pids      = 256,
    .netmode  = NET_NONE,
    .workdir   = "",
    .rootfs    = "",
    .sock      = "",
};

static uid_t g_uid;
static gid_t g_gid;
static int   g_sync[2];              /* parent -> child: uid maps ready */
static char  g_newroot[] = "/tmp/agentcell-root.XXXXXX";
static char  g_cgpath[PATH_MAX];
static int   g_have_cg;
static int   g_veth_on;              /* NETUP succeeded: NETDOWN at exit */

/* FFI spawn (libagentcell): stdio fds for the payload and an explicit
 * environment; -1 / NULL = inherit the sane defaults */
int    g_spawn_fds[3] = { -1, -1, -1 };
char **g_spawn_envp;

/* ---- long-running (serve) mode ---- */
static int   g_serve;                 /* 1 = jail stays alive, serves execs */
static int   g_host_sock = -1;        /* supervisor end of the socketpair   */
static int   g_jail_sock = -1;        /* jail end, inherited by the child   */
static char  g_sock_path[PATH_MAX];   /* host-facing unix socket            */
static char  g_info_path[PATH_MAX];   /* sidecar with cg path, execs, ...   */
static long  g_execs;
static __u64 g_lsm_cgid;              /* cell id at the agentlsm daemon    */
static int   g_lsm_on;

static void lsm_register(void);       /* defined with the exec client code */
static void lsm_unregister(void);
static int  net_veth_register(pid_t child);
static void net_veth_unregister(pid_t child);

static void write_info(pid_t jail)
{
    FILE *f = fopen(g_info_path, "w");
    if (!f) return;
    fprintf(f, "sup=%d\njail=%d\nstarted=%ld\ncg=%s\nexecs=%ld\n"
               "secure=%d\ncgid=%llu\n",
            (int)getpid(), (int)jail, (long)time(NULL),
            g_have_cg ? g_cgpath : "-", g_execs,
            C.secure, (unsigned long long)g_lsm_cgid);
    fclose(f);
}

/* read one line "key value" from a cgroup file like cpu.stat */
static long cg_stat(const char *cg, const char *file, const char *key)
{
    char p[PATH_MAX];
    snprintf(p, sizeof p, "%s/%s", cg, file);
    FILE *f = fopen(p, "r");
    if (!f) return -1;
    long v = -1;
    char line[256], k[64];
    while (fgets(line, sizeof line, f))
        if (sscanf(line, "%63s %ld", k, &v) == 2 && !strcmp(k, key))
            break;
    fclose(f);
    return v;
}

static long cg_num(const char *cg, const char *file)
{
    char p[PATH_MAX]; long v = -1;
    snprintf(p, sizeof p, "%s/%s", cg, file);
    FILE *f = fopen(p, "r");
    if (f) { if (fscanf(f, "%ld", &v) != 1) v = -1; fclose(f); }
    return v;
}

static void fmt_human(long bytes, char *out, size_t n)
{
    if (bytes < 0)            snprintf(out, n, "-");
    else if (bytes < 1<<20)   snprintf(out, n, "%ldK", bytes >> 10);
    else if (bytes < 1<<30)   snprintf(out, n, "%ldM", bytes >> 20);
    else                      snprintf(out, n, "%.1fG", bytes / 1073741824.0);
}

static int cell_info(const char *sock_base, pid_t *sup, pid_t *jail,
                     long *started, char *cg, size_t cgn, long *execs)
{
    char p[PATH_MAX];
    snprintf(p, sizeof p, "%s.info", sock_base);
    FILE *f = fopen(p, "r");
    if (!f) return -1;
    char line[256];
    cg[0] = 0;
    while (fgets(line, sizeof line, f)) {
        if (!strncmp(line, "sup=", 4))     *sup = atoi(line + 4);
        else if (!strncmp(line, "jail=", 5))   *jail = atoi(line + 5);
        else if (!strncmp(line, "started=", 8)) *started = atol(line + 8);
        else if (!strncmp(line, "cg=", 3)) { line[strcspn(line, "\n")] = 0;
                                              snprintf(cg, cgn, "%s", line + 3); }
        else if (!strncmp(line, "execs=", 6))  *execs = atol(line + 6);
    }
    fclose(f);
    return 0;
}

static int list_cells(void)
{
    const char *rt = getenv("XDG_RUNTIME_DIR");
    if (!rt) rt = "/tmp";
    DIR *d = opendir(rt);
    if (!d) { perror(rt); return 1; }

    printf("%-22s %-8s %-9s %-8s %-7s %-7s %s\n",
           "SOCKET", "SUP", "UPTIME", "EXECS", "CPU(s)", "MEM", "PIDS");
    struct dirent *e;
    int found = 0;
    while ((e = readdir(d))) {
        size_t nlen = strlen(e->d_name);
        if (nlen < 5 || strcmp(e->d_name + nlen - 5, ".sock") ||
            strncmp(e->d_name, "agentcell-", 10))
            continue;
        char base[PATH_MAX];
        snprintf(base, sizeof base, "%s/%s", rt, e->d_name);

        pid_t sup = 0, jail = 0; long started = 0, execs = 0;
        char cg[PATH_MAX] = "";
        if (cell_info(base, &sup, &jail, &started, cg, sizeof cg, &execs) < 0)
            continue;
        if (kill(sup, 0) < 0 && errno == ESRCH) continue;  /* stale */
        found++;

        long up = time(NULL) - started;
        char mem[16];
        long memc = cg[0] && strcmp(cg, "-") ? cg_num(cg, "memory.current") : -1;
        fmt_human(memc, mem, sizeof mem);
        long usec = cg[0] && strcmp(cg, "-") ? cg_stat(cg, "cpu.stat", "usage_usec") : -1;
        long pids = cg[0] && strcmp(cg, "-") ? cg_num(cg, "pids.current") : -1;

        printf("%-22s %-8d %02ld:%02ld:%02ld %-8ld %-7ld %-7s %ld\n",
               e->d_name, sup, up / 3600, (up / 60) % 60, up % 60,
               execs, usec < 0 ? -1 : usec / 1000000, mem, pids);
    }
    closedir(d);
    return found ? 0 : 1;
}

static int top_cells(const char *sock)
{
    char base[PATH_MAX];
    const char *dot = strstr(sock, ".sock");
    if (!dot) { fprintf(stderr, "sand: not a cell socket: %s\n", sock); return 2; }
    snprintf(base, sizeof base, "%.*s", (int)(dot - sock + 5), sock);

    pid_t sup, jail; long started, execs; char cg[PATH_MAX];
    if (cell_info(base, &sup, &jail, &started, cg, sizeof cg, &execs) < 0) {
        fprintf(stderr, "sand: no info for %s\n", sock); return 1;
    }
    fprintf(stderr, "cell pid %d  cg %s  — Ctrl-C to stop\n\n", jail, cg);

    long prev_usec = 0;
    for (;;) {
        long usec = cg_stat(cg, "cpu.stat", "usage_usec");
        long mem  = cg_num(cg, "memory.current");
        long pids = cg_num(cg, "pids.current");
        long memmax = cg_num(cg, "memory.max");
        long dusec = usec - prev_usec; prev_usec = usec;
        char mems[16], maxs[16];
        fmt_human(mem, mems, sizeof mems);
        fmt_human(memmax, maxs, sizeof maxs);
        printf("\rcpu %6ldms/s  mem %s/%s  pids %ld  execs %ld    ",
               dusec / 1000, mems, maxs, pids, execs);
        fflush(stdout);
        sleep(1);
        /* refresh execs from sidecar */
        cell_info(base, &sup, &jail, &started, cg, sizeof cg, &execs);
    }
    return 0;
}

/* ------------------------------------------------------------------ */
/* 1. cgroup v2 limits (unprivileged, via systemd's delegated subtree) */
/* ------------------------------------------------------------------ */

static void cgroup_setup(void)
{
    char self[PATH_MAX] = {0}, base[PATH_MAX], line[512], p[PATH_MAX], v[64];
    FILE *f = fopen("/proc/self/cgroup", "r");
    if (!f) return;
    while (fgets(line, sizeof line, f))
        if (strncmp(line, "0::", 3) == 0) {
            line[strcspn(line, "\n")] = 0;
            snprintf(self, sizeof self, "%s", line + 3);
        }
    fclose(f);
    if (!self[0]) return;

    /* systemd session scopes and DelegateSubgroup= leaves are not writable
     * for subtree_control (no-internal-process). Cut back to the delegated
     * unit: user@UID.service or any *.service. */
    snprintf(base, sizeof base, "/sys/fs/cgroup%s", self);
    char *svc = strstr(base, ".service");
    if (svc) {
        char *after = svc + strlen(".service");
        if (*after == '/')
            *after = 0;
    } else {
        char *usr = strstr(base, "/user@");
        if (usr) {
            char *slash = strchr(usr + 1, '/');
            if (slash)
                *slash = 0;
        }
    }

    /* arm controllers for our children; EPERM is fine if not delegated */
    snprintf(p, sizeof p, "%s/cgroup.subtree_control", base);
    write_file(p, "+cpu +memory +pids");
    if (C.io_rbps || C.io_wbps)
        write_file(p, "+io");   /* separate: often not delegated */

    snprintf(g_cgpath, sizeof g_cgpath, "%s/agentcell-%d", base, (int)getpid());
    if (mkdir(g_cgpath, 0755) < 0) {
        warn2("create cgroup (running without resource limits)");
        return;
    }

    snprintf(p, sizeof p, "%s/cpu.max", g_cgpath);     write_file(p, C.cpu_max);
    snprintf(v, sizeof v, "%ld", C.mem_bytes);
    snprintf(p, sizeof p, "%s/memory.max", g_cgpath);  write_file(p, v);
    snprintf(v, sizeof v, "%d", C.pids);
    snprintf(p, sizeof p, "%s/pids.max", g_cgpath);    write_file(p, v);

    /* io.max throttles real block I/O on the workspace device; the
     * in-sandbox tmpfs scratch (/tmp) has no backing device and is
     * never throttled — only what actually hits the disk */
    if (C.io_rbps || C.io_wbps) {
        struct stat st;
        if (!stat(C.workdir, &st)) {
            size_t off = snprintf(v, sizeof v, "%u:%u",
                                  major(st.st_dev), minor(st.st_dev));
            if (C.io_rbps)
                off += snprintf(v + off, sizeof v - off,
                                " rbps=%ld", C.io_rbps);
            if (C.io_wbps)
                snprintf(v + off, sizeof v - off, " wbps=%ld", C.io_wbps);
            snprintf(p, sizeof p, "%s/io.max", g_cgpath);
            write_file(p, v);
        }
    }
    g_have_cg = 1;
}

/* ------------------------------------------------------------------ */
/* 2+3. build a minimal root in a tmpfs, then pivot_root               */
/* ------------------------------------------------------------------ */

#define NR(path) snprintf(p, sizeof p, "%s%s", g_newroot, path)

/* mirror a host top-level path (/bin, /lib64, ...) into the jail root:
 * symlink -> recreate with the same target (relative targets keep
 * working because /usr is bound), real dir -> read-only bind.
 * Needed because distros disagree on usrmerge targets: Arch has
 * /lib64 -> usr/lib, Ubuntu has /lib64 -> usr/lib64 — hardcoding
 * either breaks the ELF interpreter path on the other. */
/* host path for the OS view: --rootfs DIR prefixes, else the real / */
static void os_src(char *out, size_t n, const char *abs)
{
    if (C.rootfs[0])
        snprintf(out, n, "%s%s", C.rootfs, abs);
    else
        snprintf(out, n, "%s", abs);
}

static void mirror_top(const char *path)
{
    char p[PATH_MAX], tgt[PATH_MAX], src[PATH_MAX];
    struct stat st;
    os_src(src, sizeof src, path);
    NR(path);
    if (lstat(src, &st) < 0) return;
    if (S_ISLNK(st.st_mode)) {
        ssize_t n = readlink(src, tgt, sizeof tgt - 1);
        if (n <= 0) return;
        tgt[n] = 0;
        if (symlink(tgt, p) && errno != EEXIST) die(path);
    } else {
        mmkdir(p, 0755);
        bind_mount(src, p, 1, 1);
    }
}

static void bind_os_ro(const char *abs, int required)
{
    char src[PATH_MAX], p[PATH_MAX];
    struct stat st;
    os_src(src, sizeof src, abs);
    if (lstat(src, &st) < 0) {
        if (required) die(src);
        return;
    }
    NR(abs);
    mmkdir(p, 0755);
    bind_mount(src, p, 1, 1);
}

static void do_mounts(void)
{
    char p[PATH_MAX];

    /* whole namespace private: nothing propagates back to the host */
    if (mount(NULL, "/", NULL, MS_REC | MS_PRIVATE, NULL) < 0)
        die("make mounts private");

    /* the new root itself is a tiny tmpfs */
    if (mount("tmpfs", g_newroot, "tmpfs", MS_NOSUID, "size=16m,mode=0755") < 0)
        die("newroot tmpfs");

    /* read-only OS view: host /usr /etc, or --rootfs DIR (no recursive
     * bind of the live distro tree — cheaper start, reproducible root) */
    bind_os_ro("/usr", 1);
    bind_os_ro("/etc", 1);
    bind_os_ro("/opt", 0);

    /* /bin /sbin /lib /lib64: mirror the host layout exactly */
    mirror_top("/bin");
    mirror_top("/sbin");
    mirror_top("/lib");
    mirror_top("/lib64");

    /* the agent's writable workspace */
    NR("/home/agent"); mmkdir_p(p, 0755);
    if (C.workdir_size > 0) {
        /* hard size cap without root: a RAM-backed workspace.  Counts
         * against the cell's memory.max, so size it with --mem */
        char opts[64];
        snprintf(opts, sizeof opts, "size=%ld,mode=0755", C.workdir_size);
        tmpfs_mount(p, opts);
    } else {
        bind_mount(C.workdir, p, 0, 0);
    }

    /* extra binds land under /mnt/<basename> */
    NR("/mnt"); mmkdir(p, 0755);
    for (int i = 0; i < C.n_ro; i++) {
        char dst[PATH_MAX];
        snprintf(dst, sizeof dst, "%s/mnt/%s", g_newroot, basename_of(C.ro[i]));
        mmkdir_p(dst, 0755);
        bind_mount(C.ro[i], dst, 1, 1);
    }
    for (int i = 0; i < C.n_rw; i++) {
        char dst[PATH_MAX];
        snprintf(dst, sizeof dst, "%s/mnt/%s", g_newroot, basename_of(C.rw[i]));
        mmkdir_p(dst, 0755);
        bind_mount(C.rw[i], dst, 0, 1);
    }

    /* custom mounts: exact paths inside the sandbox */
    for (int i = 0; i < C.n_binds; i++) {
        char dst[PATH_MAX];
        snprintf(dst, sizeof dst, "%s%s", g_newroot, C.binds[i].dst);
        mmkdir_p(dst, 0755);
        bind_mount(C.binds[i].src, dst, C.binds[i].ro, 1);
    }

    /* scratch space: tmpfs = RAM speed (2.1 GB/s vs 509 MB/s SSD here) */
    NR("/tmp");     mmkdir(p, 01777);  tmpfs_mount(p, "size=1g,mode=1777");

    /* --overlay DIR: copy-on-write view of a host dir.  The lower is the
     * host path (a filesystem root can't be a lower, but any subdir
     * can); upper+work live on the scratch tmpfs and die with the
     * sandbox — the host dir is never modified.  Writes still pass DAC
     * as our unprivileged uid, so this shines for dirs WE own
     * (~/src/myrepo): the agent edits freely, nothing persists. */
    for (int i = 0; i < C.n_ov; i++) {
        char dst[PATH_MAX], up[PATH_MAX], wk[PATH_MAX], opts[PATH_MAX * 3];
        const char *base = basename_of(C.ov[i]);
        snprintf(dst, sizeof dst, "%s/mnt/%s", g_newroot, base);
        mmkdir_p(dst, 0755);
        snprintf(up, sizeof up, "%s/tmp/.ovl/%d.up", g_newroot, i);
        snprintf(wk, sizeof wk, "%s/tmp/.ovl/%d.wk", g_newroot, i);
        mmkdir_p(up, 0700);
        mmkdir_p(wk, 0700);
        snprintf(opts, sizeof opts, "lowerdir=%s,upperdir=%s,workdir=%s",
                 C.ov[i], up, wk);
        if (mount("overlay", dst, "overlay", 0, opts) < 0)
            die("overlay mount (userns overlayfs needs kernel >= 5.11)");
    }

    NR("/var/tmp"); mmkdir_p(p, 01777); tmpfs_mount(p, "size=128m,mode=1777");
    NR("/run");     mmkdir(p, 0755);   tmpfs_mount(p, "size=64m,mode=755");

    /* --secret DST=SRC: drop 0600 copies on the cell's tmpfs so tokens
     * and keys never touch the host disk.  do_mounts() runs before
     * pivot_root, so DST is resolved inside the new root. */
    for (int i = 0; i < C.n_secrets; i++) {
        char full[PATH_MAX];
        snprintf(full, sizeof full, "%s%s", g_newroot, C.secret_dst[i]);
        char *slash = strrchr(full, '/');
        if (slash) { *slash = 0; mmkdir_p(full, 0700); *slash = '/'; }
        int sfd = open(full, O_WRONLY | O_CREAT | O_TRUNC | O_NOFOLLOW, 0600);
        if (sfd < 0 || write_full(sfd, C.secret_data[i], C.secret_len[i]) < 0)
            warn2("secret");
        if (sfd >= 0) close(sfd);
    }
    /* with host networking, systemd-resolved lives behind /run/systemd —
     * bind it ro so /etc/resolv.conf's symlink and the resolver socket work */
    if (C.netmode == NET_HOST) {
        NR("/run/systemd"); mmkdir(p, 0755);
        /* note: no ro-remount — the mount is owned by the init userns and
         * EPERMs; but real DAC applies (agent uid == our uid on host)    */
        if (mount("/run/systemd", p, NULL, MS_BIND | MS_REC, NULL) < 0)
            warn2("bind /run/systemd (DNS may fail)");
    }

    /* veth: /etc/resolv.conf usually points at the host's LOOPBACK stub
     * resolver (127.0.0.53) — unreachable from our netns.  Put
     * systemd-resolved's UPSTREAM list where resolv.conf points
     * (following the symlink: it dangles inside the jail otherwise). */
    if (C.netmode == NET_VETH) {
        struct stat st;
        const char *up = "/run/systemd/resolve/resolv.conf";
        if (stat(up, &st) == 0) {
            char tgt[PATH_MAX];
            ssize_t n = readlink("/etc/resolv.conf", tgt, sizeof tgt - 1);
            if (n > 0) {
                tgt[n] = 0;
                if (tgt[0] != '/') {
                    char rel[PATH_MAX];
                    snprintf(rel, sizeof rel, "%s", tgt);
                    snprintf(tgt, sizeof tgt, "/etc/%s", rel);
                }
                normalize_path(tgt);
            } else {
                snprintf(tgt, sizeof tgt, "/etc/resolv.conf");
            }
            char dst[PATH_MAX];
            snprintf(dst, sizeof dst, "%s%s", g_newroot, tgt);
            char *slash = strrchr(dst, '/');
            *slash = 0; mmkdir_p(dst, 0755); *slash = '/';
            int fd = open(dst, O_CREAT | O_RDONLY, 0644);
            if (fd >= 0) close(fd);
            /* no ro-remount: like the --net host /run/systemd bind, this
             * EPERMs (the source sb is owned by init_userns).  DAC still
             * applies — the file is root-owned 0644 and the agent's uid
             * is our unprivileged uid on the host, so it stays read-only
             * in practice. */
            bind_mount(up, dst, 0, 0);
        }
    }

    /* fresh /proc for our PID namespace (the child is PID 1 of it) */
    NR("/proc"); mmkdir(p, 0555);
    if (mount("proc", p, "proc", MS_NOSUID | MS_NODEV, NULL) < 0)
        warn2("mount proc");

    /* /sys + cgroup2: allowed in our own userns, tolerate failure */
    NR("/sys"); mmkdir(p, 0555);
    if (mount("sysfs", p, "sysfs", MS_RDONLY | MS_NOSUID | MS_NODEV, NULL) < 0)
        warn2("mount sysfs");
    {
        char q[PATH_MAX];
        snprintf(q, sizeof q, "%s/fs/cgroup", p);
        mmkdir_p(q, 0555);
        if (mount("cgroup2", q, "cgroup2", MS_RDONLY | MS_NOSUID | MS_NODEV,
                  NULL) < 0)
            warn2("mount cgroup2");
    }

    /* minimal /dev: tmpfs + 5 bound device nodes + the usual symlinks */
    NR("/dev"); mmkdir(p, 0755); tmpfs_mount(p, "size=1m,mode=755");
    static const char *devs[] = { "null", "zero", "full", "random", "urandom" };
    for (unsigned i = 0; i < sizeof devs / sizeof *devs; i++) {
        char src[64], dst[PATH_MAX];
        snprintf(src, sizeof src, "/dev/%s", devs[i]);
        snprintf(dst, sizeof dst, "%s/dev/%s", g_newroot, devs[i]);
        int fd = open(dst, O_CREAT | O_EXCL, 0666);   /* reserve the name */
        if (fd >= 0) close(fd);
        if (mount(src, dst, NULL, MS_BIND, NULL) < 0) {
            unlink(dst);
            char msg[128];
            snprintf(msg, sizeof msg, "bind /dev/%s", devs[i]);
            die(msg);
        }
    }
    NR("/dev/fd");     if (symlink("/proc/self/fd",    p) && errno != EEXIST) die("symlink fd");
    NR("/dev/stdin");  if (symlink("/proc/self/fd/0",  p) && errno != EEXIST) die("symlink stdin");
    NR("/dev/stdout"); if (symlink("/proc/self/fd/1",  p) && errno != EEXIST) die("symlink stdout");
    NR("/dev/stderr"); if (symlink("/proc/self/fd/2",  p) && errno != EEXIST) die("symlink stderr");

    /* the hole where the host root lands during pivot_root */
    NR("/.put_old"); mmkdir(p, 0755);
}

/* ------------------------------------------------------------------ */
/* 4. Landlock — path allowlist                                        */
/* ------------------------------------------------------------------ */

#ifndef LANDLOCK_ACCESS_FS_REFER
#define LANDLOCK_ACCESS_FS_REFER (1ULL << 11)
#endif
#ifndef LANDLOCK_ACCESS_FS_TRUNCATE
#define LANDLOCK_ACCESS_FS_TRUNCATE (1ULL << 14)
#endif
#ifndef LANDLOCK_ACCESS_FS_IOCTL_DEV
#define LANDLOCK_ACCESS_FS_IOCTL_DEV (1ULL << 16)
#endif

#ifndef SYS_landlock_create_ruleset
#define SYS_landlock_create_ruleset 444
#define SYS_landlock_add_rule       445
#define SYS_landlock_restrict_self  446
#endif

static void ll_allow(int ruleset_fd, const char *path, u_int64_t access)
{
    int fd = open(path, O_PATH | O_CLOEXEC);
    if (fd < 0) { warn2(path); return; }
    struct landlock_path_beneath_attr pb = {
        .allowed_access = access,
        .parent_fd = fd,
    };
    if (syscall(SYS_landlock_add_rule, ruleset_fd,
                LANDLOCK_RULE_PATH_BENEATH, &pb, 0) < 0)
        warn2(path);
    close(fd);
}

static void landlock_apply(void)
{
    int abi = syscall(SYS_landlock_create_ruleset, NULL, 0,
                      LANDLOCK_CREATE_RULESET_VERSION);
    if (abi < 0) { warn2("landlock unavailable"); return; }

    u_int64_t ro = LANDLOCK_ACCESS_FS_EXECUTE | LANDLOCK_ACCESS_FS_READ_FILE |
                   LANDLOCK_ACCESS_FS_READ_DIR;
    u_int64_t rw = ro | LANDLOCK_ACCESS_FS_WRITE_FILE |
                   LANDLOCK_ACCESS_FS_REMOVE_DIR  | LANDLOCK_ACCESS_FS_REMOVE_FILE |
                   LANDLOCK_ACCESS_FS_MAKE_CHAR   | LANDLOCK_ACCESS_FS_MAKE_DIR |
                   LANDLOCK_ACCESS_FS_MAKE_REG    | LANDLOCK_ACCESS_FS_MAKE_SOCK |
                   LANDLOCK_ACCESS_FS_MAKE_FIFO   | LANDLOCK_ACCESS_FS_MAKE_SYM |
                   LANDLOCK_ACCESS_FS_MAKE_BLOCK;
    u_int64_t handled = rw;
    if (abi >= 2) { rw |= LANDLOCK_ACCESS_FS_REFER;      handled |= LANDLOCK_ACCESS_FS_REFER; }
    if (abi >= 3) { rw |= LANDLOCK_ACCESS_FS_TRUNCATE;   handled |= LANDLOCK_ACCESS_FS_TRUNCATE; }
    if (abi >= 5) { rw |= LANDLOCK_ACCESS_FS_IOCTL_DEV;  handled |= LANDLOCK_ACCESS_FS_IOCTL_DEV; }

    /* Newer libc headers grew landlock_ruleset_attr (net/scoped). A
     * sizeof that the running kernel rejects comes back as EINVAL. */
    struct landlock_ruleset_attr attr = { .handled_access_fs = handled };
    int fd = -1;
    const size_t try_sz[] = { 8, 16, 24, sizeof attr };
    for (unsigned i = 0; i < sizeof try_sz / sizeof try_sz[0] && fd < 0; i++)
        fd = (int)syscall(SYS_landlock_create_ruleset, &attr, try_sz[i], 0);
    if (fd < 0) {
        handled = LANDLOCK_ACCESS_FS_EXECUTE | LANDLOCK_ACCESS_FS_READ_FILE |
                  LANDLOCK_ACCESS_FS_READ_DIR | LANDLOCK_ACCESS_FS_WRITE_FILE |
                  LANDLOCK_ACCESS_FS_REMOVE_DIR | LANDLOCK_ACCESS_FS_REMOVE_FILE |
                  LANDLOCK_ACCESS_FS_MAKE_REG | LANDLOCK_ACCESS_FS_MAKE_DIR;
        rw = handled;
        attr.handled_access_fs = handled;
        fd = (int)syscall(SYS_landlock_create_ruleset, &attr, 8, 0);
    }
    if (fd < 0) { warn2("landlock_create_ruleset"); return; }

    /* read-only OS view (the / rule makes the root listable; writes are
     * still blocked everywhere except where an rw rule applies)          */
    ll_allow(fd, "/",    ro);
    ll_allow(fd, "/usr",  ro);
    ll_allow(fd, "/etc",  ro);
    ll_allow(fd, "/opt",  ro);
    ll_allow(fd, "/proc", ro);
    ll_allow(fd, "/sys",  ro);

    /* writable scratch + workspace */
    ll_allow(fd, "/tmp",        rw);
    ll_allow(fd, "/var/tmp",    rw);
    ll_allow(fd, "/run",        rw);
    ll_allow(fd, "/dev",        rw);
    ll_allow(fd, "/home/agent", rw);

    /* extra binds */
    for (int i = 0; i < C.n_ro; i++) {
        char p[PATH_MAX];
        snprintf(p, sizeof p, "/mnt/%s", basename_of(C.ro[i]));
        ll_allow(fd, p, ro);
    }
    for (int i = 0; i < C.n_rw; i++) {
        char p[PATH_MAX];
        snprintf(p, sizeof p, "/mnt/%s", basename_of(C.rw[i]));
        ll_allow(fd, p, rw);
    }
    /* overlay binds: rw — writes land in the disposable upper */
    for (int i = 0; i < C.n_ov; i++) {
        char p[PATH_MAX];
        snprintf(p, sizeof p, "/mnt/%s", basename_of(C.ov[i]));
        ll_allow(fd, p, rw);
    }

    /* custom mounts */
    for (int i = 0; i < C.n_binds; i++)
        ll_allow(fd, C.binds[i].dst, C.binds[i].ro ? ro : rw);

    if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) < 0) die("no_new_privs");
    if (syscall(SYS_landlock_restrict_self, fd, 0) < 0)
        warn2("landlock_restrict_self");
    close(fd);
}

/* ------------------------------------------------------------------ */
/* 5. Seccomp — raw BPF deny-list                                      */
/* ------------------------------------------------------------------ */

#define DENY_EPERM (SECCOMP_RET_ERRNO | (EPERM & SECCOMP_RET_DATA))
#define DENY_KILL  (SECCOMP_RET_KILL_PROCESS)

/* --ask: park blocked syscalls and ask the supervisor instead of EPERM
 * (seccomp user notification, kernel >= 5.0).  Fallbacks for old headers. */
#ifndef SECCOMP_RET_USER_NOTIF
#define SECCOMP_RET_USER_NOTIF 0x7fc00000U
struct seccomp_notif {
    __u64 id;
    __u32 pid;
    __u32 flags;
    struct seccomp_data data;
};
struct seccomp_notif_resp {
    __u64 id;
    __s64 val;
    __s32 error;
    __u32 flags;
};
#define SECCOMP_IOC_MAGIC '!'
#define SECCOMP_IOR(nr, type)  _IOR(SECCOMP_IOC_MAGIC, nr, type)
#define SECCOMP_IOWR(nr, type) _IOWR(SECCOMP_IOC_MAGIC, nr, type)
#define SECCOMP_IOCTL_NOTIF_RECV     SECCOMP_IOWR(0, struct seccomp_notif)
#define SECCOMP_IOCTL_NOTIF_SEND     SECCOMP_IOWR(1, struct seccomp_notif_resp)
#define SECCOMP_IOCTL_NOTIF_ID_VALID SECCOMP_IOR(2, __u64)
#endif
#ifndef SECCOMP_FILTER_FLAG_NEW_LISTENER
#define SECCOMP_FILTER_FLAG_NEW_LISTENER (1UL << 3)
#endif
#ifndef SECCOMP_USER_NOTIF_FLAG_CONTINUE
#define SECCOMP_USER_NOTIF_FLAG_CONTINUE (1UL << 0)
#endif

/* seccomp_data layout: nr @0 (int), arch @4 (u32), ip @8, args[0] @16 */
#define OFF_NR   0
#define OFF_ARCH 4
#define OFF_ARG0 16

static struct sock_filter g_flt[512];
static int g_n;

static void f_push(struct sock_filter f) { g_flt[g_n++] = f; }

/* deny-list collected here (nr + display name), compiled to a balanced
 * binary-search tree; what a match gets: EPERM, or a supervisor
 * question under --ask */
struct sc_deny { long nr; const char *name; };
static struct sc_deny g_deny[128];
static int  g_ndeny;
static __u32 g_deny_ret = DENY_EPERM;

static void deny(long nr, const char *name)
{
    g_deny[g_ndeny].nr = nr;
    g_deny[g_ndeny++].name = name;
}
#define DENY(sym) deny(SYS_##sym, #sym)

static void denylist_build(void);

/* the generated deny-list / TRIP-naming table (src/arch headers) */
static const struct ac_sys ac_syscalls[] = { AC_SYSCALL_TAB };

static int cmp_sc(const void *a, const void *b)
{
    long x = ((const struct sc_deny *)a)->nr;
    long y = ((const struct sc_deny *)b)->nr;
    return x < y ? -1 : x > y;
}

/*
 * Emit a binary search tree over the sorted deny list. Classic BPF only
 * allows forward jumps, so the layout per node is:
 *
 *   [node]   JGT mid, ->right   (patched below)
 *            JEQ mid, 0, 1      (== mid -> RET below; != -> left subtree)
 *            RET EPERM
 *   [left subtree: values < mid]
 *   [right subtree: values > mid]
 *
 * O(log n) comparisons per syscall instead of a linear JEQ chain.
 */
static void emit_bst(int lo, int hi)
{
    if (lo > hi)
        return;
    int mid = (lo + hi) / 2;
    int node = g_n;

    f_push((struct sock_filter)BPF_JUMP(BPF_JMP | BPF_JGT | BPF_K,
                                        g_deny[mid].nr, 0, 0)); /* patched */
    f_push((struct sock_filter)BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K,
                                        g_deny[mid].nr, 0, 1));
    f_push((struct sock_filter)BPF_STMT(BPF_RET | BPF_K, g_deny_ret));

    emit_bst(lo, mid - 1);                    /* values < mid */

    int right = g_n;                          /* right subtree start */
    g_flt[node].jt = right - node - 1;        /* nr > mid -> right */

    emit_bst(mid + 1, hi);                    /* values > mid */
}

/* "syscall does not exist" — makes libc fall back to the old API.
 * Used for clone3: callers retry with clone(2), which we flag-filter. */
static void deny_enosys(long nr)
{
    f_push((struct sock_filter)BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, nr, 0, 1));
    f_push((struct sock_filter)BPF_STMT(BPF_RET | BPF_K,
            SECCOMP_RET_ERRNO | (ENOSYS & SECCOMP_RET_DATA)));
}

static int seccomp_apply(void)
{
    if (C.ask)
        g_deny_ret = SECCOMP_RET_USER_NOTIF;

    /* [0] load arch
     * [1] if arch == AUDIT_ARCH_X86_64 jump over kill
     * [2] kill process (wrong arch → never make it to a syscall)
     * [3] load syscall nr
     */
    f_push((struct sock_filter)BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF_ARCH));
    f_push((struct sock_filter)BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K,
                                        AC_AUDIT_ARCH, 1, 0));
    f_push((struct sock_filter)BPF_STMT(BPF_RET | BPF_K, DENY_KILL));
    f_push((struct sock_filter)BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF_NR));

    /* clone(2) stays allowed, but never with CLONE_NEWUSER / CLONE_NEWNET:
     *   [k]   if nr != SYS_clone jump +4 (nr register still valid)
     *   [k+1] load args[0] (low 32 bits of clone flags)
     *   [k+2] if flags & mask == 0 jump +1 (flags clean → ok)
     *   [k+3] EPERM
     *   [k+4] reload nr for the deny chain below
     */
    f_push((struct sock_filter)BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, AC_SYS_clone, 0, 4));
    f_push((struct sock_filter)BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF_ARG0));
    f_push((struct sock_filter)BPF_JUMP(BPF_JMP | BPF_JSET | BPF_K,
                                        CLONE_NEWUSER | CLONE_NEWNET, 0, 1));
    f_push((struct sock_filter)BPF_STMT(BPF_RET | BPF_K, DENY_EPERM));
    f_push((struct sock_filter)BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF_NR));

    denylist_build();
    /* clone3: ENOSYS so libc falls back to clone(2), which is masked */
    if (AC_SYS_clone3 >= 0)
        deny_enosys(AC_SYS_clone3);

    /* deny-list -> sorted balanced BST: O(log n) per syscall */
    qsort(g_deny, g_ndeny, sizeof g_deny[0], cmp_sc);
    emit_bst(0, g_ndeny - 1);

    /* everything else is allowed */
    f_push((struct sock_filter)BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW));

    struct sock_fprog prog = { .len = (unsigned short)g_n, .filter = g_flt };

    if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) < 0) die("no_new_privs");
    unsigned long fl = SECCOMP_FILTER_FLAG_LOG;
    if (C.ask) fl |= SECCOMP_FILTER_FLAG_NEW_LISTENER;
    int rc = (int)syscall(SYS_seccomp, SECCOMP_SET_MODE_FILTER, fl, &prog);
    if (rc < 0) die("seccomp install (--ask needs kernel >= 5.0)");
    return rc;   /* 0 normally; the notify listener fd under --ask */
}

/* the deny-list: built in the child by seccomp_apply() (compiled into
 * the filter) and in the parent under --ask (for sc_name display) */
static void denylist_build(void)
{
    /* generated per-arch table; syscalls absent on this arch (ioperm on
     * arm64, vm86 on x86_64, ...) were already dropped by the generator */
    for (size_t i = 0; i < sizeof ac_syscalls / sizeof ac_syscalls[0]; i++)
        deny(ac_syscalls[i].nr, ac_syscalls[i].name);
}

/* ------------------------------------------------------------------ */
/* --ask: human-in-the-loop approval for blocked syscalls              */
/*                                                                     */
/* With --ask the deny-list returns SECCOMP_RET_USER_NOTIF instead of  */
/* EPERM: the syscall parks in-kernel and the supervisor (the parent)  */
/* decides per call — y = run it, n = EPERM, a = always allow this nr, */
/* k = kill the payload.  The question goes to /dev/tty so the         */
/* payload's stdio stays untouched.                                    */
/* ------------------------------------------------------------------ */

static int   g_ask_sp[2] = { -1, -1 };  /* fd-pass channel: child -> sup */
static int   g_ask_fd = -1;             /* notify listener (supervisor)  */
static __u64 g_always[8];               /* "always allow" bitmap (nr<512) */

static const char *sc_name(long nr)
{
    for (int i = 0; i < g_ndeny; i++)
        if (g_deny[i].nr == nr) return g_deny[i].name;
    return "?";
}

/* mirror of send_fd() (defined with the serve code): receive one fd */
static int recv_fd(int sock)
{
    char b;
    char cbuf[CMSG_SPACE(sizeof(int))];
    struct iovec iov = { .iov_base = &b, .iov_len = 1 };
    struct msghdr msg = {0};
    msg.msg_iov = &iov;
    msg.msg_iovlen = 1;
    msg.msg_control = cbuf;
    msg.msg_controllen = sizeof cbuf;
    if (recvmsg(sock, &msg, 0) <= 0) return -1;
    struct cmsghdr *c = CMSG_FIRSTHDR(&msg);
    if (!c || c->cmsg_level != SOL_SOCKET || c->cmsg_type != SCM_RIGHTS)
        return -1;
    return *(int *)CMSG_DATA(c);
}

/* one parked syscall: show it, ask, answer.  The payload's thread
 * stays blocked in the kernel until the response (or its death). */
static void ask_handle(int fd, pid_t payload)
{
    struct seccomp_notif req = {0};
    struct seccomp_notif_resp resp = {0};

    if (ioctl(fd, SECCOMP_IOCTL_NOTIF_RECV, &req) < 0)
        return;                            /* filter gone (child exited) */
    resp.id = req.id;

    long nr = req.data.nr;
    if (nr >= 0 && nr < 512 && (g_always[nr >> 6] & (1ULL << (nr & 63)))) {
        resp.flags = SECCOMP_USER_NOTIF_FLAG_CONTINUE;
        goto answer;
    }

    FILE *tt = fopen("/dev/tty", "r+");
    if (!tt) {                             /* no terminal: cannot ask */
        resp.error = -EPERM;
        goto answer;
    }
    fprintf(tt, "\n[sand-ask] pid %u requests %s(%#llx, %#llx, %#llx, ...)\n"
                "[sand-ask] y=allow once  n=deny (EPERM)  a=always  "
                "k=kill payload > ",
            req.pid, sc_name(nr),
            (unsigned long long)req.data.args[0],
            (unsigned long long)req.data.args[1],
            (unsigned long long)req.data.args[2]);
    fflush(tt);
    int c = fgetc(tt), d;
    while (c != '\n' && c != EOF && (d = fgetc(tt)) != '\n' && d != EOF)
        ;                                   /* drain rest of the line */
    fclose(tt);

    switch (c) {
    case 'y': case 'Y':
        resp.flags = SECCOMP_USER_NOTIF_FLAG_CONTINUE;
        break;
    case 'a': case 'A':
        if (nr >= 0 && nr < 512)
            g_always[nr >> 6] |= 1ULL << (nr & 63);
        resp.flags = SECCOMP_USER_NOTIF_FLAG_CONTINUE;
        break;
    case 'k': case 'K':
        kill(payload, SIGKILL);
        resp.error = -EPERM;
        break;
    default:
        resp.error = -EPERM;
        break;
    }

answer:
    /* the syscalling thread may have died while we asked (--timeout or
     * a 'k' answer); only respond if the notification is still valid */
    if (ioctl(fd, SECCOMP_IOCTL_NOTIF_ID_VALID, &req.id) == 0)
        ioctl(fd, SECCOMP_IOCTL_NOTIF_SEND, &resp);
}

/* ------------------------------------------------------------------ */
/* bring loopback up inside an empty netns                             */
/* ------------------------------------------------------------------ */

static void net_lo_up(void)
{
    struct ifreq ifr;
    int s = socket(AF_INET, SOCK_DGRAM, 0);
    if (s < 0) return;
    memset(&ifr, 0, sizeof ifr);
    strcpy(ifr.ifr_name, "lo");
    if (ioctl(s, SIOCGIFFLAGS, &ifr) == 0 && !(ifr.ifr_flags & IFF_UP)) {
        ifr.ifr_flags |= IFF_UP;
        if (ioctl(s, SIOCSIFFLAGS, &ifr) < 0) warn2("ifup lo");
    }
    close(s);
}

/* --net veth: configure the interface the agentlsm daemon pushed into
 * our netns (we own the netns, so plain ioctls suffice — no iproute2,
 * no netlink library).  Parameters arrived via the sync pipe. */
static void net_veth_up(void)
{
    int s = socket(AF_INET, SOCK_DGRAM, 0);
    if (s < 0) { warn2("veth socket"); return; }

    struct ifreq ifr;
    memset(&ifr, 0, sizeof ifr);
    snprintf(ifr.ifr_name, sizeof ifr.ifr_name, "%s", C.veth_if);
    struct sockaddr_in *sin = (struct sockaddr_in *)&ifr.ifr_addr;
    sin->sin_family = AF_INET;

    if (inet_pton(AF_INET, C.veth_ip, &sin->sin_addr) != 1 ||
        ioctl(s, SIOCSIFADDR, &ifr) < 0)
        { warn2("veth addr"); goto out; }
    inet_pton(AF_INET, "255.255.255.252", &sin->sin_addr);   /* /30 */
    if (ioctl(s, SIOCSIFNETMASK, &ifr) < 0) { warn2("veth netmask"); goto out; }
    if (ioctl(s, SIOCGIFFLAGS, &ifr) == 0) {
        ifr.ifr_flags |= IFF_UP;
        if (ioctl(s, SIOCSIFFLAGS, &ifr) < 0) { warn2("veth up"); goto out; }
    }

    /* default route via the host end of the pair */
    struct rtentry rt;
    memset(&rt, 0, sizeof rt);
    struct sockaddr_in *dst = (struct sockaddr_in *)&rt.rt_dst;
    struct sockaddr_in *gw  = (struct sockaddr_in *)&rt.rt_gateway;
    struct sockaddr_in *msk = (struct sockaddr_in *)&rt.rt_genmask;
    dst->sin_family = AF_INET;
    msk->sin_family = AF_INET;
    gw->sin_family  = AF_INET;
    if (inet_pton(AF_INET, C.veth_gw, &gw->sin_addr) != 1) { warn2("veth gw"); goto out; }
    rt.rt_flags = RTF_UP | RTF_GATEWAY;
    rt.rt_dev   = C.veth_if;
    if (ioctl(s, SIOCADDRT, &rt) < 0) warn2("veth default route");
out:
    close(s);
}

/* ------------------------------------------------------------------ */
/* long-running mode: the jail stays alive, commands stream in over a  */
/* unix socket. Connection fds are passed across the namespace with   */
/* SCM_RIGHTS, so data flows client <-> jailed command directly.      */
/* wire format (little endian):
 *   request:  u32 argc { u32 len, bytes }*argc — then the socket turns
 *             full-duplex: whatever the client writes becomes the
 *             command's stdin, LIVE (SHUT_WR signals EOF)
 *   response: the command's stdout+stderr bytes, then u32 exit status,
 *             then EOF
 */
/* ------------------------------------------------------------------ */

static void put_u32(char *b, uint32_t v)
{
    b[0] = v; b[1] = v >> 8; b[2] = v >> 16; b[3] = v >> 24;
}

static uint32_t get_u32(const char *b)
{
    return (uint8_t)b[0] | ((uint8_t)b[1] << 8) |
           ((uint8_t)b[2] << 16) | ((uint32_t)(uint8_t)b[3] << 24);
}

static int read_full(int fd, void *buf, size_t n)
{
    char *p = buf;
    while (n) {
        ssize_t r = read(fd, p, n);
        if (r <= 0) return -1;
        p += r; n -= r;
    }
    return 0;
}

static int write_full(int fd, const void *buf, size_t n)
{
    const char *p = buf;
    while (n) {
        ssize_t r = write(fd, p, n);
        if (r <= 0) return -1;
        p += r; n -= r;
    }
    return 0;
}

/* the jail side: run one command with its stdio on the client socket.
 * stdin is pumped live: socket bytes go into a pipe, the client's
 * SHUT_WR becomes the child's EOF.  stdout/stderr flow back directly
 * (dup2 onto the socket). */
static void handle_conn(int conn)
{
    enum { MAXARGS = 256 };
    char *argv[MAXARGS + 1] = {0};
    uint32_t argc;

    if (read_full(conn, &argc, 4) || argc == 0 || argc > MAXARGS)
        goto out;

    for (uint32_t i = 0; i < argc; i++) {
        uint32_t len;
        if (read_full(conn, &len, 4) || len == 0 || len > 65536)
            goto out;
        argv[i] = malloc(len + 1);
        if (!argv[i] || read_full(conn, argv[i], len))
            goto out;
        argv[i][len] = 0;
    }

    int inpipe[2] = { -1, -1 };
    if (pipe(inpipe) < 0) goto out;

    pid_t p = fork();
    if (p == 0) {
        dup2(inpipe[0], 0);
        dup2(conn, 1);
        dup2(conn, 2);
        for (int fd = 3; fd < 64; fd++) close(fd);
        execvp(argv[0], argv);
        _exit(127);
    }
    close(inpipe[0]);

    /* pump conn -> pipe until stdin EOF or child exit.  A child that
     * never reads stdin just gets its input discarded — backpressure,
     * never deadlock. */
    int st = 0, stdin_eof = 0;
    for (;;) {
        if (waitpid(p, &st, WNOHANG) == p) break;
        if (stdin_eof) {            /* nothing left to pump; just wait */
            struct timespec ts = { 0, 100 * 1000 * 1000 };
            nanosleep(&ts, NULL);
            continue;
        }
        struct pollfd pf = { .fd = conn, .events = POLLIN };
        if (poll(&pf, 1, 100) < 0) {
            if (errno == EINTR) continue;
            break;
        }
        if (!(pf.revents & POLLIN)) continue;
        char buf[65536];
        ssize_t r = read(conn, buf, sizeof buf);
        if (r <= 0) {                          /* client half-closed */
            stdin_eof = 1;
            close(inpipe[1]); inpipe[1] = -1;  /* child sees EOF */
        } else if (inpipe[1] >= 0 && write_full(inpipe[1], buf, r) < 0) {
            close(inpipe[1]); inpipe[1] = -1;  /* child stopped reading */
        }
    }
    if (inpipe[1] >= 0) close(inpipe[1]);
    waitpid(p, &st, 0);
    uint32_t code = WIFEXITED(st) ? (uint32_t)WEXITSTATUS(st)
                  : WIFSIGNALED(st) ? 128u + (uint32_t)WTERMSIG(st) : 1;
    put_u32((char *)&code, code);
    write_full(conn, &code, 4);

out:
    for (uint32_t i = 0; argv[i]; i++) free(argv[i]);
    close(conn);
}

/* the jail side: receive client fds from the supervisor, forever */
static void jail_server(int fd)
{
    for (;;) {
        char cmd;
        char cbuf[CMSG_SPACE(sizeof(int))];
        struct iovec iov = { .iov_base = &cmd, .iov_len = 1 };
        struct msghdr msg = {0};
        msg.msg_iov = &iov;
        msg.msg_iovlen = 1;
        msg.msg_control = cbuf;
        msg.msg_controllen = sizeof cbuf;

        ssize_t r = recvmsg(fd, &msg, 0);
        if (r <= 0)
            break;                       /* supervisor gone -> die */
        struct cmsghdr *c = CMSG_FIRSTHDR(&msg);
        if (!c || c->cmsg_level != SOL_SOCKET || c->cmsg_type != SCM_RIGHTS)
            continue;
        handle_conn(*(int *)CMSG_DATA(c));
    }
    _exit(0);
}

/* supervisor: hand one client connection into the jail */
static void send_fd(int sock, int fd)
{
    char b = 'E';
    char cbuf[CMSG_SPACE(sizeof(int))];
    struct iovec iov = { .iov_base = &b, .iov_len = 1 };
    struct msghdr msg = {0};
    msg.msg_iov = &iov;
    msg.msg_iovlen = 1;
    msg.msg_control = cbuf;
    msg.msg_controllen = sizeof cbuf;
    struct cmsghdr *c = CMSG_FIRSTHDR(&msg);
    c->cmsg_level = SOL_SOCKET;
    c->cmsg_type = SCM_RIGHTS;
    c->cmsg_len = CMSG_LEN(sizeof(int));
    *(int *)CMSG_DATA(c) = fd;
    sendmsg(sock, &msg, 0);
}

/* supervisor: accept on the host socket until the jail dies */
static volatile sig_atomic_t g_stop;

static void on_stop(int sig) { (void)sig; g_stop = 1; }

static void serve_loop(pid_t jail)
{
    close(g_jail_sock);
    signal(SIGINT, on_stop);
    signal(SIGTERM, on_stop);

    int lfd = socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0);
    struct sockaddr_un a = { .sun_family = AF_UNIX };
    if (C.sock[0]) {
        snprintf(g_sock_path, sizeof g_sock_path, "%s", C.sock);
    } else {
        const char *rt = getenv("XDG_RUNTIME_DIR");
        if (!rt) rt = "/tmp";
        snprintf(g_sock_path, sizeof g_sock_path, "%s/agentcell-%d.sock", rt,
                 (int)jail);
    }
    unlink(g_sock_path);
    snprintf(a.sun_path, sizeof a.sun_path, "%s", g_sock_path);
    socklen_t alen = offsetof(struct sockaddr_un, sun_path) +
                     strlen(a.sun_path) + 1;
    if (bind(lfd, (struct sockaddr *)&a, alen) < 0 ||
        listen(lfd, 16) < 0)
        die("listen socket");
    chmod(g_sock_path, 0600);

    snprintf(g_info_path, sizeof g_info_path, "%s.info", g_sock_path);
    write_info(jail);

    fprintf(stderr, "AGENTCELL_SOCK=%s\n", g_sock_path);
    fprintf(stderr, "sand: serving %s  (jail pid %d, Ctrl-C to stop)\n",
            g_sock_path, jail);

    for (;;) {
        if (g_stop) break;
        struct pollfd pf[2] = {
            { .fd = lfd,         .events = POLLIN },
            { .fd = g_host_sock, .events = POLLIN },
        };
        if (poll(pf, 2, -1) < 0) {
            if (errno == EINTR) continue;
            break;
        }
        /* jail closed its end? */
        if (pf[1].revents) {
            char b;
            if (recv(g_host_sock, &b, 1, MSG_PEEK | MSG_DONTWAIT) <= 0)
                break;
        }
        if (pf[0].revents & POLLIN) {
            int c = accept4(lfd, NULL, NULL, SOCK_CLOEXEC);
            if (c >= 0) {
                send_fd(g_host_sock, c);
                close(c);
                g_execs++;
                write_info(jail);
            }
        }
        int st;
        if (waitpid(jail, &st, WNOHANG) == jail)
            break;
    }

    kill(jail, SIGKILL);
    waitpid(jail, NULL, 0);
    lsm_unregister();
    net_veth_unregister(jail);
    unlink(g_sock_path);
    unlink(g_info_path);
    fprintf(stderr, "sand: jail stopped\n");
}

/* host client: sand exec SOCK [--] CMD ARGS... */
static int client_exec(char **av)
{
    /* av = [SOCK, ("--"), CMD, ARGS...] */
    if (!av[0] || !av[1]) {
        fprintf(stderr, "usage: sand exec SOCK [--] CMD ARGS...\n");
        return 2;
    }
    char *sock = av[0];
    char **args = av + 1;
    if (!strcmp(args[0], "--")) {
        if (!args[1]) { fprintf(stderr, "sand: no command after --\n"); return 2; }
        args++;
    }

    int s = socket(AF_UNIX, SOCK_STREAM, 0);
    struct sockaddr_un a = { .sun_family = AF_UNIX };
    snprintf(a.sun_path, sizeof a.sun_path, "%s", sock);
    if (connect(s, (struct sockaddr *)&a, sizeof a) < 0) {
        fprintf(stderr, "sand: connect %s: %s\n", av[0], strerror(errno));
        return 2;
    }

    /* build request header: argc + args (stdin streams live afterwards) */
    size_t cap = 1 << 16, len = 0;
    char *req = malloc(cap);
    if (!req) return 2;
    uint32_t argc = 0;
    for (char **p = args; *p; p++) argc++;

    #define APPEND(ptr, n) do { \
        if (len + (n) > cap) { \
            while (len + (n) > cap) cap <<= 1; \
            req = realloc(req, cap); \
            if (!req) return 2; \
        } \
        memcpy(req + len, ptr, (n)); len += (n); \
    } while (0)

    char b4[4];
    put_u32(b4, argc);
    APPEND(b4, 4);
    for (char **p = args; *p; p++) {
        put_u32(b4, strlen(*p));
        APPEND(b4, 4);
        APPEND(*p, strlen(*p));
    }

    if (write_full(s, req, len)) { fprintf(stderr, "sand: send failed\n"); return 2; }
    free(req);

    /* full-duplex phase: our stdin -> socket (live; a tty works too),
     * socket -> stdout, LIVE.  The reply's final 4 bytes are the exit
     * status, so printing always holds back a 4-byte tail until EOF.
     * SIGPIPE off: a command that exits early must not kill us. */
    signal(SIGPIPE, SIG_IGN);
    unsigned char pend[4];
    int npend = 0;
    int wr_open = 1;
    for (;;) {
        struct pollfd pf[2] = {
            { .fd = s, .events = POLLIN },                    /* reply   */
            { .fd = 0, .events = wr_open ? POLLIN : 0 },      /* stdin   */
        };
        if (poll(pf, 2, -1) < 0) {
            if (errno == EINTR) continue;
            break;
        }
        if (pf[0].revents & (POLLIN | POLLHUP | POLLERR)) {
            char buf[65536];
            ssize_t r = read(s, buf, sizeof buf);
            if (r <= 0) break;              /* EOF: reply complete */
            /* emit everything except the trailing 4 bytes */
            size_t total = (size_t)npend + (size_t)r;
            size_t emit = total > 4 ? total - 4 : 0;
            size_t from_pend = emit < (size_t)npend ? emit : (size_t)npend;
            if (from_pend) fwrite(pend, 1, from_pend, stdout);
            if (emit > from_pend)
                fwrite(buf, 1, emit - from_pend, stdout);
            fflush(stdout);
            unsigned char np[4] = {0};
            for (size_t i = emit, j = 0; i < total && j < 4; i++, j++)
                np[j] = i < (size_t)npend ? pend[i] : (unsigned char)buf[i - npend];
            memcpy(pend, np, 4);
            npend = (int)(total - emit);
        }
        if (wr_open && (pf[1].revents & (POLLIN | POLLHUP | POLLERR))) {
            char buf[65536];
            ssize_t r = read(0, buf, sizeof buf);
            if (r <= 0 || write_full(s, buf, r) < 0) {
                shutdown(s, SHUT_WR);       /* stdin EOF -> jail */
                wr_open = 0;
            }
        }
    }
    if (npend != 4) { fprintf(stderr, "sand: protocol error\n"); return 2; }
    return (int)get_u32((char *)pend);
}

/* ------------------------------------------------------------------ */
/* agentlsm integration: sand --secure registers this cell's cgroup   */
/* with the root daemon (sudo agentlsm serve) over /run/agentcell/.   */
/* Denials happen in-kernel at the LSM layer; events stream back to   */
/* whoever WATCHes the daemon (sand lsm -f).                          */
/* ------------------------------------------------------------------ */

#define LSM_SOCK "/run/agentcell/lsm.sock"

static int lsm_connect(void)
{
    int s = socket(AF_UNIX, SOCK_STREAM, 0);
    struct sockaddr_un a = { .sun_family = AF_UNIX };
    snprintf(a.sun_path, sizeof a.sun_path, "%s", LSM_SOCK);
    if (connect(s, (struct sockaddr *)&a, sizeof a) < 0) {
        close(s);
        return -1;
    }
    return s;
}

/* send one command line, read the one-line reply ("OK"/"ERR..."/"END")
 * — always read it, even if the caller doesn't care: closing first
 * would turn the daemon's reply write into SIGPIPE/EPIPE */
static int lsm_cmd(const char *cmd, char *rep, size_t repn)
{
    int s = lsm_connect();
    if (s < 0) return -1;
    char line[4200], scratch[64];
    snprintf(line, sizeof line, "%s\n", cmd);
    if (write_full(s, line, strlen(line)) < 0) { close(s); return -1; }
    if (!rep) { rep = scratch; repn = sizeof scratch; }
    ssize_t r = read(s, rep, repn - 1);
    if (r > 0) rep[r] = 0;
    close(s);
    return r > 0 ? 0 : -1;
}

/* arm this cell's policy at the daemon; called after cgroup park */
static void lsm_register(void)
{
    struct stat st;
    if (stat(g_cgpath, &st) < 0) return;
    g_lsm_cgid = (__u64)st.st_ino;

    /* defaults keep secrets of the host out of agent reach; note the
     * prefixes are paths AS SEEN INSIDE the cell (that's what d_path
     * yields for its bind mounts) */
    const char *def[2] = { "/etc/shadow", "/etc/gshadow" };
    int n = C.n_deny ? C.n_deny : 2;

    int s = lsm_connect();
    if (s < 0) {
        fprintf(stderr, "sand: --secure: agentlsm daemon not running "
                        "(sudo agentlsm serve) — LSM enforcement OFF\n");
        return;
    }

    int ok = 0;
    for (int i = 0; i < n; i++) {
        const char *pfx = C.n_deny ? C.deny[i] : def[i];
        char cmd[320], rep[64];
        snprintf(cmd, sizeof cmd, "ADD %llu %s",
                 (unsigned long long)g_lsm_cgid, pfx);
        if (write_full(s, cmd, strlen(cmd)) || write_full(s, "\n", 1) ||
            read(s, rep, sizeof rep - 1) <= 0 || strncmp(rep, "OK", 2))
            { close(s); fprintf(stderr, "sand: agentlsm ADD failed\n"); return; }
        ok++;
    }
    close(s);
    g_lsm_on = 1;
    fprintf(stderr, "sand: LSM armed: %d deny prefix%s via agentlsm "
                    "(cgid %llu)\n", ok, ok == 1 ? "" : "es",
                    (unsigned long long)g_lsm_cgid);
}

static void lsm_unregister(void)
{
    if (!g_lsm_on) return;
    g_lsm_on = 0;
    char cmd[64];
    snprintf(cmd, sizeof cmd, "CLR %llu", (unsigned long long)g_lsm_cgid);
    lsm_cmd(cmd, NULL, 0);
}

/* --egress HOST[:PORT]: append to the veth allowlist.  Port defaults
 * to 443 when omitted.  Returns 0 on success, -1 on invalid/overflow. */
static int egress_add(const char *spec)
{
    if (C.n_egress >= MAX_EGRESS || !*spec) return -1;
    for (const char *q = spec; *q; q++)
        if ((unsigned char)*q <= ' ') return -1;   /* no spaces/controls */
    const char *port = "443";
    size_t hl = strlen(spec);
    const char *c = strrchr(spec, ':');
    if (c && c[1] && strspn(c + 1, "0123456789") == strlen(c + 1)) {
        port = c + 1;
        hl = (size_t)(c - spec);
    }
    if (hl == 0 || hl >= sizeof C.egress_host[0]) return -1;
    if (memchr(spec, ':', hl)) return -1;          /* IPv6 literal: unsupported */
    for (int i = 0; i < C.n_egress; i++)
        if (!strncmp(C.egress_host[i], spec, hl) &&
            !C.egress_host[i][hl] && !strcmp(C.egress_port[i], port))
            return 0;                              /* duplicate: keep going */
    snprintf(C.egress_host[C.n_egress], sizeof C.egress_host[0],
             "%.*s", (int)hl, spec);
    snprintf(C.egress_port[C.n_egress], sizeof C.egress_port[0],
             "%s", port);
    C.n_egress++;
    C.netmode = NET_VETH;    /* egress filtering rides on veth */
    return 0;
}

/* Read a whole regular file into a NUL-terminated malloc buffer. */
static char *slurp(const char *path, size_t *out_len)
{
    int fd = open(path, O_RDONLY | O_CLOEXEC);
    if (fd < 0) return NULL;
    struct stat st;
    if (fstat(fd, &st) < 0 || !S_ISREG(st.st_mode)) { close(fd); return NULL; }
    size_t n = (size_t)st.st_size, off = 0;
    char *buf = malloc(n + 1);
    if (!buf) { close(fd); return NULL; }
    while (off < n) {
        ssize_t r = read(fd, buf + off, n - off);
        if (r <= 0) break;
        off += (size_t)r;
    }
    close(fd);
    buf[off] = 0;
    if (out_len) *out_len = off;
    return buf;
}

static void env_add(const char *kv)
{
    if (C.n_env >= MAX_ENV || !strchr(kv, '=')) return;
    C.env[C.n_env++] = strdup(kv);
}

static int env_file_load(const char *path)
{
    char *buf = slurp(path, NULL);
    if (!buf) return -1;
    char *save = NULL;
    for (char *line = strtok_r(buf, "\n", &save); line;
         line = strtok_r(NULL, "\n", &save)) {
        size_t l = strlen(line);
        while (l && (line[l - 1] == '\r' || line[l - 1] == ' '))
            line[--l] = 0;
        while (*line == ' ') line++;
        if (!*line || *line == '#') continue;
        env_add(line);
    }
    free(buf);
    return 0;
}

/* --secret DST=SRC: SRC must be a host file, DST an in-cell tmpfs path. */
static int secret_add(const char *spec)
{
    if (C.n_secrets >= MAX_SECRET) return -1;
    const char *eq = strchr(spec, '=');
    if (!eq || eq == spec) return -1;
    size_t dl = (size_t)(eq - spec);
    if (dl >= sizeof C.secret_dst[0]) return -1;
    char dst[PATH_MAX];
    memcpy(dst, spec, dl);
    dst[dl] = 0;
    if (strncmp(dst, "/tmp/", 5) && strncmp(dst, "/run/", 5) &&
        strncmp(dst, "/var/tmp/", 9))
        return -1;               /* only tmpfs destinations are allowed */
    size_t len = 0;
    char *data = slurp(eq + 1, &len);
    if (!data) return -1;
    snprintf(C.secret_dst[C.n_secrets], sizeof C.secret_dst[0], "%s", dst);
    C.secret_data[C.n_secrets] = data;
    C.secret_len[C.n_secrets] = len;
    C.n_secrets++;
    return 0;
}

/* Parse `nameserver` lines from a resolv.conf into C.resolv[]. */
static void resolv_add_file(const char *path)
{
    FILE *f = fopen(path, "r");
    if (!f) return;
    char line[256];
    while (fgets(line, sizeof line, f)) {
        char *p = line;
        while (*p == ' ' || *p == '\t') p++;
        if (strncmp(p, "nameserver", 10)) continue;
        p += 10;
        while (*p == ' ' || *p == '\t') p++;
        char *e = p;
        while (*e && !isspace((unsigned char)*e)) e++;
        *e = 0;
        if (!*p) continue;
        int dup = 0;
        for (int i = 0; i < C.n_resolv; i++)
            if (!strcmp(C.resolv[i], p)) { dup = 1; break; }
        if (!dup && C.n_resolv < MAX_RESOLV)
            snprintf(C.resolv[C.n_resolv++], sizeof C.resolv[0], "%s", p);
    }
    fclose(f);
}

/* The cell's DNS source under veth is systemd-resolved's upstream list
 * (do_mounts() binds it over the rootfs resolv.conf); fall back to the
 * rootfs/host file only when that one is absent. */
static void resolv_collect(void)
{
    C.n_resolv = 0;
    resolv_add_file("/run/systemd/resolve/resolv.conf");
    if (C.n_resolv == 0 && C.rootfs[0]) {
        char p[PATH_MAX];
        snprintf(p, sizeof p, "%s/etc/resolv.conf", C.rootfs);
        resolv_add_file(p);
    }
    if (C.n_resolv == 0)
        resolv_add_file("/etc/resolv.conf");
}

/* --net veth: the daemon (root) builds the pair + NAT; we configure
 * our end ourselves once it lands in the cell's netns.  The reply
 * rides the sync pipe: plain "x" means fallback to no network.
 * Returns 0 ok, -1 soft failure (no egress requested), -2 fatal. */
static int net_veth_register(pid_t child)
{
    if (C.n_resolv == 0) resolv_collect();
    char cmd[4096], rep[192] = {0};
    int off = snprintf(cmd, sizeof cmd, "NETUP %d", (int)child);
    for (int i = 0; i < C.n_egress; i++) {
        int w = snprintf(cmd + off, sizeof cmd - (size_t)off,
                         " EGRESS %s %s", C.egress_host[i], C.egress_port[i]);
        if (w < 0 || off + w >= (int)sizeof cmd) {
            fprintf(stderr, "sand: egress list too long for NETUP\n");
            return -1;
        }
        off += w;
    }
    for (int i = 0; i < C.n_resolv; i++) {
        int w = snprintf(cmd + off, sizeof cmd - (size_t)off,
                         " RESOLV %s", C.resolv[i]);
        if (w < 0 || off + w >= (int)sizeof cmd) {
            fprintf(stderr, "sand: resolv list too long for NETUP\n");
            return -1;
        }
        off += w;
    }
    if (lsm_cmd(cmd, rep, sizeof rep) < 0 || strncmp(rep, "OK ", 3) ||
        sscanf(rep + 3, "%63s %63s %63s",
               C.veth_if, C.veth_ip, C.veth_gw) != 3) {
        char reason[96];
        if (rep[0]) {
            int n = (int)strcspn(rep, "\r\n");
            if (n >= (int)sizeof reason) n = (int)sizeof reason - 1;
            memcpy(reason, rep, (size_t)n);
            reason[n] = 0;
        } else {
            snprintf(reason, sizeof reason, "no agentlsm daemon");
        }
        if (C.n_egress > 0) {
            fprintf(stderr, "sand: egress unavailable: %s\n", reason);
            return -2;              /* do not silently drop to --net none */
        }
        fprintf(stderr, "sand: --net veth needs the agentlsm daemon "
                        "(sudo agentlsm serve) — falling back to --net none\n");
        return -1;
    }
    g_veth_on = 1;
    return 0;
}

static void net_veth_unregister(pid_t child)
{
    if (!g_veth_on) return;
    g_veth_on = 0;
    char cmd[64];
    snprintf(cmd, sizeof cmd, "NETDOWN %d", (int)child);
    lsm_cmd(cmd, NULL, 0);
}

/* cgid -> cell-name table built from the *.info sidecars */
struct cellname { __u64 cgid; char name[64]; };

static int build_cell_table(struct cellname *cells, int max)
{
    int ncells = 0;
    const char *rt = getenv("XDG_RUNTIME_DIR");
    if (!rt) rt = "/tmp";
    DIR *d = opendir(rt);
    if (!d) return 0;
    struct dirent *e;
    while ((e = readdir(d)) && ncells < max) {
        size_t nlen = strlen(e->d_name);
        if (nlen < 5 || strcmp(e->d_name + nlen - 5, ".sock") ||
            strncmp(e->d_name, "agentcell-", 10))
            continue;
        char base[PATH_MAX], cg[PATH_MAX] = "", line[256];
        snprintf(base, sizeof base, "%s/%s.info", rt, e->d_name);
        FILE *f = fopen(base, "r");
        if (!f) continue;
        while (fgets(line, sizeof line, f))
            if (!strncmp(line, "cg=", 3)) {
                line[strcspn(line, "\n")] = 0;
                snprintf(cg, sizeof cg, "%s", line + 3);
                break;
            }
        fclose(f);
        struct stat st;
        if (cg[0] && !stat(cg, &st)) {
            cells[ncells].cgid = (__u64)st.st_ino;
            snprintf(cells[ncells].name, 64, "%s", e->d_name);
            ncells++;
        }
    }
    closedir(d);
    return ncells;
}

static const char *cell_of(const struct cellname *cells, int n, __u64 cgid)
{
    for (int i = 0; i < n; i++)
        if (cells[i].cgid == cgid) return cells[i].name;
    return "?";
}

/* resolve a user-supplied cell selector — sock path, sock basename,
 * unique name prefix, or a raw cgid (all digits) — to a cgroup id */
static int resolve_target(const char *sel, const struct cellname *cells,
                          int ncells, __u64 *cgid, char *nameout, size_t nn)
{
    int alldigit = 1;
    for (const char *p = sel; *p; p++)
        if (!isdigit((unsigned char)*p)) { alldigit = 0; break; }
    if (alldigit) {
        *cgid = strtoull(sel, NULL, 10);
        snprintf(nameout, nn, "%s", cell_of(cells, ncells, *cgid));
        return 0;
    }
    const char *base = strrchr(sel, '/');
    base = base ? base + 1 : sel;
    int hit = -1, hits = 0;
    for (int i = 0; i < ncells; i++) {
        if (!strcmp(cells[i].name, base) ||
            !strncmp(cells[i].name, base, strlen(base)))
            { hit = i; hits++; }
    }
    if (hits == 1) {
        *cgid = cells[hit].cgid;
        snprintf(nameout, nn, "%s", cells[hit].name);
        return 0;
    }
    return -1;
}

/* sand lsm deny|allow|reset CELL PREFIX... — hot policy updates for a
 * running cell. "deny" also works on cells started WITHOUT --secure:
 * registering the cgroup id with the daemon is all it takes. */
static int lsm_ctl_cmd(char *sub, char **av)
{
    if (!av[0] || (strcmp(sub, "reset") && !av[1])) {
        fprintf(stderr, "usage: sand lsm %s CELL %s\n", sub,
                !strcmp(sub, "reset") ? "" : "PREFIX...");
        return 2;
    }
    struct cellname cells[MAXBIND];
    int ncells = build_cell_table(cells, MAXBIND);
    __u64 cgid;
    char name[64];
    if (resolve_target(av[0], cells, ncells, &cgid, name, sizeof name) < 0) {
        fprintf(stderr, "sand: cannot resolve cell '%s'", av[0]);
        if (ncells)
            fprintf(stderr, " — running cells:");
        fprintf(stderr, "\n");
        for (int i = 0; i < ncells; i++)
            fprintf(stderr, "  %s\n", cells[i].name);
        return 1;
    }

    char cmd[320], rep[64];
    int rc = 0, n = 0;

    if (!strcmp(sub, "reset")) {
        snprintf(cmd, sizeof cmd, "CLR %llu", (unsigned long long)cgid);
        if (lsm_cmd(cmd, rep, sizeof rep) < 0 || strncmp(rep, "OK", 2)) {
            fprintf(stderr, "sand: agentlsm reset failed%s%s\n",
                    rep[0] ? ": " : "", rep);
            return 1;
        }
        printf("%s reset (all rules) — effective immediately\n", name);
        return 0;
    }

    for (char **p = &av[1]; *p; p++) {
        snprintf(cmd, sizeof cmd, "%s %llu %s",
                 !strcmp(sub, "deny") ? "ADD" : "DEL",
                 (unsigned long long)cgid, *p);
        if (lsm_cmd(cmd, rep, sizeof rep) < 0 || strncmp(rep, "OK", 2)) {
            fprintf(stderr, "sand: agentlsm %s %s failed%s%s\n", sub, *p,
                    rep[0] ? ": " : "", rep);
            rc = 1;
        } else {
            n++;
            printf("%s %s %s — effective immediately\n", name, sub, *p);
        }
    }
    (void)n;
    return rc;
}

/* sand lsm [-f]: enforcement status, and live denial events.
 * cgroup ids are resolved to cell names via the *.info sidecars. */
static int lsm_status(char **av)
{
    setvbuf(stdout, NULL, _IOLBF, 0);   /* live events, flush per line */
    if (av[0] && (!strcmp(av[0], "deny") || !strcmp(av[0], "allow") ||
                  !strcmp(av[0], "reset")))
        return lsm_ctl_cmd(av[0], av + 1);
    int follow = av[0] && (!strcmp(av[0], "-f") || !strcmp(av[0], "--follow"));
    /* optional class filter: sand lsm -f deny,exec,open,net,trip */
    const char *classes = follow && av[1] ? av[1] : NULL;

    struct cellname cells[MAXBIND];
    int ncells = build_cell_table(cells, MAXBIND);

    /* LIST: armed policies */
    int s = lsm_connect();
    if (s < 0) {
        fprintf(stderr, "sand: agentlsm daemon not running "
                        "(start it: sudo agentlsm serve)\n");
        return 1;
    }
    write_full(s, "LIST\n", 5);
    char lrep[320];
    ssize_t r;
    printf("%-10s %-26s %s\n", "CGID", "CELL", "DENY PREFIX");
    while ((r = read(s, lrep, sizeof lrep - 1)) > 0) {
        lrep[r] = 0;
        char *p = lrep, *nl;
        while ((nl = strchr(p, '\n'))) {
            *nl = 0;
            unsigned long long cgid;
            char pfx[256];
            if (!strncmp(p, "END", 3)) goto listed;
            if (sscanf(p, "%llu %255s", &cgid, pfx) == 2)
                printf("%-10llu %-26s %s\n", cgid,
                       cell_of(cells, ncells, cgid), pfx);
            p = nl + 1;
        }
    }
listed:
    if (!follow) { close(s); return 0; }

    /* WATCH: stream cell events (deny + exec/open/net/trip),
     * resolving cgid -> cell name */
    printf("-- following cell events (Ctrl-C to stop) --\n");
    if (classes) {
        char w[300];
        snprintf(w, sizeof w, "WATCH %s\n", classes);
        write_full(s, w, strlen(w));
    } else {
        write_full(s, "WATCH\n", 6);
    }
    for (;;) {
        ssize_t n = read(s, lrep, sizeof lrep - 1);
        if (n <= 0) break;
        lrep[n] = 0;
        char *p = lrep, *nl;
        while ((nl = strchr(p, '\n'))) {
            *nl = 0;
            unsigned long long cgid;
            int off = 0;
            if (sscanf(p, "EV %llu %n", &cgid, &off) == 1 && off)
                printf("%s  %s\n", cell_of(cells, ncells, cgid), p + off);
            p = nl + 1;
        }
    }
    close(s);
    return 0;
}

/* ------------------------------------------------------------------ */
/* child: future PID 1 of the sandbox                                  */
/* ------------------------------------------------------------------ */

static int child_main(void *arg)
{
    (void)arg;

    /* die with the supervisor */
    prctl(PR_SET_PDEATHSIG, SIGKILL, 0, 0, 0);

    if (g_ask_sp[0] >= 0) close(g_ask_sp[0]);   /* supervisor's end */

    /* wait until parent wrote our uid_map / gid_map AND parked us in the
     * sandbox cgroup (must happen while we still share its cgroup view).
     * The sync byte doubles as the veth config channel: "x" alone means
     * no veth (or fallback); "x <if> <ip> <gw>" means configure it. */
    char buf[160];
    ssize_t rn = read(g_sync[0], buf, sizeof(buf) - 1);
    if (rn < 1) _exit(126);
    buf[rn] = 0;
    int have_veth = 0;
    if (C.netmode == NET_VETH)
        have_veth = sscanf(buf + 1, "%63s %63s %63s",
                           C.veth_if, C.veth_ip, C.veth_gw) == 3;

    /* now adopt a private cgroup view rooted at the sandbox cgroup */
    if (unshare(CLONE_NEWCGROUP) < 0) warn2("cgroup namespace");

    do_mounts();

    /* swap roots — the host filesystem disappears entirely */
    if (chdir(g_newroot) < 0) die("chdir newroot");
    if (syscall(SYS_pivot_root, ".", ".put_old") < 0) die("pivot_root");
    if (chdir("/") < 0) die("chdir /");
    umount2("/.put_old", MNT_DETACH);
    rmdir("/.put_old");

    /* root tmpfs itself becomes read-only; submounts keep their own perms */
    if (mount(NULL, "/", NULL, MS_BIND | MS_REMOUNT | MS_RDONLY, NULL) < 0)
        warn2("remount / ro");

    if (!C.no_landlock) landlock_apply();
    if (!C.no_seccomp) {
        int nfd = seccomp_apply();
        if (C.ask) {           /* hand the notify listener to the parent */
            send_fd(g_ask_sp[1], nfd);
            close(nfd);
        }
    }
    if (C.netmode != NET_HOST) {
        net_lo_up();
        if (have_veth) net_veth_up();
    }

    if (chdir("/home/agent") < 0) warn2("chdir workdir");

    clearenv();
    if (g_spawn_envp) {
        for (char **e = g_spawn_envp; *e; e++) putenv(*e);
    } else {
        setenv("HOME",   "/home/agent", 1);
        setenv("PATH",   "/usr/bin:/bin", 1);
        setenv("TMPDIR", "/tmp", 1);
        setenv("SHELL",  "/bin/bash", 1);
        setenv("LANG",   "C.UTF-8", 1);
        setenv("TERM",   "xterm-256color", 1);
    }
    if (C.n_egress == 1) {
        char p[192];
        snprintf(p, sizeof p, "http://%s:%s",
                 C.egress_host[0], C.egress_port[0]);
        setenv("http_proxy",  p, 1);
        setenv("https_proxy", p, 1);
        setenv("all_proxy",   p, 1);
        setenv("no_proxy", "localhost,127.0.0.1", 1);
    }
    /* --env / --env-file override the defaults and any spawn envp */
    for (int i = 0; i < C.n_env; i++) {
        char *eq = strchr(C.env[i], '=');
        if (!eq) continue;
        *eq = 0;
        setenv(C.env[i], eq + 1, 1);
        *eq = '=';
    }

    if (g_spawn_fds[0] >= 0) {      /* FFI spawn: caller's stdio */
        dup2(g_spawn_fds[0], 0);
        dup2(g_spawn_fds[1], 1);
        dup2(g_spawn_fds[2], 2);
    }

    if (g_serve) {
        close(g_host_sock);
        jail_server(g_jail_sock);      /* never returns */
    }

    char *def[] = { "/bin/bash", NULL };
    char **av = C.argv ? (char **)C.argv : def;
    execvp(av[0], av);
    die("execvp");
    return 1;
}

/* ------------------------------------------------------------------ */
/* parent: clone + write uid maps + cgroup + wait                      */
/* ------------------------------------------------------------------ */

static long parse_mem(const char *s)
{
    char *end;
    long v = strtol(s, &end, 10);
    if (end == s) die("bad --mem value");
    switch (*end) {
    case 'G': case 'g': v <<= 30; break;
    case 'M': case 'm': v <<= 20; break;
    case 'K': case 'k': v <<= 10; break;
    case '\0': break;
    default: die("bad --mem suffix");
    }
    return v;
}

static void write_uid_maps(pid_t pid)
{
    char path[128], buf[128];
    int fd;

    snprintf(path, sizeof path, "/proc/%d/setgroups", pid);
    fd = open(path, O_WRONLY);
    if (fd >= 0) { if (write(fd, "deny", 4) < 0) warn2("setgroups"); close(fd); }

    snprintf(path, sizeof path, "/proc/%d/uid_map", pid);
    snprintf(buf, sizeof buf, "0 %d 1\n", g_uid);
    fd = open(path, O_WRONLY);
    if (fd < 0) die("open uid_map");
    if (write(fd, buf, strlen(buf)) < 0) die("write uid_map");
    close(fd);

    snprintf(path, sizeof path, "/proc/%d/gid_map", pid);
    snprintf(buf, sizeof buf, "0 %d 1\n", g_gid);
    fd = open(path, O_WRONLY);
    if (fd < 0) die("open gid_map");
    if (write(fd, buf, strlen(buf)) < 0) die("write gid_map");
    close(fd);
}

static void usage(FILE *out)
{
    fprintf(out,
"usage: sand [options] -- CMD [ARGS...]\n"
"\n"
"options:\n"
"  --mem SIZE    memory.max  (512M, 2G, bytes; default 2G)\n"
"  --cpu N       cpu.max quota in cores (0.5, 2; default 2)\n"
"  --pids N      pids.max    (default 256)\n"
"  --net MODE    none | host | veth (default none — loopback only;\n"
"                veth = real networking with NAT, needs agentlsm daemon)\n"
"  --egress H[:P] outbound allowlist via --net veth (repeatable): DNS\n"
"                plus every H (all A records) and port P (default 443)\n"
"                passes; everything else DROPped at the host firewall.\n"
"                One entry also sets http_proxy/https_proxy inside the cell\n"
"  --env K=V     set an env var in the cell (repeatable).  NOT for\n"
"                secrets: argv is visible to other host users\n"
"  --env-file F  load K=V lines from F (use a 0600 file) into the cell env\n"
"  --secret DST=SRC  copy host file SRC into the cell at DST (0600), which\n"
"                must be under /tmp, /run or /var/tmp — RAM only\n"
"  --workdir-size SIZE  RAM-backed workspace (tmpfs) of SIZE instead of\n"
"                the rw bind: a hard cap that cannot fill the node disk\n"
"  --rootfs DIR  OS view from DIR instead of the host /usr /etc /opt\n"
"                (pack with os/cell-root/build.sh; directory, not an image)\n"
"  --workdir DIR writable workspace (default ~/agent-work)\n"
"  --ro DIR      extra read-only bind (repeatable, lands in /mnt/NAME)\n"
"  --rw DIR      extra read-write bind (repeatable, lands in /mnt/NAME)\n"
"  --overlay DIR copy-on-write view of DIR at /mnt/NAME: reads see the\n"
"                host, writes land in a throwaway tmpfs (repeatable)\n"
"  --bind S:D    mount host path S at path D inside the sandbox (rw)\n"
"  --bind-ro S:D same, but read-only\n"
"  --timeout S   kill payload after S seconds\n"
"  --secure      arm kernel LSM policy via the agentlsm daemon\n"
"                (deny /etc/shadow & /etc/gshadow by default)\n"
"  --deny PREFIX extra LSM deny prefix (repeatable, implies --secure;\n"
"                paths as seen INSIDE the sandbox, e.g. /mnt/NAME)\n"
"  --no-landlock | --no-seccomp   debug switches\n"
"  --capabilities print feature flags (egress_multi, egress_refresh,\n"
"                egress_resolv, env_file, secret, workdir_size) and exit\n"
"  --io-rbps SIZE  io.max read bytes/s on the workspace device\n"
"  --io-wbps SIZE  io.max write bytes/s (e.g. 8M; throttles disk writes)\n"
"  --ask         park denied syscalls and ask the supervisor on /dev/tty\n"
"                (y=allow once, n=deny, a=always, k=kill; one-shot only)\n"
"                (y=allow once, n=deny, a=always, k=kill; one-shot only)\n"
"\n"
"long-running mode (isolation set up once, then reused):\n"
"  --sock PATH  serve: listen on PATH instead of XDG_RUNTIME_DIR/agentcell-<pid>.sock\n"
"  sand serve [options]       start a jailed exec server; prints AGENTCELL_SOCK=\n"
"  sand exec SOCK [--] CMD..  run CMD inside that jail\n"
"  sand cells | sand top      list running cells / live view\n"
"  sand lsm [-f [classes]]    LSM policies; -f: live event stream from\n"
"                            the daemon (deny,exec,open,net,trip; default all)\n"
"  sand lsm deny CELL PREFIX..  hot-add deny rule to a RUNNING cell\n"
"  sand lsm allow CELL PREFIX..  hot-remove; reset CELL: drop all rules\n");
}

int main(int argc, char **argv)
{
    g_uid = getuid();
    g_gid = getgid();

    /* subcommands */
    if (argc > 1 && !strcmp(argv[1], "exec"))
        return client_exec(argv + 2);
    if (argc > 1 && !strcmp(argv[1], "cells"))
        return list_cells();
    if (argc > 1 && !strcmp(argv[1], "top"))
        return top_cells(argv[2]);
    if (argc > 1 && !strcmp(argv[1], "lsm"))
        return lsm_status(argv + 2);
    if (argc > 1 && !strcmp(argv[1], "serve")) {
        g_serve = 1;
        argv++;
        argc--;
    }

    /* default memory limit = 60% of RAM (avoids reclaim storms; --mem wins) */
    {
        FILE *f = fopen("/proc/meminfo", "r");
        char k[64]; long v;
        while (f && fscanf(f, "%63s %ld kB", k, &v) == 2)
            if (!strcmp(k, "MemTotal:")) {
                C.mem_bytes = (long)((double)v * 1024 * 0.6);
                break;
            }
        if (f) fclose(f);
    }

    static struct option opts[] = {
        {"mem",         required_argument, 0, 'm'},
        {"cpu",         required_argument, 0, 'c'},
        {"pids",        required_argument, 0, 'P'},
        {"net",         required_argument, 0, 'n'},
        {"rootfs",      required_argument, 0, 1002},
        {"sock",        required_argument, 0, 1004},
        {"workdir",     required_argument, 0, 'w'},
        {"ro",          required_argument, 0, 'r'},
        {"rw",          required_argument, 0, 'W'},
        {"overlay",     required_argument, 0, 'O'},
        {"bind",        required_argument, 0, 'b'},
        {"bind-ro",     required_argument, 0, 'B'},
        {"timeout",     required_argument, 0, 't'},
        {"overlay",     required_argument, 0, 'O'},
        {"io-rbps",     required_argument, 0, 1000},
        {"io-wbps",     required_argument, 0, 1001},
        {"egress",      required_argument, 0, 1003},
        {"env",         required_argument, 0, 1005},
        {"env-file",    required_argument, 0, 1006},
        {"secret",      required_argument, 0, 1007},
        {"workdir-size",required_argument, 0, 1008},
        {"capabilities",no_argument,      0, 1009},
        {"ask",         no_argument, &C.ask, 1},
        {"secure",      no_argument, &C.secure, 1},
        {"deny",        required_argument, 0, 'd'},
        {"no-landlock", no_argument, &C.no_landlock, 1},
        {"no-seccomp",  no_argument, &C.no_seccomp, 1},
        {"help",        no_argument, 0, 'h'},
        {0, 0, 0, 0},
    };
    int o;
    while ((o = getopt_long(argc, argv, "+", opts, 0)) != -1) {
        switch (o) {
        case 'm': C.mem_bytes = parse_mem(optarg); break;
        case 'c': {
            double q = atof(optarg);
            if (q <= 0)
                snprintf(C.cpu_max, sizeof C.cpu_max, "max 100000");
            else
                snprintf(C.cpu_max, sizeof C.cpu_max, "%ld 100000",
                         (long)(q * 100000));
            break;
        }
        case 'P': C.pids = atoi(optarg); break;
        case 'n':
            if (!strcmp(optarg, "host")) C.netmode = NET_HOST;
            else if (!strcmp(optarg, "veth")) C.netmode = NET_VETH;
            else if (strcmp(optarg, "none")) { usage(stderr); return 2; }
            break;
        case 'w':
            if (!realpath(optarg, C.workdir)) die(optarg);
            break;
        case 'r': if (C.n_ro < MAXBIND) C.ro[C.n_ro++] = optarg; break;
        case 'W': if (C.n_rw < MAXBIND) C.rw[C.n_rw++] = optarg; break;
        case 'O': if (C.n_ov < MAXBIND) C.ov[C.n_ov++] = optarg; break;
        case 'b': case 'B': {
            if (C.n_binds >= MAXBIND) break;
            char *colon = strchr(optarg, ':');
            if (!colon || colon == optarg || colon[1] != '/') {
                fprintf(stderr, "sand: --bind needs SRC:DST (DST absolute)\n");
                return 2;
            }
            *colon = 0;
            struct bind *b = &C.binds[C.n_binds];
            if (!realpath(optarg, b->src)) die(optarg);
            snprintf(b->dst, sizeof b->dst, "%s", colon + 1);
            for (char *e = b->dst + strlen(b->dst) - 1;
                 e > b->dst && *e == '/'; e--) *e = 0;
            b->ro = (o == 'B');
            C.n_binds++;
            break;
        }
        case 't': C.timeout = atoi(optarg); break;
        case 1000: C.io_rbps = parse_mem(optarg); break;
        case 1001: C.io_wbps = parse_mem(optarg); break;
        case 1002:
            if (!realpath(optarg, C.rootfs)) die(optarg);
            break;
        case 1004:
            if (optarg[0] == '/') {
                snprintf(C.sock, sizeof C.sock, "%s", optarg);
            } else {
                char cwd[PATH_MAX];
                if (!getcwd(cwd, sizeof cwd)) die("getcwd");
                snprintf(C.sock, sizeof C.sock, "%s/%s", cwd, optarg);
            }
            break;
        case 1003:
            if (egress_add(optarg)) {
                fprintf(stderr, "sand: bad or too many --egress "
                                "(want HOST[:PORT], max %d)\n", MAX_EGRESS);
                return 2;
            }
            break;
        case 1005: env_add(optarg); break;
        case 1006:
            if (env_file_load(optarg)) die(optarg);
            break;
        case 1007:
            if (secret_add(optarg)) {
                fprintf(stderr, "sand: --secret wants DST=SRC with DST "
                                "under /tmp, /run or /var/tmp\n");
                return 2;
            }
            break;
        case 1008: C.workdir_size = parse_mem(optarg); break;
        case 1009:
            printf("egress_multi=1 egress_refresh=1 egress_resolv=1 "
                   "env=1 env_file=1 secret=1 workdir_size=1\n");
            return 0;
        case 'd':
            if (C.n_deny < MAXBIND) {
                snprintf(C.deny[C.n_deny], 256, "%s", optarg);
                C.n_deny++;
            }
            C.secure = 1;               /* --deny implies --secure */
            break;
        case 'h': usage(stdout); return 0;
        case 0: break;
        default: usage(stderr); return 2;
        }
    }
    if (g_serve && C.ask) {
        fprintf(stderr, "sand: --ask is one-shot only "
                        "(serve mode unsupported)\n");
        return 2;
    }
    if (C.ask && C.no_seccomp) {
        fprintf(stderr, "sand: --ask needs the seccomp filter; "
                        "ignoring --ask\n");
        C.ask = 0;
    }
    if (C.rootfs[0]) {
        struct stat st;
        if (stat(C.rootfs, &st) < 0 || !S_ISDIR(st.st_mode)) {
            fprintf(stderr, "sand: --rootfs must be a directory "
                            "(mount squashfs/erofs, then pass the mountpoint)\n");
            return 2;
        }
    }
    if (optind < argc) C.argv = (char *const *)&argv[optind];

    /* default workspace */
    if (!C.workdir[0]) {
        char def[PATH_MAX];
        snprintf(def, sizeof def, "%s/agent-work", getenv("HOME") ?: "/tmp");
        mmkdir_p(def, 0755);
        if (!realpath(def, C.workdir)) die(def);
    }

    /* resolve extra binds to absolute paths now (host paths vanish later) */
    for (int i = 0; i < C.n_ro; i++) {
        char *r = realpath(C.ro[i], NULL);
        if (!r) die(C.ro[i]);
        C.ro[i] = r;
    }
    for (int i = 0; i < C.n_rw; i++) {
        char *r = realpath(C.rw[i], NULL);
        if (!r) die(C.rw[i]);
        C.rw[i] = r;
    }
    for (int i = 0; i < C.n_ov; i++) {
        char *r = realpath(C.ov[i], NULL);
        if (!r) die(C.ov[i]);
        C.ov[i] = r;
    }

    if (!mkdtemp(g_newroot)) die("mkdtemp");

    cgroup_setup();

    if (pipe(g_sync) < 0) die("pipe");

    if (g_serve) {
        int sp[2];
        if (socketpair(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0, sp) < 0)
            die("socketpair");
        g_host_sock = sp[0];
        g_jail_sock = sp[1];
    }

    /* --ask: the child passes its seccomp notify listener through here */
    if (C.ask && socketpair(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0,
                            g_ask_sp) < 0)
        die("socketpair");

    const int ns = CLONE_NEWUSER | CLONE_NEWNS | CLONE_NEWPID | CLONE_NEWIPC |
                   CLONE_NEWUTS |
                   (C.netmode != NET_HOST ? CLONE_NEWNET : 0);

    const size_t SZ = 1 << 20;
    char *stack = malloc(SZ);
    if (!stack) die("malloc");

    pid_t pid = clone(child_main, stack + SZ, ns | SIGCHLD, NULL);
    if (pid < 0) die("clone (userns disabled? sysctl kernel.unprivileged_userns_clone)");

    close(g_sync[0]);
    if (g_ask_sp[1] >= 0) close(g_ask_sp[1]);    /* child's end */

    /* give the child its identity: uid 0 inside == uid 1000 outside */
    write_uid_maps(pid);

    /* park the whole payload in its own cgroup — must happen while the
     * child still shares our cgroup view, before it unshares its own   */
    if (g_have_cg) {
        char p[PATH_MAX], v[32];
        snprintf(p, sizeof p, "%s/cgroup.procs", g_cgpath);
        snprintf(v, sizeof v, "%d", pid);
        write_file(p, v);
        fprintf(stderr, "sand: pid %d  cgroup %s\n", pid, g_cgpath);
    }

    if (C.secure && g_have_cg)
        lsm_register();

    /* --net veth: the daemon moves one end of a fresh pair into the
     * child's netns (created by clone, child still waits on the pipe);
     * config travels to the child in the sync message itself */
    if (C.netmode == NET_VETH) {
        int vr = net_veth_register(pid);
        if (vr == -2) {
            /* egress was requested but could not be provisioned: fail loud
             * instead of handing back a cell with no network */
            kill(pid, SIGKILL);
            waitpid(pid, NULL, 0);
            if (C.secure && g_have_cg) lsm_unregister();
            if (g_have_cg) rmdir(g_cgpath);
            _exit(127);
        }
    }

    char syncmsg[160] = "x";
    if (g_veth_on)
        snprintf(syncmsg, sizeof syncmsg, "x %s %s %s",
                 C.veth_if, C.veth_ip, C.veth_gw);
    if (write(g_sync[1], syncmsg, strlen(syncmsg)) < 0) warn2("sync child");

    /* the child installs the filter after its mounts, then hands us the
     * notify listener; parked syscalls queue in-kernel, so no race */
    if (C.ask) {
        denylist_build();       /* sc_name() in the prompt needs it */
        g_ask_fd = recv_fd(g_ask_sp[0]);
        if (g_ask_fd < 0) warn2("recv notify listener (--ask inactive)");
        close(g_ask_sp[0]);
    }

    if (g_serve)
        serve_loop(pid);         /* reaps the jail, cleans socket+cgroup */

    /* survive terminal Ctrl-C so we can reap the child and clean up */
    signal(SIGINT,  SIG_IGN);
    signal(SIGTERM, SIG_IGN);

    int status = 0;
    if (g_ask_fd >= 0) {
        /* --ask: delegated syscalls park until we answer; poll the
         * listener while the payload lives (200ms tick for --timeout) */
        time_t t0 = time(NULL);
        for (;;) {
            struct pollfd pf = { .fd = g_ask_fd, .events = POLLIN };
            if (poll(&pf, 1, 200) > 0 && (pf.revents & POLLIN))
                ask_handle(g_ask_fd, pid);
            if (waitpid(pid, &status, WNOHANG) == pid)
                break;
            if (C.timeout > 0 && time(NULL) - t0 >= C.timeout) {
                kill(pid, SIGKILL);
                waitpid(pid, &status, 0);
                break;
            }
        }
        close(g_ask_fd);
    } else if (C.timeout > 0) {
        int left = C.timeout;
        while (waitpid(pid, &status, WNOHANG) == 0) {
            if (left-- <= 0) { kill(pid, SIGKILL); break; }
            sleep(1);
        }
        waitpid(pid, &status, 0);
    } else {
        waitpid(pid, &status, 0);
    }

    if (g_have_cg) rmdir(g_cgpath);
    lsm_unregister();
    net_veth_unregister(pid);
    rmdir(g_newroot);

    if (WIFEXITED(status))
        fprintf(stderr, "sand: exited %d\n", WEXITSTATUS(status));
    else if (WIFSIGNALED(status))
        fprintf(stderr, "sand: killed by signal %d\n", WTERMSIG(status));
    return WIFEXITED(status) ? WEXITSTATUS(status) : 128 + WTERMSIG(status);
}