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
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
use std::collections::HashMap;
use std::io::{BufRead, BufReader, Write};
use std::path::{Path, PathBuf};
use std::process::{Command as CommandSys, Stdio};
use std::sync::atomic::Ordering;
use std::sync::mpsc;
use nu_engine::env_to_strings;
use nu_protocol::engine::{EngineState, Stack};
use nu_protocol::{ast::Call, engine::Command, ShellError, Signature, SyntaxShape, Value};
use nu_protocol::{Category, Example, ListStream, PipelineData, RawStream, Span, Spanned};
use itertools::Itertools;
use nu_engine::CallExt;
use pathdiff::diff_paths;
use regex::Regex;
const OUTPUT_BUFFER_SIZE: usize = 1024;
const OUTPUT_BUFFERS_IN_FLIGHT: usize = 3;
#[derive(Clone)]
pub struct External;
impl Command for External {
fn name(&self) -> &str {
"run-external"
}
fn usage(&self) -> &str {
"Runs external command"
}
fn signature(&self) -> nu_protocol::Signature {
Signature::build(self.name())
.switch("redirect-stdout", "redirect-stdout", None)
.switch("redirect-stderr", "redirect-stderr", None)
.rest("rest", SyntaxShape::Any, "external command to run")
.category(Category::System)
}
fn run(
&self,
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
input: PipelineData,
) -> Result<PipelineData, ShellError> {
let name: Spanned<String> = call.req(engine_state, stack, 0)?;
let args: Vec<Value> = call.rest(engine_state, stack, 1)?;
let redirect_stdout = call.has_flag("redirect-stdout");
let redirect_stderr = call.has_flag("redirect-stderr");
let env_vars_str = env_to_strings(engine_state, stack)?;
fn value_as_spanned(value: Value) -> Result<Spanned<String>, ShellError> {
let span = value.span()?;
value
.as_string()
.map(|item| Spanned { item, span })
.map_err(|_| {
ShellError::ExternalCommand(
"Cannot convert argument to a string".into(),
"All arguments to an external command need to be string-compatible".into(),
span,
)
})
}
let mut spanned_args = vec![];
for one_arg in args {
match one_arg {
Value::List { vals, .. } => {
for v in vals {
spanned_args.push(value_as_spanned(v)?)
}
}
val => spanned_args.push(value_as_spanned(val)?),
}
}
let command = ExternalCommand {
name,
args: spanned_args,
redirect_stdout,
redirect_stderr,
env_vars: env_vars_str,
};
command.run_with_input(engine_state, stack, input)
}
fn examples(&self) -> Vec<Example> {
vec![Example {
description: "Run an external command",
example: r#"run-external "echo" "-n" "hello""#,
result: None,
}]
}
}
pub struct ExternalCommand {
pub name: Spanned<String>,
pub args: Vec<Spanned<String>>,
pub redirect_stdout: bool,
pub redirect_stderr: bool,
pub env_vars: HashMap<String, String>,
}
impl ExternalCommand {
pub fn run_with_input(
&self,
engine_state: &EngineState,
stack: &mut Stack,
input: PipelineData,
) -> Result<PipelineData, ShellError> {
let head = self.name.span;
let ctrlc = engine_state.ctrlc.clone();
let mut process = self.create_process(&input, false, head)?;
let child;
#[cfg(windows)]
{
match process.spawn() {
Err(_) => {
let mut process = self.create_process(&input, true, head)?;
child = process.spawn();
}
Ok(process) => {
child = Ok(process);
}
}
}
#[cfg(not(windows))]
{
child = process.spawn()
}
match child {
Err(err) => Err(ShellError::ExternalCommand(
"can't run executable".to_string(),
err.to_string(),
self.name.span,
)),
Ok(mut child) => {
if !input.is_nothing() {
let mut engine_state = engine_state.clone();
let mut stack = stack.clone();
engine_state.config.use_ansi_coloring = false;
if let Some(mut stdin_write) = child.stdin.take() {
std::thread::spawn(move || {
let input = crate::Table::run(
&crate::Table,
&engine_state,
&mut stack,
&Call::new(head),
input,
);
if let Ok(input) = input {
for value in input.into_iter() {
let buf = match value {
Value::String { val, .. } => val.into_bytes(),
Value::Binary { val, .. } => val,
_ => return Err(()),
};
if stdin_write.write(&buf).is_err() {
return Ok(());
}
}
}
Ok(())
});
}
}
let redirect_stdout = self.redirect_stdout;
let redirect_stderr = self.redirect_stderr;
let span = self.name.span;
let output_ctrlc = ctrlc.clone();
let (stdout_tx, stdout_rx) = mpsc::sync_channel(OUTPUT_BUFFERS_IN_FLIGHT);
let (stderr_tx, stderr_rx) = mpsc::sync_channel(OUTPUT_BUFFERS_IN_FLIGHT);
let (exit_code_tx, exit_code_rx) = mpsc::channel();
#[cfg(unix)]
let (exit_status_tx, exit_status_rx) = mpsc::channel();
std::thread::spawn(move || {
if redirect_stderr {
let stderr = child.stderr.take().ok_or_else(|| {
ShellError::ExternalCommand(
"Error taking stderr from external".to_string(),
"Redirects need access to stderr of an external command"
.to_string(),
span,
)
})?;
let mut buf_read = BufReader::with_capacity(OUTPUT_BUFFER_SIZE, stderr);
while let Ok(bytes) = buf_read.fill_buf() {
if bytes.is_empty() {
break;
}
let bytes = bytes.to_vec();
let length = bytes.len();
buf_read.consume(length);
if let Some(ctrlc) = &ctrlc {
if ctrlc.load(Ordering::SeqCst) {
break;
}
}
match stderr_tx.send(bytes) {
Ok(_) => continue,
Err(_) => break,
}
}
}
if redirect_stdout {
let stdout = child.stdout.take().ok_or_else(|| {
ShellError::ExternalCommand(
"Error taking stdout from external".to_string(),
"Redirects need access to stdout of an external command"
.to_string(),
span,
)
})?;
let mut buf_read = BufReader::with_capacity(OUTPUT_BUFFER_SIZE, stdout);
while let Ok(bytes) = buf_read.fill_buf() {
if bytes.is_empty() {
break;
}
let bytes = bytes.to_vec();
let length = bytes.len();
buf_read.consume(length);
if let Some(ctrlc) = &ctrlc {
if ctrlc.load(Ordering::SeqCst) {
break;
}
}
match stdout_tx.send(bytes) {
Ok(_) => continue,
Err(_) => break,
}
}
}
match child.wait() {
Err(err) => Err(ShellError::ExternalCommand(
"External command exited with error".into(),
err.to_string(),
span,
)),
Ok(x) => {
#[cfg(unix)]
let _ = exit_status_tx.send(x);
if let Some(code) = x.code() {
let _ = exit_code_tx.send(Value::Int {
val: code as i64,
span: head,
});
} else if x.success() {
let _ = exit_code_tx.send(Value::Int { val: 0, span: head });
} else {
let _ = exit_code_tx.send(Value::Int {
val: -1,
span: head,
});
}
Ok(())
}
}
});
let stdout_receiver = ChannelReceiver::new(stdout_rx);
let stderr_receiver = ChannelReceiver::new(stderr_rx);
let exit_code_receiver = ValueReceiver::new(exit_code_rx);
#[cfg(unix)]
{
use signal_hook::low_level::signal_name;
use std::os::unix::process::ExitStatusExt;
use std::time::Duration;
if let Ok(status) = exit_status_rx.recv_timeout(Duration::from_millis(100)) {
if status.core_dumped() {
if let Some(sig) = status.signal().and_then(signal_name) {
return Err(ShellError::ExternalCommand(
format!("{sig} (core dumped)"),
"Child process core dumped".to_string(),
span,
));
}
}
}
}
Ok(PipelineData::ExternalStream {
stdout: if redirect_stdout {
Some(RawStream::new(
Box::new(stdout_receiver),
output_ctrlc.clone(),
head,
))
} else {
None
},
stderr: Some(RawStream::new(
Box::new(stderr_receiver),
output_ctrlc.clone(),
head,
)),
exit_code: Some(ListStream::from_stream(
Box::new(exit_code_receiver),
output_ctrlc,
)),
span: head,
metadata: None,
})
}
}
}
fn create_process(
&self,
input: &PipelineData,
use_cmd: bool,
span: Span,
) -> Result<CommandSys, ShellError> {
let mut process = if let Some(d) = self.env_vars.get("PWD") {
let mut process = if use_cmd {
self.spawn_cmd_command()
} else {
self.create_command(d)?
};
if Path::new(&d).exists() {
process.current_dir(d);
}
process
} else {
return Err(ShellError::GenericError(
"Current directory not found".to_string(),
"did not find PWD environment variable".to_string(),
Some(span),
Some(concat!(
"The environment variable 'PWD' was not found. ",
"It is required to define the current directory when running an external command."
).to_string()),
Vec::new(),
));
};
process.envs(&self.env_vars);
if self.redirect_stdout {
process.stdout(Stdio::piped());
}
if self.redirect_stderr {
process.stderr(Stdio::piped());
}
if !matches!(input, PipelineData::Value(Value::Nothing { .. }, ..)) {
process.stdin(Stdio::piped());
}
Ok(process)
}
fn create_command(&self, cwd: &str) -> Result<CommandSys, ShellError> {
if cfg!(windows) {
if self.name.item.ends_with(".cmd") || self.name.item.ends_with(".bat") {
Ok(self.spawn_cmd_command())
} else {
self.spawn_simple_command(cwd)
}
} else if self.name.item.ends_with(".sh") {
Ok(self.spawn_sh_command())
} else {
self.spawn_simple_command(cwd)
}
}
pub fn spawn_simple_command(&self, cwd: &str) -> Result<std::process::Command, ShellError> {
let head = trim_enclosing_quotes(&self.name.item);
let head = nu_path::expand_to_real_path(head)
.to_string_lossy()
.to_string();
let mut process = std::process::Command::new(&head);
for arg in self.args.iter() {
let mut arg = Spanned {
item: remove_quotes(trim_enclosing_quotes(&arg.item)),
span: arg.span,
};
arg.item = nu_path::expand_tilde(arg.item)
.to_string_lossy()
.to_string();
let cwd = PathBuf::from(cwd);
if arg.item.contains('*') {
if let Ok((prefix, matches)) =
nu_engine::glob_from(&arg, &cwd, self.name.span, None)
{
let matches: Vec<_> = matches.collect();
if matches.is_empty() {
process.arg(&arg.item);
}
for m in matches {
if let Ok(arg) = m {
let arg = if let Some(prefix) = &prefix {
if let Ok(remainder) = arg.strip_prefix(&prefix) {
let new_prefix = if let Some(pfx) = diff_paths(&prefix, &cwd) {
pfx
} else {
prefix.to_path_buf()
};
new_prefix.join(remainder).to_string_lossy().to_string()
} else {
arg.to_string_lossy().to_string()
}
} else {
arg.to_string_lossy().to_string()
};
process.arg(&arg);
} else {
process.arg(&arg.item);
}
}
}
} else {
process.arg(&arg.item);
}
}
Ok(process)
}
pub fn spawn_cmd_command(&self) -> std::process::Command {
let mut process = std::process::Command::new("cmd");
process.arg("/D");
process.arg("/c");
process.arg(&self.name.item);
for arg in &self.args {
let arg = arg.item.replace('|', "^|");
process.arg(&arg);
}
process
}
pub fn spawn_sh_command(&self) -> std::process::Command {
let joined_and_escaped_arguments = self
.args
.iter()
.map(|arg| shell_arg_escape(&arg.item))
.join(" ");
let cmd_with_args = vec![self.name.item.clone(), joined_and_escaped_arguments].join(" ");
let mut process = std::process::Command::new("sh");
process.arg("-c").arg(cmd_with_args);
process
}
}
fn has_unsafe_shell_characters(arg: &str) -> bool {
let re: Regex = Regex::new(r"[^\w@%+=:,./-]").expect("regex to be valid");
re.is_match(arg)
}
fn shell_arg_escape(arg: &str) -> String {
match arg {
"" => String::from("''"),
s if !has_unsafe_shell_characters(s) => String::from(s),
_ => {
let single_quotes_escaped = arg.split('\'').join("'\"'\"'");
format!("'{}'", single_quotes_escaped)
}
}
}
fn trim_enclosing_quotes(input: &str) -> String {
let mut chars = input.chars();
match (chars.next(), chars.next_back()) {
(Some('"'), Some('"')) => chars.collect(),
(Some('\''), Some('\'')) => chars.collect(),
(Some('`'), Some('`')) => chars.collect(),
_ => input.to_string(),
}
}
fn remove_quotes(input: String) -> String {
let mut chars = input.chars();
match chars.next_back() {
Some('"') => chars
.collect::<String>()
.replacen('"', "", 1)
.replace(r#"\""#, "\""),
Some('\'') => chars.collect::<String>().replacen('\'', "", 1),
_ => input,
}
}
struct ChannelReceiver {
rx: mpsc::Receiver<Vec<u8>>,
}
impl ChannelReceiver {
pub fn new(rx: mpsc::Receiver<Vec<u8>>) -> Self {
Self { rx }
}
}
impl Iterator for ChannelReceiver {
type Item = Result<Vec<u8>, ShellError>;
fn next(&mut self) -> Option<Self::Item> {
match self.rx.recv() {
Ok(v) => Some(Ok(v)),
Err(_) => None,
}
}
}
struct ValueReceiver {
rx: mpsc::Receiver<Value>,
}
impl ValueReceiver {
pub fn new(rx: mpsc::Receiver<Value>) -> Self {
Self { rx }
}
}
impl Iterator for ValueReceiver {
type Item = Value;
fn next(&mut self) -> Option<Self::Item> {
match self.rx.recv() {
Ok(v) => Some(v),
Err(_) => None,
}
}
}