1#[cfg(unix)]
2use anyhow::Context;
3#[cfg(feature = "serde_support")]
4use serde_derive::*;
5use std::collections::BTreeMap;
6use std::ffi::{OsStr, OsString};
7#[cfg(windows)]
8use std::os::windows::ffi::OsStrExt;
9#[cfg(unix)]
10use std::path::Component;
11use std::path::Path;
12
13#[derive(Clone, Debug, PartialEq, PartialOrd)]
15#[cfg_attr(feature = "serde_support", derive(Serialize, Deserialize))]
16struct EnvEntry {
17 is_from_base_env: bool,
20
21 preferred_key: OsString,
23
24 value: OsString,
26}
27
28impl EnvEntry {
29 fn map_key(k: OsString) -> OsString {
30 if cfg!(windows) {
31 match k.to_str() {
33 Some(s) => s.to_lowercase().into(),
34 None => k,
35 }
36 } else {
37 k
38 }
39 }
40}
41
42#[cfg(unix)]
43fn get_shell() -> String {
44 use nix::unistd::{access, AccessFlags};
45 use std::ffi::CStr;
46 use std::str;
47
48 let ent = unsafe { libc::getpwuid(libc::getuid()) };
49 if !ent.is_null() {
50 let shell = unsafe { CStr::from_ptr((*ent).pw_shell) };
51 match shell.to_str().map(str::to_owned) {
52 Err(err) => {
53 log::warn!(
54 "passwd database shell could not be \
55 represented as utf-8: {err:#}, \
56 falling back to /bin/sh"
57 );
58 }
59 Ok(shell) => {
60 if let Err(err) = access(Path::new(&shell), AccessFlags::X_OK) {
61 log::warn!(
62 "passwd database shell={shell:?} which is \
63 not executable ({err:#}), falling back to /bin/sh"
64 );
65 } else {
66 return shell;
67 }
68 }
69 }
70 }
71 "/bin/sh".into()
72}
73
74fn get_base_env() -> BTreeMap<OsString, EnvEntry> {
75 let mut env: BTreeMap<OsString, EnvEntry> = std::env::vars_os()
76 .map(|(key, value)| {
77 (
78 EnvEntry::map_key(key.clone()),
79 EnvEntry {
80 is_from_base_env: true,
81 preferred_key: key,
82 value,
83 },
84 )
85 })
86 .collect();
87
88 #[cfg(unix)]
89 {
90 let key = EnvEntry::map_key("SHELL".into());
91 if !env.contains_key(&key) {
93 env.insert(
94 EnvEntry::map_key("SHELL".into()),
95 EnvEntry {
96 is_from_base_env: true,
97 preferred_key: "SHELL".into(),
98 value: get_shell().into(),
99 },
100 );
101 }
102 }
103
104 #[cfg(windows)]
105 {
106 use std::os::windows::ffi::OsStringExt;
107 use winapi::um::processenv::ExpandEnvironmentStringsW;
108 use winreg::enums::{RegType, HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE};
109 use winreg::types::FromRegValue;
110 use winreg::{RegKey, RegValue};
111
112 fn reg_value_to_string(value: &RegValue) -> anyhow::Result<OsString> {
113 match value.vtype {
114 RegType::REG_EXPAND_SZ => {
115 let src = unsafe {
116 std::slice::from_raw_parts(
117 value.bytes.as_ptr() as *const u16,
118 value.bytes.len() / 2,
119 )
120 };
121 let size =
122 unsafe { ExpandEnvironmentStringsW(src.as_ptr(), std::ptr::null_mut(), 0) };
123 let mut buf = vec![0u16; size as usize + 1];
124 unsafe {
125 ExpandEnvironmentStringsW(src.as_ptr(), buf.as_mut_ptr(), buf.len() as u32)
126 };
127
128 let mut buf = buf.as_slice();
129 while let Some(0) = buf.last() {
130 buf = &buf[0..buf.len() - 1];
131 }
132 Ok(OsString::from_wide(buf))
133 }
134 _ => Ok(OsString::from_reg_value(value)?),
135 }
136 }
137
138 if let Ok(sys_env) = RegKey::predef(HKEY_LOCAL_MACHINE)
139 .open_subkey("System\\CurrentControlSet\\Control\\Session Manager\\Environment")
140 {
141 for (name, value) in sys_env.enum_values().flatten() {
142 if name.eq_ignore_ascii_case("username") {
143 continue;
144 }
145 if let Ok(value) = reg_value_to_string(&value) {
146 log::trace!("adding SYS env: {:?} {:?}", name, value);
147 env.insert(
148 EnvEntry::map_key(name.clone().into()),
149 EnvEntry {
150 is_from_base_env: true,
151 preferred_key: name.into(),
152 value,
153 },
154 );
155 }
156 }
157 }
158
159 if let Ok(sys_env) = RegKey::predef(HKEY_CURRENT_USER).open_subkey("Environment") {
160 for (name, value) in sys_env.enum_values().flatten() {
161 if let Ok(value) = reg_value_to_string(&value) {
162 let value = if name.eq_ignore_ascii_case("path") {
164 match env.get(&EnvEntry::map_key(name.clone().into())) {
165 Some(entry) => {
166 let mut result = OsString::new();
167 result.push(&entry.value);
168 result.push(";");
169 result.push(&value);
170 result
171 }
172 None => value,
173 }
174 } else {
175 value
176 };
177
178 log::trace!("adding USER env: {:?} {:?}", name, value);
179 env.insert(
180 EnvEntry::map_key(name.clone().into()),
181 EnvEntry {
182 is_from_base_env: true,
183 preferred_key: name.into(),
184 value,
185 },
186 );
187 }
188 }
189 }
190 }
191
192 env
193}
194
195#[derive(Clone, Debug, PartialEq)]
198#[cfg_attr(feature = "serde_support", derive(Serialize, Deserialize))]
199pub struct CommandBuilder {
200 args: Vec<OsString>,
201 envs: BTreeMap<OsString, EnvEntry>,
202 cwd: Option<OsString>,
203 #[cfg(unix)]
204 pub(crate) umask: Option<libc::mode_t>,
205 controlling_tty: bool,
206}
207
208impl CommandBuilder {
209 pub fn new<S: AsRef<OsStr>>(program: S) -> Self {
212 Self {
213 args: vec![program.as_ref().to_owned()],
214 envs: get_base_env(),
215 cwd: None,
216 #[cfg(unix)]
217 umask: None,
218 controlling_tty: true,
219 }
220 }
221
222 pub fn from_argv(args: Vec<OsString>) -> Self {
224 Self {
225 args,
226 envs: get_base_env(),
227 cwd: None,
228 #[cfg(unix)]
229 umask: None,
230 controlling_tty: true,
231 }
232 }
233
234 pub fn set_controlling_tty(&mut self, controlling_tty: bool) {
241 self.controlling_tty = controlling_tty;
242 }
243
244 pub fn get_controlling_tty(&self) -> bool {
245 self.controlling_tty
246 }
247
248 pub fn new_default_prog() -> Self {
251 Self {
252 args: vec![],
253 envs: get_base_env(),
254 cwd: None,
255 #[cfg(unix)]
256 umask: None,
257 controlling_tty: true,
258 }
259 }
260
261 pub fn is_default_prog(&self) -> bool {
263 self.args.is_empty()
264 }
265
266 pub fn arg<S: AsRef<OsStr>>(&mut self, arg: S) {
269 if self.is_default_prog() {
270 panic!("attempted to add args to a default_prog builder");
271 }
272 self.args.push(arg.as_ref().to_owned());
273 }
274
275 pub fn args<I, S>(&mut self, args: I)
277 where
278 I: IntoIterator<Item = S>,
279 S: AsRef<OsStr>,
280 {
281 for arg in args {
282 self.arg(arg);
283 }
284 }
285
286 pub fn get_argv(&self) -> &Vec<OsString> {
287 &self.args
288 }
289
290 pub fn get_argv_mut(&mut self) -> &mut Vec<OsString> {
291 &mut self.args
292 }
293
294 pub fn env<K, V>(&mut self, key: K, value: V)
296 where
297 K: AsRef<OsStr>,
298 V: AsRef<OsStr>,
299 {
300 let key: OsString = key.as_ref().into();
301 let value: OsString = value.as_ref().into();
302 self.envs.insert(
303 EnvEntry::map_key(key.clone()),
304 EnvEntry {
305 is_from_base_env: false,
306 preferred_key: key,
307 value,
308 },
309 );
310 }
311
312 pub fn env_remove<K>(&mut self, key: K)
313 where
314 K: AsRef<OsStr>,
315 {
316 let key = key.as_ref().into();
317 self.envs.remove(&EnvEntry::map_key(key));
318 }
319
320 pub fn env_clear(&mut self) {
321 self.envs.clear();
322 }
323
324 pub fn get_env<K>(&self, key: K) -> Option<&OsStr>
325 where
326 K: AsRef<OsStr>,
327 {
328 let key = key.as_ref().into();
329 self.envs.get(&EnvEntry::map_key(key)).map(
330 |EnvEntry {
331 is_from_base_env: _,
332 preferred_key: _,
333 value,
334 }| value.as_os_str(),
335 )
336 }
337
338 pub fn cwd<D>(&mut self, dir: D)
339 where
340 D: AsRef<OsStr>,
341 {
342 self.cwd = Some(dir.as_ref().to_owned());
343 }
344
345 pub fn clear_cwd(&mut self) {
346 self.cwd.take();
347 }
348
349 pub fn get_cwd(&self) -> Option<&OsString> {
350 self.cwd.as_ref()
351 }
352
353 pub fn iter_extra_env_as_str(&self) -> impl Iterator<Item = (&str, &str)> {
357 self.envs.values().filter_map(
358 |EnvEntry {
359 is_from_base_env,
360 preferred_key,
361 value,
362 }| {
363 if *is_from_base_env {
364 None
365 } else {
366 let key = preferred_key.to_str()?;
367 let value = value.to_str()?;
368 Some((key, value))
369 }
370 },
371 )
372 }
373
374 pub fn iter_full_env_as_str(&self) -> impl Iterator<Item = (&str, &str)> {
375 self.envs.values().filter_map(
376 |EnvEntry {
377 preferred_key,
378 value,
379 ..
380 }| {
381 let key = preferred_key.to_str()?;
382 let value = value.to_str()?;
383 Some((key, value))
384 },
385 )
386 }
387
388 pub fn as_unix_command_line(&self) -> anyhow::Result<String> {
391 let mut strs = vec![];
392 for arg in &self.args {
393 let s = arg
394 .to_str()
395 .ok_or_else(|| anyhow::anyhow!("argument cannot be represented as utf8"))?;
396 strs.push(s);
397 }
398 Ok(shell_words::join(strs))
399 }
400}
401
402#[cfg(unix)]
403impl CommandBuilder {
404 pub fn umask(&mut self, mask: Option<libc::mode_t>) {
405 self.umask = mask;
406 }
407
408 fn resolve_path(&self) -> Option<&OsStr> {
409 self.get_env("PATH")
410 }
411
412 fn search_path(&self, exe: &OsStr, cwd: &OsStr) -> anyhow::Result<OsString> {
413 use nix::unistd::{access, AccessFlags};
414
415 let exe_path: &Path = exe.as_ref();
416 if exe_path.is_relative() {
417 let cwd: &Path = cwd.as_ref();
418 let mut errors = vec![];
419
420 if is_cwd_relative_path(exe_path) {
423 let abs_path = cwd.join(exe_path);
424
425 if abs_path.is_dir() {
426 anyhow::bail!(
427 "Unable to spawn {} because it is a directory",
428 abs_path.display()
429 );
430 } else if access(&abs_path, AccessFlags::X_OK).is_ok() {
431 return Ok(abs_path.into_os_string());
432 } else if access(&abs_path, AccessFlags::F_OK).is_ok() {
433 anyhow::bail!(
434 "Unable to spawn {} because it is not executable",
435 abs_path.display()
436 );
437 }
438
439 anyhow::bail!(
440 "Unable to spawn {} because it does not exist",
441 abs_path.display()
442 );
443 }
444
445 if let Some(path) = self.resolve_path() {
446 for path in std::env::split_paths(&path) {
447 let candidate = cwd.join(&path).join(exe);
448
449 if candidate.is_dir() {
450 errors.push(format!("{} exists but is a directory", candidate.display()));
451 } else if access(&candidate, AccessFlags::X_OK).is_ok() {
452 return Ok(candidate.into_os_string());
453 } else if access(&candidate, AccessFlags::F_OK).is_ok() {
454 errors.push(format!(
455 "{} exists but is not executable",
456 candidate.display()
457 ));
458 }
459 }
460 errors.push(format!("No viable candidates found in PATH {path:?}"));
461 } else {
462 errors.push("Unable to resolve the PATH".to_string());
463 }
464 anyhow::bail!(
465 "Unable to spawn {} because:\n{}",
466 exe_path.display(),
467 errors.join(".\n")
468 );
469 } else if exe_path.is_dir() {
470 anyhow::bail!(
471 "Unable to spawn {} because it is a directory",
472 exe_path.display()
473 );
474 } else {
475 if let Err(err) = access(exe_path, AccessFlags::X_OK) {
476 if access(exe_path, AccessFlags::F_OK).is_ok() {
477 anyhow::bail!(
478 "Unable to spawn {} because it is not executable ({err:#})",
479 exe_path.display()
480 );
481 } else {
482 anyhow::bail!(
483 "Unable to spawn {} because it doesn't exist on the filesystem ({err:#})",
484 exe_path.display()
485 );
486 }
487 }
488
489 Ok(exe.to_owned())
490 }
491 }
492
493 pub(crate) fn as_command(&self) -> anyhow::Result<std::process::Command> {
495 use std::os::unix::process::CommandExt;
496
497 let home = self.get_home_dir()?;
498 let dir: &OsStr = self
499 .cwd
500 .as_deref()
501 .filter(|dir| std::path::Path::new(dir).is_dir())
502 .unwrap_or(home.as_ref());
503 let shell = self.get_shell();
504
505 let mut cmd = if self.is_default_prog() {
506 let mut cmd = std::process::Command::new(&shell);
507
508 let basename = shell.rsplit('/').next().unwrap_or(&shell);
511 cmd.arg0(format!("-{basename}"));
512 cmd
513 } else {
514 let resolved = self.search_path(&self.args[0], dir)?;
515 let mut cmd = std::process::Command::new(&resolved);
516 cmd.arg0(&self.args[0]);
517 cmd.args(&self.args[1..]);
518 cmd
519 };
520
521 cmd.current_dir(dir);
522
523 cmd.env_clear();
524 cmd.env("SHELL", shell);
525 cmd.envs(self.envs.values().map(
526 |EnvEntry {
527 is_from_base_env: _,
528 preferred_key,
529 value,
530 }| (preferred_key.as_os_str(), value.as_os_str()),
531 ));
532
533 Ok(cmd)
534 }
535
536 pub fn get_shell(&self) -> String {
540 use nix::unistd::{access, AccessFlags};
541
542 if let Some(shell) = self.get_env("SHELL").and_then(OsStr::to_str) {
543 match access(shell, AccessFlags::X_OK) {
544 Ok(()) => return shell.into(),
545 Err(err) => log::warn!(
546 "$SHELL -> {shell:?} which is \
547 not executable ({err:#}), falling back to password db lookup"
548 ),
549 }
550 }
551
552 get_shell()
553 }
554
555 fn get_home_dir(&self) -> anyhow::Result<String> {
556 if let Some(home_dir) = self.get_env("HOME").and_then(OsStr::to_str) {
557 return Ok(home_dir.into());
558 }
559
560 let ent = unsafe { libc::getpwuid(libc::getuid()) };
561 if ent.is_null() {
562 Ok("/".into())
563 } else {
564 use std::ffi::CStr;
565 use std::str;
566 let home = unsafe { CStr::from_ptr((*ent).pw_dir) };
567 home.to_str()
568 .map(str::to_owned)
569 .context("failed to resolve home dir")
570 }
571 }
572}
573
574#[cfg(windows)]
575impl CommandBuilder {
576 fn search_path(&self, exe: &OsStr) -> OsString {
577 if let Some(path) = self.get_env("PATH") {
578 let extensions = self.get_env("PATHEXT").unwrap_or(OsStr::new(".EXE"));
579 for path in std::env::split_paths(&path) {
580 let candidate = path.join(exe);
582 if candidate.exists() {
583 return candidate.into_os_string();
584 }
585
586 for ext in std::env::split_paths(&extensions) {
590 let ext = ext.to_str().expect("PATHEXT entries must be utf8");
593 let path = path.join(exe).with_extension(&ext[1..]);
594 if path.exists() {
595 return path.into_os_string();
596 }
597 }
598 }
599 }
600
601 exe.to_owned()
602 }
603
604 pub(crate) fn current_directory(&self) -> Option<Vec<u16>> {
605 let home: Option<&OsStr> = self
606 .get_env("USERPROFILE")
607 .filter(|path| Path::new(path).is_dir());
608 let cwd: Option<&OsStr> = self.cwd.as_deref().filter(|path| Path::new(path).is_dir());
609 let dir: Option<&OsStr> = cwd.or(home);
610
611 dir.map(|dir| {
612 let mut wide = vec![];
613
614 if Path::new(dir).is_relative() {
615 if let Ok(ccwd) = std::env::current_dir() {
616 wide.extend(ccwd.join(dir).as_os_str().encode_wide());
617 } else {
618 wide.extend(dir.encode_wide());
619 }
620 } else {
621 wide.extend(dir.encode_wide());
622 }
623
624 wide.push(0);
625 wide
626 })
627 }
628
629 pub(crate) fn environment_block(&self) -> Vec<u16> {
634 let mut block = vec![];
636
637 for EnvEntry {
638 is_from_base_env: _,
639 preferred_key,
640 value,
641 } in self.envs.values()
642 {
643 block.extend(preferred_key.encode_wide());
644 block.push(b'=' as u16);
645 block.extend(value.encode_wide());
646 block.push(0);
647 }
648 block.push(0);
650
651 block
652 }
653
654 pub fn get_shell(&self) -> String {
655 let exe: OsString = self
656 .get_env("ComSpec")
657 .unwrap_or(OsStr::new("cmd.exe"))
658 .into();
659 exe.into_string()
660 .unwrap_or_else(|_| "%CompSpec%".to_string())
661 }
662
663 pub(crate) fn cmdline(&self) -> anyhow::Result<(Vec<u16>, Vec<u16>)> {
664 let mut cmdline = Vec::<u16>::new();
665
666 let exe: OsString = if self.is_default_prog() {
667 self.get_env("ComSpec")
668 .unwrap_or(OsStr::new("cmd.exe"))
669 .into()
670 } else {
671 self.search_path(&self.args[0])
672 };
673
674 Self::append_quoted(&exe, &mut cmdline);
675
676 let mut exe: Vec<u16> = exe.encode_wide().collect();
679 exe.push(0);
680
681 for arg in self.args.iter().skip(1) {
682 cmdline.push(' ' as u16);
683 anyhow::ensure!(
684 !arg.encode_wide().any(|c| c == 0),
685 "invalid encoding for command line argument {:?}",
686 arg
687 );
688 Self::append_quoted(arg, &mut cmdline);
689 }
690 cmdline.push(0);
692 Ok((exe, cmdline))
693 }
694
695 fn append_quoted(arg: &OsStr, cmdline: &mut Vec<u16>) {
698 if !arg.is_empty()
699 && !arg.encode_wide().any(|c| {
700 c == ' ' as u16
701 || c == '\t' as u16
702 || c == '\n' as u16
703 || c == '\x0b' as u16
704 || c == '\"' as u16
705 })
706 {
707 cmdline.extend(arg.encode_wide());
708 return;
709 }
710 cmdline.push('"' as u16);
711
712 let arg: Vec<_> = arg.encode_wide().collect();
713 let mut i = 0;
714 while i < arg.len() {
715 let mut num_backslashes = 0;
716 while i < arg.len() && arg[i] == '\\' as u16 {
717 i += 1;
718 num_backslashes += 1;
719 }
720
721 if i == arg.len() {
722 for _ in 0..num_backslashes * 2 {
723 cmdline.push('\\' as u16);
724 }
725 break;
726 } else if arg[i] == b'"' as u16 {
727 for _ in 0..num_backslashes * 2 + 1 {
728 cmdline.push('\\' as u16);
729 }
730 cmdline.push(arg[i]);
731 } else {
732 for _ in 0..num_backslashes {
733 cmdline.push('\\' as u16);
734 }
735 cmdline.push(arg[i]);
736 }
737 i += 1;
738 }
739 cmdline.push('"' as u16);
740 }
741}
742
743#[cfg(unix)]
744fn is_cwd_relative_path<P: AsRef<Path>>(p: P) -> bool {
746 matches!(
747 p.as_ref().components().next(),
748 Some(Component::CurDir | Component::ParentDir)
749 )
750}
751
752#[cfg(test)]
753mod tests {
754 use super::*;
755
756 #[cfg(unix)]
757 #[test]
758 fn test_cwd_relative() {
759 assert!(is_cwd_relative_path("."));
760 assert!(is_cwd_relative_path("./foo"));
761 assert!(is_cwd_relative_path("../foo"));
762 assert!(!is_cwd_relative_path("foo"));
763 assert!(!is_cwd_relative_path("/foo"));
764 }
765
766 #[test]
767 fn test_env() {
768 let mut cmd = CommandBuilder::new("dummy");
769 let package_authors = cmd.get_env("CARGO_PKG_AUTHORS");
770 println!("package_authors: {package_authors:?}");
771 assert!(package_authors == Some(OsStr::new("Wez Furlong:3 Leaps, LLC")));
772
773 cmd.env("foo key", "foo value");
774 cmd.env("bar key", "bar value");
775
776 let iterated_envs = cmd.iter_extra_env_as_str().collect::<Vec<_>>();
777 println!("iterated_envs: {iterated_envs:?}");
778 assert!(iterated_envs == vec![("bar key", "bar value"), ("foo key", "foo value")]);
779
780 {
781 let mut cmd = cmd.clone();
782 cmd.env_remove("foo key");
783
784 let iterated_envs = cmd.iter_extra_env_as_str().collect::<Vec<_>>();
785 println!("iterated_envs: {iterated_envs:?}");
786 assert!(iterated_envs == vec![("bar key", "bar value")]);
787 }
788
789 {
790 let mut cmd = cmd.clone();
791 cmd.env_remove("bar key");
792
793 let iterated_envs = cmd.iter_extra_env_as_str().collect::<Vec<_>>();
794 println!("iterated_envs: {iterated_envs:?}");
795 assert!(iterated_envs == vec![("foo key", "foo value")]);
796 }
797
798 {
799 let mut cmd = cmd.clone();
800 cmd.env_clear();
801
802 let iterated_envs = cmd.iter_extra_env_as_str().collect::<Vec<_>>();
803 println!("iterated_envs: {iterated_envs:?}");
804 assert!(iterated_envs.is_empty());
805 }
806 }
807
808 #[cfg(windows)]
809 #[test]
810 fn test_env_case_insensitive_override() {
811 let mut cmd = CommandBuilder::new("dummy");
812 cmd.env("Cargo_Pkg_Authors", "Not Wez");
813 assert!(cmd.get_env("cargo_pkg_authors") == Some(OsStr::new("Not Wez")));
814
815 cmd.env_remove("cARGO_pKG_aUTHORS");
816 assert!(cmd.get_env("CARGO_PKG_AUTHORS").is_none());
817 }
818}