| 1 | #![allow(unsafe_code)] |
| 2 | |
| 3 | use std::ffi::OsString; |
| 4 | use std::fs::File; |
| 5 | use std::io::{Read, Seek, Write}; |
| 6 | use std::net::Shutdown; |
| 7 | use std::os::unix::{fs::OpenOptionsExt, net::UnixStream, process::ExitStatusExt}; |
| 8 | use std::path::{Path, PathBuf}; |
| 9 | use std::process::Command; |
| 10 | use std::{io, process}; |
| 11 | |
| 12 | use crate::common::SudoPath; |
| 13 | use crate::exec::ExitReason; |
| 14 | use crate::log::{user_error, user_info}; |
| 15 | use crate::system::file::{FileLock, create_temporary_dir}; |
| 16 | use crate::system::wait::{Wait, WaitError, WaitOptions}; |
| 17 | use crate::system::{ForkResult, audit, fork, mark_fds_as_cloexec}; |
| 18 | |
| 19 | struct ParentFileInfo<'a> { |
| 20 | path: &'a Path, |
| 21 | file: File, |
| 22 | lock: FileLock, |
| 23 | old_data: Vec<u8>, |
| 24 | new_data_rx: UnixStream, |
| 25 | new_data: Option<Vec<u8>>, |
| 26 | } |
| 27 | |
| 28 | struct ChildFileInfo<'a> { |
| 29 | path: &'a Path, |
| 30 | old_data: Vec<u8>, |
| 31 | tempfile_path: Option<PathBuf>, |
| 32 | new_data_tx: UnixStream, |
| 33 | } |
| 34 | |
| 35 | pub(super) fn edit_files( |
| 36 | editor: (PathBuf, Vec<OsString>), |
| 37 | selected_files: Vec<(&SudoPath, File)>, |
| 38 | ) -> io::Result<ExitReason> { |
| 39 | let mut files = vec![]; |
| 40 | let mut child_files = vec![]; |
| 41 | for (path, mut file) in selected_files { |
| 42 | // Error for special files |
| 43 | let metadata = file.metadata().map_err(|e| { |
| 44 | io::Error::new( |
| 45 | e.kind(), |
| 46 | xlat!( |
| 47 | "failed to read metadata for {path}: {error}", |
| 48 | path = path.display(), |
| 49 | error = e |
| 50 | ), |
| 51 | ) |
| 52 | })?; |
| 53 | if !metadata.is_file() { |
| 54 | return Err(io::Error::other(xlat!( |
| 55 | "file {path} is not a regular file", |
| 56 | path = path.display() |
| 57 | ))); |
| 58 | } |
| 59 | |
| 60 | // Take file lock |
| 61 | let lock = FileLock::exclusive(&file, true).map_err(|e| { |
| 62 | io::Error::new( |
| 63 | e.kind(), |
| 64 | xlat!( |
| 65 | "failed to lock {path}: {error}", |
| 66 | path = path.display(), |
| 67 | error = e |
| 68 | ), |
| 69 | ) |
| 70 | })?; |
| 71 | |
| 72 | // Read file |
| 73 | let mut old_data = Vec::new(); |
| 74 | file.read_to_end(&mut old_data).map_err(|e| { |
| 75 | io::Error::new( |
| 76 | e.kind(), |
| 77 | xlat!( |
| 78 | "failed to read {path}: {error}", |
| 79 | path = path.display(), |
| 80 | error = e |
| 81 | ), |
| 82 | ) |
| 83 | })?; |
| 84 | |
| 85 | // Create socket |
| 86 | let (parent_socket, child_socket) = UnixStream::pair()?; |
| 87 | |
| 88 | files.push(ParentFileInfo { |
| 89 | path, |
| 90 | file, |
| 91 | lock, |
| 92 | old_data: old_data.clone(), |
| 93 | new_data_rx: parent_socket, |
| 94 | new_data: None, |
| 95 | }); |
| 96 | |
| 97 | child_files.push(ChildFileInfo { |
| 98 | path, |
| 99 | old_data, |
| 100 | tempfile_path: None, |
| 101 | new_data_tx: child_socket, |
| 102 | }); |
| 103 | } |
| 104 | |
| 105 | // Spawn child |
| 106 | // SAFETY: There should be no other threads at this point. |
| 107 | let ForkResult::Parent(command_pid) = unsafe { fork() }? else { |
| 108 | drop(files); |
| 109 | handle_child(editor, child_files) |
| 110 | }; |
| 111 | drop(child_files); |
| 112 | |
| 113 | for file in &mut files { |
| 114 | // Read from socket |
| 115 | file.new_data = |
| 116 | Some(read_stream(&mut file.new_data_rx).map_err(|e| { |
| 117 | io::Error::new(e.kind(), format!("Failed to read from socket: {e}")) |
| 118 | })?); |
| 119 | } |
| 120 | |
| 121 | // If child has error, exit with non-zero exit code |
| 122 | let status = loop { |
| 123 | match command_pid.wait(WaitOptions::new()) { |
| 124 | Ok((_, status)) => break status, |
| 125 | Err(WaitError::Io(err)) if err.kind() == io::ErrorKind::Interrupted => {} |
| 126 | Err(err) => panic!("{err:?}"), |
| 127 | } |
| 128 | }; |
| 129 | assert!(status.did_exit()); |
| 130 | |
| 131 | if let Some(signal) = status.term_signal() { |
| 132 | return Ok(ExitReason::Signal(signal)); |
| 133 | } else if let Some(code) = status.exit_status() { |
| 134 | if code != 0 { |
| 135 | return Ok(ExitReason::Code(code)); |
| 136 | } |
| 137 | } else { |
| 138 | return Ok(ExitReason::Code(1)); |
| 139 | } |
| 140 | |
| 141 | for mut file in files { |
| 142 | let data = file.new_data.expect("filled in above"); |
| 143 | if data == file.old_data { |
| 144 | // File unchanged. No need to write it again. |
| 145 | user_info!("{path} unchanged", path = file.path.display()); |
| 146 | continue; |
| 147 | } |
| 148 | |
| 149 | // FIXME check if modified since reading and if so ask user what to do |
| 150 | |
| 151 | // Write file |
| 152 | (move || { |
| 153 | file.file.rewind()?; |
| 154 | file.file.write_all(&data)?; |
| 155 | file.file.set_len( |
| 156 | data.len() |
| 157 | .try_into() |
| 158 | .expect("more than 18 exabyte of data???"), |
| 159 | ) |
| 160 | })() |
| 161 | .map_err(|e| { |
| 162 | io::Error::new( |
| 163 | e.kind(), |
| 164 | xlat!( |
| 165 | "failed to write {path}: {error}", |
| 166 | path = file.path.display(), |
| 167 | error = e |
| 168 | ), |
| 169 | ) |
| 170 | })?; |
| 171 | |
| 172 | drop(file.lock); |
| 173 | } |
| 174 | |
| 175 | Ok(ExitReason::Code(0)) |
| 176 | } |
| 177 | |
| 178 | struct TempDirDropGuard(PathBuf); |
| 179 | |
| 180 | impl Drop for TempDirDropGuard { |
| 181 | fn drop(&mut self) { |
| 182 | if let Err(e) = std::fs::remove_dir_all(&self.0) { |
| 183 | user_error!( |
| 184 | "failed to remove temporary directory {path}: {error}", |
| 185 | path = self.0.display(), |
| 186 | error = e |
| 187 | ); |
| 188 | }; |
| 189 | } |
| 190 | } |
| 191 | |
| 192 | fn handle_child(editor: (PathBuf, Vec<OsString>), file: Vec<ChildFileInfo<'_>>) -> ! { |
| 193 | match handle_child_inner(editor, file) { |
| 194 | Ok(()) => process::exit(0), |
| 195 | Err(err) => { |
| 196 | user_error!("{error}", error = err); |
| 197 | process::exit(1); |
| 198 | } |
| 199 | } |
| 200 | } |
| 201 | |
| 202 | // FIXME maybe use pipes once std::io::pipe has been stabilized long enough. |
| 203 | fn handle_child_inner( |
| 204 | editor: (PathBuf, Vec<OsString>), |
| 205 | mut files: Vec<ChildFileInfo<'_>>, |
| 206 | ) -> Result<(), String> { |
| 207 | mark_fds_as_cloexec().map_err(|e| format!("Failed to mark fds as CLOEXEC: {e}"))?; |
| 208 | |
| 209 | // root privileges are dangerous after this point, since we are about to manipulate the |
| 210 | // file system and execute a command under control of the user, so drop them |
| 211 | audit::irrevocably_drop_privileges(); |
| 212 | |
| 213 | let tempdir = TempDirDropGuard( |
| 214 | create_temporary_dir() |
| 215 | .map_err(|e| xlat!("failed to create temporary directory: {error}", error = e))?, |
| 216 | ); |
| 217 | |
| 218 | for (i, file) in files.iter_mut().enumerate() { |
| 219 | // Create temp file |
| 220 | let dir = tempdir.0.join(format!("{i}")); |
| 221 | std::fs::create_dir(&dir).map_err(|e| { |
| 222 | xlat!( |
| 223 | "failed to create temporary directory {path}: {error}", |
| 224 | path = dir.display(), |
| 225 | error = e |
| 226 | ) |
| 227 | })?; |
| 228 | let tempfile_path = dir.join(file.path.file_name().expect("file must have filename")); |
| 229 | let mut tempfile = std::fs::OpenOptions::new() |
| 230 | .read(true) |
| 231 | .write(true) |
| 232 | .create_new(true) |
| 233 | .mode(0o600) |
| 234 | .open(&tempfile_path) |
| 235 | .map_err(|e| { |
| 236 | xlat!( |
| 237 | "failed to create temporary file {path}: {error}", |
| 238 | path = tempfile_path.display(), |
| 239 | error = e |
| 240 | ) |
| 241 | })?; |
| 242 | |
| 243 | // Write to temp file |
| 244 | tempfile.write_all(&file.old_data).map_err(|e| { |
| 245 | xlat!( |
| 246 | "failed to write to temporary file {path}: {error}", |
| 247 | path = tempfile_path.display(), |
| 248 | error = e |
| 249 | ) |
| 250 | })?; |
| 251 | drop(tempfile); |
| 252 | file.tempfile_path = Some(tempfile_path); |
| 253 | } |
| 254 | |
| 255 | // Spawn editor |
| 256 | let status = Command::new(&editor.0) |
| 257 | .args(editor.1) |
| 258 | .args( |
| 259 | files |
| 260 | .iter() |
| 261 | .map(|file| file.tempfile_path.as_ref().expect("filled in above")), |
| 262 | ) |
| 263 | .status() |
| 264 | .map_err(|e| { |
| 265 | xlat!( |
| 266 | "failed to run editor {path}: {error}", |
| 267 | path = editor.0.display(), |
| 268 | error = e |
| 269 | ) |
| 270 | })?; |
| 271 | |
| 272 | if !status.success() { |
| 273 | drop(tempdir); |
| 274 | |
| 275 | if let Some(signal) = status.signal() { |
| 276 | process::exit(128 + signal); |
| 277 | } |
| 278 | process::exit(status.code().unwrap_or(1)); |
| 279 | } |
| 280 | |
| 281 | for mut file in files { |
| 282 | let tempfile_path = file.tempfile_path.as_ref().expect("filled in above"); |
| 283 | |
| 284 | // Read from temp file |
| 285 | let new_data = std::fs::read(tempfile_path).map_err(|e| { |
| 286 | xlat!( |
| 287 | "failed to read from temporary file {path}: {error}", |
| 288 | path = tempfile_path.display(), |
| 289 | error = e |
| 290 | ) |
| 291 | })?; |
| 292 | |
| 293 | // FIXME preserve temporary file if the original couldn't be written to |
| 294 | std::fs::remove_file(tempfile_path).map_err(|e| { |
| 295 | xlat!( |
| 296 | "failed to remove temporary file {path}: {error}", |
| 297 | path = tempfile_path.display(), |
| 298 | error = e |
| 299 | ) |
| 300 | })?; |
| 301 | |
| 302 | // If the file has been changed to be empty, ask the user what to do. |
| 303 | if new_data.is_empty() && new_data != file.old_data { |
| 304 | // TRANSLATORS: the initial letters of 'yes' and 'no' responses, in that order |
| 305 | let answers = xlat!("yn"); |
| 306 | |
| 307 | match crate::visudo::ask_response( |
| 308 | &xlat!( |
| 309 | "sudoedit: truncate {path} to zero? (y/n) [n] ", |
| 310 | path = file.path.display() |
| 311 | ), |
| 312 | answers, |
| 313 | answers |
| 314 | .chars() |
| 315 | .last() |
| 316 | .expect("translation files are corrupted"), |
| 317 | ) { |
| 318 | Ok(val) if answers.starts_with(val) => {} |
| 319 | // a fallback: also accept 'yes' based on Debian's apt behaviour |
| 320 | Ok('y') if !answers.contains('y') => {} |
| 321 | _ => { |
| 322 | user_info!("not overwriting {path}", path = file.path.display()); |
| 323 | |
| 324 | // Parent ignores write when new data matches old data |
| 325 | write_stream(&mut file.new_data_tx, &file.old_data) |
| 326 | .map_err(|e| xlat!("failed to write data to parent: {error}", error = e))?; |
| 327 | |
| 328 | continue; |
| 329 | } |
| 330 | } |
| 331 | } |
| 332 | |
| 333 | // Write to socket |
| 334 | write_stream(&mut file.new_data_tx, &new_data) |
| 335 | .map_err(|e| xlat!("failed to write data to parent: {error}", error = e))?; |
| 336 | } |
| 337 | |
| 338 | process::exit(0); |
| 339 | } |
| 340 | |
| 341 | fn write_stream(socket: &mut UnixStream, data: &[u8]) -> io::Result<()> { |
| 342 | socket.write_all(data)?; |
| 343 | socket.shutdown(Shutdown::Both)?; |
| 344 | Ok(()) |
| 345 | } |
| 346 | |
| 347 | fn read_stream(socket: &mut UnixStream) -> io::Result<Vec<u8>> { |
| 348 | let mut new_data = Vec::new(); |
| 349 | socket.read_to_end(&mut new_data)?; |
| 350 | Ok(new_data) |
| 351 | } |