syd 3.52.0

rock-solid application kernel
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
//
// Syd: rock-solid application kernel
// src/namespace.rs: Namespace utilities
//
// Copyright (c) 2026 Ali Polatel <alip@chesswob.org>
//
// SPDX-License-Identifier: GPL-3.0

//! Set of functions to manage namespaces

use std::{
    borrow::Cow,
    env,
    ffi::{CStr, OsStr},
    net::{IpAddr, SocketAddrV4, SocketAddrV6},
    os::{
        fd::{AsFd, AsRawFd},
        unix::{ffi::OsStrExt, net::UnixStream, process::CommandExt},
    },
    process::{Command, Stdio},
};

use libc::setdomainname;
use memchr::arch::all::is_equal;
use nix::{
    errno::Errno,
    fcntl::{AtFlags, OFlag, AT_FDCWD},
    mount::{umount2, MntFlags, MsFlags},
    sys::{
        signal::Signal,
        socket::{bind, socket, SockFlag, SockaddrIn, SockaddrIn6},
        stat::{mkdirat, mknodat, umask, Mode, SFlag},
    },
    time::{clock_gettime, ClockId},
    unistd::{chdir, fchdir, linkat, pivot_root, sethostname, setsid, symlinkat, Gid, Pid, Uid},
    NixPath,
};

use crate::{
    caps::{securebits::set_keepcaps, CapSet},
    compat::{
        openat2, set_name, set_no_new_privs, set_pdeathsig, try_from_bytes, ResolveFlag, SockType,
    },
    config::{HAVE_NAMESPACED_PID_MAX, LANDLOCK_ABI, NPROC},
    confine::{confine_landlock_scope, safe_drop_caps},
    err::{err2no, SydResult},
    error,
    fd::{is_dev_null, pidfd_open, send_with_fd, set_cloexec, SafeOwnedFd, AT_BADFD},
    info,
    landlock::{AccessFs, AccessNet},
    log_enabled,
    lookup::{file_type, safe_mkdir_all, safe_open_how},
    mount::{
        api::MountAttrFlags,
        util::{mount_bind, mount_fs, set_root_mount_propagation},
    },
    path::{XPath, XPathBuf},
    proc::{proc_map_user, proc_pid_max, proc_set_time},
    retry::retry_on_eintr,
    sandbox::MountOp,
    syslog::LogLevel,
    warn,
};

/// Set up user namespace.
pub fn ns_setup_user<Fd: AsFd>(fd_proc: Fd, uid: Uid, gid: Gid, map_root: bool) -> SydResult<()> {
    // Write uid/gid map for user namespace.
    proc_map_user(fd_proc, uid, gid, map_root).inspect_err(|errno| {
        error!("ctx": "setup_user_namespace", "op": "map_user",
            "uid": uid.as_raw(), "gid": gid.as_raw(),
            "map_root": map_root, "err": *errno as i32,
            "msg": format!("set up uid/gid mapping for user namespace failed: {errno}"),
            "tip": "configure your system to allow user namespaces");
    })?;

    // Set inheritable mask and ambient caps to retain caps after execve(2).
    set_keepcaps(true)?;
    let permitted_caps = crate::caps::read(None, CapSet::Permitted)?;
    crate::caps::set(None, CapSet::Inheritable, permitted_caps)?;
    // Set the same capabilities as ambient, if necessary.
    for flag in permitted_caps {
        let cap = flag.try_into()?;
        crate::caps::raise(None, CapSet::Ambient, cap)?;
    }

    Ok(())
}

/// Set time offsets in new time namespace.
pub fn ns_setup_time<Fd: AsFd>(
    fd_proc: Fd,
    boottime: Option<i64>,
    monotime: Option<i64>,
) -> SydResult<()> {
    let boffset = if let Some(boffset) = boottime {
        boffset
    } else {
        let btime = clock_gettime(ClockId::CLOCK_BOOTTIME)?;
        // Into is necessary on 32-bit.
        #[expect(clippy::useless_conversion)]
        btime.tv_sec().checked_neg().ok_or(Errno::EOVERFLOW)?.into()
    };
    let moffset = if let Some(moffset) = monotime {
        moffset
    } else {
        let mtime = clock_gettime(ClockId::CLOCK_MONOTONIC)?;
        // Into is necessary on 32-bit.
        #[expect(clippy::useless_conversion)]
        mtime.tv_sec().checked_neg().ok_or(Errno::EOVERFLOW)?.into()
    };

    if boffset != 0 || moffset != 0 {
        proc_set_time(fd_proc, boffset, moffset).inspect_err(|errno| {
            error!("ctx": "setup_time_namespace", "op": "set_boot_time",
                "err": *errno as i32,
                "msg": format!("set boot time in time namespace failed: {errno}"),
                "tip": "configure your system to allow unprivileged user namespaces");
        })?;
        info!("ctx": "setup_time_namespace", "op": "set_boot_time",
            "timens_offsets": [moffset, boffset],
            "msg": "set boot time in time namespace");
    }

    Ok(())
}

/// Set host/domain name in UTS namespace.
pub fn ns_setup_uts(hostname: Option<&CStr>, domainname: Option<&CStr>) -> SydResult<()> {
    if let Some(domainname) = domainname {
        let domainsize = domainname.to_bytes().len(); // without NUL.
        let domainname = domainname.as_ptr().cast();

        // SAFETY: No setdomainname(2) wrapper in nix yet.
        Errno::result(unsafe { setdomainname(domainname, domainsize) }).inspect_err(|errno| {
            error!("ctx": "setup_uts_namespace", "op": "set_domain_name",
                "msg": format!("set NIS/YP domain name failed: {errno}"),
                "tip": "configure `uts/domain:none'",
                "err": *errno as i32);
        })?;
    }

    if let Some(hostname) = hostname.as_ref() {
        let hostname = OsStr::from_bytes(hostname.to_bytes());
        sethostname(hostname).inspect_err(|errno| {
            error!("ctx": "setup_uts_namespace", "op": "set_host_name",
                "msg": format!("set host name failed: {errno}"),
                "tip": "configure `uts/host:none'",
                "err": *errno as i32);
        })?;
    }

    Ok(())
}

/// Set up pid namespace.
pub fn ns_setup_pid<Fd: AsFd>(fd_proc: Fd, pid_max: u64) -> SydResult<()> {
    // Set namespaced kernel.pid_max sysctl:
    // 1. The kernel reserves 300 pids via RESERVED_PIDS in kernel/pid.c
    // 2. Kernel adapts reserved pids based on number of CPUs on the system.
    // 3. We cannot do this after private procfs mount due to subset=pid.
    if !*HAVE_NAMESPACED_PID_MAX {
        return Ok(());
    }

    const PIDS_PER_CPU_MIN: u64 = 8;
    const RESERVED_PIDS: u64 = if cfg!(target_arch = "s390x") {
        // TODO: Figure out where this limit on s390x comes from and document.
        512
    } else {
        301
    };

    #[expect(clippy::arithmetic_side_effects)]
    let pid_max = pid_max
        .max(RESERVED_PIDS)
        .max(PIDS_PER_CPU_MIN * (*NPROC as u64));

    proc_pid_max(fd_proc, pid_max)?;
    info!("ctx": "setup_pid_namespace", "op": "set_pid_max", "max": pid_max,
        "msg": format!("set namespaced kernel.pid_max sysctl to {pid_max}"));

    Ok(())
}

