| 1 | use super::super::cli::SudoEditOptions; |
| 2 | use crate::common::{Context, DisplayOsStr, Error}; |
| 3 | use crate::log::{user_error, user_info}; |
| 4 | use crate::sudoers::Authorization; |
| 5 | use crate::system::audit; |
| 6 | |
| 7 | pub fn run_edit(edit_opts: SudoEditOptions) -> Result<(), Error> { |
| 8 | let policy = super::read_sudoers()?; |
| 9 | |
| 10 | let context = Context::from_edit_opts(edit_opts)?; |
| 11 | |
| 12 | let policy = super::judge(policy, &context)?; |
| 13 | |
| 14 | let Authorization::Allowed(auth, _controls) = policy.authorization() else { |
| 15 | return Err(Error::Authorization(context.current_user.name.to_string())); |
| 16 | }; |
| 17 | |
| 18 | let mut pam_context = super::auth_and_update_record_file(&context, auth)?; |
| 19 | |
| 20 | let mut opened_files = Vec::with_capacity(context.files_to_edit.len()); |
| 21 | for (path, arg) in context.files_to_edit.iter().zip(&context.command.arguments) { |
| 22 | if let Some(path) = path { |
| 23 | match audit::secure_open_for_sudoedit( |
| 24 | path, |
| 25 | &context.current_user, |
| 26 | &context.target_user, |
| 27 | &context.target_group, |
| 28 | ) { |
| 29 | Ok(file) => opened_files.push((path, file)), |
| 30 | // ErrorKind::FilesystemLoop was only stabilized in 1.83 |
| 31 | Err(error) if error.raw_os_error() == Some(libc::ELOOP) => { |
| 32 | user_error!( |
| 33 | "{path}: editing symbolic links is not permitted", |
| 34 | path = DisplayOsStr(arg), |
| 35 | ) |
| 36 | } |
| 37 | Err(error) => { |
| 38 | user_error!( |
| 39 | "error opening {path}: {error}", |
| 40 | path = DisplayOsStr(arg), |
| 41 | error = error, |
| 42 | ) |
| 43 | } |
| 44 | } |
| 45 | } else { |
| 46 | user_error!("invalid path: {path}", path = DisplayOsStr(arg)); |
| 47 | } |
| 48 | } |
| 49 | |
| 50 | if opened_files.len() != context.files_to_edit.len() { |
| 51 | user_info!("please address the problems and try again"); |
| 52 | return Err(Error::Silent); |
| 53 | } |
| 54 | |
| 55 | // run command and return corresponding exit code |
| 56 | let command_exit_reason = { |
| 57 | super::log_command_execution(&context); |
| 58 | |
| 59 | let editor = policy.preferred_editor(); |
| 60 | |
| 61 | crate::sudo::edit::edit_files(editor, opened_files) |
| 62 | }; |
| 63 | |
| 64 | pam_context.close_session(); |
| 65 | |
| 66 | match command_exit_reason?.exit_process()? {} |
| 67 | } |