-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprocess_sub.rs
More file actions
309 lines (272 loc) · 10.4 KB
/
Copy pathprocess_sub.rs
File metadata and controls
309 lines (272 loc) · 10.4 KB
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
// SPDX-License-Identifier: MPL-2.0
// Copyright (c) Jonathan D.A. Jewell <j.d.a.jewell@open.ac.uk>
//! Process Substitution Implementation
//!
//! Implements POSIX-style process substitution for treating command output as files.
//!
//! # Examples
//!
//! ```bash
//! # Input process substitution
//! diff <(ls dir1) <(ls dir2)
//!
//! # Output process substitution
//! tee >(wc -l) >(grep pattern)
//! ```
use anyhow::{anyhow, Result};
use std::path::{Path, PathBuf};
use std::process::{Child, Command as ProcessCommand};
use crate::parser::{parse_command, Command, ProcessSubType};
use crate::state::ShellState;
/// Process substitution instance
pub struct ProcessSubstitution {
/// Path to the FIFO
pub fifo_path: PathBuf,
/// Command being executed
pub command: String,
/// Type (input or output)
pub sub_type: ProcessSubType,
/// Background process handle
pub child_process: Option<Child>,
}
impl ProcessSubstitution {
/// Create new process substitution with FIFO
pub fn create(sub_type: ProcessSubType, cmd: String, state: &mut ShellState) -> Result<Self> {
// Generate globally-unique FIFO path:
// /tmp/vsh-fifo-<pid>-<counter>-<uuidv4>
// The pid + counter make collisions improbable in single-process use;
// the UUID v4 suffix prevents collisions when two ShellState
// instances share a pid (e.g., parallel cargo tests where each test
// creates a fresh state with counter starting at 0).
let pid = std::process::id();
let fifo_id = state.next_fifo_id();
let unique = uuid::Uuid::new_v4().simple();
let fifo_path = PathBuf::from(format!("/tmp/vsh-fifo-{}-{}-{}", pid, fifo_id, unique));
// Create FIFO using mkfifo(2) syscall
#[cfg(unix)]
{
use std::ffi::CString;
let path_str = fifo_path.to_str().ok_or_else(|| {
anyhow!("FIFO path contains invalid UTF-8: {}", fifo_path.display())
})?;
let path_cstr = CString::new(path_str)
.map_err(|_| anyhow!("FIFO path contains null bytes: {}", fifo_path.display()))?;
// SAFETY: path_cstr is a valid NUL-terminated C string; mkfifo is a POSIX syscall
// that creates a FIFO special file at the given path with the specified permissions.
let result = unsafe { libc::mkfifo(path_cstr.as_ptr(), 0o600) };
if result != 0 {
let err = std::io::Error::last_os_error();
// If FIFO already exists, try to remove and recreate
if err.kind() == std::io::ErrorKind::AlreadyExists {
std::fs::remove_file(&fifo_path)?;
// SAFETY: same as above — path_cstr unchanged, mkfifo is safe with valid CString
let result = unsafe { libc::mkfifo(path_cstr.as_ptr(), 0o600) };
if result != 0 {
let err = std::io::Error::last_os_error();
return Err(anyhow!(
"Failed to create FIFO {}: {}",
fifo_path.display(),
err
));
}
} else {
return Err(anyhow!(
"Failed to create FIFO {}: {}",
fifo_path.display(),
err
));
}
}
}
#[cfg(not(unix))]
{
return Err(anyhow!(
"Process substitution requires Unix (FIFOs not supported on Windows)"
));
}
Ok(Self {
fifo_path,
command: cmd,
sub_type,
child_process: None,
})
}
/// Start background process
pub fn start(&mut self, state: &mut ShellState) -> Result<()> {
// Parse command
let parsed_cmd = parse_command(&self.command)?;
// Start background process with appropriate redirection
let child = match self.sub_type {
ProcessSubType::Input => {
// <(cmd): Command writes to FIFO (stdout → FIFO)
start_command_with_output_redirect(&parsed_cmd, state, &self.fifo_path)?
}
ProcessSubType::Output => {
// >(cmd): Command reads from FIFO (FIFO → stdin)
start_command_with_input_redirect(&parsed_cmd, state, &self.fifo_path)?
}
};
self.child_process = Some(child);
Ok(())
}
/// Wait for background process and cleanup
pub fn cleanup(mut self) -> Result<()> {
// Wait for background process to finish
if let Some(mut child) = self.child_process.take() {
let status = child.wait()?;
if !status.success() {
eprintln!(
"Process substitution command failed: {} (exit code: {})",
self.command,
status.code().unwrap_or(-1)
);
}
}
// Remove FIFO (ignore NotFound — another process may have already cleaned it up)
match std::fs::remove_file(&self.fifo_path) {
Ok(()) => {}
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
Err(e) => return Err(e.into()),
}
Ok(())
}
}
/// Safety net: remove FIFO on drop if cleanup() was never called
impl Drop for ProcessSubstitution {
fn drop(&mut self) {
// Kill lingering child process
if let Some(ref mut child) = self.child_process {
let _ = child.kill();
let _ = child.wait();
}
// Remove leaked FIFO (unconditional — ignore NotFound to avoid TOCTOU)
let _ = std::fs::remove_file(&self.fifo_path);
}
}
/// Start command with stdout redirected to file (for <(cmd))
fn start_command_with_output_redirect(
cmd: &Command,
state: &mut ShellState,
output_path: &Path,
) -> Result<Child> {
// For FIFOs, we use shell redirection (sh -c "cmd > fifo") to avoid blocking
// The shell handles the FIFO opening in the background properly
let cmd_string = match cmd {
Command::External { program, args, .. } => {
let expanded_program = crate::parser::expand_with_command_sub(program, state)?;
let expanded_args: Result<Vec<String>> = args
.iter()
.map(|arg| crate::parser::expand_with_command_sub(arg, state))
.collect();
let expanded_args = expanded_args?;
// Build command string: prog arg1 arg2 > fifo
let mut cmd = expanded_program;
for arg in expanded_args {
cmd.push(' ');
// Simple shell escaping (single quotes)
cmd.push_str(&format!("'{}'", arg.replace('\'', "'\\''")));
}
cmd
}
Command::Pwd { .. } => "pwd".to_string(),
Command::Ls { path, .. } => {
let mut cmd = "ls".to_string();
if let Some(p) = path {
let expanded = crate::parser::expand_with_command_sub(p, state)?;
cmd.push_str(&format!(" '{}'", expanded.replace('\'', "'\\''")));
}
cmd
}
_ => {
return Err(anyhow!(
"Command type not supported in process substitution"
))
}
};
// Use sh -c to run: cmd > fifo_path
let shell_cmd = format!("{} > {}", cmd_string, output_path.display());
let child = ProcessCommand::new("sh")
.arg("-c")
.arg(&shell_cmd)
.spawn()?;
Ok(child)
}
/// Start command with stdin redirected from file (for >(cmd))
fn start_command_with_input_redirect(
cmd: &Command,
state: &mut ShellState,
input_path: &Path,
) -> Result<Child> {
// For FIFOs, use shell redirection: sh -c "cmd < fifo"
let cmd_string = match cmd {
Command::External { program, args, .. } => {
let expanded_program = crate::parser::expand_with_command_sub(program, state)?;
let expanded_args: Result<Vec<String>> = args
.iter()
.map(|arg| crate::parser::expand_with_command_sub(arg, state))
.collect();
let expanded_args = expanded_args?;
// Build command string
let mut cmd = expanded_program;
for arg in expanded_args {
cmd.push(' ');
cmd.push_str(&format!("'{}'", arg.replace('\'', "'\\''")));
}
cmd
}
_ => {
return Err(anyhow!(
"Command type not supported for output process substitution"
))
}
};
// Use sh -c to run: cmd < fifo_path
let shell_cmd = format!("{} < {}", cmd_string, input_path.display());
let child = ProcessCommand::new("sh")
.arg("-c")
.arg(&shell_cmd)
.spawn()?;
Ok(child)
}
#[cfg(test)]
mod tests {
use super::*;
use tempfile::TempDir;
#[test]
fn test_fifo_creation() {
let temp_dir = TempDir::new().unwrap();
let mut state = ShellState::new(temp_dir.path().to_str().unwrap()).unwrap();
let proc_sub =
ProcessSubstitution::create(ProcessSubType::Input, "echo test".to_string(), &mut state)
.unwrap();
// FIFO should exist
assert!(proc_sub.fifo_path.exists());
// Should be a FIFO
#[cfg(unix)]
{
let metadata = std::fs::metadata(&proc_sub.fifo_path).unwrap();
use std::os::unix::fs::FileTypeExt;
assert!(metadata.file_type().is_fifo());
}
// Cleanup should remove FIFO
let fifo_path = proc_sub.fifo_path.clone();
proc_sub.cleanup().unwrap();
assert!(!fifo_path.exists());
}
#[test]
fn test_fifo_path_unique() {
let temp_dir = TempDir::new().unwrap();
let mut state = ShellState::new(temp_dir.path().to_str().unwrap()).unwrap();
let proc_sub1 =
ProcessSubstitution::create(ProcessSubType::Input, "echo a".to_string(), &mut state)
.unwrap();
let proc_sub2 =
ProcessSubstitution::create(ProcessSubType::Input, "echo b".to_string(), &mut state)
.unwrap();
// FIFOs should have different paths
assert_ne!(proc_sub1.fifo_path, proc_sub2.fifo_path);
// Cleanup
proc_sub1.cleanup().unwrap();
proc_sub2.cleanup().unwrap();
}
}