/// Set up mount namespace after fork.
///
/// This function is not thread-safe due to use of umask(2).
pub fn ns_setup_mnt(
    root: Option<&XPath>,
    mnt_ops: Option<&[MountOp]>,
    workdir: Option<&XPath>,
    restrict_proc_files: bool,
) -> Result<(), Errno> {
    let mymask = umask(Mode::S_IRWXG | Mode::S_IRWXO);
    let result = do_setup_mnt(root, mnt_ops, workdir, restrict_proc_files);
    umask(mymask);
    result
}

#[expect(clippy::cognitive_complexity)]
fn do_setup_mnt(
    root: Option<&XPath>,
    mnt_ops: Option<&[MountOp]>,
    workdir: Option<&XPath>,
    restrict_proc_files: bool,
) -> Result<(), Errno> {
    let how = safe_open_how(OFlag::O_PATH | OFlag::O_NOFOLLOW, ResolveFlag::empty())
        // Drop RESOLVE_BENEATH which we cannot use here.
        .resolve(ResolveFlag::RESOLVE_NO_MAGICLINKS | ResolveFlag::RESOLVE_NO_SYMLINKS);
    let how_dir =
        how.flags(OFlag::O_CLOEXEC | OFlag::O_PATH | OFlag::O_NOFOLLOW | OFlag::O_DIRECTORY);
    let how_xdev = safe_open_how(
        OFlag::O_PATH | OFlag::O_NOFOLLOW,
        ResolveFlag::RESOLVE_NO_XDEV,
    );
    let how_xdev_dir =
        how_xdev.flags(OFlag::O_CLOEXEC | OFlag::O_PATH | OFlag::O_NOFOLLOW | OFlag::O_DIRECTORY);
    let how_xdev_new = how_xdev
        .flags(OFlag::O_CLOEXEC | OFlag::O_RDONLY | OFlag::O_CREAT | OFlag::O_EXCL)
        .mode(Mode::S_IRUSR);

    // Set root mount propagation to private recursively.
    set_root_mount_propagation(MsFlags::MS_PRIVATE)?;

    let (root_fd, root_is_tmpfs) = if let Some(root) = root {
        let root_tmp = if root.is_equal(b"ramfs") {
            Some("ramfs")
        } else if root.is_equal(b"tmpfs") {
            Some("tmpfs")
        } else {
            None
        };
        let root = if root_tmp.is_some() {
            // Use proc_pid_fdinfo(5) as private root directory.
            // This avoids the need for a temporary directory.
            // Syd requires proc(5) so this isn't an added dependency.
            let mut pfd = XPathBuf::from("/proc");
            pfd.push_pid(Pid::this());
            pfd.push(b"fdinfo");
            Cow::Owned(pfd)
        } else {
            // Use specified new-root directory.
            Cow::Borrowed(root)
        };

        #[expect(clippy::disallowed_methods)]
        let mut fd = retry_on_eintr(|| openat2(AT_BADFD, root.as_ref(), how_dir))?;

        #[expect(clippy::disallowed_methods)]
        if let Some(root_tmp) = root_tmp {
            // Mount tmpfs over root filesystem with default options.
            // This also ensures rootfs is a mountpoint which is required
            // by pivot_root(2).
            mount_fs(
                OsStr::new(root_tmp),
                fd,
                MountAttrFlags::MOUNT_ATTR_NOSUID
                    | MountAttrFlags::MOUNT_ATTR_NODEV
                    | MountAttrFlags::MOUNT_ATTR_NOEXEC
                    | MountAttrFlags::MOUNT_ATTR_NOATIME
                    | MountAttrFlags::MOUNT_ATTR_NOSYMFOLLOW,
                Some("mode=700"),
            )?;

            // Reopen rootfd after rootfs mount.
            fd = retry_on_eintr(|| openat2(AT_BADFD, root.as_ref(), how_dir))?;

            // Ensure safe CWD.
            // This is important because we may recursively
            // create directories later on in this directory.
            // This point is too early for safe_chdir,
            // here we run without confinement.
            retry_on_eintr(|| fchdir(&fd))?;

            // Create /dev and /proc directories.
            retry_on_eintr(|| mkdirat(&fd, "dev", Mode::S_IRWXU))?;
            retry_on_eintr(|| mkdirat(&fd, "proc", Mode::S_IRWXU))?;
        } else {
            // Make new root directory a mountpoint with a self-bind.
            // This is required by pivot_root(2).
            mount_bind(&fd, &fd, MountAttrFlags::empty())?;

            // Reopen rootfd after rootfs mount.
            drop(fd);
            fd = retry_on_eintr(|| openat2(AT_BADFD, root.as_ref(), how_dir))?;

            // Mount /dev tmpfs with default options.
            // Do it early here so the user can populate it.
            #[expect(clippy::disallowed_methods)]
            let fd = retry_on_eintr(|| openat2(&fd, "dev", how_dir))?;

            mount_fs(
                OsStr::new("tmpfs"),
                fd,
                MountAttrFlags::MOUNT_ATTR_NOSUID
                    | MountAttrFlags::MOUNT_ATTR_NOEXEC
                    | MountAttrFlags::MOUNT_ATTR_NOATIME
                    | MountAttrFlags::MOUNT_ATTR_NOSYMFOLLOW,
                Some("mode=700"),
            )?;
        }

        (Some(fd), root_tmp.is_some())
    } else {
        (None, false)
    };

    // Process mount operations as necessary.
    if let Some(mnt_ops) = mnt_ops {
        for mnt_op in mnt_ops {
            match mnt_op {
                MountOp::Bind { .. } => ns_setup_bind(mnt_op, root_fd.as_ref(), root_is_tmpfs)?,
                MountOp::Link { sym: false, .. } if root_is_tmpfs => {
                    // root_is_tmpfs=true asserts root_fd is Some.
                    #[expect(clippy::disallowed_methods)]
                    ns_setup_link(mnt_op, root_fd.as_ref().unwrap())?
                }
                MountOp::Link { sym: true, .. } if root_is_tmpfs => {
                    // root_is_tmpfs=true asserts root_fd is Some.
                    #[expect(clippy::disallowed_methods)]
                    ns_setup_symlink(mnt_op, root_fd.as_ref().unwrap())?
                }
                MountOp::MakeNod { .. } if root_is_tmpfs => {
                    // root_is_tmpfs=true asserts root_fd is Some.
                    #[expect(clippy::disallowed_methods)]
                    ns_setup_mknod(mnt_op, root_fd.as_ref().unwrap())?
                }
                MountOp::Link { sym: false, .. } => {
                    warn!("ctx": "setup_mount_namespace", "op": "make_link",
                        "mnt": mnt_op, "err": Errno::EOPNOTSUPP as i32,
                        "msg": format!("skip create link `{mnt_op}' due to root isn't tmpfs"));
                }
                MountOp::Link { sym: true, .. } => {
                    warn!("ctx": "setup_mount_namespace", "op": "make_symlink",
                        "mnt": mnt_op, "err": Errno::EOPNOTSUPP as i32,
                        "msg": format!("skip create symlink `{mnt_op}' due to root isn't tmpfs"));
                }
                MountOp::MakeNod { .. } => {
                    warn!("ctx": "setup_mount_namespace", "op": "make_node",
                        "mnt": mnt_op, "err": Errno::EOPNOTSUPP as i32,
                        "msg": format!("skip create node `{mnt_op}' due to root isn't tmpfs"));
                }
            }
        }
    }

    // Unshare/Mount implies Unshare/PID.
    //
    // Mount private procfs.
    //
    // The target directory may be under the chroot directory.
    // Use hidepid=2 to hide pid=1.
    // As of version 3.37.2 we use hidepid=4 which is Linux>=5.8.
    // As of version 3.39.0 we use subset=pid which is Linux>=5.8.
    //
    // Private proc(5) is mounted _after_ custom bind mounts
    // to ensure they cannot interfere with this mount.
    #[expect(clippy::disallowed_methods)]
    let proc_fd = if let Some(ref root_fd) = root_fd {
        retry_on_eintr(|| openat2(root_fd, "proc", how_xdev_dir))
    } else {
        retry_on_eintr(|| openat2(AT_BADFD, "/proc", how_dir))
    }?;

    let flags = MountAttrFlags::MOUNT_ATTR_NOSUID
        | MountAttrFlags::MOUNT_ATTR_NOEXEC
        | MountAttrFlags::MOUNT_ATTR_NODEV;
    let mut opts = "hidepid=4".to_string();
    if restrict_proc_files {
        opts.push_str(",subset=pid");
    }
    mount_fs(OsStr::new("proc"), proc_fd, flags, Some(opts.as_str()))?;
    if log_enabled!(LogLevel::Info) {
        let mnt = MountOp::Bind {
            src: "proc".into(),
            dst: "/proc".into(),
            opt: flags,
            dat: Some(opts),
            r#try: false,
        };
        info!("ctx": "setup_mount_namespace", "op": "mount_procfs", "mnt": &mnt,
            "msg": format!("mounted procfs `{mnt}'"));
    }

    if let Some(ref root_fd) = root_fd {
        // Provide /dev/null which is required by Syd.
        #[expect(clippy::disallowed_methods)]
        let src_fd = retry_on_eintr(|| openat2(AT_BADFD, "/dev/null", how))?;

        // Validate what we've opened is indeed `/dev/null`.
        if !is_dev_null(&src_fd).unwrap_or(false) {
            let errno = Errno::ENODEV;
            error!("ctx": "setup_mount_namespace", "op": "null_mount", "err": errno as i32,
                "msg": format!("/dev/null is not a character device"));
            return Err(errno);
        }

        #[expect(clippy::disallowed_methods)]
        let dev_fd = retry_on_eintr(|| {
            openat2(
                root_fd,
                "dev",
                if root_is_tmpfs { how_xdev_dir } else { how_dir },
            )
        })?;

        #[expect(clippy::disallowed_methods)]
        let dst_fd = retry_on_eintr(|| openat2(&dev_fd, "null", how_xdev_new))?;

        // Perform recursive bind mount.
        mount_bind(src_fd, dst_fd, MountAttrFlags::empty())?;

        // Provide symbolic links for standard file descriptors.
        //
        // Note, these symbolic links are user-owned so the sandbox
        // process may remove them. Since these symbolic links are
        // only for convenience, we do not check for errors.
        //
        // /dev/stdin
        let _ = retry_on_eintr(|| symlinkat("/proc/thread-self/fd/0", &dev_fd, "stdin"));
        // /dev/stdout
        let _ = retry_on_eintr(|| symlinkat("/proc/thread-self/fd/1", &dev_fd, "stdout"));
        // /dev/stderr
        let _ = retry_on_eintr(|| symlinkat("/proc/thread-self/fd/2", &dev_fd, "stderr"));
        drop(dev_fd);

        // All set, change root directory.
        // Move old mount over itself.
        // This point is too early for safe_chdir,
        // here we run without confinement.
        retry_on_eintr(|| fchdir(root_fd))?;
        retry_on_eintr(|| pivot_root(".", "."))?;

        // Unmount old root directory.
        retry_on_eintr(|| umount2(".", MntFlags::MNT_DETACH))?;

        // Ensure CWD equals root.
        retry_on_eintr(|| chdir("/"))?;

        // Handle custom working directory without symlinks.
        if let Some(workdir) = workdir {
            #[expect(clippy::disallowed_methods)]
            retry_on_eintr(|| openat2(AT_BADFD, workdir, how_dir))
                .and_then(|fd| retry_on_eintr(|| fchdir(&fd)))?;
        }
    }

    Ok(())
}

