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
use std::fs::File;
use std::io::{self, Error, ErrorKind, IoSlice, Result, StdinLock, StdoutLock};
use std::os::unix::io::{AsFd, BorrowedFd};
use std::pin::Pin;
use std::task::{Context, Poll};

use rustix::fs::{fcntl_getfl, fcntl_setfl, fstat, FileType, OFlags};
use rustix::io::{dup, stdin, stdout};
use tokio::io::{AsyncRead, AsyncWrite, ReadBuf};
use tokio::net::unix::pipe;

#[derive(Debug)]
struct NonBlocking<T: AsFd> {
    inner: T,
    prev_flags: OFlags,
}

impl<T: AsFd> NonBlocking<T> {
    fn new(inner: T) -> Result<Self> {
        let ft = FileType::from_raw_mode(fstat(&inner)?.st_mode);
        if !matches!(
            ft,
            FileType::Fifo | FileType::Socket | FileType::CharacterDevice | FileType::BlockDevice
        ) {
            return Err(Error::new(
                ErrorKind::Other,
                format!("File type {ft:?} is not pipe-like"),
            ));
        }

        let prev_flags = fcntl_getfl(&inner)?;
        fcntl_setfl(&inner, prev_flags | OFlags::NONBLOCK)?;
        Ok(Self { inner, prev_flags })
    }
}

impl<T: AsFd> Drop for NonBlocking<T> {
    fn drop(&mut self) {
        let _: std::result::Result<_, _> = fcntl_setfl(&self.inner, self.prev_flags);
    }
}

#[derive(Debug)]
pub struct PipeStdin {
    inner: pipe::Receiver,
    // NB. `_lock` is dropped after `inner` closes the duplicate.
    // So that we can safely reset the flags.
    _lock: NonBlocking<StdinLock<'static>>,
}

impl PipeStdin {
    pub fn lock() -> Result<Self> {
        let lock = NonBlocking::new(io::stdin().lock())?;
        // We must not close the stdin, but we have to pass an owned `File` into tokio.
        // Here we dup the file descripTOR to make it sound.
        // Note that the duplicate shares the same file descriptION.
        let file = File::from(dup(stdin())?);
        let inner = pipe::Receiver::from_file_unchecked(file)?;
        Ok(Self { inner, _lock: lock })
    }
}

impl AsFd for PipeStdin {
    fn as_fd(&self) -> BorrowedFd<'_> {
        self.inner.as_fd()
    }
}

impl AsyncRead for PipeStdin {
    fn poll_read(
        mut self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        buf: &mut ReadBuf<'_>,
    ) -> Poll<Result<()>> {
        Pin::new(&mut self.inner).poll_read(cx, buf)
    }
}

#[derive(Debug)]
pub struct PipeStdout {
    inner: pipe::Sender,
    // NB. `_lock` is dropped after `inner` closes the duplicate.
    // See `PipeStdin`.
    _lock: NonBlocking<StdoutLock<'static>>,
}

impl PipeStdout {
    pub fn lock() -> Result<Self> {
        let lock = NonBlocking::new(io::stdout().lock())?;
        // See `PipeStdin::lock`.
        let file = File::from(dup(stdout())?);
        let inner = pipe::Sender::from_file_unchecked(file)?;
        Ok(Self { inner, _lock: lock })
    }
}

impl AsFd for PipeStdout {
    fn as_fd(&self) -> BorrowedFd<'_> {
        self.inner.as_fd()
    }
}

impl AsyncWrite for PipeStdout {
    fn poll_write(
        mut self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        buf: &[u8],
    ) -> Poll<Result<usize>> {
        Pin::new(&mut self.inner).poll_write(cx, buf)
    }

    fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<()>> {
        Pin::new(&mut self.inner).poll_flush(cx)
    }

    fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<()>> {
        Pin::new(&mut self.inner).poll_shutdown(cx)
    }

    fn poll_write_vectored(
        mut self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        bufs: &[IoSlice<'_>],
    ) -> Poll<Result<usize>> {
        Pin::new(&mut self.inner).poll_write_vectored(cx, bufs)
    }

    fn is_write_vectored(&self) -> bool {
        self.inner.is_write_vectored()
    }
}