syd 3.58.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
//
// Syd: rock-solid application kernel
// src/bins/pty.rs: PTY to STDIO bidirectional forwarder
//
// Copyright (c) 2025, 2026 Ali Polatel <alip@chesswob.org>
//
// SPDX-License-Identifier: GPL-3.0

// SAFETY: This binary has been liberated from unsafe code!
#![forbid(unsafe_code)]

//! Syd's PTY to STDIO bidirectional forwarder.
//!
//! This module contains the entry point and all helper functions for the syd-pty(1) binary.

use std::{
    io::{stdin, stdout},
    os::{
        fd::{AsFd, AsRawFd, RawFd},
        unix::ffi::OsStrExt,
    },
    process::exit,
    sync::atomic::Ordering,
};

use libc::{
    c_uint, c_ushort, epoll_event, winsize, STDIN_FILENO, STDOUT_FILENO, TIOCGWINSZ, TIOCSWINSZ,
};
use libseccomp::{scmp_cmp, ScmpAction, ScmpFilterContext};
use nix::{
    errno::Errno,
    fcntl::{splice, OFlag, SpliceFFlags},
    poll::PollTimeout,
    sched::CloneFlags,
    sys::{
        epoll::{Epoll, EpollCreateFlags, EpollEvent, EpollFlags},
        resource::{getrlimit, Resource},
        signal::{sigprocmask, SigmaskHow, Signal},
        signalfd::{SfdFlags, SigSet, SignalFd},
        stat::{umask, Mode},
        termios::{cfmakeraw, tcgetattr, tcsetattr, LocalFlags, SetArg},
    },
    unistd::{chdir, isatty, pipe2},
};

use crate::{
    compat::{epoll_ctl_safe, set_dumpable, set_name, set_no_new_privs},
    config::{PTY_FCNTL_OPS, VDSO_SYSCALLS},
    confine::{
        confine_mdwe, confine_rlimit, confine_rlimit_zero, confine_scmp_close,
        confine_scmp_exit_group, confine_scmp_fcntl, pivot_root_cwd, safe_drop_caps, secure_getenv,
        try_unshare, Sydcall, CLONE_NEWTIME,
    },
    cookie::{safe_exit_group, CookieIdx, SYSCOOKIE_POOL},
    eprintfln,
    err::SydResult,
    fd::{
        close, closeexcept, read_signal, set_exclusive, set_nonblock, to_active_fd, SafeOwnedFd,
        SIGINFO_SIZE,
    },
    id::SydId,
    ignore_signals,
    landlock_policy::LandlockPolicy,
    log::LOG_FD,
    main, printfln,
    pty::{winsize_get, winsize_set},
    rng::duprand,
    IgnoreSignalOpts,
};

// This is from <linux/tty.h>, libc does not export it.
const N_TTY_BUF_SIZE: usize = 4096;
const PIPE_BUF: usize = N_TTY_BUF_SIZE;

// Entrypoint for syd-pty(1).
main! { pty_bin_main =>
    // Ensure stdin(3) and stdout(3) are attached to TTY.
    if !isatty(stdin()).unwrap_or(false) {
        eprintfln!("syd-pty: Error: Standard input is not a TTY.")?;
        return Err(Errno::ENOTTY.into());
    }
    if !isatty(stdout()).unwrap_or(false) {
        eprintfln!("syd-pty: Error: Standard output is not a TTY.")?;
        return Err(Errno::ENOTTY.into());
    }

    // Run PTY to standard I/O forwarder.
    let result = pty_bin_run(None);

    // Exit with cookies.
    let code = match result {
        Ok(()) => 0,
        Err(err) => err.errno().map(|errno| errno as i32).unwrap_or(128),
    };
    safe_exit_group(code)
}