// Set up a single bind mount or special-fs mount operation.
//
// Panics if `bind_op` is not `MountOp::Bind`.
#[expect(clippy::cognitive_complexity)]
fn ns_setup_bind(
    bind_op: &MountOp,
    root_fd: Option<&SafeOwnedFd>,
    root_is_tmpfs: bool,
) -> Result<(), Errno> {
    let how = safe_open_how(OFlag::O_PATH | OFlag::O_NOFOLLOW, ResolveFlag::empty())
        // Drop RESOLVE_BENEATH which we cannot use here.
        .resolve(ResolveFlag::RESOLVE_NO_MAGICLINKS | ResolveFlag::RESOLVE_NO_SYMLINKS);
    let how_dir =
        how.flags(OFlag::O_CLOEXEC | OFlag::O_PATH | OFlag::O_NOFOLLOW | OFlag::O_DIRECTORY);
    let how_xdev = safe_open_how(
        OFlag::O_PATH | OFlag::O_NOFOLLOW,
        ResolveFlag::RESOLVE_NO_XDEV,
    );
    let how_xdev_dir =
        how_xdev.flags(OFlag::O_CLOEXEC | OFlag::O_PATH | OFlag::O_NOFOLLOW | OFlag::O_DIRECTORY);

    let (src, dst, opt, dat, r#try) = if let MountOp::Bind {
        src,
        dst,
        opt,
        dat,
        r#try,
    } = bind_op
    {
        (src, dst, opt, dat, r#try)
    } else {
        panic!("ns_setup_bind without MountOp::Bind")
    };

    // Ensure root cannot be mounted over.
    if root_fd.is_some() && dst.is_root() {
        let errno = Errno::EINVAL;
        error!("ctx": "setup_mount_namespace", "op": "spec_mount",
            "mnt": bind_op, "err": errno as i32,
            "msg": format!("mount over rootfs is not permitted: {errno}"));
        return Err(errno);
    }

    // Validate src/dst:
    //
    // 1. Deny if dst is not absolute or any ".." in src/dst
    if dst.is_relative() || src.has_parent_dot() || dst.has_parent_dot() {
        return Err(Errno::EINVAL);
    }
    // 2. Deny if src is `proc` or `/proc/*`, mounting alternative
    //    proc(5) can be used to circumvent path sandboxing.
    if src.is_equal(b"proc") || src.is_procfs() || src.is_proc() {
        return Err(Errno::EPERM);
    }

    if src.is_relative() {
        let dst_fd = if let Some(root_fd) = root_fd {
            // Turn `dst` into relative path.
            let mut dst = dst.clone();
            dst.clean_consecutive_slashes();
            dst.remove(0); // Remove leading "/".
            if !dst.is_relative() {
                return Err(Errno::EINVAL);
            }

            if root_is_tmpfs && !dst.is_empty() {
                // Create directories recursively under temporary root:
                // 1. `dst` is relative.
                // 2. `dst` has no `..` components.
                // 3. Uses fd-based mkdirat+O_NOFOLLOW to prevent symlink attacks.
                safe_mkdir_all(root_fd, &dst)
            } else {
                #[expect(clippy::disallowed_methods)]
                retry_on_eintr(|| openat2(root_fd, &dst, how_xdev_dir))
            }
        } else {
            #[expect(clippy::disallowed_methods)]
            retry_on_eintr(|| openat2(AT_BADFD, dst, how_dir))
        }?;

        match mount_fs(src.as_os_str(), dst_fd, *opt, dat.as_deref()) {
            Ok(_) => {
                info!("ctx": "setup_mount_namespace", "op": "spec_mount", "mnt": bind_op,
                    "msg": format!("mounted special-fs `{bind_op}'"));
            }
            Err(errno) => {
                error!("ctx": "setup_mount_namespace", "op": "spec_mount",
                    "mnt": bind_op, "err": errno as i32,
                    "msg": format!("mount special-fs `{bind_op}' failed: {errno}"));
                return Err(errno);
            }
        }
    } else {
        #[expect(clippy::disallowed_methods)]
        let src_fd = match retry_on_eintr(|| openat2(AT_BADFD, src, how)) {
            Ok(fd) => fd,
            Err(Errno::ENOENT) if *r#try => {
                warn!("ctx": "setup_mount_namespace", "op": "bind_mount",
                    "mnt": bind_op, "err": Errno::ENOENT as i32,
                    "msg": format!("skip non-existent file `{bind_op}' due to bind-try"));
                return Ok(());
            }
            Err(errno) => return Err(errno),
        };
        let is_dir = file_type(&src_fd, None, false)?.is_dir();

        let dst_fd = if let Some(root_fd) = root_fd {
            // Turn `dst` into relative path.
            let mut dst = dst.clone();
            dst.clean_consecutive_slashes();
            dst.remove(0); // Remove leading "/".
            if !dst.is_relative() {
                return Err(Errno::EINVAL);
            }
            let empty = dst.is_empty();

            // Create file or directory under temporary root.
            if root_is_tmpfs && !empty {
                if is_dir {
                    // Create all directories (including target) safely:
                    // 1. `dst` is relative.
                    // 2. `dst` has no `..` components.
                    // 3. Uses fd-based mkdirat+O_NOFOLLOW per component.
                    safe_mkdir_all(root_fd, &dst).map(drop)?;
                } else {
                    // Create parent directories safely, then create the
                    // file target using the parent fd to avoid
                    // multi-component paths in mknodat(2).
                    let (parent, base) = dst.split();
                    if base.is_empty() || base.is_root() {
                        // No parent: Use root_fd directly.
                        retry_on_eintr(|| mknodat(root_fd, base, SFlag::S_IFREG, Mode::S_IRUSR, 0))
                    } else {
                        safe_mkdir_all(root_fd, parent).and_then(|fd| {
                            retry_on_eintr(|| mknodat(&fd, base, SFlag::S_IFREG, Mode::S_IRUSR, 0))
                        })
                    }?;
                }
            }

            // Ensure we open current directory for `/`.
            if dst.is_empty() {
                dst.append_byte(b'.');
            }

            #[expect(clippy::disallowed_methods)]
            retry_on_eintr(|| openat2(root_fd, &dst, if is_dir { how_xdev_dir } else { how_xdev }))
        } else {
            #[expect(clippy::disallowed_methods)]
            retry_on_eintr(|| openat2(AT_BADFD, dst, if is_dir { how_dir } else { how }))
        }?;

        // Perform recursive bind mount.
        match mount_bind(src_fd, dst_fd, *opt) {
            Ok(_) => {
                info!("ctx": "setup_mount_namespace", "op": "bind_mount", "mnt": bind_op,
                    "msg": format!("bind mounted `{bind_op}'"));
            }
            Err(errno) => {
                error!("ctx": "setup_mount_namespace", "op": "bind_mount",
                    "mnt": bind_op, "err": errno as i32,
                    "msg": format!("bind mount `{bind_op}' failed: {errno}"));
                return Err(errno);
            }
        }
    }

    Ok(())
}

