Skip to main content

dvm_run/
command.rs

1use std::future::{Future, IntoFuture};
2use std::pin::Pin;
3use std::sync::Arc;
4
5use dvm_api::{SandboxProgram, SandboxRun};
6
7use crate::sandbox_session::{Operation, Session};
8use crate::{Error, Result};
9
10/// Argv (an array or vector), or a shell script (a string).
11#[derive(Clone, Debug)]
12pub struct CommandLine(pub(crate) SandboxProgram);
13
14impl From<&str> for CommandLine {
15    fn from(script: &str) -> Self {
16        Self(SandboxProgram::Script(script.to_owned()))
17    }
18}
19impl From<String> for CommandLine {
20    fn from(script: String) -> Self {
21        Self(SandboxProgram::Script(script))
22    }
23}
24impl<T: Into<String>> From<Vec<T>> for CommandLine {
25    fn from(argv: Vec<T>) -> Self {
26        Self(SandboxProgram::Argv(
27            argv.into_iter().map(Into::into).collect(),
28        ))
29    }
30}
31impl<T: Into<String>, const N: usize> From<[T; N]> for CommandLine {
32    fn from(argv: [T; N]) -> Self {
33        Self::from(Vec::from(argv))
34    }
35}
36
37/// A command's bytes and exit code, or 128 + its killing signal.
38/// Nonzero is a result; the protocol cannot distinguish a signal from
39/// an explicit exit with that code.
40#[derive(Clone, Debug, Default, PartialEq, Eq)]
41pub struct CommandResult {
42    pub exit_code: i32,
43    pub stdout: Vec<u8>,
44    pub stderr: Vec<u8>,
45}
46
47/// A started command. With omitted stdin the handle keeps it open.
48#[derive(Debug)]
49pub struct Command {
50    pub(crate) session: Arc<Session>,
51    pub(crate) operation: Operation,
52    pub(crate) stdin_closed: tokio::sync::Mutex<bool>,
53}
54
55impl Command {
56    pub async fn wait(&self) -> Result<CommandResult> {
57        self.operation.wait(false).await?;
58        Ok(self.operation.state.borrow().output.clone())
59    }
60
61    /// Sends to the process group. The protocol has no success acknowledgment.
62    pub async fn signal(&self, number: i32) -> Result<()> {
63        if !(1..=64).contains(&number) {
64            return Err(Error::SandboxRequest {
65                reason: "signal must be between 1 and 64".into(),
66            });
67        }
68        self.session.signal(&self.operation, number).await
69    }
70
71    pub async fn write_stdin(&self, data: &[u8]) -> Result<()> {
72        let closed = self.stdin_closed.lock().await;
73        if *closed {
74            return Err(Error::SandboxRequest {
75                reason: "command stdin is closed".into(),
76            });
77        }
78        self.session.stdin(&self.operation, data, false).await
79    }
80
81    pub async fn close_stdin(&self) -> Result<()> {
82        let mut closed = self.stdin_closed.lock().await;
83        if !*closed {
84            self.session.stdin(&self.operation, &[], true).await?;
85            *closed = true;
86        }
87        Ok(())
88    }
89}
90
91/// Options for starting a command, applied before awaiting it.
92#[must_use = "await to start the command"]
93pub struct StartBuilder {
94    pub(crate) session: Option<Arc<Session>>,
95    pub(crate) run: SandboxRun,
96    pub(crate) stdin: Option<Vec<u8>>,
97}
98
99impl StartBuilder {
100    pub fn env(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
101        self.run.env.insert(name.into(), value.into());
102        self
103    }
104    pub fn cwd(mut self, path: impl Into<String>) -> Self {
105        self.run.cwd = Some(path.into());
106        self
107    }
108    /// As `docker exec --user`: a name or uid, optionally `:group` or `:gid`.
109    /// Omitted, the command runs as the sandbox server's user.
110    pub fn user(mut self, user: impl Into<String>) -> Self {
111        self.run.user = Some(user.into());
112        self
113    }
114    /// Sends bytes, then closes stdin. Omitted stdin stays open on a handle.
115    pub fn stdin(mut self, data: impl AsRef<[u8]>) -> Self {
116        self.stdin = Some(data.as_ref().to_vec());
117        self
118    }
119
120    async fn start(self) -> Result<Command> {
121        let session = self.session.ok_or_else(no_commands)?;
122        session.start(self.run, self.stdin).await
123    }
124}
125
126impl IntoFuture for StartBuilder {
127    type Output = Result<Command>;
128    type IntoFuture = Pin<Box<dyn Future<Output = Self::Output> + Send>>;
129    fn into_future(self) -> Self::IntoFuture {
130        Box::pin(self.start())
131    }
132}
133
134/// Options for a command run to its end. Omitted stdin is closed empty.
135#[must_use = "await to run the command"]
136pub struct RunBuilder(pub(crate) StartBuilder);
137impl RunBuilder {
138    pub fn env(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
139        self.0 = self.0.env(name, value);
140        self
141    }
142    pub fn cwd(mut self, path: impl Into<String>) -> Self {
143        self.0 = self.0.cwd(path);
144        self
145    }
146    pub fn user(mut self, user: impl Into<String>) -> Self {
147        self.0 = self.0.user(user);
148        self
149    }
150    pub fn stdin(mut self, data: impl AsRef<[u8]>) -> Self {
151        self.0 = self.0.stdin(data);
152        self
153    }
154}
155impl IntoFuture for RunBuilder {
156    type Output = Result<CommandResult>;
157    type IntoFuture = Pin<Box<dyn Future<Output = Self::Output> + Send>>;
158    fn into_future(mut self) -> Self::IntoFuture {
159        self.0.stdin.get_or_insert_default();
160        Box::pin(async move { self.0.await?.wait().await })
161    }
162}
163
164#[must_use = "await to write the file"]
165pub struct WriteFileBuilder {
166    pub(crate) session: Option<Arc<Session>>,
167    pub(crate) path: String,
168    pub(crate) data: Vec<u8>,
169    pub(crate) mode: Option<u32>,
170}
171impl WriteFileBuilder {
172    pub fn mode(mut self, mode: u32) -> Self {
173        self.mode = Some(mode);
174        self
175    }
176}
177impl IntoFuture for WriteFileBuilder {
178    type Output = Result<()>;
179    type IntoFuture = Pin<Box<dyn Future<Output = Self::Output> + Send>>;
180    fn into_future(self) -> Self::IntoFuture {
181        Box::pin(async move {
182            self.session
183                .ok_or_else(no_commands)?
184                .write_file(self.path, &self.data, self.mode)
185                .await
186        })
187    }
188}
189
190pub(crate) fn no_commands() -> Error {
191    Error::Conflict {
192        reason: "this sandbox runs a supplied program and does not take commands".into(),
193    }
194}