// Run PTY to standard I/O forwarder.
pub(crate) fn pty_bin_run(opts: Option<PtyBinOpts>) -> SydResult<()> {
    // Set name for easier identification.
    let _ = set_name(SydId::get_cname(c"syd-pty"));

    // Drop all Linux capabilities(7).
    safe_drop_caps()?;

    // Set NO_NEW_PRIVS as early as possible.
    set_no_new_privs()?;

    // Confine early if trusted feature is not enabled.
    if !cfg!(feature = "trusted") {
        pty_confine_dump()?;
        pty_confine_name()?;
        pty_confine_lock()?;
        pty_confine_rlim_main()?;
    }

    // Ignore all signals except SIG{CHLD,KILL,STOP,WINCH}.
    // This is used to ensure we can deny {rt_,}sigreturn(2) to mitigate SROP.
    ignore_signals(IgnoreSignalOpts::NoWinch)?;

    // Set umask(2) to a sane value.
    umask(Mode::from_bits_retain(0o777));

    // Parse options as necessary.
    let opts = match opts {
        Some(opts) => opts,
        None => parse_options()?,
    };

    let PtyBinOpts {
        fpty,
        ws_x,
        ws_y,
        is_debug,
    } = opts;

    // Close all file descriptors, except:
    // 1. stdin(3) and stdout(3).
    // 2. PTY fd passed by syd(1).
    // 3. Do it before FD randomization.
    #[expect(clippy::cast_sign_loss)]
    let fd = fpty.as_raw_fd() as c_uint;
    closeexcept(&[0, 1, fd])?;

    // Turn off logging in fork child.
    // TODO: Make logging work.
    LOG_FD.store(-42, Ordering::Release);

    // Attempt to set file-max to hard limit overriding soft limit.
    // This is done before FD randomization to improve entropy.
    if let Ok((soft_limit, hard_limit)) = getrlimit(Resource::RLIMIT_NOFILE) {
        if soft_limit < hard_limit {
            let _ = confine_rlimit(Resource::RLIMIT_NOFILE, Some(hard_limit));
        }
    }

    // Randomize PTY fd for hardening.
    let fpty_fd = duprand(fpty.as_raw_fd(), OFlag::O_CLOEXEC)?;
    drop(fpty);
    let fpty = fpty_fd;

    // Create epoll(7) instance.
    let epoll = Epoll::new(EpollCreateFlags::EPOLL_CLOEXEC)?;

    // Randomize epoll(7) fd for hardening.
    let epoll_fd = duprand(epoll.0.as_raw_fd(), OFlag::O_CLOEXEC)?;
    drop(epoll);
    let epoll = Epoll(epoll_fd.into());

    // Block SIGWINCH and create signalfd, unless window size is pinned.
    let fsig: Option<SignalFd> = if ws_x.is_some() && ws_y.is_some() {
        None
    } else {
        let mut mask = SigSet::empty();
        mask.add(Signal::SIGWINCH);
        sigprocmask(SigmaskHow::SIG_BLOCK, Some(&mask), None)?;

        // Randomize signal-fd for hardening.
        let fl = SfdFlags::SFD_NONBLOCK | SfdFlags::SFD_CLOEXEC;
        let fd = SignalFd::with_flags(&mask, fl)?;
        Some(duprand(fd.as_raw_fd(), OFlag::O_CLOEXEC)?.into())
    };

    // Create pipes for bidirectional splice(2).
    //
    // Randomize pipe fds for hardening.
    let (pipe_pty_rd, pipe_pty_wr) = {
        let (rd, wr) = pipe2(OFlag::O_NONBLOCK | OFlag::O_CLOEXEC)?;
        let rd = duprand(rd.as_raw_fd(), OFlag::O_CLOEXEC)?;
        let wr = duprand(wr.as_raw_fd(), OFlag::O_CLOEXEC)?;
        (rd, wr)
    };
    let (pipe_std_rd, pipe_std_wr) = {
        let (rd, wr) = pipe2(OFlag::O_NONBLOCK | OFlag::O_CLOEXEC)?;
        let rd = duprand(rd.as_raw_fd(), OFlag::O_CLOEXEC)?;
        let wr = duprand(wr.as_raw_fd(), OFlag::O_CLOEXEC)?;
        (rd, wr)
    };

    // Randomize stdio(3) fds for hardening.
    let fstd_rd = duprand(STDIN_FILENO, OFlag::O_CLOEXEC)?;
    let fstd_wr = duprand(STDOUT_FILENO, OFlag::O_CLOEXEC)?;
    let _ = close(STDIN_FILENO);
    let _ = close(STDOUT_FILENO);

    // Set PTY to exclusive mode to harden against sniffing.
    set_exclusive(&fpty, true)?;

    // Set PTY fd non-blocking.
    set_nonblock(&fpty, true)?;

    // Set stdio(3) non-blocking.
    set_nonblock(&fstd_rd, true)?;
    set_nonblock(&fstd_wr, true)?;

    // Refresh terminal settings.
    refresh_pty(&fstd_rd, &fpty)?;

    // Refresh window size.
    refresh_win(&fstd_rd, &fpty, ws_x, ws_y);

    // Confine with landlock(7), namespaces(7).
    // This prevents all filesystem and network access.
    if !cfg!(feature = "trusted") {
        pty_confine_rlim_file()?;
    } else if !is_debug {
        pty_confine_dump()?;
        pty_confine_name()?;
        pty_confine_lock()?;
        pty_confine_rlim_main()?;
        pty_confine_rlim_file()?;
    }

    // Load seccomp(2) filter.
    if !is_debug {
        let ctx = pty_confine_scmp(fsig.as_ref(), &fstd_rd, &fpty)?;
        ctx.load()?;
    }

    // Run PTY forwarder.
    let result = pty_bin_fwd(
        &epoll,
        fsig.as_ref(),
        fpty,
        (fstd_rd, fstd_wr),
        (pipe_pty_rd, pipe_pty_wr),
        (pipe_std_rd, pipe_std_wr),
        (ws_x, ws_y),
    );

    // Close epoll(7) fd and signalfd(7) using cookies.
    drop(SafeOwnedFd::from(epoll.0));
    drop(fsig.map(SafeOwnedFd::from));

    result
}