// Set up a single hardlink mount operation.
//
// Panics if `link_op` is not `MountOp::Link`.
#[expect(clippy::cognitive_complexity)]
fn ns_setup_link(link_op: &MountOp, root_fd: &SafeOwnedFd) -> Result<(), Errno> {
    let how = safe_open_how(
        OFlag::O_PATH | OFlag::O_NOFOLLOW,
        ResolveFlag::RESOLVE_NO_XDEV,
    );

    let (dst, mut src, sym, r#try) = if let MountOp::Link {
        dst,
        src,
        sym,
        r#try,
    } = link_op
    {
        (dst, src.clone(), *sym, *r#try)
    } else {
        panic!("ns_setup_link without MountOp::Link")
    };
    assert!(!sym, "ns_setup_link with symbolic link");

    // Reject relative paths and paths with `..` component.
    if src.is_relative() || src.has_parent_dot() {
        return Err(Errno::EINVAL);
    }
    if dst.is_relative() || dst.has_parent_dot() {
        return Err(Errno::EINVAL);
    }

    // Turn src into relative path.
    src.clean_consecutive_slashes();
    src.remove(0); // Remove leading "/".
    if !src.is_relative() {
        return Err(Errno::EINVAL);
    }

    // Open src safely.
    #[expect(clippy::disallowed_methods)]
    let src_fd = retry_on_eintr(|| openat2(root_fd, &src, how))?;

    // linkat(2) needs proc(5) indirection for direct-fd access
    // without AT_EMPTY_PATH and CAP_DAC_READ_SEARCH.
    let mut src = XPathBuf::from("/proc/thread-self/fd");
    src.push_fd(src_fd.as_raw_fd());

    // Split dst into parent and base.
    let (parent, base) = dst.split();
    if base.is_dot() {
        return Err(Errno::EINVAL);
    }

    // Open parent safely and create link.
    // linkat(2) doesn't follow symlinks in dst base.
    let result = if base.is_empty() || base.is_root() {
        if r#try {
            Ok(())
        } else {
            Err(Errno::EEXIST)
        }
    } else if parent.is_empty() || parent.is_root() {
        retry_on_eintr(|| linkat(AT_FDCWD, &src, root_fd, base, AtFlags::AT_SYMLINK_FOLLOW))
    } else {
        // Turn parent into relative path.
        let mut parent = parent.to_owned();
        parent.clean_consecutive_slashes();
        parent.remove(0); // Remove leading "/".
        if !parent.is_relative() {
            return Err(Errno::EINVAL);
        }

        // Create parent directories safely, then create the file target
        // using the parent fd to avoid multi-component paths in linkat(2).
        let parent_fd = safe_mkdir_all(root_fd, &parent)?;
        retry_on_eintr(|| linkat(AT_FDCWD, &src, &parent_fd, base, AtFlags::AT_SYMLINK_FOLLOW))
    };

    match result {
        Ok(_) => {
            info!("ctx": "setup_mount_namespace", "op": "make_link", "mnt": link_op,
                "msg": format!("created link `{link_op}'"));
            Ok(())
        }
        Err(Errno::EEXIST) if r#try => {
            warn!("ctx": "setup_mount_namespace", "op": "make_link",
                "mnt": link_op, "err": Errno::EEXIST as i32,
                "msg": format!("skip existing link `{link_op}' due to try"));
            Ok(())
        }
        Err(errno) => {
            error!("ctx": "setup_mount_namespace", "op": "make_link",
                "mnt": link_op, "err": errno as i32,
                "msg": format!("create link `{link_op}' failed: {errno}"));
            Err(errno)
        }
    }
}

