-
Notifications
You must be signed in to change notification settings - Fork 5.5k
/
Copy pathcommand.rs
260 lines (227 loc) · 5.73 KB
/
command.rs
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
// Copyright 2018-2021 the Deno authors. All rights reserved. MIT license.
use super::io::ChildStderrResource;
use super::io::ChildStdinResource;
use super::io::ChildStdoutResource;
use crate::permissions::Permissions;
use deno_core::error::AnyError;
use deno_core::op;
use deno_core::AsyncRefCell;
use deno_core::Extension;
use deno_core::OpState;
use deno_core::RcRef;
use deno_core::Resource;
use deno_core::ResourceId;
use deno_core::ZeroCopyBuf;
use serde::Deserialize;
use serde::Serialize;
use std::borrow::Cow;
use std::cell::RefCell;
use std::process::ExitStatus;
use std::rc::Rc;
#[cfg(unix)]
use std::os::unix::prelude::ExitStatusExt;
#[cfg(unix)]
use std::os::unix::process::CommandExt;
pub fn init() -> Extension {
Extension::builder()
.ops(vec![
op_command_spawn::decl(),
op_command_wait::decl(),
op_command_sync::decl(),
])
.build()
}
struct ChildResource(AsyncRefCell<tokio::process::Child>);
impl Resource for ChildResource {
fn name(&self) -> Cow<str> {
"child".into()
}
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum Stdio {
Inherit,
Piped,
Null,
}
fn subprocess_stdio_map(s: &Stdio) -> Result<std::process::Stdio, AnyError> {
match s {
Stdio::Inherit => Ok(std::process::Stdio::inherit()),
Stdio::Piped => Ok(std::process::Stdio::piped()),
Stdio::Null => Ok(std::process::Stdio::null()),
}
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CommandArgs {
cmd: String,
args: Vec<String>,
cwd: Option<String>,
clear_env: bool,
env: Vec<(String, String)>,
#[cfg(unix)]
gid: Option<u32>,
#[cfg(unix)]
uid: Option<u32>,
#[serde(flatten)]
stdio: CommandStdio,
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CommandStdio {
stdin: Stdio,
stdout: Stdio,
stderr: Stdio,
}
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CommandStatus {
success: bool,
code: i32,
signal: Option<i32>,
}
impl From<std::process::ExitStatus> for CommandStatus {
fn from(status: ExitStatus) -> Self {
let code = status.code();
#[cfg(unix)]
let signal = status.signal();
#[cfg(not(unix))]
let signal = None;
if let Some(signal) = signal {
CommandStatus {
success: false,
code: 128 + signal,
signal: Some(signal),
}
} else {
let code = code.expect("Should have either an exit code or a signal.");
CommandStatus {
success: code == 0,
code,
signal: None,
}
}
}
}
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CommandOutput {
status: CommandStatus,
stdout: Option<ZeroCopyBuf>,
stderr: Option<ZeroCopyBuf>,
}
fn create_command(
state: &mut OpState,
args: CommandArgs,
) -> Result<std::process::Command, AnyError> {
super::check_unstable(state, "Deno.spawn");
state.borrow_mut::<Permissions>().run.check(&args.cmd)?;
let mut command = std::process::Command::new(args.cmd);
command.args(args.args);
if let Some(cwd) = args.cwd {
command.current_dir(cwd);
}
if args.clear_env {
command.env_clear();
}
command.envs(args.env);
#[cfg(unix)]
if let Some(gid) = args.gid {
super::check_unstable(state, "Deno.Command.gid");
command.gid(gid);
}
#[cfg(unix)]
if let Some(uid) = args.uid {
super::check_unstable(state, "Deno.Command.uid");
command.uid(uid);
}
#[cfg(unix)]
unsafe {
command.pre_exec(|| {
libc::setgroups(0, std::ptr::null());
Ok(())
});
}
command.stdin(subprocess_stdio_map(&args.stdio.stdin)?);
command.stdout(subprocess_stdio_map(&args.stdio.stdout)?);
command.stderr(subprocess_stdio_map(&args.stdio.stderr)?);
Ok(command)
}
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
struct Child {
rid: ResourceId,
pid: u32,
stdin_rid: Option<ResourceId>,
stdout_rid: Option<ResourceId>,
stderr_rid: Option<ResourceId>,
}
#[op]
fn op_command_spawn(
state: &mut OpState,
args: CommandArgs,
) -> Result<Child, AnyError> {
let mut command = tokio::process::Command::from(create_command(state, args)?);
// TODO(@crowlkats): allow detaching processes.
// currently deno will orphan a process when exiting with an error or Deno.exit()
// We want to kill child when it's closed
command.kill_on_drop(true);
let mut child = command.spawn()?;
let pid = child.id().expect("Process ID should be set.");
let stdin_rid = child
.stdin
.take()
.map(|stdin| state.resource_table.add(ChildStdinResource::from(stdin)));
let stdout_rid = child
.stdout
.take()
.map(|stdout| state.resource_table.add(ChildStdoutResource::from(stdout)));
let stderr_rid = child
.stderr
.take()
.map(|stderr| state.resource_table.add(ChildStderrResource::from(stderr)));
let child_rid = state
.resource_table
.add(ChildResource(AsyncRefCell::new(child)));
Ok(Child {
rid: child_rid,
pid,
stdin_rid,
stdout_rid,
stderr_rid,
})
}
#[op]
async fn op_command_wait(
state: Rc<RefCell<OpState>>,
rid: ResourceId,
) -> Result<CommandStatus, AnyError> {
let resource = state
.borrow_mut()
.resource_table
.take::<ChildResource>(rid)?;
let mut child = RcRef::map(resource, |r| &r.0).borrow_mut().await;
Ok(child.wait().await?.into())
}
#[op]
fn op_command_sync(
state: &mut OpState,
args: CommandArgs,
) -> Result<CommandOutput, AnyError> {
let stdout = matches!(args.stdio.stdout, Stdio::Piped);
let stderr = matches!(args.stdio.stderr, Stdio::Piped);
let output = create_command(state, args)?.output()?;
Ok(CommandOutput {
status: output.status.into(),
stdout: if stdout {
Some(output.stdout.into())
} else {
None
},
stderr: if stderr {
Some(output.stderr.into())
} else {
None
},
})
}