// Run PTY forwarder.
fn pty_bin_fwd<Fd1, Fd2, Fd3, Fd4, Fd5, Fd6, Fd7>(
    epoll: &Epoll,
    sig_fd: Option<&SignalFd>,
    pty_fd: Fd1,
    std_fd: (Fd2, Fd3),
    pipe_pty: (Fd4, Fd5),
    pipe_std: (Fd6, Fd7),
    win_sz: (Option<c_ushort>, Option<c_ushort>),
) -> SydResult<()>
where
    Fd1: AsFd,
    Fd2: AsFd,
    Fd3: AsFd,
    Fd4: AsFd,
    Fd5: AsFd,
    Fd6: AsFd,
    Fd7: AsFd,
{
    // Unpack file descriptors and window size overrides.
    let (std_rd, std_wr) = std_fd;
    let (pipe_pty_rd, pipe_pty_wr) = pipe_pty;
    let (pipe_std_rd, pipe_std_wr) = pipe_std;
    let (ws_x, ws_y) = win_sz;

    // Add PTY main fd to epoll for read/write (not necessary to set EPOLL{ERR,HUP}).
    #[expect(clippy::cast_sign_loss)]
    let event = epoll_event {
        events: (EpollFlags::EPOLLET
            | EpollFlags::EPOLLIN
            | EpollFlags::EPOLLOUT
            | EpollFlags::EPOLLRDHUP)
            .bits() as u32,
        u64: pty_fd.as_fd().as_raw_fd() as u64,
    };
    epoll_ctl_safe(&epoll.0, pty_fd.as_fd().as_raw_fd(), Some(event))?;

    // Add stdin fd to epoll read readiness (not necessary to set EPOLL{ERR,HUP}).
    #[expect(clippy::cast_sign_loss)]
    let event = epoll_event {
        events: (EpollFlags::EPOLLET | EpollFlags::EPOLLIN | EpollFlags::EPOLLRDHUP).bits() as u32,
        u64: std_rd.as_fd().as_raw_fd() as u64,
    };
    epoll_ctl_safe(&epoll.0, std_rd.as_fd().as_raw_fd(), Some(event))?;

    // Add stdout fd to epoll write readiness (not necessary to set EPOLL{ERR,HUP}).
    #[expect(clippy::cast_sign_loss)]
    let event = epoll_event {
        events: (EpollFlags::EPOLLET | EpollFlags::EPOLLOUT | EpollFlags::EPOLLRDHUP).bits() as u32,
        u64: std_wr.as_fd().as_raw_fd() as u64,
    };
    epoll_ctl_safe(&epoll.0, std_wr.as_fd().as_raw_fd(), Some(event))?;

    // Add signal fd to epoll read readiness (not necessary to set EPOLL{ERR,HUP}).
    if let Some(sig_fd) = sig_fd {
        #[expect(clippy::cast_sign_loss)]
        let event = epoll_event {
            events: (EpollFlags::EPOLLET | EpollFlags::EPOLLIN | EpollFlags::EPOLLRDHUP).bits()
                as u32,
            u64: sig_fd.as_fd().as_raw_fd() as u64,
        };
        epoll_ctl_safe(&epoll.0, sig_fd.as_fd().as_raw_fd(), Some(event))?;
    }

    // TODO: MAX_EVENTS=1024 move to config.rs
    let mut events = [EpollEvent::empty(); 1024];
    loop {
        // Wait for events and handle EINTR.
        let n = match epoll.wait(&mut events, PollTimeout::NONE) {
            Ok(n) => n,
            Err(Errno::EINTR) => continue, // Retry if interrupted by a signal.
            Err(errno) => return Err(errno.into()),
        };

        'eventloop: for event in events.iter().take(n) {
            let fd = event.data() as RawFd;
            let mut event_flags = event.events();

            let is_inp = event_flags
                .contains(EpollFlags::EPOLLIN)
                .then(|| event_flags.remove(EpollFlags::EPOLLIN))
                .is_some();
            let is_out = event_flags
                .contains(EpollFlags::EPOLLOUT)
                .then(|| event_flags.remove(EpollFlags::EPOLLOUT))
                .is_some();
            let is_err = !event_flags.is_empty();

            if let Some(sig_fd) = sig_fd.filter(|sfd| is_inp && fd == sfd.as_raw_fd()) {
                // Handle window resize event.
                loop {
                    let sig_info = match read_signal(sig_fd) {
                        Ok(sig_info) => {
                            // We caught a signal.
                            sig_info
                        }
                        Err(Errno::EAGAIN) => {
                            // No signals waiting.
                            continue 'eventloop;
                        }
                        Err(Errno::EINTR) => continue,
                        Err(errno) => return Err(errno.into()),
                    };

                    #[expect(clippy::cast_possible_wrap)]
                    if sig_info.ssi_signo as i32 == Signal::SIGWINCH as i32 {
                        // Refresh window size, respecting pinned sizes.
                        refresh_win(&std_rd, &pty_fd, ws_x, ws_y);
                    }
                }
            }

            if is_inp {
                // Handle readable events.
                if fd == std_rd.as_fd().as_raw_fd() {
                    // splice from STDIN into PTY via pipe1.
                    if splice_move(&std_rd, &pty_fd, &pipe_pty_rd, &pipe_pty_wr)? {
                        // STDIN hung up.
                        // splice from pipe1 into PTY, and exit.
                        splice_pipe(&pipe_pty_rd, &pty_fd)?;
                        return Ok(());
                    }
                } else if fd == pty_fd.as_fd().as_raw_fd() {
                    // splice from PTY into STDOUT via pipe2.
                    splice_move(&pty_fd, &std_wr, &pipe_std_rd, &pipe_std_wr)?;
                }
            }

            if is_out {
                // Handle writable events.
                if fd == std_wr.as_fd().as_raw_fd() {
                    // splice from pipe2 into STDOUT.
                    // splice from PTY into STDOUT via pipe2.
                    splice_pipe(&pipe_std_rd, &std_wr)?;
                    splice_move(&pty_fd, &std_wr, &pipe_std_rd, &pipe_std_wr)?;
                } else if fd == pty_fd.as_fd().as_raw_fd() {
                    // splice from pipe1 into PTY.
                    // splice from STDIN into PTY via pipe1.
                    splice_pipe(&pipe_pty_rd, &pty_fd)?;
                    splice_move(&std_rd, &pty_fd, &pipe_pty_rd, &pipe_pty_wr)?;
                }
            }

            if is_err {
                // Drain other side on error.
                if fd == std_wr.as_fd().as_raw_fd() {
                    // splice from pipe1 into PTY.
                    splice_pipe(&pipe_pty_rd, &pty_fd)?;
                } else if fd == pty_fd.as_fd().as_raw_fd() {
                    // Set STDOUT blocking.
                    // TTY writes don't honor SPLICE_F_NONBLOCK,
                    // so EAGAIN means empty pipe.
                    set_nonblock(&std_wr, false)?;

                    // splice from pipe2 into STDOUT.
                    splice_pipe(&pipe_std_rd, &std_wr)?;

                    // splice from PTY into STDOUT via pipe2.
                    splice_move(&pty_fd, &std_wr, &pipe_std_rd, &pipe_std_wr)?;

                    // Exit after PTY main hung up.
                    return Ok(());
                } else if fd == std_rd.as_fd().as_raw_fd() {
                    // splice from pipe1 into PTY.
                    splice_pipe(&pipe_pty_rd, &pty_fd)?;

                    // Exit after STDIN hung up.
                    return Ok(());
                }
            }
        }
    }
}