// Set up a single symlink mount operation.
//
// Panics if `link_op` is not `MountOp::Link`.
#[expect(clippy::cognitive_complexity)]
fn ns_setup_symlink(link_op: &MountOp, root_fd: &SafeOwnedFd) -> Result<(), Errno> {
    let (dst, src, sym, r#try) = if let MountOp::Link {
        dst,
        src,
        sym,
        r#try,
    } = link_op
    {
        (dst, src, *sym, *r#try)
    } else {
        panic!("ns_setup_link without MountOp::Link")
    };
    assert!(sym, "ns_setup_link with hard link");

    // Reject relative dst paths and paths with `..` component.
    // Reject src paths with `..` component.
    // Relative src paths are OK.
    if dst.is_relative() || dst.has_parent_dot() {
        return Err(Errno::EINVAL);
    }
    if src.has_parent_dot() {
        return Err(Errno::EINVAL);
    }

    // Split dst into parent and base.
    let (parent, base) = dst.split();
    if base.is_dot() {
        return Err(Errno::EINVAL);
    }

    // Open parent safely and create symlink.
    // symlinkat(2) doesn't follow symlinks in base.
    let result = if base.is_empty() || base.is_root() {
        if r#try {
            Ok(())
        } else {
            Err(Errno::EEXIST)
        }
    } else if parent.is_empty() || parent.is_root() {
        retry_on_eintr(|| symlinkat(src, root_fd, base))
    } else {
        // Turn parent into relative path.
        let mut parent = parent.to_owned();
        parent.clean_consecutive_slashes();
        parent.remove(0); // Remove leading "/".
        if !parent.is_relative() {
            return Err(Errno::EINVAL);
        }

        // Create parent directories safely, then create the file target
        // using the parent fd to avoid multi-component paths in symlinkat(2).
        let parent_fd = safe_mkdir_all(root_fd, &parent)?;
        retry_on_eintr(|| symlinkat(src, &parent_fd, base))
    };

    match result {
        Ok(_) => {
            info!("ctx": "setup_mount_namespace", "op": "make_symlink", "mnt": link_op,
                "msg": format!("created symlink `{link_op}'"));
            Ok(())
        }
        Err(Errno::EEXIST) if r#try => {
            warn!("ctx": "setup_mount_namespace", "op": "make_symlink",
                "mnt": link_op, "err": Errno::EEXIST as i32,
                "msg": format!("skip existing symlink `{link_op}' due to try"));
            Ok(())
        }
        Err(errno) => {
            error!("ctx": "setup_mount_namespace", "op": "make_symlink",
                "mnt": link_op, "err": errno as i32,
                "msg": format!("create symlink `{link_op}' failed: {errno}"));
            Err(errno)
        }
    }
}

// Set up a single mkdir, mkfifo, or mkfile mount operation.
//
// Panics if `file_op` is not `MountOp::MakeNod`.
#[expect(clippy::cognitive_complexity)]
fn ns_setup_mknod(file_op: &MountOp, root_fd: &SafeOwnedFd) -> Result<(), Errno> {
    let (kind, path, mut mode, r#try) = if let MountOp::MakeNod {
        kind,
        path,
        mode,
        r#try,
    } = file_op
    {
        (*kind, path, *mode, *r#try)
    } else {
        panic!("ns_setup_mknod without MountOp::MakeNod")
    };

    // Strip unsafe mode.
    // This is the second layer with umask(2).
    mode.remove(Mode::S_IRWXG | Mode::S_IRWXO | Mode::S_ISUID | Mode::S_ISGID);

    // Reject invalid kind.
    if !matches!(kind, SFlag::S_IFREG | SFlag::S_IFDIR | SFlag::S_IFIFO) {
        return Err(Errno::EINVAL);
    }

    // Reject relative paths and paths with `..` component.
    if path.is_relative() || path.has_parent_dot() {
        return Err(Errno::EINVAL);
    }

    // Split path into parent and base.
    let (parent, base) = path.split();
    if base.is_dot() {
        return Err(Errno::EINVAL);
    }

    // Open parent safely and create node.
    // mkdirat(2) and mknodat(2) don't follow symlinks in base.
    let result = if base.is_empty() || base.is_root() {
        if r#try {
            Ok(())
        } else {
            Err(Errno::EEXIST)
        }
    } else if parent.is_empty() || parent.is_root() {
        match kind {
            SFlag::S_IFREG | SFlag::S_IFIFO => {
                retry_on_eintr(|| mknodat(root_fd, base, kind, mode, 0))
            }
            SFlag::S_IFDIR => retry_on_eintr(|| mkdirat(root_fd, base, mode)),
            _ => return Err(Errno::EINVAL),
        }
    } else {
        // Turn parent into relative path.
        let mut parent = parent.to_owned();
        parent.clean_consecutive_slashes();
        parent.remove(0); // Remove leading "/".
        if !parent.is_relative() {
            return Err(Errno::EINVAL);
        }

        // Create parent directories safely, then create the file target
        // using the parent fd to avoid multi-component paths in
        // mkdirat(2) and mknodat(2).
        let parent_fd = safe_mkdir_all(root_fd, &parent)?;
        match kind {
            SFlag::S_IFREG | SFlag::S_IFIFO => {
                retry_on_eintr(|| mknodat(&parent_fd, base, kind, mode, 0))
            }
            SFlag::S_IFDIR => retry_on_eintr(|| mkdirat(&parent_fd, base, mode)),
            _ => return Err(Errno::EINVAL),
        }
    };

    match result {
        Ok(_) => {
            info!("ctx": "setup_mount_namespace", "op": "make_node", "mnt": file_op,
                "msg": format!("created node `{file_op}'"));
            Ok(())
        }
        Err(Errno::EEXIST) if r#try => {
            warn!("ctx": "setup_mount_namespace", "op": "make_node",
                "mnt": file_op, "err": Errno::EEXIST as i32,
                "msg": format!("skip existing node `{file_op}' due to try"));
            Ok(())
        }
        Err(errno) => {
            error!("ctx": "setup_mount_namespace", "op": "make_node",
                "mnt": file_op, "err": errno as i32,
                "msg": format!("create node `{file_op}' failed: {errno}"));
            Err(errno)
        }
    }
}

