2024-01-01 14:58:21 -05:00
|
|
|
// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
|
2020-09-05 20:34:02 -04:00
|
|
|
|
2023-09-11 18:10:43 -04:00
|
|
|
use deno_core::op2;
|
2022-04-26 09:26:05 -04:00
|
|
|
use deno_core::serde_json;
|
2020-12-16 11:14:12 -05:00
|
|
|
use deno_core::AsyncMutFuture;
|
|
|
|
use deno_core::AsyncRefCell;
|
2020-09-10 09:57:45 -04:00
|
|
|
use deno_core::OpState;
|
2020-12-16 11:14:12 -05:00
|
|
|
use deno_core::RcRef;
|
|
|
|
use deno_core::Resource;
|
2021-03-19 13:25:37 -04:00
|
|
|
use deno_core::ResourceId;
|
2023-06-22 17:37:56 -04:00
|
|
|
use deno_core::ToJsBuffer;
|
2023-05-04 14:28:42 -04:00
|
|
|
use deno_io::fs::FileResource;
|
2023-03-05 07:19:34 -05:00
|
|
|
use deno_io::ChildStderrResource;
|
|
|
|
use deno_io::ChildStdinResource;
|
|
|
|
use deno_io::ChildStdoutResource;
|
2024-09-27 15:35:37 -04:00
|
|
|
use deno_io::IntoRawIoHandle;
|
2024-06-06 23:37:53 -04:00
|
|
|
use deno_permissions::PermissionsContainer;
|
2024-09-16 16:39:37 -04:00
|
|
|
use deno_permissions::RunQueryDescriptor;
|
2020-09-16 12:43:08 -04:00
|
|
|
use serde::Deserialize;
|
2021-04-05 12:40:24 -04:00
|
|
|
use serde::Serialize;
|
2020-12-16 11:14:12 -05:00
|
|
|
use std::borrow::Cow;
|
2020-09-10 09:57:45 -04:00
|
|
|
use std::cell::RefCell;
|
2024-09-04 08:51:24 -04:00
|
|
|
use std::collections::HashMap;
|
2024-09-16 16:39:37 -04:00
|
|
|
use std::ffi::OsString;
|
2024-09-27 15:35:37 -04:00
|
|
|
use std::io::Write;
|
2024-09-04 08:51:24 -04:00
|
|
|
use std::path::Path;
|
|
|
|
use std::path::PathBuf;
|
2023-03-05 07:19:34 -05:00
|
|
|
use std::process::ExitStatus;
|
2020-08-18 12:30:13 -04:00
|
|
|
use std::rc::Rc;
|
2019-12-30 08:57:17 -05:00
|
|
|
use tokio::process::Command;
|
2019-08-14 11:03:02 -04:00
|
|
|
|
2023-03-05 07:19:34 -05:00
|
|
|
#[cfg(windows)]
|
|
|
|
use std::os::windows::process::CommandExt;
|
2019-08-14 11:03:02 -04:00
|
|
|
|
2024-10-22 04:41:08 -04:00
|
|
|
use crate::ops::signal::SignalError;
|
2023-03-05 07:19:34 -05:00
|
|
|
#[cfg(unix)]
|
|
|
|
use std::os::unix::prelude::ExitStatusExt;
|
|
|
|
#[cfg(unix)]
|
|
|
|
use std::os::unix::process::CommandExt;
|
2019-10-11 14:41:54 -04:00
|
|
|
|
2023-10-12 11:55:50 -04:00
|
|
|
pub const UNSTABLE_FEATURE_NAME: &str = "process";
|
|
|
|
|
2022-09-19 04:25:03 -04:00
|
|
|
#[derive(Copy, Clone, Eq, PartialEq, Deserialize)]
|
2024-06-07 13:21:32 -04:00
|
|
|
#[serde(rename_all = "snake_case")]
|
2022-04-26 09:26:05 -04:00
|
|
|
pub enum Stdio {
|
|
|
|
Inherit,
|
|
|
|
Piped,
|
|
|
|
Null,
|
2024-06-07 13:21:32 -04:00
|
|
|
IpcForInternalUse,
|
2022-04-26 09:26:05 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
impl Stdio {
|
|
|
|
pub fn as_stdio(&self) -> std::process::Stdio {
|
|
|
|
match &self {
|
|
|
|
Stdio::Inherit => std::process::Stdio::inherit(),
|
|
|
|
Stdio::Piped => std::process::Stdio::piped(),
|
|
|
|
Stdio::Null => std::process::Stdio::null(),
|
2024-06-07 13:21:32 -04:00
|
|
|
_ => unreachable!(),
|
2022-04-26 09:26:05 -04:00
|
|
|
}
|
|
|
|
}
|
2019-11-14 12:10:25 -05:00
|
|
|
}
|
|
|
|
|
2022-09-19 04:25:03 -04:00
|
|
|
#[derive(Copy, Clone, Eq, PartialEq)]
|
2022-04-26 09:26:05 -04:00
|
|
|
pub enum StdioOrRid {
|
|
|
|
Stdio(Stdio),
|
|
|
|
Rid(ResourceId),
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<'de> Deserialize<'de> for StdioOrRid {
|
|
|
|
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
|
|
|
|
where
|
|
|
|
D: serde::Deserializer<'de>,
|
|
|
|
{
|
|
|
|
use serde_json::Value;
|
|
|
|
let value = Value::deserialize(deserializer)?;
|
|
|
|
match value {
|
|
|
|
Value::String(val) => match val.as_str() {
|
|
|
|
"inherit" => Ok(StdioOrRid::Stdio(Stdio::Inherit)),
|
|
|
|
"piped" => Ok(StdioOrRid::Stdio(Stdio::Piped)),
|
|
|
|
"null" => Ok(StdioOrRid::Stdio(Stdio::Null)),
|
2024-06-07 13:21:32 -04:00
|
|
|
"ipc_for_internal_use" => {
|
|
|
|
Ok(StdioOrRid::Stdio(Stdio::IpcForInternalUse))
|
|
|
|
}
|
2022-04-26 09:26:05 -04:00
|
|
|
val => Err(serde::de::Error::unknown_variant(
|
|
|
|
val,
|
|
|
|
&["inherit", "piped", "null"],
|
|
|
|
)),
|
|
|
|
},
|
|
|
|
Value::Number(val) => match val.as_u64() {
|
|
|
|
Some(val) if val <= ResourceId::MAX as u64 => {
|
|
|
|
Ok(StdioOrRid::Rid(val as ResourceId))
|
|
|
|
}
|
|
|
|
_ => Err(serde::de::Error::custom("Expected a positive integer")),
|
|
|
|
},
|
|
|
|
_ => Err(serde::de::Error::custom(
|
|
|
|
r#"Expected a resource id, "inherit", "piped", or "null""#,
|
|
|
|
)),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl StdioOrRid {
|
|
|
|
pub fn as_stdio(
|
|
|
|
&self,
|
|
|
|
state: &mut OpState,
|
2024-10-22 04:41:08 -04:00
|
|
|
) -> Result<std::process::Stdio, ProcessError> {
|
2022-04-26 09:26:05 -04:00
|
|
|
match &self {
|
|
|
|
StdioOrRid::Stdio(val) => Ok(val.as_stdio()),
|
2023-05-04 14:28:42 -04:00
|
|
|
StdioOrRid::Rid(rid) => {
|
|
|
|
FileResource::with_file(state, *rid, |file| Ok(file.as_stdio()?))
|
2024-10-22 04:41:08 -04:00
|
|
|
.map_err(ProcessError::Resource)
|
2023-05-04 14:28:42 -04:00
|
|
|
}
|
2022-04-26 09:26:05 -04:00
|
|
|
}
|
2019-08-14 11:03:02 -04:00
|
|
|
}
|
2024-06-07 13:21:32 -04:00
|
|
|
|
|
|
|
pub fn is_ipc(&self) -> bool {
|
|
|
|
matches!(self, StdioOrRid::Stdio(Stdio::IpcForInternalUse))
|
|
|
|
}
|
2019-08-14 11:03:02 -04:00
|
|
|
}
|
|
|
|
|
2024-09-27 15:35:37 -04:00
|
|
|
#[allow(clippy::disallowed_types)]
|
|
|
|
pub type NpmProcessStateProviderRc =
|
|
|
|
deno_fs::sync::MaybeArc<dyn NpmProcessStateProvider>;
|
|
|
|
|
|
|
|
pub trait NpmProcessStateProvider:
|
|
|
|
std::fmt::Debug + deno_fs::sync::MaybeSend + deno_fs::sync::MaybeSync
|
|
|
|
{
|
|
|
|
/// Gets a string containing the serialized npm state of the process.
|
|
|
|
///
|
|
|
|
/// This will be set on the `DENO_DONT_USE_INTERNAL_NODE_COMPAT_STATE` environment
|
|
|
|
/// variable when doing a `child_process.fork`. The implementor can then check this environment
|
|
|
|
/// variable on startup to repopulate the internal npm state.
|
|
|
|
fn get_npm_process_state(&self) -> String {
|
|
|
|
// This method is only used in the CLI.
|
|
|
|
String::new()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[derive(Debug)]
|
|
|
|
pub struct EmptyNpmProcessStateProvider;
|
|
|
|
impl NpmProcessStateProvider for EmptyNpmProcessStateProvider {}
|
2023-03-17 14:22:15 -04:00
|
|
|
deno_core::extension!(
|
|
|
|
deno_process,
|
|
|
|
ops = [
|
|
|
|
op_spawn_child,
|
|
|
|
op_spawn_wait,
|
|
|
|
op_spawn_sync,
|
2023-05-11 08:53:45 -04:00
|
|
|
op_spawn_kill,
|
2023-03-17 14:22:15 -04:00
|
|
|
deprecated::op_run,
|
|
|
|
deprecated::op_run_status,
|
|
|
|
deprecated::op_kill,
|
2023-03-18 18:30:04 -04:00
|
|
|
],
|
2024-09-27 15:35:37 -04:00
|
|
|
options = { get_npm_process_state: Option<NpmProcessStateProviderRc> },
|
|
|
|
state = |state, options| {
|
|
|
|
state.put::<NpmProcessStateProviderRc>(options.get_npm_process_state.unwrap_or(deno_fs::sync::MaybeArc::new(EmptyNpmProcessStateProvider)));
|
|
|
|
},
|
2023-03-17 14:22:15 -04:00
|
|
|
);
|
2023-03-05 07:19:34 -05:00
|
|
|
|
2023-05-11 08:53:45 -04:00
|
|
|
/// Second member stores the pid separately from the RefCell. It's needed for
|
|
|
|
/// `op_spawn_kill`, where the RefCell is borrowed mutably by `op_spawn_wait`.
|
|
|
|
struct ChildResource(RefCell<tokio::process::Child>, u32);
|
2023-03-05 07:19:34 -05:00
|
|
|
|
|
|
|
impl Resource for ChildResource {
|
|
|
|
fn name(&self) -> Cow<str> {
|
|
|
|
"child".into()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-08-26 08:50:21 -04:00
|
|
|
#[derive(Deserialize)]
|
|
|
|
#[serde(rename_all = "camelCase")]
|
2023-03-05 07:19:34 -05:00
|
|
|
pub struct SpawnArgs {
|
|
|
|
cmd: String,
|
|
|
|
args: Vec<String>,
|
2019-08-26 08:50:21 -04:00
|
|
|
cwd: Option<String>,
|
2021-08-04 15:47:43 -04:00
|
|
|
clear_env: bool,
|
2019-08-26 08:50:21 -04:00
|
|
|
env: Vec<(String, String)>,
|
2021-09-14 15:38:35 -04:00
|
|
|
#[cfg(unix)]
|
2021-09-13 13:26:23 -04:00
|
|
|
gid: Option<u32>,
|
2021-09-14 15:38:35 -04:00
|
|
|
#[cfg(unix)]
|
2021-09-13 13:26:23 -04:00
|
|
|
uid: Option<u32>,
|
2023-03-05 07:19:34 -05:00
|
|
|
#[cfg(windows)]
|
|
|
|
windows_raw_arguments: bool,
|
2023-12-13 05:14:16 -05:00
|
|
|
ipc: Option<i32>,
|
2023-03-05 07:19:34 -05:00
|
|
|
|
|
|
|
#[serde(flatten)]
|
|
|
|
stdio: ChildStdio,
|
2024-08-15 12:38:46 -04:00
|
|
|
|
|
|
|
extra_stdio: Vec<Stdio>,
|
2024-09-12 15:24:58 -04:00
|
|
|
detached: bool,
|
2024-09-27 15:35:37 -04:00
|
|
|
needs_npm_process_state: bool,
|
2019-08-26 08:50:21 -04:00
|
|
|
}
|
|
|
|
|
2024-10-22 04:41:08 -04:00
|
|
|
#[derive(Debug, thiserror::Error)]
|
|
|
|
pub enum ProcessError {
|
|
|
|
#[error("Failed to spawn '{command}': {error}")]
|
|
|
|
SpawnFailed {
|
|
|
|
command: String,
|
|
|
|
#[source]
|
|
|
|
error: Box<ProcessError>,
|
|
|
|
},
|
|
|
|
#[error("{0}")]
|
|
|
|
Io(#[from] std::io::Error),
|
|
|
|
#[cfg(unix)]
|
|
|
|
#[error(transparent)]
|
|
|
|
Nix(nix::Error),
|
|
|
|
#[error("failed resolving cwd: {0}")]
|
|
|
|
FailedResolvingCwd(#[source] std::io::Error),
|
|
|
|
#[error(transparent)]
|
2024-11-04 12:17:21 -05:00
|
|
|
Permission(#[from] deno_permissions::PermissionCheckError),
|
|
|
|
#[error(transparent)]
|
|
|
|
RunPermission(#[from] CheckRunPermissionError),
|
2024-10-22 04:41:08 -04:00
|
|
|
#[error(transparent)]
|
|
|
|
Resource(deno_core::error::AnyError),
|
|
|
|
#[error(transparent)]
|
|
|
|
BorrowMut(std::cell::BorrowMutError),
|
|
|
|
#[error(transparent)]
|
|
|
|
Which(which::Error),
|
|
|
|
#[error("Child process has already terminated.")]
|
|
|
|
ChildProcessAlreadyTerminated,
|
|
|
|
#[error("Invalid pid")]
|
|
|
|
InvalidPid,
|
|
|
|
#[error(transparent)]
|
|
|
|
Signal(#[from] SignalError),
|
|
|
|
#[error("Missing cmd")]
|
|
|
|
MissingCmd, // only for Deno.run
|
|
|
|
}
|
|
|
|
|
2023-03-05 07:19:34 -05:00
|
|
|
#[derive(Deserialize)]
|
|
|
|
#[serde(rename_all = "camelCase")]
|
|
|
|
pub struct ChildStdio {
|
2024-06-07 13:21:32 -04:00
|
|
|
stdin: StdioOrRid,
|
|
|
|
stdout: StdioOrRid,
|
|
|
|
stderr: StdioOrRid,
|
2020-12-16 11:14:12 -05:00
|
|
|
}
|
|
|
|
|
2023-03-05 07:19:34 -05:00
|
|
|
#[derive(Serialize)]
|
|
|
|
#[serde(rename_all = "camelCase")]
|
|
|
|
pub struct ChildStatus {
|
|
|
|
success: bool,
|
|
|
|
code: i32,
|
|
|
|
signal: Option<String>,
|
2020-12-16 11:14:12 -05:00
|
|
|
}
|
|
|
|
|
2023-03-05 07:19:34 -05:00
|
|
|
impl TryFrom<ExitStatus> for ChildStatus {
|
2024-10-22 04:41:08 -04:00
|
|
|
type Error = SignalError;
|
2023-03-05 07:19:34 -05:00
|
|
|
|
|
|
|
fn try_from(status: ExitStatus) -> Result<Self, Self::Error> {
|
|
|
|
let code = status.code();
|
|
|
|
#[cfg(unix)]
|
|
|
|
let signal = status.signal();
|
|
|
|
#[cfg(not(unix))]
|
|
|
|
let signal: Option<i32> = None;
|
|
|
|
|
|
|
|
let status = if let Some(signal) = signal {
|
|
|
|
ChildStatus {
|
|
|
|
success: false,
|
|
|
|
code: 128 + signal,
|
|
|
|
#[cfg(unix)]
|
2024-11-29 17:36:43 -05:00
|
|
|
signal: Some(crate::signal::signal_int_to_str(signal)?.to_string()),
|
2023-03-05 07:19:34 -05:00
|
|
|
#[cfg(not(unix))]
|
|
|
|
signal: None,
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
let code = code.expect("Should have either an exit code or a signal.");
|
|
|
|
|
|
|
|
ChildStatus {
|
|
|
|
success: code == 0,
|
|
|
|
code,
|
|
|
|
signal: None,
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
Ok(status)
|
2020-12-16 11:14:12 -05:00
|
|
|
}
|
2019-11-07 18:52:21 -05:00
|
|
|
}
|
|
|
|
|
2021-04-05 12:40:24 -04:00
|
|
|
#[derive(Serialize)]
|
|
|
|
#[serde(rename_all = "camelCase")]
|
2023-03-05 07:19:34 -05:00
|
|
|
pub struct SpawnOutput {
|
|
|
|
status: ChildStatus,
|
2023-06-22 17:37:56 -04:00
|
|
|
stdout: Option<ToJsBuffer>,
|
|
|
|
stderr: Option<ToJsBuffer>,
|
2021-04-05 12:40:24 -04:00
|
|
|
}
|
|
|
|
|
2024-08-15 12:38:46 -04:00
|
|
|
type CreateCommand = (
|
|
|
|
std::process::Command,
|
|
|
|
Option<ResourceId>,
|
|
|
|
Vec<Option<ResourceId>>,
|
|
|
|
Vec<deno_io::RawBiPipeHandle>,
|
|
|
|
);
|
2023-12-13 05:14:16 -05:00
|
|
|
|
2024-09-27 15:35:37 -04:00
|
|
|
pub fn npm_process_state_tempfile(
|
|
|
|
contents: &[u8],
|
2024-10-22 04:41:08 -04:00
|
|
|
) -> Result<deno_io::RawIoHandle, std::io::Error> {
|
2024-09-27 15:35:37 -04:00
|
|
|
let mut temp_file = tempfile::tempfile()?;
|
|
|
|
temp_file.write_all(contents)?;
|
|
|
|
let handle = temp_file.into_raw_io_handle();
|
|
|
|
#[cfg(windows)]
|
|
|
|
{
|
|
|
|
use windows_sys::Win32::Foundation::HANDLE_FLAG_INHERIT;
|
|
|
|
// make the handle inheritable
|
|
|
|
// SAFETY: winapi call, handle is valid
|
|
|
|
unsafe {
|
|
|
|
windows_sys::Win32::Foundation::SetHandleInformation(
|
|
|
|
handle as _,
|
|
|
|
HANDLE_FLAG_INHERIT,
|
|
|
|
HANDLE_FLAG_INHERIT,
|
|
|
|
);
|
|
|
|
}
|
|
|
|
Ok(handle)
|
|
|
|
}
|
|
|
|
#[cfg(unix)]
|
|
|
|
{
|
|
|
|
// SAFETY: libc call, fd is valid
|
|
|
|
let inheritable = unsafe {
|
|
|
|
// duplicate the FD to get a new one that doesn't have the CLOEXEC flag set
|
|
|
|
// so it can be inherited by the child process
|
|
|
|
libc::dup(handle)
|
|
|
|
};
|
|
|
|
// SAFETY: libc call, fd is valid
|
|
|
|
unsafe {
|
|
|
|
// close the old one
|
|
|
|
libc::close(handle);
|
|
|
|
}
|
|
|
|
Ok(inheritable)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
pub const NPM_RESOLUTION_STATE_FD_ENV_VAR_NAME: &str =
|
|
|
|
"DENO_DONT_USE_INTERNAL_NODE_COMPAT_STATE_FD";
|
|
|
|
|
2023-03-05 07:19:34 -05:00
|
|
|
fn create_command(
|
|
|
|
state: &mut OpState,
|
2024-06-07 13:21:32 -04:00
|
|
|
mut args: SpawnArgs,
|
2023-03-05 07:19:34 -05:00
|
|
|
api_name: &str,
|
2024-10-22 04:41:08 -04:00
|
|
|
) -> Result<CreateCommand, ProcessError> {
|
2024-09-27 15:35:37 -04:00
|
|
|
let maybe_npm_process_state = if args.needs_npm_process_state {
|
|
|
|
let provider = state.borrow::<NpmProcessStateProviderRc>();
|
|
|
|
let process_state = provider.get_npm_process_state();
|
|
|
|
let fd = npm_process_state_tempfile(process_state.as_bytes())?;
|
|
|
|
args.env.push((
|
|
|
|
NPM_RESOLUTION_STATE_FD_ENV_VAR_NAME.to_string(),
|
|
|
|
(fd as usize).to_string(),
|
|
|
|
));
|
|
|
|
Some(fd)
|
|
|
|
} else {
|
|
|
|
None
|
|
|
|
};
|
|
|
|
|
2024-09-04 08:51:24 -04:00
|
|
|
let (cmd, run_env) = compute_run_cmd_and_check_permissions(
|
|
|
|
&args.cmd,
|
|
|
|
args.cwd.as_deref(),
|
|
|
|
&args.env,
|
|
|
|
args.clear_env,
|
|
|
|
state,
|
|
|
|
api_name,
|
|
|
|
)?;
|
|
|
|
let mut command = std::process::Command::new(cmd);
|
2023-03-05 07:19:34 -05:00
|
|
|
|
|
|
|
#[cfg(windows)]
|
2024-09-12 15:24:58 -04:00
|
|
|
{
|
|
|
|
if args.detached {
|
|
|
|
// TODO(nathanwhit): Currently this causes the process to hang
|
|
|
|
// until the detached process exits (so never). It repros with just the
|
|
|
|
// rust std library, so it's either a bug or requires more control than we have.
|
|
|
|
// To be resolved at the same time as additional stdio support.
|
|
|
|
log::warn!("detached processes are not currently supported on Windows");
|
|
|
|
}
|
|
|
|
if args.windows_raw_arguments {
|
|
|
|
for arg in args.args.iter() {
|
|
|
|
command.raw_arg(arg);
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
command.args(args.args);
|
2023-03-05 07:19:34 -05:00
|
|
|
}
|
|
|
|
}
|
2021-08-04 15:47:43 -04:00
|
|
|
|
2023-03-05 07:19:34 -05:00
|
|
|
#[cfg(not(windows))]
|
|
|
|
command.args(args.args);
|
|
|
|
|
2024-09-04 08:51:24 -04:00
|
|
|
command.current_dir(run_env.cwd);
|
|
|
|
command.env_clear();
|
|
|
|
command.envs(run_env.envs);
|
2019-08-14 11:03:02 -04:00
|
|
|
|
2021-09-13 13:26:23 -04:00
|
|
|
#[cfg(unix)]
|
2023-03-05 07:19:34 -05:00
|
|
|
if let Some(gid) = args.gid {
|
|
|
|
command.gid(gid);
|
2021-09-13 13:26:23 -04:00
|
|
|
}
|
|
|
|
#[cfg(unix)]
|
2023-03-05 07:19:34 -05:00
|
|
|
if let Some(uid) = args.uid {
|
|
|
|
command.uid(uid);
|
2021-09-13 13:26:23 -04:00
|
|
|
}
|
|
|
|
|
2024-06-07 13:21:32 -04:00
|
|
|
if args.stdio.stdin.is_ipc() {
|
|
|
|
args.ipc = Some(0);
|
|
|
|
} else {
|
|
|
|
command.stdin(args.stdio.stdin.as_stdio(state)?);
|
|
|
|
}
|
|
|
|
|
2023-03-05 07:19:34 -05:00
|
|
|
command.stdout(match args.stdio.stdout {
|
2024-06-07 13:21:32 -04:00
|
|
|
StdioOrRid::Stdio(Stdio::Inherit) => StdioOrRid::Rid(1).as_stdio(state)?,
|
|
|
|
value => value.as_stdio(state)?,
|
2023-03-05 07:19:34 -05:00
|
|
|
});
|
|
|
|
command.stderr(match args.stdio.stderr {
|
2024-06-07 13:21:32 -04:00
|
|
|
StdioOrRid::Stdio(Stdio::Inherit) => StdioOrRid::Rid(2).as_stdio(state)?,
|
|
|
|
value => value.as_stdio(state)?,
|
2023-03-05 07:19:34 -05:00
|
|
|
});
|
|
|
|
|
2023-12-13 05:14:16 -05:00
|
|
|
#[cfg(unix)]
|
|
|
|
// TODO(bartlomieju):
|
|
|
|
#[allow(clippy::undocumented_unsafe_blocks)]
|
|
|
|
unsafe {
|
2024-08-15 12:38:46 -04:00
|
|
|
let mut extra_pipe_rids = Vec::new();
|
|
|
|
let mut fds_to_dup = Vec::new();
|
|
|
|
let mut fds_to_close = Vec::new();
|
|
|
|
let mut ipc_rid = None;
|
2024-09-27 15:35:37 -04:00
|
|
|
if let Some(fd) = maybe_npm_process_state {
|
|
|
|
fds_to_close.push(fd);
|
|
|
|
}
|
2023-12-13 05:14:16 -05:00
|
|
|
if let Some(ipc) = args.ipc {
|
2024-08-15 12:38:46 -04:00
|
|
|
if ipc >= 0 {
|
|
|
|
let (ipc_fd1, ipc_fd2) = deno_io::bi_pipe_pair_raw()?;
|
|
|
|
fds_to_dup.push((ipc_fd2, ipc));
|
|
|
|
fds_to_close.push(ipc_fd2);
|
|
|
|
/* One end returned to parent process (this) */
|
|
|
|
let pipe_rid =
|
|
|
|
state
|
|
|
|
.resource_table
|
|
|
|
.add(deno_node::IpcJsonStreamResource::new(
|
|
|
|
ipc_fd1 as _,
|
|
|
|
deno_node::IpcRefTracker::new(state.external_ops_tracker.clone()),
|
|
|
|
)?);
|
|
|
|
/* The other end passed to child process via NODE_CHANNEL_FD */
|
|
|
|
command.env("NODE_CHANNEL_FD", format!("{}", ipc));
|
|
|
|
ipc_rid = Some(pipe_rid);
|
2023-12-13 05:14:16 -05:00
|
|
|
}
|
2024-08-15 12:38:46 -04:00
|
|
|
}
|
2023-12-13 05:14:16 -05:00
|
|
|
|
2024-08-15 12:38:46 -04:00
|
|
|
for (i, stdio) in args.extra_stdio.into_iter().enumerate() {
|
|
|
|
// index 0 in `extra_stdio` actually refers to fd 3
|
|
|
|
// because we handle stdin,stdout,stderr specially
|
|
|
|
let fd = (i + 3) as i32;
|
|
|
|
// TODO(nathanwhit): handle inherited, but this relies on the parent process having
|
|
|
|
// fds open already. since we don't generally support dealing with raw fds,
|
|
|
|
// we can't properly support this
|
|
|
|
if matches!(stdio, Stdio::Piped) {
|
|
|
|
let (fd1, fd2) = deno_io::bi_pipe_pair_raw()?;
|
|
|
|
fds_to_dup.push((fd2, fd));
|
|
|
|
fds_to_close.push(fd2);
|
|
|
|
let rid = state.resource_table.add(
|
|
|
|
match deno_io::BiPipeResource::from_raw_handle(fd1) {
|
|
|
|
Ok(v) => v,
|
|
|
|
Err(e) => {
|
|
|
|
log::warn!("Failed to open bidirectional pipe for fd {fd}: {e}");
|
|
|
|
extra_pipe_rids.push(None);
|
|
|
|
continue;
|
2023-12-13 05:14:16 -05:00
|
|
|
}
|
2024-08-15 12:38:46 -04:00
|
|
|
},
|
|
|
|
);
|
|
|
|
extra_pipe_rids.push(Some(rid));
|
|
|
|
} else {
|
|
|
|
extra_pipe_rids.push(None);
|
2023-12-13 05:14:16 -05:00
|
|
|
}
|
2024-08-15 12:38:46 -04:00
|
|
|
}
|
2023-12-13 05:14:16 -05:00
|
|
|
|
2024-09-12 15:24:58 -04:00
|
|
|
let detached = args.detached;
|
2024-08-15 12:38:46 -04:00
|
|
|
command.pre_exec(move || {
|
2024-09-12 15:24:58 -04:00
|
|
|
if detached {
|
|
|
|
libc::setsid();
|
|
|
|
}
|
2024-08-15 12:38:46 -04:00
|
|
|
for &(src, dst) in &fds_to_dup {
|
|
|
|
if src >= 0 && dst >= 0 {
|
|
|
|
let _fd = libc::dup2(src, dst);
|
|
|
|
libc::close(src);
|
2023-12-13 05:14:16 -05:00
|
|
|
}
|
2024-08-15 12:38:46 -04:00
|
|
|
}
|
|
|
|
libc::setgroups(0, std::ptr::null());
|
|
|
|
Ok(())
|
|
|
|
});
|
2023-12-13 05:14:16 -05:00
|
|
|
|
2024-08-15 12:38:46 -04:00
|
|
|
Ok((command, ipc_rid, extra_pipe_rids, fds_to_close))
|
2023-12-13 05:14:16 -05:00
|
|
|
}
|
|
|
|
|
2023-12-19 07:37:22 -05:00
|
|
|
#[cfg(windows)]
|
2024-08-15 12:38:46 -04:00
|
|
|
{
|
|
|
|
let mut ipc_rid = None;
|
|
|
|
let mut handles_to_close = Vec::with_capacity(1);
|
2024-09-27 15:35:37 -04:00
|
|
|
if let Some(handle) = maybe_npm_process_state {
|
|
|
|
handles_to_close.push(handle);
|
|
|
|
}
|
2023-12-19 07:37:22 -05:00
|
|
|
if let Some(ipc) = args.ipc {
|
2024-08-15 12:38:46 -04:00
|
|
|
if ipc >= 0 {
|
|
|
|
let (hd1, hd2) = deno_io::bi_pipe_pair_raw()?;
|
2023-12-19 07:37:22 -05:00
|
|
|
|
2024-08-15 12:38:46 -04:00
|
|
|
/* One end returned to parent process (this) */
|
|
|
|
let pipe_rid = Some(state.resource_table.add(
|
|
|
|
deno_node::IpcJsonStreamResource::new(
|
|
|
|
hd1 as i64,
|
|
|
|
deno_node::IpcRefTracker::new(state.external_ops_tracker.clone()),
|
|
|
|
)?,
|
|
|
|
));
|
2023-12-19 07:37:22 -05:00
|
|
|
|
2024-08-15 12:38:46 -04:00
|
|
|
/* The other end passed to child process via NODE_CHANNEL_FD */
|
|
|
|
command.env("NODE_CHANNEL_FD", format!("{}", hd2 as i64));
|
2023-12-19 07:37:22 -05:00
|
|
|
|
2024-08-15 12:38:46 -04:00
|
|
|
handles_to_close.push(hd2);
|
2023-12-19 07:37:22 -05:00
|
|
|
|
2024-08-15 12:38:46 -04:00
|
|
|
ipc_rid = pipe_rid;
|
2023-12-19 07:37:22 -05:00
|
|
|
}
|
2024-08-15 12:38:46 -04:00
|
|
|
}
|
2023-12-19 07:37:22 -05:00
|
|
|
|
2024-08-15 12:38:46 -04:00
|
|
|
if args.extra_stdio.iter().any(|s| matches!(s, Stdio::Piped)) {
|
|
|
|
log::warn!(
|
|
|
|
"Additional stdio pipes beyond stdin/stdout/stderr are not currently supported on windows"
|
|
|
|
);
|
2023-12-19 07:37:22 -05:00
|
|
|
}
|
|
|
|
|
2024-08-15 12:38:46 -04:00
|
|
|
Ok((command, ipc_rid, vec![], handles_to_close))
|
|
|
|
}
|
2023-03-05 07:19:34 -05:00
|
|
|
}
|
2019-08-14 11:03:02 -04:00
|
|
|
|
2023-03-05 07:19:34 -05:00
|
|
|
#[derive(Serialize)]
|
|
|
|
#[serde(rename_all = "camelCase")]
|
|
|
|
struct Child {
|
|
|
|
rid: ResourceId,
|
|
|
|
pid: u32,
|
|
|
|
stdin_rid: Option<ResourceId>,
|
|
|
|
stdout_rid: Option<ResourceId>,
|
|
|
|
stderr_rid: Option<ResourceId>,
|
2024-08-15 12:38:46 -04:00
|
|
|
ipc_pipe_rid: Option<ResourceId>,
|
|
|
|
extra_pipe_rids: Vec<Option<ResourceId>>,
|
2023-03-05 07:19:34 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
fn spawn_child(
|
|
|
|
state: &mut OpState,
|
|
|
|
command: std::process::Command,
|
2024-08-15 12:38:46 -04:00
|
|
|
ipc_pipe_rid: Option<ResourceId>,
|
|
|
|
extra_pipe_rids: Vec<Option<ResourceId>>,
|
2024-09-12 15:24:58 -04:00
|
|
|
detached: bool,
|
2024-10-22 04:41:08 -04:00
|
|
|
) -> Result<Child, ProcessError> {
|
2023-03-05 07:19:34 -05:00
|
|
|
let mut command = tokio::process::Command::from(command);
|
|
|
|
// TODO(@crowlkats): allow detaching processes.
|
|
|
|
// currently deno will orphan a process when exiting with an error or Deno.exit()
|
2019-12-30 08:57:17 -05:00
|
|
|
// We want to kill child when it's closed
|
2024-09-12 15:24:58 -04:00
|
|
|
if !detached {
|
|
|
|
command.kill_on_drop(true);
|
|
|
|
}
|
2023-03-05 07:19:34 -05:00
|
|
|
|
2023-09-18 13:48:54 -04:00
|
|
|
let mut child = match command.spawn() {
|
|
|
|
Ok(child) => child,
|
|
|
|
Err(err) => {
|
|
|
|
let command = command.as_std();
|
|
|
|
let command_name = command.get_program().to_string_lossy();
|
|
|
|
|
|
|
|
if let Some(cwd) = command.get_current_dir() {
|
|
|
|
// launching a sub process always depends on the real
|
|
|
|
// file system so using these methods directly is ok
|
|
|
|
#[allow(clippy::disallowed_methods)]
|
|
|
|
if !cwd.exists() {
|
|
|
|
return Err(
|
|
|
|
std::io::Error::new(
|
|
|
|
std::io::ErrorKind::NotFound,
|
|
|
|
format!(
|
|
|
|
"Failed to spawn '{}': No such cwd '{}'",
|
|
|
|
command_name,
|
|
|
|
cwd.to_string_lossy()
|
|
|
|
),
|
|
|
|
)
|
|
|
|
.into(),
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
|
|
|
#[allow(clippy::disallowed_methods)]
|
|
|
|
if !cwd.is_dir() {
|
|
|
|
return Err(
|
|
|
|
std::io::Error::new(
|
|
|
|
std::io::ErrorKind::NotFound,
|
|
|
|
format!(
|
|
|
|
"Failed to spawn '{}': cwd is not a directory '{}'",
|
|
|
|
command_name,
|
|
|
|
cwd.to_string_lossy()
|
|
|
|
),
|
|
|
|
)
|
|
|
|
.into(),
|
|
|
|
);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-10-22 04:41:08 -04:00
|
|
|
return Err(ProcessError::SpawnFailed {
|
|
|
|
command: command.get_program().to_string_lossy().to_string(),
|
|
|
|
error: Box::new(err.into()),
|
|
|
|
});
|
2023-09-18 13:48:54 -04:00
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2023-03-05 07:19:34 -05:00
|
|
|
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)));
|
2019-11-07 18:52:21 -05:00
|
|
|
|
2023-03-05 07:19:34 -05:00
|
|
|
let stdout_rid = child
|
|
|
|
.stdout
|
|
|
|
.take()
|
|
|
|
.map(|stdout| state.resource_table.add(ChildStdoutResource::from(stdout)));
|
2019-08-14 11:03:02 -04:00
|
|
|
|
2023-03-05 07:19:34 -05:00
|
|
|
let stderr_rid = child
|
|
|
|
.stderr
|
|
|
|
.take()
|
|
|
|
.map(|stderr| state.resource_table.add(ChildStderrResource::from(stderr)));
|
|
|
|
|
2023-05-11 08:53:45 -04:00
|
|
|
let child_rid = state
|
|
|
|
.resource_table
|
|
|
|
.add(ChildResource(RefCell::new(child), pid));
|
2023-03-05 07:19:34 -05:00
|
|
|
|
|
|
|
Ok(Child {
|
2021-04-05 12:40:24 -04:00
|
|
|
rid: child_rid,
|
|
|
|
pid,
|
|
|
|
stdin_rid,
|
|
|
|
stdout_rid,
|
|
|
|
stderr_rid,
|
2024-08-15 12:38:46 -04:00
|
|
|
ipc_pipe_rid,
|
|
|
|
extra_pipe_rids,
|
2021-04-05 12:40:24 -04:00
|
|
|
})
|
2019-08-26 08:50:21 -04:00
|
|
|
}
|
2019-08-24 16:20:48 -04:00
|
|
|
|
2024-09-04 08:51:24 -04:00
|
|
|
fn compute_run_cmd_and_check_permissions(
|
|
|
|
arg_cmd: &str,
|
|
|
|
arg_cwd: Option<&str>,
|
|
|
|
arg_envs: &[(String, String)],
|
|
|
|
arg_clear_env: bool,
|
|
|
|
state: &mut OpState,
|
|
|
|
api_name: &str,
|
2024-10-22 04:41:08 -04:00
|
|
|
) -> Result<(PathBuf, RunEnv), ProcessError> {
|
|
|
|
let run_env =
|
|
|
|
compute_run_env(arg_cwd, arg_envs, arg_clear_env).map_err(|e| {
|
|
|
|
ProcessError::SpawnFailed {
|
|
|
|
command: arg_cmd.to_string(),
|
|
|
|
error: Box::new(e),
|
|
|
|
}
|
|
|
|
})?;
|
|
|
|
let cmd =
|
|
|
|
resolve_cmd(arg_cmd, &run_env).map_err(|e| ProcessError::SpawnFailed {
|
|
|
|
command: arg_cmd.to_string(),
|
|
|
|
error: Box::new(e),
|
|
|
|
})?;
|
2024-09-04 18:57:49 -04:00
|
|
|
check_run_permission(
|
|
|
|
state,
|
2024-09-16 16:39:37 -04:00
|
|
|
&RunQueryDescriptor::Path {
|
|
|
|
requested: arg_cmd.to_string(),
|
|
|
|
resolved: cmd.clone(),
|
2024-09-04 18:57:49 -04:00
|
|
|
},
|
|
|
|
&run_env,
|
|
|
|
api_name,
|
2024-11-04 12:17:21 -05:00
|
|
|
)?;
|
2024-09-04 08:51:24 -04:00
|
|
|
Ok((cmd, run_env))
|
|
|
|
}
|
|
|
|
|
|
|
|
struct RunEnv {
|
2024-09-16 16:39:37 -04:00
|
|
|
envs: HashMap<OsString, OsString>,
|
2024-09-04 08:51:24 -04:00
|
|
|
cwd: PathBuf,
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Computes the current environment, which will then be used to inform
|
|
|
|
/// permissions and finally spawning. This is very important to compute
|
|
|
|
/// ahead of time so that the environment used to verify permissions is
|
|
|
|
/// the same environment used to spawn the sub command. This protects against
|
|
|
|
/// someone doing timing attacks by changing the environment on a worker.
|
|
|
|
fn compute_run_env(
|
|
|
|
arg_cwd: Option<&str>,
|
|
|
|
arg_envs: &[(String, String)],
|
|
|
|
arg_clear_env: bool,
|
2024-10-22 04:41:08 -04:00
|
|
|
) -> Result<RunEnv, ProcessError> {
|
2024-09-04 08:51:24 -04:00
|
|
|
#[allow(clippy::disallowed_methods)]
|
2024-10-22 04:41:08 -04:00
|
|
|
let cwd =
|
|
|
|
std::env::current_dir().map_err(ProcessError::FailedResolvingCwd)?;
|
2024-09-04 08:51:24 -04:00
|
|
|
let cwd = arg_cwd
|
|
|
|
.map(|cwd_arg| resolve_path(cwd_arg, &cwd))
|
|
|
|
.unwrap_or(cwd);
|
|
|
|
let envs = if arg_clear_env {
|
2024-09-16 16:39:37 -04:00
|
|
|
arg_envs
|
|
|
|
.iter()
|
|
|
|
.map(|(k, v)| (OsString::from(k), OsString::from(v)))
|
|
|
|
.collect()
|
2024-09-04 08:51:24 -04:00
|
|
|
} else {
|
2024-09-16 16:39:37 -04:00
|
|
|
let mut envs = std::env::vars_os()
|
|
|
|
.map(|(k, v)| {
|
|
|
|
(
|
|
|
|
if cfg!(windows) {
|
|
|
|
k.to_ascii_uppercase()
|
|
|
|
} else {
|
|
|
|
k
|
|
|
|
},
|
|
|
|
v,
|
|
|
|
)
|
|
|
|
})
|
|
|
|
.collect::<HashMap<_, _>>();
|
2024-09-04 08:51:24 -04:00
|
|
|
for (key, value) in arg_envs {
|
2024-09-16 16:39:37 -04:00
|
|
|
envs.insert(
|
|
|
|
OsString::from(if cfg!(windows) {
|
|
|
|
key.to_ascii_uppercase()
|
|
|
|
} else {
|
|
|
|
key.clone()
|
|
|
|
}),
|
|
|
|
OsString::from(value.clone()),
|
|
|
|
);
|
2024-09-04 08:51:24 -04:00
|
|
|
}
|
|
|
|
envs
|
|
|
|
};
|
|
|
|
Ok(RunEnv { envs, cwd })
|
|
|
|
}
|
|
|
|
|
2024-10-22 04:41:08 -04:00
|
|
|
fn resolve_cmd(cmd: &str, env: &RunEnv) -> Result<PathBuf, ProcessError> {
|
2024-09-04 08:51:24 -04:00
|
|
|
let is_path = cmd.contains('/');
|
|
|
|
#[cfg(windows)]
|
|
|
|
let is_path = is_path || cmd.contains('\\') || Path::new(&cmd).is_absolute();
|
|
|
|
if is_path {
|
|
|
|
Ok(resolve_path(cmd, &env.cwd))
|
|
|
|
} else {
|
2024-09-16 16:39:37 -04:00
|
|
|
let path = env.envs.get(&OsString::from("PATH"));
|
2024-09-04 08:51:24 -04:00
|
|
|
match which::which_in(cmd, path, &env.cwd) {
|
|
|
|
Ok(cmd) => Ok(cmd),
|
|
|
|
Err(which::Error::CannotFindBinaryPath) => {
|
|
|
|
Err(std::io::Error::from(std::io::ErrorKind::NotFound).into())
|
|
|
|
}
|
2024-10-22 04:41:08 -04:00
|
|
|
Err(err) => Err(ProcessError::Which(err)),
|
2024-09-04 08:51:24 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn resolve_path(path: &str, cwd: &Path) -> PathBuf {
|
2024-09-28 07:55:01 -04:00
|
|
|
deno_path_util::normalize_path(cwd.join(path))
|
2024-09-04 08:51:24 -04:00
|
|
|
}
|
|
|
|
|
2024-11-04 12:17:21 -05:00
|
|
|
#[derive(Debug, thiserror::Error)]
|
|
|
|
pub enum CheckRunPermissionError {
|
|
|
|
#[error(transparent)]
|
|
|
|
Permission(#[from] deno_permissions::PermissionCheckError),
|
|
|
|
#[error("{0}")]
|
|
|
|
Other(deno_core::error::AnyError),
|
|
|
|
}
|
|
|
|
|
2024-09-04 08:51:24 -04:00
|
|
|
fn check_run_permission(
|
|
|
|
state: &mut OpState,
|
2024-09-16 16:39:37 -04:00
|
|
|
cmd: &RunQueryDescriptor,
|
2024-09-04 08:51:24 -04:00
|
|
|
run_env: &RunEnv,
|
|
|
|
api_name: &str,
|
2024-11-04 12:17:21 -05:00
|
|
|
) -> Result<(), CheckRunPermissionError> {
|
2024-09-04 08:51:24 -04:00
|
|
|
let permissions = state.borrow_mut::<PermissionsContainer>();
|
|
|
|
if !permissions.query_run_all(api_name) {
|
|
|
|
// error the same on all platforms
|
|
|
|
let env_var_names = get_requires_allow_all_env_vars(run_env);
|
|
|
|
if !env_var_names.is_empty() {
|
|
|
|
// we don't allow users to launch subprocesses with any LD_ or DYLD_*
|
|
|
|
// env vars set because this allows executing code (ex. LD_PRELOAD)
|
2024-11-12 17:14:19 -05:00
|
|
|
return Err(CheckRunPermissionError::Other(
|
|
|
|
deno_core::error::custom_error(
|
|
|
|
"NotCapable",
|
|
|
|
format!(
|
|
|
|
"Requires --allow-run permissions to spawn subprocess with {0} environment variable{1}. Alternatively, spawn with {2} environment variable{1} unset.",
|
|
|
|
env_var_names.join(", "),
|
|
|
|
if env_var_names.len() != 1 { "s" } else { "" },
|
|
|
|
if env_var_names.len() != 1 { "these" } else { "the" }
|
|
|
|
),
|
|
|
|
),
|
|
|
|
));
|
2024-09-04 08:51:24 -04:00
|
|
|
}
|
|
|
|
permissions.check_run(cmd, api_name)?;
|
|
|
|
}
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
|
|
|
fn get_requires_allow_all_env_vars(env: &RunEnv) -> Vec<&str> {
|
|
|
|
fn requires_allow_all(key: &str) -> bool {
|
|
|
|
let key = key.trim();
|
|
|
|
// we could be more targted here, but there are quite a lot of
|
|
|
|
// LD_* and DYLD_* env variables
|
|
|
|
key.starts_with("LD_") || key.starts_with("DYLD_")
|
|
|
|
}
|
|
|
|
|
2024-09-16 16:39:37 -04:00
|
|
|
fn is_empty(value: &OsString) -> bool {
|
|
|
|
value.is_empty()
|
|
|
|
|| value.to_str().map(|v| v.trim().is_empty()).unwrap_or(false)
|
|
|
|
}
|
|
|
|
|
2024-09-04 08:51:24 -04:00
|
|
|
let mut found_envs = env
|
|
|
|
.envs
|
|
|
|
.iter()
|
2024-09-16 16:39:37 -04:00
|
|
|
.filter_map(|(k, v)| {
|
|
|
|
let key = k.to_str()?;
|
|
|
|
if requires_allow_all(key) && !is_empty(v) {
|
|
|
|
Some(key)
|
|
|
|
} else {
|
|
|
|
None
|
|
|
|
}
|
|
|
|
})
|
2024-09-04 08:51:24 -04:00
|
|
|
.collect::<Vec<_>>();
|
|
|
|
found_envs.sort();
|
|
|
|
found_envs
|
|
|
|
}
|
|
|
|
|
2024-11-20 16:24:04 -05:00
|
|
|
#[op2(stack_trace)]
|
2023-09-11 18:10:43 -04:00
|
|
|
#[serde]
|
2023-03-05 07:19:34 -05:00
|
|
|
fn op_spawn_child(
|
|
|
|
state: &mut OpState,
|
2023-09-11 18:10:43 -04:00
|
|
|
#[serde] args: SpawnArgs,
|
|
|
|
#[string] api_name: String,
|
2024-10-22 04:41:08 -04:00
|
|
|
) -> Result<Child, ProcessError> {
|
2024-09-12 15:24:58 -04:00
|
|
|
let detached = args.detached;
|
2024-08-15 12:38:46 -04:00
|
|
|
let (command, pipe_rid, extra_pipe_rids, handles_to_close) =
|
|
|
|
create_command(state, args, &api_name)?;
|
2024-09-12 15:24:58 -04:00
|
|
|
let child = spawn_child(state, command, pipe_rid, extra_pipe_rids, detached);
|
2024-08-15 12:38:46 -04:00
|
|
|
for handle in handles_to_close {
|
2024-09-27 15:35:37 -04:00
|
|
|
deno_io::close_raw_handle(handle);
|
2024-08-15 12:38:46 -04:00
|
|
|
}
|
|
|
|
child
|
2019-08-14 11:03:02 -04:00
|
|
|
}
|
|
|
|
|
2023-09-13 18:01:31 -04:00
|
|
|
#[op2(async)]
|
2023-09-11 19:12:33 -04:00
|
|
|
#[allow(clippy::await_holding_refcell_ref)]
|
2023-09-13 18:01:31 -04:00
|
|
|
#[serde]
|
2023-03-05 07:19:34 -05:00
|
|
|
async fn op_spawn_wait(
|
2020-09-10 09:57:45 -04:00
|
|
|
state: Rc<RefCell<OpState>>,
|
2023-09-13 18:01:31 -04:00
|
|
|
#[smi] rid: ResourceId,
|
2024-10-22 04:41:08 -04:00
|
|
|
) -> Result<ChildStatus, ProcessError> {
|
2020-12-16 11:14:12 -05:00
|
|
|
let resource = state
|
|
|
|
.borrow_mut()
|
|
|
|
.resource_table
|
2024-10-22 04:41:08 -04:00
|
|
|
.get::<ChildResource>(rid)
|
|
|
|
.map_err(ProcessError::Resource)?;
|
|
|
|
let result = resource
|
|
|
|
.0
|
|
|
|
.try_borrow_mut()
|
|
|
|
.map_err(ProcessError::BorrowMut)?
|
|
|
|
.wait()
|
|
|
|
.await?
|
|
|
|
.try_into()?;
|
2023-09-13 18:01:31 -04:00
|
|
|
if let Ok(resource) = state.borrow_mut().resource_table.take_any(rid) {
|
|
|
|
resource.close();
|
|
|
|
}
|
2024-10-22 04:41:08 -04:00
|
|
|
Ok(result)
|
2023-03-05 07:19:34 -05:00
|
|
|
}
|
2020-08-28 11:08:24 -04:00
|
|
|
|
2024-11-20 16:24:04 -05:00
|
|
|
#[op2(stack_trace)]
|
2023-09-11 18:10:43 -04:00
|
|
|
#[serde]
|
2023-03-05 07:19:34 -05:00
|
|
|
fn op_spawn_sync(
|
|
|
|
state: &mut OpState,
|
2023-09-11 18:10:43 -04:00
|
|
|
#[serde] args: SpawnArgs,
|
2024-10-22 04:41:08 -04:00
|
|
|
) -> Result<SpawnOutput, ProcessError> {
|
2024-06-07 13:21:32 -04:00
|
|
|
let stdout = matches!(args.stdio.stdout, StdioOrRid::Stdio(Stdio::Piped));
|
|
|
|
let stderr = matches!(args.stdio.stderr, StdioOrRid::Stdio(Stdio::Piped));
|
2024-08-15 12:38:46 -04:00
|
|
|
let (mut command, _, _, _) =
|
2023-12-13 05:14:16 -05:00
|
|
|
create_command(state, args, "Deno.Command().outputSync()")?;
|
2024-10-22 04:41:08 -04:00
|
|
|
let output = command.output().map_err(|e| ProcessError::SpawnFailed {
|
|
|
|
command: command.get_program().to_string_lossy().to_string(),
|
|
|
|
error: Box::new(e.into()),
|
2023-07-18 19:24:30 -04:00
|
|
|
})?;
|
2023-03-05 07:19:34 -05:00
|
|
|
|
|
|
|
Ok(SpawnOutput {
|
|
|
|
status: output.status.try_into()?,
|
|
|
|
stdout: if stdout {
|
|
|
|
Some(output.stdout.into())
|
|
|
|
} else {
|
|
|
|
None
|
|
|
|
},
|
|
|
|
stderr: if stderr {
|
|
|
|
Some(output.stderr.into())
|
|
|
|
} else {
|
|
|
|
None
|
|
|
|
},
|
2021-04-05 12:40:24 -04:00
|
|
|
})
|
2019-08-26 08:50:21 -04:00
|
|
|
}
|
|
|
|
|
2023-09-11 18:10:43 -04:00
|
|
|
#[op2(fast)]
|
2023-05-11 08:53:45 -04:00
|
|
|
fn op_spawn_kill(
|
|
|
|
state: &mut OpState,
|
2023-09-11 18:10:43 -04:00
|
|
|
#[smi] rid: ResourceId,
|
|
|
|
#[string] signal: String,
|
2024-10-22 04:41:08 -04:00
|
|
|
) -> Result<(), ProcessError> {
|
2023-05-11 08:53:45 -04:00
|
|
|
if let Ok(child_resource) = state.resource_table.get::<ChildResource>(rid) {
|
|
|
|
deprecated::kill(child_resource.1 as i32, &signal)?;
|
|
|
|
return Ok(());
|
|
|
|
}
|
2024-10-22 04:41:08 -04:00
|
|
|
Err(ProcessError::ChildProcessAlreadyTerminated)
|
2023-05-11 08:53:45 -04:00
|
|
|
}
|
|
|
|
|
2023-03-05 07:19:34 -05:00
|
|
|
mod deprecated {
|
|
|
|
use super::*;
|
|
|
|
|
|
|
|
#[derive(Deserialize)]
|
|
|
|
#[serde(rename_all = "camelCase")]
|
|
|
|
pub struct RunArgs {
|
|
|
|
cmd: Vec<String>,
|
|
|
|
cwd: Option<String>,
|
|
|
|
env: Vec<(String, String)>,
|
|
|
|
stdin: StdioOrRid,
|
|
|
|
stdout: StdioOrRid,
|
|
|
|
stderr: StdioOrRid,
|
|
|
|
}
|
2020-12-13 13:45:53 -05:00
|
|
|
|
2023-03-05 07:19:34 -05:00
|
|
|
struct ChildResource {
|
|
|
|
child: AsyncRefCell<tokio::process::Child>,
|
|
|
|
}
|
2022-06-13 16:39:46 -04:00
|
|
|
|
2023-03-05 07:19:34 -05:00
|
|
|
impl Resource for ChildResource {
|
|
|
|
fn name(&self) -> Cow<str> {
|
|
|
|
"child".into()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl ChildResource {
|
|
|
|
fn borrow_mut(self: Rc<Self>) -> AsyncMutFuture<tokio::process::Child> {
|
|
|
|
RcRef::map(self, |r| &r.child).borrow_mut()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[derive(Serialize)]
|
|
|
|
#[serde(rename_all = "camelCase")]
|
|
|
|
// TODO(@AaronO): maybe find a more descriptive name or a convention for return structs
|
2023-09-11 18:10:43 -04:00
|
|
|
pub struct RunInfo {
|
2023-03-05 07:19:34 -05:00
|
|
|
rid: ResourceId,
|
|
|
|
pid: Option<u32>,
|
|
|
|
stdin_rid: Option<ResourceId>,
|
|
|
|
stdout_rid: Option<ResourceId>,
|
|
|
|
stderr_rid: Option<ResourceId>,
|
|
|
|
}
|
|
|
|
|
2024-11-20 16:24:04 -05:00
|
|
|
#[op2(stack_trace)]
|
2023-09-11 18:10:43 -04:00
|
|
|
#[serde]
|
|
|
|
pub fn op_run(
|
2023-03-05 07:19:34 -05:00
|
|
|
state: &mut OpState,
|
2023-09-11 18:10:43 -04:00
|
|
|
#[serde] run_args: RunArgs,
|
2024-10-22 04:41:08 -04:00
|
|
|
) -> Result<RunInfo, ProcessError> {
|
2023-03-05 07:19:34 -05:00
|
|
|
let args = run_args.cmd;
|
2024-10-22 04:41:08 -04:00
|
|
|
let cmd = args.first().ok_or(ProcessError::MissingCmd)?;
|
2024-09-04 08:51:24 -04:00
|
|
|
let (cmd, run_env) = compute_run_cmd_and_check_permissions(
|
|
|
|
cmd,
|
|
|
|
run_args.cwd.as_deref(),
|
|
|
|
&run_args.env,
|
|
|
|
/* clear env */ false,
|
|
|
|
state,
|
|
|
|
"Deno.run()",
|
|
|
|
)?;
|
|
|
|
|
|
|
|
let mut c = Command::new(cmd);
|
|
|
|
for arg in args.iter().skip(1) {
|
2023-03-05 07:19:34 -05:00
|
|
|
c.arg(arg);
|
2024-09-04 08:51:24 -04:00
|
|
|
}
|
|
|
|
c.current_dir(run_env.cwd);
|
2023-03-05 07:19:34 -05:00
|
|
|
|
2024-09-04 08:51:24 -04:00
|
|
|
c.env_clear();
|
|
|
|
for (key, value) in run_env.envs {
|
2023-03-05 07:19:34 -05:00
|
|
|
c.env(key, value);
|
|
|
|
}
|
|
|
|
|
|
|
|
#[cfg(unix)]
|
|
|
|
// TODO(bartlomieju):
|
|
|
|
#[allow(clippy::undocumented_unsafe_blocks)]
|
|
|
|
unsafe {
|
|
|
|
c.pre_exec(|| {
|
|
|
|
libc::setgroups(0, std::ptr::null());
|
|
|
|
Ok(())
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
// TODO: make this work with other resources, eg. sockets
|
|
|
|
c.stdin(run_args.stdin.as_stdio(state)?);
|
|
|
|
c.stdout(
|
|
|
|
match run_args.stdout {
|
|
|
|
StdioOrRid::Stdio(Stdio::Inherit) => StdioOrRid::Rid(1),
|
|
|
|
value => value,
|
|
|
|
}
|
|
|
|
.as_stdio(state)?,
|
|
|
|
);
|
|
|
|
c.stderr(
|
|
|
|
match run_args.stderr {
|
|
|
|
StdioOrRid::Stdio(Stdio::Inherit) => StdioOrRid::Rid(2),
|
|
|
|
value => value,
|
|
|
|
}
|
|
|
|
.as_stdio(state)?,
|
|
|
|
);
|
|
|
|
|
|
|
|
// We want to kill child when it's closed
|
|
|
|
c.kill_on_drop(true);
|
|
|
|
|
|
|
|
// Spawn the command.
|
|
|
|
let mut child = c.spawn()?;
|
|
|
|
let pid = child.id();
|
|
|
|
|
|
|
|
let stdin_rid = match child.stdin.take() {
|
|
|
|
Some(child_stdin) => {
|
|
|
|
let rid = state
|
|
|
|
.resource_table
|
|
|
|
.add(ChildStdinResource::from(child_stdin));
|
|
|
|
Some(rid)
|
|
|
|
}
|
|
|
|
None => None,
|
|
|
|
};
|
|
|
|
|
|
|
|
let stdout_rid = match child.stdout.take() {
|
|
|
|
Some(child_stdout) => {
|
|
|
|
let rid = state
|
|
|
|
.resource_table
|
|
|
|
.add(ChildStdoutResource::from(child_stdout));
|
|
|
|
Some(rid)
|
|
|
|
}
|
|
|
|
None => None,
|
|
|
|
};
|
|
|
|
|
|
|
|
let stderr_rid = match child.stderr.take() {
|
|
|
|
Some(child_stderr) => {
|
|
|
|
let rid = state
|
|
|
|
.resource_table
|
|
|
|
.add(ChildStderrResource::from(child_stderr));
|
|
|
|
Some(rid)
|
|
|
|
}
|
|
|
|
None => None,
|
|
|
|
};
|
|
|
|
|
|
|
|
let child_resource = ChildResource {
|
|
|
|
child: AsyncRefCell::new(child),
|
|
|
|
};
|
|
|
|
let child_rid = state.resource_table.add(child_resource);
|
|
|
|
|
|
|
|
Ok(RunInfo {
|
|
|
|
rid: child_rid,
|
|
|
|
pid,
|
|
|
|
stdin_rid,
|
|
|
|
stdout_rid,
|
|
|
|
stderr_rid,
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
#[derive(Serialize)]
|
|
|
|
#[serde(rename_all = "camelCase")]
|
2023-09-11 18:10:43 -04:00
|
|
|
pub struct ProcessStatus {
|
2023-03-05 07:19:34 -05:00
|
|
|
got_signal: bool,
|
|
|
|
exit_code: i32,
|
|
|
|
exit_signal: i32,
|
|
|
|
}
|
|
|
|
|
2023-09-11 18:10:43 -04:00
|
|
|
#[op2(async)]
|
|
|
|
#[serde]
|
|
|
|
pub async fn op_run_status(
|
2023-03-05 07:19:34 -05:00
|
|
|
state: Rc<RefCell<OpState>>,
|
2023-09-11 18:10:43 -04:00
|
|
|
#[smi] rid: ResourceId,
|
2024-10-22 04:41:08 -04:00
|
|
|
) -> Result<ProcessStatus, ProcessError> {
|
2023-03-05 07:19:34 -05:00
|
|
|
let resource = state
|
|
|
|
.borrow_mut()
|
|
|
|
.resource_table
|
2024-10-22 04:41:08 -04:00
|
|
|
.get::<ChildResource>(rid)
|
|
|
|
.map_err(ProcessError::Resource)?;
|
2023-03-05 07:19:34 -05:00
|
|
|
let mut child = resource.borrow_mut().await;
|
|
|
|
let run_status = child.wait().await?;
|
|
|
|
let code = run_status.code();
|
|
|
|
|
|
|
|
#[cfg(unix)]
|
|
|
|
let signal = run_status.signal();
|
|
|
|
#[cfg(not(unix))]
|
2023-08-27 00:04:12 -04:00
|
|
|
let signal = Default::default();
|
2023-03-05 07:19:34 -05:00
|
|
|
|
|
|
|
code
|
|
|
|
.or(signal)
|
|
|
|
.expect("Should have either an exit code or a signal.");
|
|
|
|
let got_signal = signal.is_some();
|
|
|
|
|
|
|
|
Ok(ProcessStatus {
|
|
|
|
got_signal,
|
|
|
|
exit_code: code.unwrap_or(-1),
|
|
|
|
exit_signal: signal.unwrap_or(-1),
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
#[cfg(unix)]
|
2024-10-22 04:41:08 -04:00
|
|
|
pub fn kill(pid: i32, signal: &str) -> Result<(), ProcessError> {
|
2024-11-29 17:36:43 -05:00
|
|
|
let signo = crate::signal::signal_str_to_int(signal)
|
|
|
|
.map_err(SignalError::InvalidSignalStr)?;
|
2023-03-05 07:19:34 -05:00
|
|
|
use nix::sys::signal::kill as unix_kill;
|
|
|
|
use nix::sys::signal::Signal;
|
|
|
|
use nix::unistd::Pid;
|
2024-10-22 04:41:08 -04:00
|
|
|
let sig = Signal::try_from(signo).map_err(ProcessError::Nix)?;
|
|
|
|
unix_kill(Pid::from_raw(pid), Some(sig)).map_err(ProcessError::Nix)
|
2023-03-05 07:19:34 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
#[cfg(not(unix))]
|
2024-10-22 04:41:08 -04:00
|
|
|
pub fn kill(pid: i32, signal: &str) -> Result<(), ProcessError> {
|
2023-03-05 07:19:34 -05:00
|
|
|
use std::io::Error;
|
|
|
|
use std::io::ErrorKind::NotFound;
|
|
|
|
use winapi::shared::minwindef::DWORD;
|
|
|
|
use winapi::shared::minwindef::FALSE;
|
|
|
|
use winapi::shared::minwindef::TRUE;
|
|
|
|
use winapi::shared::winerror::ERROR_INVALID_PARAMETER;
|
|
|
|
use winapi::um::errhandlingapi::GetLastError;
|
|
|
|
use winapi::um::handleapi::CloseHandle;
|
|
|
|
use winapi::um::processthreadsapi::OpenProcess;
|
|
|
|
use winapi::um::processthreadsapi::TerminateProcess;
|
|
|
|
use winapi::um::winnt::PROCESS_TERMINATE;
|
|
|
|
|
|
|
|
if !matches!(signal, "SIGKILL" | "SIGTERM") {
|
2024-11-29 17:36:43 -05:00
|
|
|
Err(
|
|
|
|
SignalError::InvalidSignalStr(crate::signal::InvalidSignalStrError(
|
|
|
|
signal.to_string(),
|
|
|
|
))
|
|
|
|
.into(),
|
|
|
|
)
|
2023-03-05 07:19:34 -05:00
|
|
|
} else if pid <= 0 {
|
2024-10-22 04:41:08 -04:00
|
|
|
Err(ProcessError::InvalidPid)
|
2021-01-13 23:52:12 -05:00
|
|
|
} else {
|
2023-03-05 07:19:34 -05:00
|
|
|
let handle =
|
2023-03-06 09:16:50 -05:00
|
|
|
// SAFETY: winapi call
|
2023-03-05 07:19:34 -05:00
|
|
|
unsafe { OpenProcess(PROCESS_TERMINATE, FALSE, pid as DWORD) };
|
|
|
|
|
|
|
|
if handle.is_null() {
|
|
|
|
// SAFETY: winapi call
|
|
|
|
let err = match unsafe { GetLastError() } {
|
|
|
|
ERROR_INVALID_PARAMETER => Error::from(NotFound), // Invalid `pid`.
|
|
|
|
errno => Error::from_raw_os_error(errno as i32),
|
|
|
|
};
|
|
|
|
Err(err.into())
|
|
|
|
} else {
|
|
|
|
// SAFETY: winapi calls
|
|
|
|
unsafe {
|
|
|
|
let is_terminated = TerminateProcess(handle, 1);
|
|
|
|
CloseHandle(handle);
|
|
|
|
match is_terminated {
|
|
|
|
FALSE => Err(Error::last_os_error().into()),
|
|
|
|
TRUE => Ok(()),
|
|
|
|
_ => unreachable!(),
|
|
|
|
}
|
2022-07-15 12:30:25 -04:00
|
|
|
}
|
2020-12-13 13:45:53 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-11-20 16:24:04 -05:00
|
|
|
#[op2(fast, stack_trace)]
|
2023-09-11 18:10:43 -04:00
|
|
|
pub fn op_kill(
|
2023-03-05 07:19:34 -05:00
|
|
|
state: &mut OpState,
|
2023-09-11 18:10:43 -04:00
|
|
|
#[smi] pid: i32,
|
|
|
|
#[string] signal: String,
|
|
|
|
#[string] api_name: String,
|
2024-10-22 04:41:08 -04:00
|
|
|
) -> Result<(), ProcessError> {
|
2023-03-05 07:19:34 -05:00
|
|
|
state
|
|
|
|
.borrow_mut::<PermissionsContainer>()
|
2024-11-04 12:17:21 -05:00
|
|
|
.check_run_all(&api_name)?;
|
2024-10-22 04:41:08 -04:00
|
|
|
kill(pid, &signal)
|
2023-03-05 07:19:34 -05:00
|
|
|
}
|
2019-08-14 11:03:02 -04:00
|
|
|
}
|