// Confine syd-pty(1) with DUMPABLE and MDWE.
fn pty_confine_dump() -> Result<(), Errno> {
    // Default panic hook won't play well with seccomp(2).
    std::panic::set_hook(Box::new(|_| {}));

    // Set process dumpable attribute to not-dumpable.
    set_dumpable(false)?;

    // Set up Memory-Deny-Write-Execute protections.
    // Ignore errors as PR_SET_MDWE may not be supported.
    let _ = confine_mdwe(false);

    Ok(())
}

// Confine syd-pty(1) with rlimit(2).
fn pty_confine_rlim_main() -> Result<(), Errno> {
    // Set nfiles, nprocs, and filesize rlimits to zero.
    // Set locks, memory lock and msgqueue rlimits to zero.
    // Set core dump file size to zero.
    confine_rlimit_zero(&[
        Resource::RLIMIT_CORE,
        Resource::RLIMIT_FSIZE,
        Resource::RLIMIT_NPROC,
        Resource::RLIMIT_LOCKS,
        Resource::RLIMIT_MEMLOCK,
        Resource::RLIMIT_MSGQUEUE,
    ])
}

// Confine syd-pty(1) with RLIMIT_NOFILE.
fn pty_confine_rlim_file() -> Result<(), Errno> {
    confine_rlimit_zero(&[Resource::RLIMIT_NOFILE])
}