/// Set up network namespace.
#[expect(clippy::cognitive_complexity)]
pub fn ns_setup_net<Fd: AsFd>(
    proxy: Option<Fd>,
    proxy_addr: IpAddr,
    proxy_port: u16,
    proxy_debug: bool,
) -> SydResult<()> {
    // Bring up loopback device for net namespace.
    let loindex = loopback_setup().inspect_err(|errno| {
        error!("ctx": "setup_network_namespace", "op": "setup_loopback",
            "err": *errno as i32,
            "msg": format!("set up loopback network device failed: {errno}"),
            "tip": "configure your system to allow network namespaces");
    })?;

    if proxy_debug {
        warn!("ctx": "setup_network_namespace", "op": "setup_loopback",
            "idx": loindex,
            "msg": format!("loopback network device is up with index:{loindex:#x}"));
    } else {
        info!("ctx": "setup_network_namespace", "op": "setup_loopback",
            "idx": loindex,
            "msg": format!("loopback network device is up with index:{loindex:#x}"));
    }

    // Handle proxy sandboxing as necessary.
    let stream_child = if let Some(stream_child) = proxy {
        stream_child
    } else {
        return Ok(());
    };

    let ipv = if proxy_addr.is_ipv6() { 6 } else { 4 };
    let fml = if ipv == 6 {
        nix::sys::socket::AddressFamily::Inet6
    } else {
        nix::sys::socket::AddressFamily::Inet
    };
    let lfd = socket(
        fml,
        SockType::Stream.try_into()?,
        SockFlag::SOCK_NONBLOCK | SockFlag::SOCK_CLOEXEC,
        None,
    )?;

    match proxy_addr {
        IpAddr::V4(addr_v4) => {
            let sockaddr = SockaddrIn::from(SocketAddrV4::new(addr_v4, proxy_port));
            bind(lfd.as_raw_fd(), &sockaddr)
        }
        IpAddr::V6(addr_v6) => {
            let sockaddr = SockaddrIn6::from(SocketAddrV6::new(addr_v6, proxy_port, 0, 0));
            bind(lfd.as_raw_fd(), &sockaddr)
        }
    }
    .inspect_err(|errno| {
        error!("ctx": "setup_network_namespace", "op": "bind_proxy",
            "msg": format!("bind proxy to IPv{ipv} {proxy_addr}!{proxy_port} failed: {errno}"),
            "err": *errno as i32);
    })?;

    if proxy_debug {
        warn!("ctx": "setup_network_namespace", "op": "bind_proxy",
            "msg": format!("proxy is now listening incoming IPv{ipv} requests from {proxy_addr}!{proxy_port}"));
    } else {
        info!("ctx": "setup_network_namespace", "op": "bind_proxy",
            "msg": format!("proxy is now listening incoming IPv{ipv} requests from {proxy_addr}!{proxy_port}"));
    }

    let lfd = lfd.as_raw_fd();
    send_with_fd(&stream_child, &[0u8; 1], &[lfd]).inspect_err(|errno| {
        error!("ctx": "setup_network_namespace", "op": "send_proxy_fd",
            "fd": lfd, "err": *errno as i32,
            "msg": format!("send proxy file descriptor {lfd} to syd-tor failed: {errno}"));
    })?;

    if proxy_debug {
        warn!("ctx": "setup_network_namespace", "op": "send_proxy_fd", "fd": lfd,
            "msg": format!("sent proxy fd {lfd} to syd-tor, IPv{ipv} traffic forwarding is now started \\o/"));
        warn!("ctx": "setup_network_namespace", "op": "send_proxy_fd", "syd": "ping",
            "msg": "Change return success. Going and coming without error.");
    } else {
        info!("ctx": "setup_network_namespace", "op": "send_proxy_fd", "fd": lfd,
            "msg": format!("sent proxy fd {lfd} to syd-tor, IPv{ipv} traffic forwarding is now started \\o/"));
        info!("ctx": "setup_network_namespace", "op": "send_proxy_fd", "syd": "ping",
            "msg": "Change return success. Going and coming without error.");
    }

    Ok(())
}

