1use nu_cmd_base::hook::eval_hook;
2use nu_engine::{command_prelude::*, env_to_strings};
3use nu_path::{AbsolutePath, dots::expand_ndots_safe, expand_tilde};
4use nu_protocol::{
5 ByteStream, NuGlob, OutDest, Signals, UseAnsiColoring, did_you_mean,
6 process::{ChildProcess, PostWaitCallback},
7 shell_error::io::IoError,
8};
9use nu_system::{ForegroundChild, kill_by_pid};
10use nu_utils::IgnoreCaseExt;
11use pathdiff::diff_paths;
12#[cfg(windows)]
13use std::os::windows::process::CommandExt;
14use std::{
15 borrow::Cow,
16 ffi::{OsStr, OsString},
17 io::Write,
18 path::{Path, PathBuf},
19 process::Stdio,
20 sync::Arc,
21 thread,
22};
23
24#[derive(Clone)]
25pub struct External;
26
27impl Command for External {
28 fn name(&self) -> &str {
29 "run-external"
30 }
31
32 fn description(&self) -> &str {
33 "Runs external command."
34 }
35
36 fn signature(&self) -> nu_protocol::Signature {
37 Signature::build(self.name())
38 .input_output_types(vec![(Type::Any, Type::Any)])
39 .rest(
40 "command",
41 SyntaxShape::OneOf(vec![SyntaxShape::GlobPattern, SyntaxShape::Any]),
42 "External command to run, with arguments.",
43 )
44 .category(Category::System)
45 }
46
47 fn run(
48 &self,
49 engine_state: &EngineState,
50 stack: &mut Stack,
51 call: &Call,
52 input: PipelineData,
53 ) -> Result<PipelineData, ShellError> {
54 let cwd = engine_state.cwd(Some(stack))?;
55 let rest = call.rest::<Value>(engine_state, stack, 0)?;
56 let name_args = rest.split_first().map(|(x, y)| (x, y.to_vec()));
57
58 let Some((name, mut call_args)) = name_args else {
59 return Err(ShellError::MissingParameter {
60 param_name: "no command given".into(),
61 span: call.head,
62 });
63 };
64
65 let name_str: Cow<str> = match &name {
66 Value::Glob { val, .. } => Cow::Borrowed(val),
67 Value::String { val, .. } => Cow::Borrowed(val),
68 Value::List { vals, .. } => {
69 let Some((first, args)) = vals.split_first() else {
70 return Err(ShellError::MissingParameter {
71 param_name: "external command given as list empty".into(),
72 span: call.head,
73 });
74 };
75 call_args.splice(0..0, args.to_vec());
77 first.coerce_str()?
78 }
79 _ => Cow::Owned(name.clone().coerce_into_string()?),
80 };
81
82 let expanded_name = match &name {
83 Value::Glob { no_expand, .. } if !*no_expand => {
85 expand_ndots_safe(expand_tilde(&*name_str))
86 }
87 _ => Path::new(&*name_str).to_owned(),
88 };
89
90 let paths = nu_engine::env::path_str(engine_state, stack, call.head)?;
91
92 let pathext_script_in_windows = if cfg!(windows) {
106 if let Some(executable) = which(&expanded_name, &paths, cwd.as_ref()) {
107 let ext = executable
108 .extension()
109 .unwrap_or_default()
110 .to_string_lossy()
111 .to_uppercase();
112
113 !["COM", "EXE", "BAT", "CMD", "PS1"]
114 .iter()
115 .any(|c| *c == ext)
116 } else {
117 false
118 }
119 } else {
120 false
121 };
122
123 let (potential_powershell_script, path_to_ps1_executable) = if cfg!(windows) {
125 if let Some(executable) = which(&expanded_name, &paths, cwd.as_ref()) {
126 let ext = executable
127 .extension()
128 .unwrap_or_default()
129 .to_string_lossy()
130 .to_uppercase();
131 (ext == "PS1", Some(executable))
132 } else {
133 (false, None)
134 }
135 } else {
136 (false, None)
137 };
138
139 let executable = if cfg!(windows)
143 && (is_cmd_internal_command(&name_str) || pathext_script_in_windows)
144 {
145 PathBuf::from("cmd.exe")
146 } else if cfg!(windows) && potential_powershell_script && path_to_ps1_executable.is_some() {
147 PathBuf::from("powershell.exe")
151 } else {
152 let Some(executable) = which(&expanded_name, &paths, cwd.as_ref()) else {
155 return Err(command_not_found(
156 &name_str,
157 call.head,
158 engine_state,
159 stack,
160 &cwd,
161 ));
162 };
163 executable
164 };
165
166 let mut command = std::process::Command::new(&executable);
168
169 command.current_dir(cwd);
171
172 let envs = env_to_strings(engine_state, stack)?;
174 command.env_clear();
175 command.envs(envs);
176
177 let args = eval_external_arguments(engine_state, stack, call_args)?;
179 #[cfg(windows)]
180 if is_cmd_internal_command(&name_str) || pathext_script_in_windows {
181 command.args(["/D", "/C", &expanded_name.to_string_lossy()]);
185 for arg in &args {
186 command.raw_arg(escape_cmd_argument(arg)?);
187 }
188 } else if potential_powershell_script {
189 command.args([
190 "-File",
191 &path_to_ps1_executable.unwrap_or_default().to_string_lossy(),
192 ]);
193 command.args(args.into_iter().map(|s| s.item));
194 } else {
195 command.args(args.into_iter().map(|s| s.item));
196 }
197 #[cfg(not(windows))]
198 command.args(args.into_iter().map(|s| s.item));
199
200 let stdout = stack.stdout();
203 let stderr = stack.stderr();
204 let merged_stream = if matches!(stdout, OutDest::Pipe) && matches!(stderr, OutDest::Pipe) {
205 let (reader, writer) =
206 os_pipe::pipe().map_err(|err| IoError::new(err, call.head, None))?;
207 command.stdout(
208 writer
209 .try_clone()
210 .map_err(|err| IoError::new(err, call.head, None))?,
211 );
212 command.stderr(writer);
213 Some(reader)
214 } else {
215 if engine_state.is_background_job()
216 && matches!(stdout, OutDest::Inherit | OutDest::Print)
217 {
218 command.stdout(Stdio::null());
219 } else {
220 command.stdout(
221 Stdio::try_from(stdout).map_err(|err| IoError::new(err, call.head, None))?,
222 );
223 }
224
225 if engine_state.is_background_job()
226 && matches!(stderr, OutDest::Inherit | OutDest::Print)
227 {
228 command.stderr(Stdio::null());
229 } else {
230 command.stderr(
231 Stdio::try_from(stderr).map_err(|err| IoError::new(err, call.head, None))?,
232 );
233 }
234
235 None
236 };
237
238 let data_to_copy_into_stdin = match input {
242 PipelineData::ByteStream(stream, metadata) => match stream.into_stdio() {
243 Ok(stdin) => {
244 command.stdin(stdin);
245 None
246 }
247 Err(stream) => {
248 command.stdin(Stdio::piped());
249 Some(PipelineData::ByteStream(stream, metadata))
250 }
251 },
252 PipelineData::Empty => {
253 command.stdin(Stdio::inherit());
254 None
255 }
256 value => {
257 command.stdin(Stdio::piped());
258 Some(value)
259 }
260 };
261
262 log::trace!("run-external spawning: {command:?}");
264
265 #[cfg(windows)]
268 let child = ForegroundChild::spawn(command);
269 #[cfg(unix)]
270 let child = ForegroundChild::spawn(
271 command,
272 engine_state.is_interactive,
273 engine_state.is_background_job(),
274 &engine_state.pipeline_externals_state,
275 );
276
277 let mut child = child.map_err(|err| {
278 IoError::new_internal(
279 err,
280 "Could not spawn foreground child",
281 nu_protocol::location!(),
282 )
283 })?;
284
285 if let Some(thread_job) = engine_state.current_thread_job() {
286 if !thread_job.try_add_pid(child.pid()) {
287 kill_by_pid(child.pid().into()).map_err(|err| {
288 ShellError::Io(IoError::new_internal(
289 err,
290 "Could not spawn external stdin worker",
291 nu_protocol::location!(),
292 ))
293 })?;
294 }
295 }
296
297 if let Some(data) = data_to_copy_into_stdin {
299 let stdin = child.as_mut().stdin.take().expect("stdin is piped");
300 let engine_state = engine_state.clone();
301 let stack = stack.clone();
302 thread::Builder::new()
303 .name("external stdin worker".into())
304 .spawn(move || {
305 let _ = write_pipeline_data(engine_state, stack, data, stdin);
306 })
307 .map_err(|err| {
308 IoError::new_with_additional_context(
309 err,
310 call.head,
311 None,
312 "Could not spawn external stdin worker",
313 )
314 })?;
315 }
316
317 let child_pid = child.pid();
318
319 let mut child = ChildProcess::new(
321 child,
322 merged_stream,
323 matches!(stderr, OutDest::Pipe),
324 call.head,
325 Some(PostWaitCallback::for_job_control(
326 engine_state,
327 Some(child_pid),
328 executable
329 .as_path()
330 .file_name()
331 .and_then(|it| it.to_str())
332 .map(|it| it.to_string()),
333 )),
334 )?;
335
336 if matches!(stdout, OutDest::Pipe | OutDest::PipeSeparate)
337 || matches!(stderr, OutDest::Pipe | OutDest::PipeSeparate)
338 {
339 child.ignore_error(true);
340 }
341
342 Ok(PipelineData::ByteStream(
343 ByteStream::child(child, call.head),
344 None,
345 ))
346 }
347
348 fn examples(&self) -> Vec<Example> {
349 vec![
350 Example {
351 description: "Run an external command",
352 example: r#"run-external "echo" "-n" "hello""#,
353 result: None,
354 },
355 Example {
356 description: "Redirect stdout from an external command into the pipeline",
357 example: r#"run-external "echo" "-n" "hello" | split chars"#,
358 result: None,
359 },
360 Example {
361 description: "Redirect stderr from an external command into the pipeline",
362 example: r#"run-external "nu" "-c" "print -e hello" e>| split chars"#,
363 result: None,
364 },
365 ]
366 }
367}
368
369pub fn eval_external_arguments(
371 engine_state: &EngineState,
372 stack: &mut Stack,
373 call_args: Vec<Value>,
374) -> Result<Vec<Spanned<OsString>>, ShellError> {
375 let cwd = engine_state.cwd(Some(stack))?;
376 let mut args: Vec<Spanned<OsString>> = Vec::with_capacity(call_args.len());
377
378 for arg in call_args {
379 let span = arg.span();
380 match arg {
381 Value::Glob { val, no_expand, .. } if !no_expand => args.extend(
383 expand_glob(
384 &val,
385 cwd.as_std_path(),
386 span,
387 engine_state.signals().clone(),
388 )?
389 .into_iter()
390 .map(|s| s.into_spanned(span)),
391 ),
392 other => args
393 .push(OsString::from(coerce_into_string(engine_state, other)?).into_spanned(span)),
394 }
395 }
396 Ok(args)
397}
398
399fn coerce_into_string(engine_state: &EngineState, val: Value) -> Result<String, ShellError> {
402 match val {
403 Value::List { .. } => Err(ShellError::CannotPassListToExternal {
404 arg: String::from_utf8_lossy(engine_state.get_span_contents(val.span())).into_owned(),
405 span: val.span(),
406 }),
407 Value::Glob { val, .. } => Ok(val),
408 _ => val.coerce_into_string(),
409 }
410}
411
412fn expand_glob(
418 arg: &str,
419 cwd: &Path,
420 span: Span,
421 signals: Signals,
422) -> Result<Vec<OsString>, ShellError> {
423 if !nu_glob::is_glob(arg) {
426 let path = expand_ndots_safe(expand_tilde(arg));
427 return Ok(vec![path.into()]);
428 }
429
430 let glob = NuGlob::Expand(arg.to_owned()).into_spanned(span);
433 if let Ok((prefix, matches)) = nu_engine::glob_from(&glob, cwd, span, None, signals.clone()) {
434 let mut result: Vec<OsString> = vec![];
435
436 for m in matches {
437 signals.check(span)?;
438 if let Ok(arg) = m {
439 let arg = resolve_globbed_path_to_cwd_relative(arg, prefix.as_ref(), cwd);
440 result.push(arg.into());
441 } else {
442 result.push(arg.into());
443 }
444 }
445
446 if result.is_empty() {
449 result.push(arg.into());
450 }
451
452 Ok(result)
453 } else {
454 Ok(vec![arg.into()])
455 }
456}
457
458fn resolve_globbed_path_to_cwd_relative(
459 path: PathBuf,
460 prefix: Option<&PathBuf>,
461 cwd: &Path,
462) -> PathBuf {
463 if let Some(prefix) = prefix {
464 if let Ok(remainder) = path.strip_prefix(prefix) {
465 let new_prefix = if let Some(pfx) = diff_paths(prefix, cwd) {
466 pfx
467 } else {
468 prefix.to_path_buf()
469 };
470 new_prefix.join(remainder)
471 } else {
472 path
473 }
474 } else {
475 path
476 }
477}
478
479fn write_pipeline_data(
487 mut engine_state: EngineState,
488 mut stack: Stack,
489 data: PipelineData,
490 mut writer: impl Write,
491) -> Result<(), ShellError> {
492 if let PipelineData::ByteStream(stream, ..) = data {
493 stream.write_to(writer)?;
494 } else if let PipelineData::Value(Value::Binary { val, .. }, ..) = data {
495 writer.write_all(&val).map_err(|err| {
496 IoError::new_internal(
497 err,
498 "Could not write pipeline data",
499 nu_protocol::location!(),
500 )
501 })?;
502 } else {
503 stack.start_collect_value();
504
505 Arc::make_mut(&mut engine_state.config).use_ansi_coloring = UseAnsiColoring::False;
507
508 let output =
510 crate::Table.run(&engine_state, &mut stack, &Call::new(Span::unknown()), data)?;
511
512 for value in output {
514 let bytes = value.coerce_into_binary()?;
515 writer.write_all(&bytes).map_err(|err| {
516 IoError::new_internal(
517 err,
518 "Could not write pipeline data",
519 nu_protocol::location!(),
520 )
521 })?;
522 }
523 }
524 Ok(())
525}
526
527pub fn command_not_found(
529 name: &str,
530 span: Span,
531 engine_state: &EngineState,
532 stack: &mut Stack,
533 cwd: &AbsolutePath,
534) -> ShellError {
535 if let Some(hook) = &stack.get_config(engine_state).hooks.command_not_found {
537 let mut stack = stack.start_collect_value();
538 let canary = "ENTERED_COMMAND_NOT_FOUND";
541 if stack.has_env_var(engine_state, canary) {
542 return ShellError::ExternalCommand {
543 label: format!(
544 "Command {name} not found while running the `command_not_found` hook"
545 ),
546 help: "Make sure the `command_not_found` hook itself does not use unknown commands"
547 .into(),
548 span,
549 };
550 }
551 stack.add_env_var(canary.into(), Value::bool(true, Span::unknown()));
552
553 let output = eval_hook(
554 &mut engine_state.clone(),
555 &mut stack,
556 None,
557 vec![("cmd_name".into(), Value::string(name, span))],
558 hook,
559 "command_not_found",
560 );
561
562 stack.remove_env_var(engine_state, canary);
564
565 match output {
566 Ok(PipelineData::Value(Value::String { val, .. }, ..)) => {
567 return ShellError::ExternalCommand {
568 label: format!("Command `{name}` not found"),
569 help: val,
570 span,
571 };
572 }
573 Err(err) => {
574 return err;
575 }
576 _ => {
577 }
579 }
580 }
581
582 if let Some(replacement) = crate::removed_commands().get(&name.to_lowercase()) {
584 return ShellError::RemovedCommand {
585 removed: name.to_lowercase(),
586 replacement: replacement.clone(),
587 span,
588 };
589 }
590
591 if let Some(module) = engine_state.which_module_has_decl(name.as_bytes(), &[]) {
593 let module = String::from_utf8_lossy(module);
594 let full_name = format!("{module} {name}");
596 if engine_state.find_decl(full_name.as_bytes(), &[]).is_some() {
597 return ShellError::ExternalCommand {
598 label: format!("Command `{name}` not found"),
599 help: format!("Did you mean `{full_name}`?"),
600 span,
601 };
602 } else {
603 return ShellError::ExternalCommand {
604 label: format!("Command `{name}` not found"),
605 help: format!(
606 "A command with that name exists in module `{module}`. Try importing it with `use`"
607 ),
608 span,
609 };
610 }
611 }
612
613 let signatures = engine_state.get_signatures_and_declids(false);
615 if let Some((sig, _)) = signatures.iter().find(|(sig, _)| {
616 sig.search_terms
617 .iter()
618 .any(|term| term.to_folded_case() == name.to_folded_case())
619 }) {
620 return ShellError::ExternalCommand {
621 label: format!("Command `{name}` not found"),
622 help: format!("Did you mean `{}`?", sig.name),
623 span,
624 };
625 }
626
627 if let Some(cmd) = did_you_mean(signatures.iter().map(|(sig, _)| &sig.name), name) {
629 if cmd == name {
632 return ShellError::ExternalCommand {
633 label: format!("Command `{name}` not found"),
634 help: "There is a built-in command with the same name".into(),
635 span,
636 };
637 }
638 return ShellError::ExternalCommand {
639 label: format!("Command `{name}` not found"),
640 help: format!("Did you mean `{cmd}`?"),
641 span,
642 };
643 }
644
645 if cwd.join(name).is_file() {
647 return ShellError::ExternalCommand {
648 label: format!("Command `{name}` not found"),
649 help: format!(
650 "`{name}` refers to a file that is not executable. Did you forget to set execute permissions?"
651 ),
652 span,
653 };
654 }
655
656 ShellError::ExternalCommand {
658 label: format!("Command `{name}` not found"),
659 help: format!("`{name}` is neither a Nushell built-in or a known external command"),
660 span,
661 }
662}
663
664pub fn which(name: impl AsRef<OsStr>, paths: &str, cwd: &Path) -> Option<PathBuf> {
674 #[cfg(windows)]
675 let paths = format!("{};{}", cwd.display(), paths);
676 which::which_in(name, Some(paths), cwd).ok()
677}
678
679fn is_cmd_internal_command(name: &str) -> bool {
682 const COMMANDS: &[&str] = &[
683 "ASSOC", "CLS", "ECHO", "FTYPE", "MKLINK", "PAUSE", "START", "VER", "VOL",
684 ];
685 COMMANDS.iter().any(|cmd| cmd.eq_ignore_ascii_case(name))
686}
687
688fn has_cmd_special_character(s: impl AsRef<[u8]>) -> bool {
690 s.as_ref()
691 .iter()
692 .any(|b| matches!(b, b'<' | b'>' | b'&' | b'|' | b'^'))
693}
694
695#[cfg_attr(not(windows), allow(dead_code))]
697fn escape_cmd_argument(arg: &Spanned<OsString>) -> Result<Cow<'_, OsStr>, ShellError> {
698 let Spanned { item: arg, span } = arg;
699 let bytes = arg.as_encoded_bytes();
700 if bytes.iter().any(|b| matches!(b, b'\r' | b'\n' | b'%')) {
701 Err(ShellError::ExternalCommand {
703 label:
704 "Arguments to CMD internal commands cannot contain new lines or percent signs '%'"
705 .into(),
706 help: "some characters currently cannot be securely escaped".into(),
707 span: *span,
708 })
709 } else if bytes.contains(&b'"') {
710 if bytes.iter().filter(|b| **b == b'"').count() == 2
713 && bytes.starts_with(b"\"")
714 && bytes.ends_with(b"\"")
715 {
716 Ok(Cow::Borrowed(arg))
717 } else {
718 Err(ShellError::ExternalCommand {
719 label: "Arguments to CMD internal commands cannot contain embedded double quotes"
720 .into(),
721 help: "this case currently cannot be securely handled".into(),
722 span: *span,
723 })
724 }
725 } else if bytes.contains(&b' ') || has_cmd_special_character(bytes) {
726 let mut new_str = OsString::new();
728 new_str.push("\"");
729 new_str.push(arg);
730 new_str.push("\"");
731 Ok(Cow::Owned(new_str))
732 } else {
733 Ok(Cow::Borrowed(arg))
735 }
736}
737
738#[cfg(test)]
739mod test {
740 use super::*;
741 use nu_test_support::{fs::Stub, playground::Playground};
742
743 #[test]
744 fn test_expand_glob() {
745 Playground::setup("test_expand_glob", |dirs, play| {
746 play.with_files(&[Stub::EmptyFile("a.txt"), Stub::EmptyFile("b.txt")]);
747
748 let cwd = dirs.test().as_std_path();
749
750 let actual = expand_glob("*.txt", cwd, Span::unknown(), Signals::empty()).unwrap();
751 let expected = &["a.txt", "b.txt"];
752 assert_eq!(actual, expected);
753
754 let actual = expand_glob("./*.txt", cwd, Span::unknown(), Signals::empty()).unwrap();
755 assert_eq!(actual, expected);
756
757 let actual = expand_glob("'*.txt'", cwd, Span::unknown(), Signals::empty()).unwrap();
758 let expected = &["'*.txt'"];
759 assert_eq!(actual, expected);
760
761 let actual = expand_glob(".", cwd, Span::unknown(), Signals::empty()).unwrap();
762 let expected = &["."];
763 assert_eq!(actual, expected);
764
765 let actual = expand_glob("./a.txt", cwd, Span::unknown(), Signals::empty()).unwrap();
766 let expected = &["./a.txt"];
767 assert_eq!(actual, expected);
768
769 let actual = expand_glob("[*.txt", cwd, Span::unknown(), Signals::empty()).unwrap();
770 let expected = &["[*.txt"];
771 assert_eq!(actual, expected);
772
773 let actual = expand_glob("~/foo.txt", cwd, Span::unknown(), Signals::empty()).unwrap();
774 let home = dirs::home_dir().expect("failed to get home dir");
775 let expected: Vec<OsString> = vec![home.join("foo.txt").into()];
776 assert_eq!(actual, expected);
777 })
778 }
779
780 #[test]
781 fn test_write_pipeline_data() {
782 let mut engine_state = EngineState::new();
783 let stack = Stack::new();
784 let cwd = std::env::current_dir()
785 .unwrap()
786 .into_os_string()
787 .into_string()
788 .unwrap();
789
790 engine_state.add_env_var("PWD".into(), Value::string(cwd, Span::test_data()));
792
793 let mut buf = vec![];
794 let input = PipelineData::Empty;
795 write_pipeline_data(engine_state.clone(), stack.clone(), input, &mut buf).unwrap();
796 assert_eq!(buf, b"");
797
798 let mut buf = vec![];
799 let input = PipelineData::Value(Value::string("foo", Span::unknown()), None);
800 write_pipeline_data(engine_state.clone(), stack.clone(), input, &mut buf).unwrap();
801 assert_eq!(buf, b"foo");
802
803 let mut buf = vec![];
804 let input = PipelineData::Value(Value::binary(b"foo", Span::unknown()), None);
805 write_pipeline_data(engine_state.clone(), stack.clone(), input, &mut buf).unwrap();
806 assert_eq!(buf, b"foo");
807
808 let mut buf = vec![];
809 let input = PipelineData::ByteStream(
810 ByteStream::read(
811 b"foo".as_slice(),
812 Span::unknown(),
813 Signals::empty(),
814 ByteStreamType::Unknown,
815 ),
816 None,
817 );
818 write_pipeline_data(engine_state.clone(), stack.clone(), input, &mut buf).unwrap();
819 assert_eq!(buf, b"foo");
820 }
821}