// Confine syd-pty(1) with landlock(7).
fn pty_confine_lock() -> SydResult<()> {
    // Set up a scoped landlock(7) sandbox.
    // Disallow all filesystem and network access.
    // This ensures a compromised syd-pty(1) cannot signal syd(1).
    // All used ioctl(2)s are permitted by landlock(7) regardless of IoctlDev.
    let abi = crate::landlock::ABI::new_current();
    let policy = LandlockPolicy::default();
    let _ = policy.restrict_self(abi);

    Ok(())
}

// Confine syd-pty(1) with namespaces(7).
fn pty_confine_name() -> SydResult<()> {
    // Change directory into safe directory.
    chdir("/proc/self/fdinfo")?;

    // Set up namespace isolation for all available namespaces.
    let namespaces = CloneFlags::CLONE_NEWUSER
        | CloneFlags::CLONE_NEWNS
        | CloneFlags::CLONE_NEWUTS
        | CloneFlags::CLONE_NEWIPC
        | CloneFlags::CLONE_NEWPID
        | CloneFlags::CLONE_NEWNET
        | CloneFlags::CLONE_NEWCGROUP
        | CLONE_NEWTIME;

    // Attempt to unshare namespaces.
    let namespaces = try_unshare(namespaces)?;

    // Pivot into safe directory in mount namespace.
    if namespaces.contains(CloneFlags::CLONE_NEWNS) {
        pivot_root_cwd()?; // /proc/self/fdinfo.
    }

    // Drop capabilities regained in user namespace.
    // This must happen after pivot_root(2).
    if namespaces.contains(CloneFlags::CLONE_NEWUSER) {
        safe_drop_caps()?;
    }

    Ok(())
}