/// Set up syd-tor for Proxy sanboxing.
pub fn ns_setup_tor(
    proxy_ext_addr: IpAddr,
    proxy_ext_port: u16,
    proxy_ext_unix: Option<&XPath>,
    proxy_repr: &str,
    proxy_debug: bool,
) -> SydResult<SafeOwnedFd> {
    // TIP to be used in logging.
    const TIP: &str = "set sandbox/proxy:off";

    // Create a PIDFd of this process.
    // PIDFD_NONBLOCK is equivalent to O_NONBLOCK,
    // we use the latter because bionic libc doesn't define former yet.
    #[expect(clippy::cast_sign_loss)]
    let pidfd = pidfd_open(Pid::this(), OFlag::O_NONBLOCK.bits() as u32).inspect_err(|errno| {
        error!("ctx": "setup_tor", "op": "pidfd_open",
                "msg": format!("syd-tor pidfd_open error: {errno}"),
                "tip": TIP, "err": *errno as i32);
    })?;

    // Create a UNIX socket pair.
    let (stream_parent, stream_child) = UnixStream::pair().inspect_err(|error| {
        error!("ctx": "setup_tor", "op": "socketpair",
                "msg": format!("syd-tor socketpair error: {error}"),
                "tip": TIP, "err": err2no(error) as i32);
    })?;

    // Unset the CLOEXEC flags on the file descriptors.
    // PIDFds and Rust sockets are automatically CLOEXEC.
    set_cloexec(&pidfd, false)?;
    set_cloexec(&stream_parent, false)?;

    // Prepare environment of the syd-tor process.
    // Filter the environment variables to only include the list below:
    // 1. LD_LIBRARY_PATH
    // 2. SYD_TOR_RULES
    // We do not need to pass SYD_TOR_DEBUG because we use -d as needed.
    let safe_env: &[&[u8]] = &[b"LD_LIBRARY_PATH", b"SYD_TOR_RULES"];

    // Spawn syd-tor process outside the namespace, pass one end of the socket-pair to it.
    // ns_init_tor sets process name which syd(1) recognizes.
    let mut cmd = Command::new("/proc/self/exe");
    cmd.arg0("syd-tor");
    cmd.stdin(Stdio::inherit());
    cmd.stdout(Stdio::inherit());
    cmd.env_clear();
    cmd.envs(
        env::vars_os().filter(|(key, _)| safe_env.iter().any(|env| is_equal(key.as_bytes(), env))),
    );
    if proxy_debug {
        cmd.arg("-d");
        cmd.stderr(Stdio::inherit());
    } else {
        cmd.stderr(Stdio::null());
    }
    let mut buf = itoa::Buffer::new();
    cmd.arg("-p");
    cmd.arg(buf.format(pidfd.as_raw_fd()));
    cmd.arg("-i");
    cmd.arg(buf.format(stream_parent.as_raw_fd()));
    // proxy/ext/unix has precedence over proxy/ext/host.
    if let Some(ref proxy_ext_unix) = proxy_ext_unix {
        cmd.arg("-u");
        cmd.arg(proxy_ext_unix);
    } else {
        cmd.arg("-o");
        cmd.arg(format!("{proxy_ext_addr}:{proxy_ext_port}"));
    }
    // SAFETY: See documentation in ns_init_tor.
    unsafe { cmd.pre_exec(|| Ok(ns_init_tor()?)) };
    let syd_tor = cmd.spawn().inspect_err(|error| {
        let errno = err2no(error);
        error!("ctx": "setup_tor", "op": "spawn",
            "msg": format!("syd-tor spawn error: {error}"),
            "tip": TIP, "err": errno as i32);
    })?;
    drop(pidfd);
    // SAFETY: Save syd-tor PID for signal protections.
    let mut buf = itoa::Buffer::new();
    env::set_var("SYD_PID_TOR", buf.format(syd_tor.id()));
    if proxy_debug {
        warn!("ctx": "setup_tor", "op": "forward_net",
            "msg": format!("syd-tor is now forwarding external traffic to {proxy_repr}"));
    } else {
        info!("ctx": "setup_tor", "op": "forward_net",
            "msg": format!("syd-tor is now forwarding external traffic to {proxy_repr}"));
    }

    // Pass the other end of the socket-pair to the new namespace.
    Ok(stream_child.into())
}

// Initialize Proxy sandboxing.
//
// This runs early in fork process before syd-tor(1) is spawned.
// Confinement happens in two-stages:
// 1. in Command::pre_exec before syd-tor(1) is spawned.
// 2. syd-tor(1) confining itself before main loop.
//
// This confinement is somewhat repetitive, however it reduces the blast
// radius when Syd is misguided into executing a malicious syd-tor(1)
// binary.
fn ns_init_tor() -> SydResult<()> {
    // 0. Set name for easier identification.
    // 1. Set parent death signal to SIGKILL.
    // 2. Drop all Linux capabilities(7).
    // 3. Set non-new-privs attribute.
    // 4. Create a new session.
    // 5. Confine landlock-scope on Linux>=6.12.
    // 6. Set umask(2) to a sane value.
    let _ = set_name(c"syd-tor");
    set_pdeathsig(Some(Signal::SIGKILL))?;
    safe_drop_caps()?;
    set_no_new_privs()?;
    setsid()?;
    confine_landlock_scope(
        None::<SafeOwnedFd>, /* unused */
        AccessFs::from_write(*LANDLOCK_ABI),
        AccessNet::BindTcp,
        true, /* scoped_abs */
    )?;
    umask(Mode::from_bits_truncate(0o777));
    Ok(())
}

#[expect(clippy::unnecessary_cast)]
const SIOCGIFINDEX: u64 = libc::SIOCGIFINDEX as u64;
#[expect(clippy::unnecessary_cast)]
const SIOCGIFFLAGS: u64 = libc::SIOCGIFFLAGS as u64;
#[expect(clippy::unnecessary_cast)]
const SIOCSIFFLAGS: u64 = libc::SIOCSIFFLAGS as u64;

/// Functionally equivalent to "ifconfig lo up".
///
/// Returns loopback interface index.
pub fn loopback_setup() -> Result<i32, Errno> {
    // Create a socket
    let sock = socket(
        nix::sys::socket::AddressFamily::Inet,
        SockType::Stream.try_into()?,
        SockFlag::empty(),
        None,
    )?;

    // Prepare the interface request
    let mut ifreq = libc::ifreq {
        #[expect(clippy::cast_possible_wrap)]
        ifr_name: [
            b'l' as libc::c_char,
            b'o' as libc::c_char,
            0,
            0,
            0,
            0,
            0,
            0,
            0,
            0,
            0,
            0,
            0,
            0,
            0,
            0,
        ],
        // SAFETY: Manually initialize ifr_ifru.
        ifr_ifru: unsafe { std::mem::zeroed() },
    };

    // SAFETY: Request loopback network device index.
    let loindex: i32 = unsafe {
        let mut ifr_index: libc::ifreq = std::mem::zeroed();
        ifr_index.ifr_name = ifreq.ifr_name;
        Errno::result(libc::syscall(
            libc::SYS_ioctl,
            sock.as_raw_fd(),
            SIOCGIFINDEX as libc::c_ulong,
            &mut ifr_index,
        ))?;
        // HACK: ifr_ifru is a union but libc crate does not define ifru_ivalue,
        // which is a libc::c_int, so here we refer to it with ifru_mtu which
        // is the same type.
        ifr_index.ifr_ifru.ifru_mtu
    };

    // Set BIGTCP to LOOPBACK_BIGTCP_MAX if available.
    // Note, we _must_ do this before setting up the network device.
    use crate::config::LOOPBACK_BIGTCP_MAX;
    match loopback_set_bigtcp(loindex, LOOPBACK_BIGTCP_MAX) {
        Ok(_) => {
            info!("ctx": "setup_network_namespace", "op": "set_bigtcp_loopback",
                "msg": "loopback network device has BIGTCP set",
                "max": LOOPBACK_BIGTCP_MAX);
        }
        Err(errno) => {
            info!("ctx": "setup_network_namespace", "op": "set_bigtcp_loopback",
                "msg": format!("set BIGTCP for loopback network device error: {errno}"),
                "err": errno as i32);
        }
    };

    // SAFETY: Get the current flags.
    Errno::result(unsafe {
        libc::syscall(
            libc::SYS_ioctl,
            sock.as_raw_fd(),
            SIOCGIFFLAGS as libc::c_ulong,
            &mut ifreq,
        )
    })?;

    // Modify the flags to bring up the interface.
    //
    // SAFETY: We're accessing the field of a union here.
    #[expect(clippy::cast_possible_truncation)]
    unsafe {
        ifreq.ifr_ifru.ifru_flags |= (libc::IFF_UP | libc::IFF_RUNNING) as libc::c_short
    };

    // SAFETY: Set the new flags.
    Errno::result(unsafe {
        libc::syscall(
            libc::SYS_ioctl,
            sock.as_raw_fd(),
            SIOCSIFFLAGS as libc::c_ulong,
            &mut ifreq,
        )
    })?;

    Ok(loindex)
}

