| 1 | use std::{ |
| 2 | ffi::{OsStr, OsString}, |
| 3 | fmt::Display, |
| 4 | os::unix::ffi::OsStringExt, |
| 5 | path::{Path, PathBuf}, |
| 6 | }; |
| 7 | |
| 8 | use crate::common::DisplayOsStr; |
| 9 | use crate::system::escape_os_str_lossy; |
| 10 | |
| 11 | use super::resolve::{canonicalize, resolve_path}; |
| 12 | |
| 13 | #[derive(Debug, Default)] |
| 14 | #[cfg_attr(test, derive(PartialEq))] |
| 15 | pub struct CommandAndArguments { |
| 16 | pub(crate) command: PathBuf, |
| 17 | pub(crate) arguments: Vec<OsString>, |
| 18 | pub(crate) resolved: bool, |
| 19 | pub(crate) arg0: Option<PathBuf>, |
| 20 | } |
| 21 | |
| 22 | impl Display for CommandAndArguments { |
| 23 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 24 | let cmd = escape_os_str_lossy(self.command.as_os_str()); |
| 25 | let args = self |
| 26 | .arguments |
| 27 | .iter() |
| 28 | .map(|a| { |
| 29 | DisplayOsStr(a) |
| 30 | .to_string() |
| 31 | .escape_default() |
| 32 | .collect::<String>() |
| 33 | }) |
| 34 | .collect::<Vec<_>>() |
| 35 | .join(" "); |
| 36 | write!(f, "{cmd} {args}") |
| 37 | } |
| 38 | } |
| 39 | |
| 40 | // when -i and -s are used, the arguments given to sudo are escaped "except for alphanumerics, underscores, hyphens, and dollar signs." |
| 41 | fn escaped(arguments: Vec<OsString>) -> OsString { |
| 42 | arguments |
| 43 | .into_iter() |
| 44 | .map(|arg| { |
| 45 | let mut escaped_arg = Vec::new(); |
| 46 | for c in arg.into_encoded_bytes() { |
| 47 | match c { |
| 48 | b'_' | b'-' | b'$' => escaped_arg.push(c), |
| 49 | c if c.is_ascii_alphanumeric() => escaped_arg.push(c), |
| 50 | _ => escaped_arg.extend_from_slice(&[b'\\', c]), |
| 51 | } |
| 52 | } |
| 53 | OsString::from_vec(escaped_arg) |
| 54 | }) |
| 55 | .collect::<Vec<OsString>>() |
| 56 | .join(OsStr::new(" ")) |
| 57 | } |
| 58 | |
| 59 | //checks whether the Path is actually describing a qualified path (i.e. contains "/") |
| 60 | //or just specifying the name of a file (in which case we are going to resolve it via PATH) |
| 61 | fn is_qualified(path: impl AsRef<Path>) -> bool { |
| 62 | path.as_ref().parent() != Some(Path::new("")) |
| 63 | } |
| 64 | |
| 65 | impl CommandAndArguments { |
| 66 | pub fn build_from_args( |
| 67 | shell: Option<PathBuf>, |
| 68 | mut arguments: Vec<OsString>, |
| 69 | path: &str, |
| 70 | ) -> Self { |
| 71 | let mut resolved = true; |
| 72 | let mut command; |
| 73 | let mut arg0 = None; |
| 74 | if let Some(chosen_shell) = shell { |
| 75 | command = chosen_shell; |
| 76 | if !arguments.is_empty() { |
| 77 | arguments = vec!["-c".into(), escaped(arguments)] |
| 78 | } |
| 79 | } else { |
| 80 | command = arguments.first().map(|s| s.into()).unwrap_or_default(); |
| 81 | arguments.remove(0); |
| 82 | |
| 83 | // remember the original binary name before resolving symlinks; this is not |
| 84 | // to be used except for setting the `arg0` |
| 85 | arg0 = Some(command.clone()); |
| 86 | |
| 87 | // resolve the command, remembering errors (but not propagating them) |
| 88 | if !is_qualified(&command) { |
| 89 | match resolve_path(&command, path) { |
| 90 | Some(qualified_path) => command = qualified_path, |
| 91 | None => resolved = false, |
| 92 | } |
| 93 | } |
| 94 | } |
| 95 | |
| 96 | // resolve symlinks, even if the command was obtained through a PATH or SHELL |
| 97 | // once again, failure to canonicalize should not stop the pipeline |
| 98 | match canonicalize(&command) { |
| 99 | Ok(canon_path) => command = canon_path, |
| 100 | Err(_) => resolved = false, |
| 101 | } |
| 102 | |
| 103 | CommandAndArguments { |
| 104 | command, |
| 105 | arguments, |
| 106 | resolved, |
| 107 | arg0, |
| 108 | } |
| 109 | } |
| 110 | } |
| 111 | |
| 112 | #[cfg(test)] |
| 113 | mod test { |
| 114 | use std::ffi::OsString; |
| 115 | |
| 116 | use super::{CommandAndArguments, escaped}; |
| 117 | |
| 118 | #[test] |
| 119 | fn test_escaped() { |
| 120 | let test = |src: &[&str], target: &str| { |
| 121 | assert_eq!(&escaped(src.iter().map(OsString::from).collect()), target); |
| 122 | }; |
| 123 | test(&["a", "b", "c"], "a b c"); |
| 124 | test(&["a", "b c"], "a b\\ c"); |
| 125 | test(&["a", "b-c"], "a b-c"); |
| 126 | test(&["a", "b#c"], "a b\\#c"); |
| 127 | test(&["1 2 3"], "1\\ 2\\ 3"); |
| 128 | test(&["! @ $"], "\\!\\ \\@\\ $"); |
| 129 | } |
| 130 | |
| 131 | #[test] |
| 132 | fn test_build_command_and_args() { |
| 133 | assert_eq!( |
| 134 | CommandAndArguments::build_from_args( |
| 135 | None, |
| 136 | vec!["/usr/bin/fmt".into(), "hello".into()], |
| 137 | "/bin" |
| 138 | ), |
| 139 | CommandAndArguments { |
| 140 | command: "/usr/bin/fmt".into(), |
| 141 | arguments: vec!["hello".into()], |
| 142 | resolved: true, |
| 143 | arg0: Some("/usr/bin/fmt".into()), |
| 144 | } |
| 145 | ); |
| 146 | |
| 147 | assert_eq!( |
| 148 | CommandAndArguments::build_from_args( |
| 149 | None, |
| 150 | vec!["fmt".into(), "hello".into()], |
| 151 | "/tmp:/usr/bin:/bin" |
| 152 | ), |
| 153 | CommandAndArguments { |
| 154 | command: "/usr/bin/fmt".into(), |
| 155 | arguments: vec!["hello".into()], |
| 156 | resolved: true, |
| 157 | arg0: Some("fmt".into()), |
| 158 | } |
| 159 | ); |
| 160 | |
| 161 | assert_eq!( |
| 162 | CommandAndArguments::build_from_args( |
| 163 | None, |
| 164 | vec!["thisdoesnotexist".into(), "hello".into()], |
| 165 | "" |
| 166 | ), |
| 167 | CommandAndArguments { |
| 168 | command: "thisdoesnotexist".into(), |
| 169 | arguments: vec!["hello".into()], |
| 170 | resolved: false, |
| 171 | arg0: Some("thisdoesnotexist".into()), |
| 172 | } |
| 173 | ); |
| 174 | |
| 175 | assert_eq!( |
| 176 | CommandAndArguments::build_from_args( |
| 177 | Some("shell".into()), |
| 178 | vec!["ls".into(), "hello".into()], |
| 179 | "/bin" |
| 180 | ), |
| 181 | CommandAndArguments { |
| 182 | command: "shell".into(), |
| 183 | arguments: vec!["-c".into(), "ls hello".into()], |
| 184 | resolved: false, |
| 185 | arg0: None, |
| 186 | } |
| 187 | ); |
| 188 | } |
| 189 | |
| 190 | #[test] |
| 191 | fn qualified_paths() { |
| 192 | use super::is_qualified; |
| 193 | assert!(is_qualified("foo/bar")); |
| 194 | assert!(is_qualified("a/b/bar")); |
| 195 | assert!(is_qualified("a/b//bar")); |
| 196 | assert!(is_qualified("/bar")); |
| 197 | assert!(is_qualified("/bar/")); |
| 198 | assert!(is_qualified("/bar/foo/")); |
| 199 | assert!(is_qualified("/")); |
| 200 | assert!(is_qualified("")); // don't try to resolve "" |
| 201 | assert!(!is_qualified("bar")); |
| 202 | } |
| 203 | } |