// Return seccomp(2) filter to transit syd-pty(1) into a confined state.
fn pty_confine_scmp<Fd1, Fd2, Fd3>(
    sig_fd: Option<Fd1>,
    std_fd: Fd2,
    pty_fd: Fd3,
) -> SydResult<ScmpFilterContext>
where
    Fd1: AsFd,
    Fd2: AsFd,
    Fd3: AsFd,
{
    // Initialize syscall argument cookie pool.
    SYSCOOKIE_POOL.init()?;

    let mut ctx = new_filter(ScmpAction::KillProcess)?;

    let allow_call = [
        // can do I/O with splice.
        "splice",
        // can use EPoll API but not create.
        "epoll_ctl",
        "epoll_wait",
        "epoll_pwait",
        "epoll_pwait2",
    ];

    // Default allowlist.
    for name in allow_call.iter().chain(VDSO_SYSCALLS) {
        if let Ok(syscall) = Sydcall::from_name(name) {
            ctx.add_rule(ScmpAction::Allow, syscall)?;
        }
    }

    // Allow safe fcntl(2) utility calls.
    confine_scmp_fcntl(&mut ctx, PTY_FCNTL_OPS)?;

    // Allow close(2) with syscall argument cookies.
    confine_scmp_close(&mut ctx, true /*restrict_cookie*/)?;

    // Allow exit_group(2) with syscall argument cookies.
    confine_scmp_exit_group(&mut ctx, true /*restrict_cookie*/)?;

    // Allow window resizing if signalfd(2) is in use.
    if let Some(sig_fd) = sig_fd {
        pty_confine_scmp_sig(&mut ctx, sig_fd, &std_fd, &pty_fd)?;
    }

    // Precompute filter on libseccomp>=2.6.
    #[cfg(libseccomp_v2_6)]
    ctx.precompute()?;

    Ok(ctx)
}