// libc crate does not define struct nl from linux/rtnetlink.h.
#[repr(C)]
#[derive(Debug, Clone, Copy)]
struct nlattr {
    nla_len: u16,
    nla_type: u16,
}

// libc crate does not define struct nlmsg from linux/rtnetlink.h.
#[repr(C)]
#[derive(Debug, Clone, Copy)]
struct nlmsg {
    hdr: libc::nlmsghdr,
    info: ifinfomsg,
    attrs: [u8; 64],
}

// libc crate does not define struct ifinfomsg from linux/rtnetlink.h yet.
#[repr(C)]
#[derive(Debug, Copy, Clone)]
struct ifinfomsg {
    family: u8,
    pad: u8,
    ifi_type: u16, // ARPHRD_*
    index: i32,    // Interface index
    flags: u32,    // IFF_* flags
    change: u32,   // IFF_* change mask
}

// These values are based on the Linux kernel headers.
const IFLA_GRO_IPV4_MAX_SIZE: libc::c_ushort = 0x40;
const IFLA_GRO_MAX_SIZE: libc::c_ushort = 0x3a;
const IFLA_GSO_IPV4_MAX_SIZE: libc::c_ushort = 0x3f;
const IFLA_GSO_MAX_SIZE: libc::c_ushort = 0x29;

/// Functionally equivalent to "ip link set dev $ifindex g{r,s}o_max_size $max_size",
/// which sets BIGTCP if available, see: https://lwn.net/Articles/884104/
///
/// Requires loopback interface index as argument.
pub fn loopback_set_bigtcp(ifindex: i32, max_size: u32) -> Result<(), Errno> {
    // Set BIGTCP to max_size if available.
    use netlink_sys::{constants::*, Socket, SocketAddr};

    // SAFETY: create netlink socket using netlink_sys for NETLINK_ROUTE.
    let mut sock = Socket::new(NETLINK_ROUTE)
        .map_err(|e| Errno::from_raw(e.raw_os_error().unwrap_or(libc::ENOSYS)))?;
    sock.bind(&SocketAddr::new(0, 0))
        .map_err(|e| Errno::from_raw(e.raw_os_error().unwrap_or(libc::ENOSYS)))?;

    // SAFETY: Zero initialize. netlink message.
    let mut msg: nlmsg = unsafe { std::mem::zeroed() };

    // Set up netlink header.
    let nl_hdr = &mut msg.hdr;
    #[expect(clippy::arithmetic_side_effects)]
    #[expect(clippy::cast_possible_truncation)]
    {
        nl_hdr.nlmsg_len = (size_of::<libc::nlmsghdr>() + size_of::<ifinfomsg>()) as u32;
        nl_hdr.nlmsg_type = libc::RTM_NEWLINK;
        nl_hdr.nlmsg_flags = (libc::NLM_F_REQUEST | libc::NLM_F_ACK) as u16;
        nl_hdr.nlmsg_seq = 1;
        nl_hdr.nlmsg_pid = 0;
    }

    // Populate ifinfomsg.
    let info = &mut msg.info;
    #[expect(clippy::cast_possible_truncation)]
    {
        info.family = libc::AF_UNSPEC as u8;
        info.index = ifindex;
        info.change = u32::MAX;
    }

    let mut offset = 0;
    for &kind in &[
        IFLA_GRO_IPV4_MAX_SIZE,
        IFLA_GRO_MAX_SIZE,
        IFLA_GSO_IPV4_MAX_SIZE,
        IFLA_GSO_MAX_SIZE,
    ] {
        // SAFETY: Write attribute header using unaligned write.
        #[expect(clippy::arithmetic_side_effects)]
        #[expect(clippy::cast_possible_truncation)]
        unsafe {
            let attr = nlattr {
                nla_type: kind,
                nla_len: (size_of::<nlattr>() + size_of::<u32>()) as u16,
            };
            let attr_ptr = msg.attrs.as_mut_ptr().add(offset);
            std::ptr::write_unaligned(attr_ptr.cast::<nlattr>(), attr);

            // Write u32 payload after the attribute header.
            let val_ptr = attr_ptr.add(size_of::<nlattr>());
            std::ptr::write_unaligned(val_ptr.cast::<u32>(), max_size);
        }

        #[expect(clippy::arithmetic_side_effects)]
        #[expect(clippy::cast_lossless)]
        #[expect(clippy::cast_sign_loss)]
        #[expect(clippy::cast_possible_truncation)]
        {
            let nla_len = (size_of::<nlattr>() + size_of::<u32>()) as u16;
            // SAFETY: NLA_ALIGN is a libc macro that computes alignment padding;
            // the input is a valid attribute length.
            offset += unsafe { libc::NLA_ALIGN(nla_len as libc::c_int) } as usize;
        }
    }

    #[expect(clippy::arithmetic_side_effects)]
    #[expect(clippy::cast_possible_truncation)]
    {
        msg.hdr.nlmsg_len += offset as u32;
    }

    // SAFETY: Cast to byte slice for send.
    let buf = unsafe {
        std::slice::from_raw_parts(
            std::ptr::addr_of!(msg) as *const u8,
            msg.hdr.nlmsg_len as usize,
        )
    };
    sock.send(buf, 0)
        .map_err(|e| Errno::from_raw(e.raw_os_error().unwrap_or(libc::ENOSYS)))?;

    // Receive response.
    let (buf, _) = sock
        .recv_from_full()
        .map_err(|e| Errno::from_raw(e.raw_os_error().unwrap_or(libc::ENOSYS)))?;

    // Check response messages for error.
    let mut offset = 0;
    #[expect(clippy::arithmetic_side_effects)]
    while offset + size_of::<libc::nlmsghdr>() <= buf.len() {
        let hdr: libc::nlmsghdr = try_from_bytes(&buf[offset..])?;

        let len = hdr.nlmsg_len as usize;
        if len < size_of::<libc::nlmsghdr>() || offset + len > buf.len() {
            return Err(Errno::EINVAL);
        }

        // Check for error message.
        #[expect(clippy::cast_possible_truncation)]
        if hdr.nlmsg_type == libc::NLMSG_ERROR as libc::c_ushort
            && len >= size_of::<libc::nlmsghdr>() + size_of::<libc::nlmsgerr>()
        {
            let err_offset = offset
                .checked_add(size_of::<libc::nlmsghdr>())
                .ok_or(Errno::EINVAL)?;
            let err: libc::nlmsgerr = try_from_bytes(&buf[err_offset..])?;
            if err.error != 0 {
                return Err(Errno::from_raw(-err.error));
            }
        }

        #[expect(clippy::cast_possible_truncation)]
        #[expect(clippy::cast_possible_wrap)]
        #[expect(clippy::cast_sign_loss)]
        {
            // SAFETY: nlmsg_len is kernel-aligned; advance to next message.
            offset += unsafe { libc::NLA_ALIGN(len as i32) as usize };
        }
    }

    Ok(())
}