| 1 | #![forbid(unsafe_code)] |
| 2 | |
| 3 | use std::ffi::OsStr; |
| 4 | use std::str; |
| 5 | use std::{borrow::Cow, ffi::OsString, mem}; |
| 6 | |
| 7 | use crate::common::{DisplayOsStr, SudoPath, SudoString}; |
| 8 | use crate::log::user_warn; |
| 9 | |
| 10 | pub mod help; |
| 11 | pub mod help_edit; |
| 12 | |
| 13 | #[cfg(test)] |
| 14 | mod tests; |
| 15 | |
| 16 | pub enum SudoAction { |
| 17 | Edit(SudoEditOptions), |
| 18 | Help(SudoHelpOptions), |
| 19 | List(SudoListOptions), |
| 20 | RemoveTimestamp(SudoRemoveTimestampOptions), |
| 21 | ResetTimestamp(SudoResetTimestampOptions), |
| 22 | Run(SudoRunOptions), |
| 23 | Validate(SudoValidateOptions), |
| 24 | Version(SudoVersionOptions), |
| 25 | } |
| 26 | |
| 27 | pub(super) fn is_sudoedit(command_path: Option<OsString>) -> bool { |
| 28 | std::path::Path::new(&command_path.unwrap_or_default()) |
| 29 | .file_name() |
| 30 | .is_some_and(|name| name.as_encoded_bytes().starts_with(b"sudoedit")) |
| 31 | } |
| 32 | |
| 33 | impl SudoAction { |
| 34 | /// try to parse and environment variable assignment |
| 35 | /// parse command line arguments from the environment and handle errors |
| 36 | pub fn from_env() -> Result<Self, String> { |
| 37 | Self::try_parse_from(std::env::args_os()) |
| 38 | } |
| 39 | |
| 40 | pub fn try_parse_from<I, T>(iter: I) -> Result<Self, String> |
| 41 | where |
| 42 | I: IntoIterator<Item = T>, |
| 43 | T: Into<OsString> + Clone, |
| 44 | { |
| 45 | let opts = SudoOptions::try_parse_from(iter)?; |
| 46 | opts.validate() |
| 47 | } |
| 48 | } |
| 49 | |
| 50 | // sudo -h | -K | -k | -V |
| 51 | pub struct SudoHelpOptions {} |
| 52 | |
| 53 | impl TryFrom<SudoOptions> for SudoHelpOptions { |
| 54 | type Error = String; |
| 55 | |
| 56 | fn try_from(mut opts: SudoOptions) -> Result<Self, Self::Error> { |
| 57 | // see `SudoOptions::validate` |
| 58 | let help = mem::take(&mut opts.help); |
| 59 | debug_assert!(help); |
| 60 | |
| 61 | Ok(Self {}) |
| 62 | } |
| 63 | } |
| 64 | |
| 65 | // sudo -h | -K | -k | -V |
| 66 | pub struct SudoVersionOptions {} |
| 67 | |
| 68 | impl TryFrom<SudoOptions> for SudoVersionOptions { |
| 69 | type Error = String; |
| 70 | |
| 71 | fn try_from(mut opts: SudoOptions) -> Result<Self, Self::Error> { |
| 72 | // see `SudoOptions::validate` |
| 73 | let version = mem::take(&mut opts.version); |
| 74 | debug_assert!(version); |
| 75 | |
| 76 | Ok(Self {}) |
| 77 | } |
| 78 | } |
| 79 | |
| 80 | // sudo -h | -K | -k | -V |
| 81 | pub struct SudoRemoveTimestampOptions {} |
| 82 | |
| 83 | impl TryFrom<SudoOptions> for SudoRemoveTimestampOptions { |
| 84 | type Error = String; |
| 85 | |
| 86 | fn try_from(mut opts: SudoOptions) -> Result<Self, Self::Error> { |
| 87 | // see `SudoOptions::validate` |
| 88 | let remove_timestamp = mem::take(&mut opts.remove_timestamp); |
| 89 | debug_assert!(remove_timestamp); |
| 90 | |
| 91 | reject_all("--remove-timestamp", opts)?; |
| 92 | |
| 93 | Ok(Self {}) |
| 94 | } |
| 95 | } |
| 96 | |
| 97 | // sudo -h | -K | -k | -V |
| 98 | pub struct SudoResetTimestampOptions {} |
| 99 | |
| 100 | impl TryFrom<SudoOptions> for SudoResetTimestampOptions { |
| 101 | type Error = String; |
| 102 | |
| 103 | fn try_from(mut opts: SudoOptions) -> Result<Self, Self::Error> { |
| 104 | // see `SudoOptions::validate` |
| 105 | let reset_timestamp = mem::take(&mut opts.reset_timestamp); |
| 106 | debug_assert!(reset_timestamp); |
| 107 | |
| 108 | reject_all("--reset-timestamp", opts)?; |
| 109 | |
| 110 | Ok(Self {}) |
| 111 | } |
| 112 | } |
| 113 | |
| 114 | // sudo -v [-ABkNnS] [-g group] [-h host] [-p prompt] [-u user] |
| 115 | pub struct SudoValidateOptions { |
| 116 | // -A |
| 117 | pub askpass: bool, |
| 118 | // -B |
| 119 | pub bell: bool, |
| 120 | // -k |
| 121 | pub reset_timestamp: bool, |
| 122 | // -n |
| 123 | pub non_interactive: bool, |
| 124 | // -S |
| 125 | pub stdin: bool, |
| 126 | // -p |
| 127 | pub prompt: Option<String>, |
| 128 | // -g |
| 129 | pub group: Option<SudoString>, |
| 130 | // -u |
| 131 | pub user: Option<SudoString>, |
| 132 | } |
| 133 | |
| 134 | impl TryFrom<SudoOptions> for SudoValidateOptions { |
| 135 | type Error = String; |
| 136 | |
| 137 | fn try_from(mut opts: SudoOptions) -> Result<Self, Self::Error> { |
| 138 | // see `SudoOptions::validate` |
| 139 | let validate = mem::take(&mut opts.validate); |
| 140 | debug_assert!(validate); |
| 141 | |
| 142 | let askpass = mem::take(&mut opts.askpass); |
| 143 | let bell = mem::take(&mut opts.bell); |
| 144 | let reset_timestamp = mem::take(&mut opts.reset_timestamp); |
| 145 | let non_interactive = mem::take(&mut opts.non_interactive); |
| 146 | let stdin = mem::take(&mut opts.stdin); |
| 147 | let prompt = mem::take(&mut opts.prompt); |
| 148 | let group = mem::take(&mut opts.group); |
| 149 | let user = mem::take(&mut opts.user); |
| 150 | |
| 151 | if bell && stdin { |
| 152 | return Err(xlat!( |
| 153 | "{context} cannot be used together with {option}", |
| 154 | context = "--bell", |
| 155 | option = "--stdin" |
| 156 | )); |
| 157 | } |
| 158 | |
| 159 | reject_all("--validate", opts)?; |
| 160 | |
| 161 | Ok(Self { |
| 162 | askpass, |
| 163 | bell, |
| 164 | reset_timestamp, |
| 165 | non_interactive, |
| 166 | stdin, |
| 167 | prompt, |
| 168 | group, |
| 169 | user, |
| 170 | }) |
| 171 | } |
| 172 | } |
| 173 | |
| 174 | // sudo -e [-ABkNnS] [-r role] [-t type] [-C num] [-D directory] [-g group] [-h host] [-p prompt] [-R directory] [-T timeout] [-u user] file ... |
| 175 | pub struct SudoEditOptions { |
| 176 | // -A |
| 177 | pub askpass: bool, |
| 178 | // -B |
| 179 | pub bell: bool, |
| 180 | // -k |
| 181 | pub reset_timestamp: bool, |
| 182 | // -n |
| 183 | pub non_interactive: bool, |
| 184 | // -S |
| 185 | pub stdin: bool, |
| 186 | // -p |
| 187 | pub prompt: Option<String>, |
| 188 | // -D |
| 189 | pub chdir: Option<SudoPath>, |
| 190 | // -g |
| 191 | pub group: Option<SudoString>, |
| 192 | // -u |
| 193 | pub user: Option<SudoString>, |
| 194 | pub positional_args: Vec<OsString>, |
| 195 | } |
| 196 | |
| 197 | impl TryFrom<SudoOptions> for SudoEditOptions { |
| 198 | type Error = String; |
| 199 | |
| 200 | fn try_from(mut opts: SudoOptions) -> Result<Self, Self::Error> { |
| 201 | // see `SudoOptions::validate` |
| 202 | let edit = mem::take(&mut opts.edit); |
| 203 | debug_assert!(edit); |
| 204 | |
| 205 | let askpass = mem::take(&mut opts.askpass); |
| 206 | let bell = mem::take(&mut opts.bell); |
| 207 | let reset_timestamp = mem::take(&mut opts.reset_timestamp); |
| 208 | let non_interactive = mem::take(&mut opts.non_interactive); |
| 209 | let stdin = mem::take(&mut opts.stdin); |
| 210 | let prompt = mem::take(&mut opts.prompt); |
| 211 | let chdir = mem::take(&mut opts.chdir); |
| 212 | let group = mem::take(&mut opts.group); |
| 213 | let user = mem::take(&mut opts.user); |
| 214 | let positional_args = mem::take(&mut opts.positional_args); |
| 215 | |
| 216 | if bell && stdin { |
| 217 | return Err(xlat!( |
| 218 | "{context} cannot be used together with {option}", |
| 219 | context = "--bell", |
| 220 | option = "--stdin" |
| 221 | )); |
| 222 | } |
| 223 | |
| 224 | reject_all("--edit", opts)?; |
| 225 | |
| 226 | if positional_args.is_empty() { |
| 227 | return Err(xlat!("must specify at least one file path").into()); |
| 228 | } |
| 229 | |
| 230 | Ok(Self { |
| 231 | askpass, |
| 232 | bell, |
| 233 | reset_timestamp, |
| 234 | non_interactive, |
| 235 | stdin, |
| 236 | prompt, |
| 237 | chdir, |
| 238 | group, |
| 239 | user, |
| 240 | positional_args, |
| 241 | }) |
| 242 | } |
| 243 | } |
| 244 | |
| 245 | // sudo -l [-ABkNnS] [-g group] [-h host] [-p prompt] [-U user] [-u user] [command [arg ...]] |
| 246 | pub struct SudoListOptions { |
| 247 | // -A |
| 248 | pub askpass: bool, |
| 249 | // -B |
| 250 | pub bell: bool, |
| 251 | // -l OR -l -l |
| 252 | pub list: List, |
| 253 | |
| 254 | // -k |
| 255 | pub reset_timestamp: bool, |
| 256 | // -n |
| 257 | pub non_interactive: bool, |
| 258 | // -S |
| 259 | pub stdin: bool, |
| 260 | // -p |
| 261 | pub prompt: Option<String>, |
| 262 | // -g |
| 263 | pub group: Option<SudoString>, |
| 264 | // -U |
| 265 | pub other_user: Option<SudoString>, |
| 266 | // -u |
| 267 | pub user: Option<SudoString>, |
| 268 | |
| 269 | pub positional_args: Vec<OsString>, |
| 270 | } |
| 271 | |
| 272 | impl TryFrom<SudoOptions> for SudoListOptions { |
| 273 | type Error = String; |
| 274 | |
| 275 | fn try_from(mut opts: SudoOptions) -> Result<Self, Self::Error> { |
| 276 | let askpass = mem::take(&mut opts.askpass); |
| 277 | let bell = mem::take(&mut opts.bell); |
| 278 | let list = opts.list.take().unwrap(); |
| 279 | let reset_timestamp = mem::take(&mut opts.reset_timestamp); |
| 280 | let non_interactive = mem::take(&mut opts.non_interactive); |
| 281 | let stdin = mem::take(&mut opts.stdin); |
| 282 | let prompt = mem::take(&mut opts.prompt); |
| 283 | let group = mem::take(&mut opts.group); |
| 284 | let other_user = mem::take(&mut opts.other_user); |
| 285 | let user = mem::take(&mut opts.user); |
| 286 | let positional_args = mem::take(&mut opts.positional_args); |
| 287 | |
| 288 | if bell && stdin { |
| 289 | return Err(xlat!( |
| 290 | "{context} cannot be used together with {option}", |
| 291 | context = "--bell", |
| 292 | option = "--stdin" |
| 293 | )); |
| 294 | } |
| 295 | |
| 296 | // when present, `-u` must be accompanied by a command |
| 297 | let has_command = !positional_args.is_empty(); |
| 298 | let valid_user_flag = user.is_none() || has_command; |
| 299 | |
| 300 | if !valid_user_flag { |
| 301 | return Err(xlat!( |
| 302 | "'{option}' flag must be accompanied by a command", |
| 303 | option = "--user" |
| 304 | )); |
| 305 | } |
| 306 | |
| 307 | reject_all("--list", opts)?; |
| 308 | |
| 309 | Ok(Self { |
| 310 | askpass, |
| 311 | bell, |
| 312 | list, |
| 313 | reset_timestamp, |
| 314 | non_interactive, |
| 315 | stdin, |
| 316 | prompt, |
| 317 | group, |
| 318 | other_user, |
| 319 | user, |
| 320 | positional_args, |
| 321 | }) |
| 322 | } |
| 323 | } |
| 324 | |
| 325 | // sudo [-ABbEHnPS] [-C num] [-D directory] [-g group] [-h host] [-p prompt] [-R directory] [-T timeout] [-u user] [VAR=value] [-i | -s] [command [arg ...]] |
| 326 | pub struct SudoRunOptions { |
| 327 | // -A |
| 328 | pub askpass: bool, |
| 329 | // -B |
| 330 | pub bell: bool, |
| 331 | // -b |
| 332 | pub background: bool, |
| 333 | // -E |
| 334 | /* ignored, part of env_var_list */ |
| 335 | // -k |
| 336 | pub reset_timestamp: bool, |
| 337 | // -n |
| 338 | pub non_interactive: bool, |
| 339 | // -S |
| 340 | pub stdin: bool, |
| 341 | // -p |
| 342 | pub prompt: Option<String>, |
| 343 | // -D |
| 344 | pub chdir: Option<SudoPath>, |
| 345 | // -g |
| 346 | pub group: Option<SudoString>, |
| 347 | // -u |
| 348 | pub user: Option<SudoString>, |
| 349 | // VAR=value |
| 350 | pub env_var_list: Vec<(String, String)>, |
| 351 | // -i |
| 352 | pub login: bool, |
| 353 | // -s |
| 354 | pub shell: bool, |
| 355 | pub positional_args: Vec<OsString>, |
| 356 | } |
| 357 | |
| 358 | impl TryFrom<SudoOptions> for SudoRunOptions { |
| 359 | type Error = String; |
| 360 | |
| 361 | fn try_from(mut opts: SudoOptions) -> Result<Self, Self::Error> { |
| 362 | let askpass = mem::take(&mut opts.askpass); |
| 363 | let bell = mem::take(&mut opts.bell); |
| 364 | let background = mem::take(&mut opts.background); |
| 365 | let reset_timestamp = mem::take(&mut opts.reset_timestamp); |
| 366 | let non_interactive = mem::take(&mut opts.non_interactive); |
| 367 | let stdin = mem::take(&mut opts.stdin); |
| 368 | let prompt = mem::take(&mut opts.prompt); |
| 369 | let chdir = mem::take(&mut opts.chdir); |
| 370 | let group = mem::take(&mut opts.group); |
| 371 | let user = mem::take(&mut opts.user); |
| 372 | let env_var_list = mem::take(&mut opts.env_var_list); |
| 373 | let login = mem::take(&mut opts.login); |
| 374 | let shell = mem::take(&mut opts.shell); |
| 375 | let positional_args = mem::take(&mut opts.positional_args); |
| 376 | |
| 377 | if bell && stdin { |
| 378 | return Err(xlat!( |
| 379 | "{context} cannot be used together with {option}", |
| 380 | context = "--bell", |
| 381 | option = "--stdin" |
| 382 | )); |
| 383 | } |
| 384 | |
| 385 | let context = match (login, shell, positional_args.is_empty()) { |
| 386 | (true, false, _) => "--login", |
| 387 | (false, true, _) => "--shell", |
| 388 | (false, false, false) => xlat!("command (positional argument)"), |
| 389 | |
| 390 | (true, true, _) => { |
| 391 | return Err(xlat!( |
| 392 | "{context} cannot be used together with {option}", |
| 393 | context = "--login", |
| 394 | option = "--shell" |
| 395 | )); |
| 396 | } |
| 397 | (false, false, true) => { |
| 398 | if cfg!(debug_assertions) { |
| 399 | // see `SudoOptions::validate` |
| 400 | panic!(); |
| 401 | } else { |
| 402 | return Err(xlat!( |
| 403 | "expected one of: --login, --shell, a command as a positional argument" |
| 404 | ) |
| 405 | .into()); |
| 406 | } |
| 407 | } |
| 408 | }; |
| 409 | |
| 410 | reject_all(context, opts)?; |
| 411 | |
| 412 | Ok(Self { |
| 413 | askpass, |
| 414 | bell, |
| 415 | background, |
| 416 | reset_timestamp, |
| 417 | non_interactive, |
| 418 | stdin, |
| 419 | prompt, |
| 420 | chdir, |
| 421 | group, |
| 422 | user, |
| 423 | env_var_list, |
| 424 | login, |
| 425 | shell, |
| 426 | positional_args, |
| 427 | }) |
| 428 | } |
| 429 | } |
| 430 | |
| 431 | #[derive(Default)] |
| 432 | struct SudoOptions { |
| 433 | // -A |
| 434 | askpass: bool, |
| 435 | // -B |
| 436 | bell: bool, |
| 437 | // -b |
| 438 | background: bool, |
| 439 | // -D |
| 440 | chdir: Option<SudoPath>, |
| 441 | // -g |
| 442 | group: Option<SudoString>, |
| 443 | // -i |
| 444 | login: bool, |
| 445 | // -n |
| 446 | non_interactive: bool, |
| 447 | // -U |
| 448 | other_user: Option<SudoString>, |
| 449 | // -E |
| 450 | /* ignored, part of env_var_list */ |
| 451 | // -s |
| 452 | shell: bool, |
| 453 | // -S |
| 454 | stdin: bool, |
| 455 | // -p |
| 456 | prompt: Option<String>, |
| 457 | // -u |
| 458 | user: Option<SudoString>, |
| 459 | |
| 460 | // additional environment |
| 461 | env_var_list: Vec<(String, String)>, |
| 462 | |
| 463 | /* actions */ |
| 464 | // -e |
| 465 | edit: bool, |
| 466 | // -h |
| 467 | help: bool, |
| 468 | // -l |
| 469 | list: Option<List>, |
| 470 | // -K |
| 471 | remove_timestamp: bool, |
| 472 | // -k |
| 473 | reset_timestamp: bool, |
| 474 | // -v |
| 475 | validate: bool, |
| 476 | // -V |
| 477 | version: bool, |
| 478 | |
| 479 | // arguments passed straight through, either separated by -- or just trailing. |
| 480 | positional_args: Vec<OsString>, |
| 481 | } |
| 482 | |
| 483 | #[derive(Debug, Clone, PartialEq)] |
| 484 | pub enum List { |
| 485 | Once, |
| 486 | Verbose, |
| 487 | } |
| 488 | |
| 489 | impl List { |
| 490 | #[must_use] |
| 491 | pub fn is_verbose(&self) -> bool { |
| 492 | matches!(self, Self::Verbose) |
| 493 | } |
| 494 | } |
| 495 | |
| 496 | enum SudoArg { |
| 497 | Flag(String), |
| 498 | Argument(String, String), |
| 499 | Environment(String, String), |
| 500 | Rest(Vec<OsString>), |
| 501 | } |
| 502 | |
| 503 | fn demand_utf8(arg: &OsStr) -> String { |
| 504 | xlat!( |
| 505 | "argument '{arg}' is not valid UTF-8", |
| 506 | arg = DisplayOsStr(arg) |
| 507 | ) |
| 508 | } |
| 509 | |
| 510 | impl SudoArg { |
| 511 | const TAKES_ARGUMENT_SHORT: &'static [char] = &['D', 'g', 'h', 'p', 'R', 'U', 'u']; |
| 512 | const TAKES_ARGUMENT: &'static [&'static str] = &[ |
| 513 | "chdir", |
| 514 | "group", |
| 515 | "host", |
| 516 | "chroot", |
| 517 | "other-user", |
| 518 | "user", |
| 519 | "prompt", |
| 520 | ]; |
| 521 | |
| 522 | /// argument assignments and shorthand options preprocessing |
| 523 | /// the iterator should only iterate over the actual arguments |
| 524 | fn normalize_arguments<I>(mut arg_iter: I) -> Result<Vec<Self>, String> |
| 525 | where |
| 526 | I: Iterator<Item = OsString>, |
| 527 | { |
| 528 | let mut processed = vec![]; |
| 529 | |
| 530 | while let Some(arg) = arg_iter.next() { |
| 531 | if arg == "--" { |
| 532 | processed.push(SudoArg::Rest(arg_iter.collect())); |
| 533 | break; |
| 534 | } else if let Some(unprefixed) = arg.as_encoded_bytes().strip_prefix(b"--") { |
| 535 | let unprefixed = str::from_utf8(unprefixed).map_err(|_| demand_utf8(&arg))?; |
| 536 | |
| 537 | if let Some((key, value)) = unprefixed.split_once('=') { |
| 538 | // convert assignment to normal tokens |
| 539 | |
| 540 | // only accept arguments when one is expected |
| 541 | // `--preserve-env` is special as it only takes an argument using this `key=value` syntax |
| 542 | if !Self::TAKES_ARGUMENT.contains(&key) && key != "preserve-env" { |
| 543 | Err(xlat!( |
| 544 | "'{option}' does not take any arguments", |
| 545 | option = key |
| 546 | ))?; |
| 547 | } |
| 548 | processed.push(SudoArg::Argument("--".to_string() + key, value.to_string())); |
| 549 | } else if Self::TAKES_ARGUMENT.contains(&unprefixed) { |
| 550 | let arg = String::from_utf8(arg.into_encoded_bytes()).expect("already checked"); |
| 551 | if let Some(next) = arg_iter.next() { |
| 552 | let next = str::from_utf8(next.as_encoded_bytes()) |
| 553 | .map_err(|_| demand_utf8(&next))?; |
| 554 | processed.push(SudoArg::Argument(arg, next.to_owned())); |
| 555 | } else { |
| 556 | Err(xlat!("'{option}' expects an argument", option = arg))?; |
| 557 | } |
| 558 | } else { |
| 559 | let arg = String::from_utf8(arg.into_encoded_bytes()).expect("already checked"); |
| 560 | processed.push(SudoArg::Flag(arg)); |
| 561 | } |
| 562 | } else if let Some(unprefixed) = arg.as_encoded_bytes().strip_prefix(b"-") { |
| 563 | let unprefixed = str::from_utf8(unprefixed).map_err(|_| demand_utf8(&arg))?; |
| 564 | |
| 565 | // split combined shorthand options |
| 566 | let mut chars = unprefixed.chars(); |
| 567 | |
| 568 | while let Some(curr) = chars.next() { |
| 569 | let flag = format!("-{curr}"); |
| 570 | // convert option argument to separate segment |
| 571 | if Self::TAKES_ARGUMENT_SHORT.contains(&curr) { |
| 572 | let rest = chars.as_str(); |
| 573 | let next = chars.next(); |
| 574 | |
| 575 | // assignment syntax is not accepted for shorthand arguments |
| 576 | if next == Some('=') { |
| 577 | Err(xlat!("invalid option '='"))?; |
| 578 | } |
| 579 | if next.is_some() { |
| 580 | processed.push(SudoArg::Argument(flag, rest.to_string())); |
| 581 | } else if let Some(next) = arg_iter.next() { |
| 582 | let next = str::from_utf8(next.as_encoded_bytes()) |
| 583 | .map_err(|_| demand_utf8(&next))?; |
| 584 | processed.push(SudoArg::Argument(flag, next.to_owned())); |
| 585 | } else if curr == 'h' { |
| 586 | // short version of --help has no arguments |
| 587 | processed.push(SudoArg::Flag(flag)); |
| 588 | } else { |
| 589 | Err(xlat!("'{option}' expects an argument", option = flag))?; |
| 590 | } |
| 591 | break; |
| 592 | } else { |
| 593 | processed.push(SudoArg::Flag(flag)); |
| 594 | } |
| 595 | } |
| 596 | } else if let Some((key, value)) = try_to_env_var(&arg)? { |
| 597 | processed.push(SudoArg::Environment(key, value)); |
| 598 | } else { |
| 599 | let mut rest = vec![arg]; |
| 600 | rest.extend(arg_iter); |
| 601 | processed.push(SudoArg::Rest(rest)); |
| 602 | break; |
| 603 | } |
| 604 | } |
| 605 | |
| 606 | Ok(processed) |
| 607 | } |
| 608 | } |
| 609 | |
| 610 | impl SudoOptions { |
| 611 | fn validate(self) -> Result<SudoAction, String> { |
| 612 | let action = if self.help { |
| 613 | SudoAction::Help(self.try_into()?) |
| 614 | } else if self.version { |
| 615 | SudoAction::Version(self.try_into()?) |
| 616 | } else if self.remove_timestamp { |
| 617 | SudoAction::RemoveTimestamp(self.try_into()?) |
| 618 | } else if self.validate { |
| 619 | SudoAction::Validate(self.try_into()?) |
| 620 | } else if self.list.is_some() { |
| 621 | SudoAction::List(self.try_into()?) |
| 622 | } else if self.edit { |
| 623 | SudoAction::Edit(self.try_into()?) |
| 624 | } else { |
| 625 | let is_run = self.login | self.shell | !self.positional_args.is_empty(); |
| 626 | |
| 627 | if is_run { |
| 628 | SudoAction::Run(self.try_into()?) |
| 629 | } else if self.reset_timestamp { |
| 630 | SudoAction::ResetTimestamp(self.try_into()?) |
| 631 | } else { |
| 632 | return Err(xlat!("expected one of these actions: --help, --version, --remove-timestamp, --validate, --list, --edit, --login, --shell, a command as a positional argument, --reset-timestamp").into()); |
| 633 | } |
| 634 | }; |
| 635 | |
| 636 | Ok(action) |
| 637 | } |
| 638 | |
| 639 | /// parse an iterator over command line arguments |
| 640 | fn try_parse_from<I, T>(iter: I) -> Result<Self, String> |
| 641 | where |
| 642 | I: IntoIterator<Item = T>, |
| 643 | T: Into<OsString> + Clone, |
| 644 | { |
| 645 | let mut arg_iter = iter.into_iter().map(Into::into); |
| 646 | |
| 647 | let invoked_as_sudoedit = is_sudoedit(arg_iter.next()); |
| 648 | |
| 649 | let mut options = Self { |
| 650 | edit: invoked_as_sudoedit, |
| 651 | ..Self::default() |
| 652 | }; |
| 653 | |
| 654 | let arg_iter = SudoArg::normalize_arguments(arg_iter)? |
| 655 | .into_iter() |
| 656 | .peekable(); |
| 657 | |
| 658 | for arg in arg_iter { |
| 659 | match arg { |
| 660 | SudoArg::Flag(flag) => match flag.as_str() { |
| 661 | "-A" | "--askpass" => { |
| 662 | options.askpass = true; |
| 663 | } |
| 664 | "-B" | "--bell" => { |
| 665 | options.bell = true; |
| 666 | } |
| 667 | "-b" | "--background" => { |
| 668 | options.background = true; |
| 669 | } |
| 670 | "-E" | "--preserve-env" => { |
| 671 | user_warn!( |
| 672 | "preserving the entire environment is not supported, '{flag}' is ignored", |
| 673 | flag = flag |
| 674 | ) |
| 675 | } |
| 676 | "-e" | "--edit" if !invoked_as_sudoedit => { |
| 677 | options.edit = true; |
| 678 | } |
| 679 | "-H" | "--set-home" => { |
| 680 | // this option is ignored, since it is the default for sudo-rs; but accept |
| 681 | // it for backwards compatibility reasons |
| 682 | } |
| 683 | "-h" | "--help" => { |
| 684 | options.help = true; |
| 685 | } |
| 686 | "-i" | "--login" => { |
| 687 | options.login = true; |
| 688 | } |
| 689 | "-K" | "--remove-timestamp" => { |
| 690 | options.remove_timestamp = true; |
| 691 | } |
| 692 | "-k" | "--reset-timestamp" => { |
| 693 | options.reset_timestamp = true; |
| 694 | } |
| 695 | "-l" | "--list" => match options.list { |
| 696 | None => options.list = Some(List::Once), |
| 697 | Some(List::Once) => options.list = Some(List::Verbose), |
| 698 | Some(List::Verbose) => {} |
| 699 | }, |
| 700 | "-n" | "--non-interactive" => { |
| 701 | options.non_interactive = true; |
| 702 | } |
| 703 | "-S" | "--stdin" => { |
| 704 | options.stdin = true; |
| 705 | } |
| 706 | "-s" | "--shell" => { |
| 707 | options.shell = true; |
| 708 | } |
| 709 | "-V" | "--version" => { |
| 710 | options.version = true; |
| 711 | } |
| 712 | "-v" | "--validate" => { |
| 713 | options.validate = true; |
| 714 | } |
| 715 | _option => { |
| 716 | Err(xlat!("invalid option provided"))?; |
| 717 | } |
| 718 | }, |
| 719 | SudoArg::Argument(option, value) => match option.as_str() { |
| 720 | "-D" | "--chdir" => { |
| 721 | options.chdir = Some(SudoPath::from_cli_string(value)); |
| 722 | } |
| 723 | "-E" | "--preserve-env" => { |
| 724 | options |
| 725 | .env_var_list |
| 726 | .extend(value.split(',').filter_map(|var| { |
| 727 | std::env::var(var) |
| 728 | .ok() |
| 729 | .map(|value| (var.to_string(), value)) |
| 730 | })); |
| 731 | } |
| 732 | "-g" | "--group" => { |
| 733 | options.group = Some(SudoString::from_cli_string(value)); |
| 734 | } |
| 735 | "-p" | "--prompt" => { |
| 736 | options.prompt = Some(value); |
| 737 | } |
| 738 | "-U" | "--other-user" => { |
| 739 | options.other_user = Some(SudoString::from_cli_string(value)); |
| 740 | } |
| 741 | "-u" | "--user" => { |
| 742 | options.user = Some(SudoString::from_cli_string(value)); |
| 743 | } |
| 744 | _option => { |
| 745 | Err(xlat!("invalid option provided"))?; |
| 746 | } |
| 747 | }, |
| 748 | SudoArg::Environment(key, value) => { |
| 749 | options.env_var_list.push((key, value)); |
| 750 | } |
| 751 | SudoArg::Rest(mut rest) => { |
| 752 | if let Some(cmd) = rest.first() { |
| 753 | let cmd = std::path::Path::new(cmd); |
| 754 | // This checks if the last character in the path is a /. This |
| 755 | // works because the OS directly splits at b'/' without regards |
| 756 | // for if it is part of another character (which it can't be |
| 757 | // with UTF-8 anyways). |
| 758 | let is_dir = cmd.as_os_str().as_encoded_bytes().ends_with(b"/"); |
| 759 | if !options.edit |
| 760 | && !is_dir |
| 761 | && (cmd.ends_with("sudoedit") || cmd.ends_with("sudoedit-rs")) |
| 762 | { |
| 763 | user_warn!("sudoedit doesn't need to be run via sudo"); |
| 764 | options.edit = true; |
| 765 | rest.remove(0); |
| 766 | } |
| 767 | } |
| 768 | |
| 769 | options.positional_args = rest; |
| 770 | } |
| 771 | } |
| 772 | } |
| 773 | |
| 774 | Ok(options) |
| 775 | } |
| 776 | } |
| 777 | |
| 778 | fn try_to_env_var(arg: &OsStr) -> Result<Option<(String, String)>, String> { |
| 779 | if !arg.as_encoded_bytes().contains(&b'=') { |
| 780 | return Ok(None); |
| 781 | } |
| 782 | |
| 783 | let arg = str::from_utf8(arg.as_encoded_bytes()).map_err(|_| demand_utf8(arg))?; |
| 784 | |
| 785 | let (name, value) = arg |
| 786 | .split_once('=') |
| 787 | .expect("checked above that an = is present"); |
| 788 | |
| 789 | if name.chars().all(|c| c.is_alphanumeric() || c == '_') { |
| 790 | Ok(Some((name.to_owned(), value.to_owned()))) |
| 791 | } else { |
| 792 | Ok(None) |
| 793 | } |
| 794 | } |
| 795 | |
| 796 | trait IsAbsent { |
| 797 | fn is_absent(&self) -> bool; |
| 798 | } |
| 799 | |
| 800 | impl IsAbsent for bool { |
| 801 | fn is_absent(&self) -> bool { |
| 802 | !*self |
| 803 | } |
| 804 | } |
| 805 | |
| 806 | impl<T> IsAbsent for Option<T> { |
| 807 | fn is_absent(&self) -> bool { |
| 808 | self.is_none() |
| 809 | } |
| 810 | } |
| 811 | |
| 812 | impl<T> IsAbsent for Vec<T> { |
| 813 | fn is_absent(&self) -> bool { |
| 814 | self.is_empty() |
| 815 | } |
| 816 | } |
| 817 | |
| 818 | fn ensure_is_absent(context: &str, thing: &dyn IsAbsent, name: &str) -> Result<(), String> { |
| 819 | if thing.is_absent() { |
| 820 | Ok(()) |
| 821 | } else { |
| 822 | Err(xlat!( |
| 823 | "{context} cannot be used together with {option}", |
| 824 | context = context, |
| 825 | option = name |
| 826 | )) |
| 827 | } |
| 828 | } |
| 829 | |
| 830 | fn reject_all(context: &str, opts: SudoOptions) -> Result<(), String> { |
| 831 | macro_rules! check_options { |
| 832 | ($($field:ident $(= $name:expr)?,)*) => {{ |
| 833 | let SudoOptions { $($field),* } = opts; |
| 834 | |
| 835 | $( |
| 836 | let name = check_options!(@name $field $($name)?); |
| 837 | ensure_is_absent(context, &$field, &name)?; |
| 838 | )* |
| 839 | |
| 840 | Ok(()) |
| 841 | }}; |
| 842 | (@name $field:ident) => {{ |
| 843 | let name = concat!("--", stringify!($field)); |
| 844 | if name.contains('_') { |
| 845 | Cow::Owned(name.replace('_', "-")) |
| 846 | } else { |
| 847 | Cow::Borrowed(name) |
| 848 | } |
| 849 | }}; |
| 850 | (@name $field:ident $name:expr) => { |
| 851 | $name |
| 852 | }; |
| 853 | } |
| 854 | |
| 855 | check_options!( |
| 856 | askpass, |
| 857 | bell, |
| 858 | background, |
| 859 | chdir, |
| 860 | edit, |
| 861 | group, |
| 862 | help, |
| 863 | list, |
| 864 | login, |
| 865 | non_interactive, |
| 866 | other_user, |
| 867 | remove_timestamp, |
| 868 | reset_timestamp, |
| 869 | shell, |
| 870 | stdin, |
| 871 | prompt, |
| 872 | user, |
| 873 | validate, |
| 874 | version, |
| 875 | positional_args = xlat!("command"), |
| 876 | env_var_list = xlat!("environment variable"), |
| 877 | ) |
| 878 | } |