// Edit given seccomp(2) filter to allow window resizing.
fn pty_confine_scmp_sig<Fd1, Fd2, Fd3>(
    ctx: &mut ScmpFilterContext,
    sig_fd: Fd1,
    std_fd: Fd2,
    pty_fd: Fd3,
) -> SydResult<()>
where
    Fd1: AsFd,
    Fd2: AsFd,
    Fd3: AsFd,
{
    // Allow read(2) to signal fd only.
    #[expect(clippy::disallowed_methods)]
    let syscall = Sydcall::from_name("read").unwrap();

    #[expect(clippy::cast_sign_loss)]
    #[expect(clippy::useless_conversion)]
    ctx.add_rule_conditional(
        ScmpAction::Allow,
        syscall,
        &[
            scmp_cmp!($arg0 == sig_fd.as_fd().as_raw_fd() as u64),
            scmp_cmp!($arg2 == SIGINFO_SIZE as u64),
            scmp_cmp!($arg3 == SYSCOOKIE_POOL.try_get(CookieIdx::ReadArg3)?.into()),
            scmp_cmp!($arg4 == SYSCOOKIE_POOL.try_get(CookieIdx::ReadArg4)?.into()),
            scmp_cmp!($arg5 == SYSCOOKIE_POOL.try_get(CookieIdx::ReadArg5)?.into()),
        ],
    )?;

    // Allow ioctl(2) requests:
    // 1. TIOCGWINSZ, aka winsize_get, for stdin.
    // 2. TIOCSWINSZ, aka winsize_set, for PTY fd.
    #[expect(clippy::disallowed_methods)]
    let syscall = Sydcall::from_name("ioctl").unwrap();

    #[expect(clippy::cast_sign_loss)]
    #[expect(clippy::unnecessary_cast)]
    {
        ctx.add_rule_conditional(
            ScmpAction::Allow,
            syscall,
            &[
                scmp_cmp!($arg0 == std_fd.as_fd().as_raw_fd() as u64),
                scmp_cmp!($arg1 & 0xFFFFFFFF == TIOCGWINSZ as u64),
            ],
        )?;
        ctx.add_rule_conditional(
            ScmpAction::Allow,
            syscall,
            &[
                scmp_cmp!($arg0 == pty_fd.as_fd().as_raw_fd() as u64),
                scmp_cmp!($arg1 & 0xFFFFFFFF == TIOCSWINSZ as u64),
            ],
        )?;
    }

    Ok(())
}

fn new_filter(action: ScmpAction) -> SydResult<ScmpFilterContext> {
    let mut filter = ScmpFilterContext::new(action)?;

    // Enforce the NO_NEW_PRIVS functionality before
    // loading the seccomp filter into the kernel.
    filter.set_ctl_nnp(true)?;

    // Kill process for bad arch.
    filter.set_act_badarch(ScmpAction::KillProcess)?;

    // Use a binary tree sorted by syscall number, if possible.
    let _ = filter.set_ctl_optimize(2);

    Ok(filter)
}

// splice(2) helper
fn splice_data<Fd1: AsFd, Fd2: AsFd>(src: Fd1, dst: Fd2) -> Result<usize, Errno> {
    match splice(
        src,
        None,
        dst,
        None,
        PIPE_BUF,
        SpliceFFlags::SPLICE_F_NONBLOCK | SpliceFFlags::SPLICE_F_MORE,
    ) {
        Err(Errno::EINVAL | Errno::EIO) => Ok(0), // TTY {v,}hangup is EOF.
        result => result,
    }
}

fn splice_pipe<Fd1: AsFd, Fd2: AsFd>(src: Fd1, dst: Fd2) -> Result<(), Errno> {
    loop {
        return match splice_data(&src, &dst) {
            Ok(0) | Err(Errno::EAGAIN) => Ok(()),
            Ok(_) | Err(Errno::EINTR) => continue,
            Err(errno) => Err(errno),
        };
    }
}

fn splice_move<Fd1: AsFd, Fd2: AsFd, Fd3: AsFd, Fd4: AsFd>(
    src: Fd1,
    dst: Fd2,
    pipe_rd: Fd3,
    pipe_wr: Fd4,
) -> Result<bool, Errno> {
    loop {
        match splice_data(&src, &pipe_wr) {
            Ok(0) => return Ok(true),
            Ok(_) => splice_pipe(&pipe_rd, &dst)?,
            Err(Errno::EINTR) => {}
            Err(Errno::EAGAIN) => return Ok(false),
            Err(errno) => return Err(errno),
        }
    }
}

// Handle window resize propagation.
fn refresh_win<Fd1: AsFd, Fd2: AsFd>(
    src: Fd1,
    dst: Fd2,
    ws_x: Option<c_ushort>,
    ws_y: Option<c_ushort>,
) {
    if let Some(ws_row) = ws_x {
        if let Some(ws_col) = ws_y {
            let ws = winsize {
                ws_row,
                ws_col,
                ws_xpixel: 0,
                ws_ypixel: 0,
            };
            let _ = winsize_set(&dst, ws);
            return;
        }
    }

    if let Ok(mut ws) = winsize_get(&src) {
        if let Some(ws_row) = ws_x {
            ws.ws_row = ws_row;
        }
        if let Some(ws_col) = ws_y {
            ws.ws_col = ws_col;
        }
        let _ = winsize_set(&dst, ws);
    }
}

// Handle terminal settings, called once at startup.
#[expect(clippy::disallowed_methods)]
fn refresh_pty<Fd1: AsFd, Fd2: AsFd>(src: Fd1, dst: Fd2) -> Result<(), Errno> {
    let mut tio = tcgetattr(&src)?;

    // Inherit host terminal settings for PTY.
    tcsetattr(&dst, SetArg::TCSANOW, &tio)?;

    // Set raw mode for input TTY.
    // Disable background processes from writing.
    cfmakeraw(&mut tio);
    tio.local_flags.insert(LocalFlags::TOSTOP);
    tcsetattr(&src, SetArg::TCSANOW, &tio)?;

    Ok(())
}

// Parse command line options.
pub(crate) struct PtyBinOpts {
    // -i pty-fd
    pub(crate) fpty: SafeOwnedFd,

    // -x row-size
    pub(crate) ws_x: Option<c_ushort>,

    // -y column-size
    pub(crate) ws_y: Option<c_ushort>,

    // -d
    // UNSAFE! Run in debug mode without confinement.
    pub(crate) is_debug: bool,
}

fn parse_options() -> SydResult<PtyBinOpts> {
    use lexopt::prelude::*;

    // Parse CLI options.
    let mut opt_fpty = None;
    let mut opt_ws_x = None;
    let mut opt_ws_y = None;

    // Skip confinement if SYD_PTY_DEBUG environment variable is set.
    // Another way to achieve the same is the `-d` CLI option.
    // Both methods are only permitted for trusted Syd builds.
    let mut opt_debug = secure_getenv("SYD_PTY_DEBUG").is_some();

    let mut parser = lexopt::Parser::from_env();
    while let Some(arg) = parser.next()? {
        match arg {
            Short('h') => {
                help()?;
                exit(0);
            }
            Short('i') => opt_fpty = Some(parser.value()?),
            Short('x') => opt_ws_x = Some(parser.value()?.parse::<String>()?.parse::<c_ushort>()?),
            Short('y') => opt_ws_y = Some(parser.value()?.parse::<String>()?.parse::<c_ushort>()?),
            Short('d') if cfg!(feature = "trusted") => opt_debug = true,
            Short('d') => {
                eprintfln!("syd-pty: Error: -d option isn't permitted.")?;
                eprintfln!("syd-pty: Syd isn't built with trusted feature.")?;
                return Err(Errno::EPERM.into());
            }
            _ => return Err(arg.unexpected().into()),
        }
    }

    let fpty = if let Some(fpty) = opt_fpty {
        to_active_fd(fpty.as_bytes())?
    } else {
        eprintfln!("syd-pty: Error: -i is required.")?;
        help()?;
        exit(1);
    };

    Ok(PtyBinOpts {
        fpty,
        ws_x: opt_ws_x,
        ws_y: opt_ws_y,
        is_debug: opt_debug,
    })
}

fn help() -> Result<(), Errno> {
    printfln!("Usage: syd-pty [-dh] -i <pty-fd> [-x x-size] [-y y-size]")?;
    printfln!("Syd's PTY to STDIO bidirectional forwarder")?;
    printfln!("Forwards data between the given pty(7) main file descriptor and stdio(3).")?;
    printfln!("  -h             Print this help message and exit.")?;
    printfln!("  -i <pty-fd>    PTY main file descriptor.")?;
    printfln!("  -x <x-size>    Specify window row size (default: inherit).")?;
    printfln!("  -y <y-size>    Specify window column size (default: inherit).")?;
    printfln!("  -d             Run in debug mode without confinement.")?;
    printfln!("                 This requires Syd built with trusted feature.")?;
    Ok(())
}