writer.rs (15240B)
1 use std::ffi::{OsStr, OsString}; 2 #[cfg(any(test, not(unix)))] 3 use std::fs; 4 use std::fs::File; 5 use std::io::{self, Write}; 6 use std::path::{Path, PathBuf}; 7 8 #[cfg(all(test, unix))] 9 #[path = "writer_file_kind_tests.rs"] 10 mod file_kind_tests; 11 12 const DEFAULT_MAX_FILE_BYTES: u64 = 10 * 1024 * 1024; 13 const DEFAULT_RETAINED_FILES: usize = 5; 14 15 #[derive(Debug, Clone, Copy, PartialEq, Eq)] 16 pub(super) struct LogRotation { 17 max_file_bytes: u64, 18 retained_files: usize, 19 } 20 21 impl Default for LogRotation { 22 fn default() -> Self { 23 Self { 24 max_file_bytes: DEFAULT_MAX_FILE_BYTES, 25 retained_files: DEFAULT_RETAINED_FILES, 26 } 27 } 28 } 29 30 pub(super) struct SizeRotatingWriter { 31 #[cfg(not(unix))] 32 path: PathBuf, 33 #[cfg(unix)] 34 directory: File, 35 file_name: OsString, 36 file: Option<File>, 37 bytes_written: u64, 38 policy: LogRotation, 39 } 40 41 impl SizeRotatingWriter { 42 pub(super) fn new(path: PathBuf, policy: LogRotation) -> io::Result<Self> { 43 let file_name = path 44 .file_name() 45 .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "log target has no name"))? 46 .to_owned(); 47 #[cfg(unix)] 48 let directory = open_secure_directory(path.parent().ok_or_else(|| { 49 io::Error::new(io::ErrorKind::InvalidInput, "log target has no parent") 50 })?)?; 51 #[cfg(unix)] 52 let file = open_append_at(&directory, &file_name)?; 53 #[cfg(not(unix))] 54 let file = open_append(&path)?; 55 let bytes_written = file.metadata()?.len(); 56 let mut writer = Self { 57 #[cfg(not(unix))] 58 path, 59 #[cfg(unix)] 60 directory, 61 file_name, 62 file: Some(file), 63 bytes_written, 64 policy, 65 }; 66 if writer.bytes_written >= writer.policy.max_file_bytes { 67 writer.rotate()?; 68 } 69 Ok(writer) 70 } 71 72 fn rotate(&mut self) -> io::Result<()> { 73 if let Some(mut file) = self.file.take() { 74 file.flush()?; 75 file.sync_data()?; 76 } 77 if self.policy.retained_files == 1 { 78 self.remove_if_present(&self.file_name)?; 79 } else { 80 self.remove_if_present(&rotated_name( 81 &self.file_name, 82 self.policy.retained_files - 1, 83 ))?; 84 for index in (2..self.policy.retained_files).rev() { 85 self.rename_if_present( 86 &rotated_name(&self.file_name, index - 1), 87 &rotated_name(&self.file_name, index), 88 )?; 89 } 90 self.rename_if_present(&self.file_name, &rotated_name(&self.file_name, 1))?; 91 } 92 #[cfg(unix)] 93 let file = open_append_at(&self.directory, &self.file_name)?; 94 #[cfg(not(unix))] 95 let file = open_append(&self.path)?; 96 self.file = Some(file); 97 self.bytes_written = 0; 98 Ok(()) 99 } 100 101 fn remove_if_present(&self, name: &OsStr) -> io::Result<()> { 102 #[cfg(unix)] 103 { 104 use rustix::fs::{AtFlags, unlinkat}; 105 match unlinkat(&self.directory, name, AtFlags::empty()) { 106 Ok(()) => Ok(()), 107 Err(error) if error == rustix::io::Errno::NOENT => Ok(()), 108 Err(error) => Err(io::Error::from_raw_os_error(error.raw_os_error())), 109 } 110 } 111 #[cfg(not(unix))] 112 remove_if_present(&self.path.with_file_name(name)) 113 } 114 115 fn rename_if_present(&self, source: &OsStr, target: &OsStr) -> io::Result<()> { 116 #[cfg(unix)] 117 { 118 use rustix::fs::renameat; 119 match renameat(&self.directory, source, &self.directory, target) { 120 Ok(()) => Ok(()), 121 Err(error) if error == rustix::io::Errno::NOENT => Ok(()), 122 Err(error) => Err(io::Error::from_raw_os_error(error.raw_os_error())), 123 } 124 } 125 #[cfg(not(unix))] 126 rename_if_present( 127 &self.path.with_file_name(source), 128 &self.path.with_file_name(target), 129 ) 130 } 131 132 fn file_mut(&mut self) -> io::Result<&mut File> { 133 self.file 134 .as_mut() 135 .ok_or_else(|| io::Error::other("log file is unavailable")) 136 } 137 } 138 139 impl Write for SizeRotatingWriter { 140 fn write(&mut self, buffer: &[u8]) -> io::Result<usize> { 141 let incoming = u64::try_from(buffer.len()) 142 .map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, "log event is too large"))?; 143 if incoming > self.policy.max_file_bytes { 144 return Err(io::Error::new( 145 io::ErrorKind::InvalidData, 146 "log event exceeds the configured file limit", 147 )); 148 } 149 if self.bytes_written > 0 150 && self.bytes_written.saturating_add(incoming) > self.policy.max_file_bytes 151 { 152 self.rotate()?; 153 } 154 let written = self.file_mut()?.write(buffer)?; 155 self.bytes_written = self 156 .bytes_written 157 .saturating_add(u64::try_from(written).unwrap_or(u64::MAX)); 158 Ok(written) 159 } 160 161 fn flush(&mut self) -> io::Result<()> { 162 self.file_mut()?.flush() 163 } 164 } 165 166 #[cfg(test)] 167 fn reject_unsafe_target(path: &Path) -> io::Result<()> { 168 match fs::symlink_metadata(path) { 169 Ok(metadata) if metadata.file_type().is_symlink() || !metadata.is_file() => Err( 170 io::Error::new(io::ErrorKind::InvalidInput, "log target is not a safe file"), 171 ), 172 Ok(_) => Ok(()), 173 Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(()), 174 Err(error) => Err(error), 175 } 176 } 177 178 #[cfg(unix)] 179 fn open_secure_directory(path: &Path) -> io::Result<File> { 180 use rustix::fs::{FileType, Mode, OFlags, fstat, open}; 181 use rustix::process::geteuid; 182 183 let directory = open( 184 path, 185 OFlags::RDONLY | OFlags::DIRECTORY | OFlags::NOFOLLOW | OFlags::CLOEXEC, 186 Mode::empty(), 187 ) 188 .map_err(errno_to_io)?; 189 let status = fstat(&directory).map_err(errno_to_io)?; 190 if FileType::from_raw_mode(status.st_mode) != FileType::Directory 191 || status.st_uid != geteuid().as_raw() 192 || status.st_mode & 0o022 != 0 193 { 194 return Err(io::Error::new( 195 io::ErrorKind::PermissionDenied, 196 "log parent must be an owner-controlled non-writable directory", 197 )); 198 } 199 Ok(File::from(directory)) 200 } 201 202 #[cfg(unix)] 203 fn open_append_at(directory: &File, name: &OsStr) -> io::Result<File> { 204 use rustix::fs::{FileType, Mode, OFlags, fchmod, fstat, openat}; 205 206 let descriptor = openat( 207 directory, 208 name, 209 OFlags::WRONLY 210 | OFlags::APPEND 211 | OFlags::CREATE 212 | OFlags::NOFOLLOW 213 | OFlags::NONBLOCK 214 | OFlags::CLOEXEC, 215 Mode::RUSR | Mode::WUSR, 216 ) 217 .map_err(errno_to_io)?; 218 let status = fstat(&descriptor).map_err(errno_to_io)?; 219 if FileType::from_raw_mode(status.st_mode) != FileType::RegularFile || status.st_nlink != 1 { 220 return Err(io::Error::new( 221 io::ErrorKind::InvalidInput, 222 "log target must be one regular file link", 223 )); 224 } 225 fchmod(&descriptor, Mode::RUSR | Mode::WUSR).map_err(errno_to_io)?; 226 Ok(File::from(descriptor)) 227 } 228 229 #[cfg(unix)] 230 fn errno_to_io(error: rustix::io::Errno) -> io::Error { 231 io::Error::from_raw_os_error(error.raw_os_error()) 232 } 233 234 #[cfg(not(unix))] 235 fn open_append(_path: &Path) -> io::Result<File> { 236 Err(io::Error::new( 237 io::ErrorKind::Unsupported, 238 "secure file logging is unavailable without a no-follow ACL implementation", 239 )) 240 } 241 242 #[cfg(test)] 243 fn rotated_path(path: &Path, index: usize) -> PathBuf { 244 let mut value = path.as_os_str().to_owned(); 245 value.push(format!(".{index}")); 246 PathBuf::from(value) 247 } 248 249 fn rotated_name(name: &OsStr, index: usize) -> OsString { 250 let mut value = name.to_owned(); 251 value.push(format!(".{index}")); 252 value 253 } 254 255 #[cfg(any(test, not(unix)))] 256 fn remove_if_present(path: &Path) -> io::Result<()> { 257 match fs::remove_file(path) { 258 Ok(()) => Ok(()), 259 Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(()), 260 Err(error) => Err(error), 261 } 262 } 263 264 #[cfg(any(test, not(unix)))] 265 fn rename_if_present(source: &Path, target: &Path) -> io::Result<()> { 266 match fs::rename(source, target) { 267 Ok(()) => Ok(()), 268 Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(()), 269 Err(error) => Err(error), 270 } 271 } 272 273 #[cfg(test)] 274 #[cfg_attr(coverage_nightly, coverage(off))] 275 mod tests { 276 use super::{ 277 LogRotation, SizeRotatingWriter, reject_unsafe_target, remove_if_present, 278 rename_if_present, rotated_path, 279 }; 280 use std::ffi::OsStr; 281 use std::io::Write; 282 283 #[test] 284 fn rotation_is_size_bounded_and_retention_is_finite() { 285 let directory = tempfile::tempdir().expect("temporary log directory"); 286 let path = directory.path().join("radroots.log"); 287 let mut writer = SizeRotatingWriter::new( 288 path.clone(), 289 LogRotation { 290 max_file_bytes: 5, 291 retained_files: 3, 292 }, 293 ) 294 .expect("writer"); 295 for value in [b"1111", b"2222", b"3333", b"4444"] { 296 writer.write_all(value).expect("log entry"); 297 } 298 writer.flush().expect("flush"); 299 assert_eq!(std::fs::read(&path).expect("current"), b"4444"); 300 assert_eq!( 301 std::fs::read(rotated_path(&path, 1)).expect("first retained"), 302 b"3333" 303 ); 304 assert_eq!( 305 std::fs::read(rotated_path(&path, 2)).expect("second retained"), 306 b"2222" 307 ); 308 assert!(!rotated_path(&path, 3).exists()); 309 } 310 311 #[test] 312 fn single_file_rotation_removes_the_previous_file() { 313 let directory = tempfile::tempdir().expect("temporary log directory"); 314 let path = directory.path().join("radroots.log"); 315 std::fs::write(&path, b"full!").expect("fixture"); 316 let mut writer = SizeRotatingWriter::new( 317 path.clone(), 318 LogRotation { 319 max_file_bytes: 5, 320 retained_files: 1, 321 }, 322 ) 323 .expect("writer"); 324 writer.write_all(b"next").expect("write"); 325 writer.flush().expect("flush"); 326 assert_eq!(std::fs::read(path).expect("current"), b"next"); 327 } 328 329 #[test] 330 fn oversized_events_and_unavailable_files_fail_closed() { 331 let directory = tempfile::tempdir().expect("temporary log directory"); 332 let path = directory.path().join("radroots.log"); 333 let mut writer = SizeRotatingWriter::new( 334 path, 335 LogRotation { 336 max_file_bytes: 3, 337 retained_files: 2, 338 }, 339 ) 340 .expect("writer"); 341 assert_eq!( 342 writer.write(b"four").expect_err("oversized").kind(), 343 std::io::ErrorKind::InvalidData 344 ); 345 writer.write_all(b"a").expect("first short write"); 346 writer.write_all(b"b").expect("second short write"); 347 writer.file = None; 348 assert_eq!( 349 writer.flush().expect_err("missing file").kind(), 350 std::io::ErrorKind::Other 351 ); 352 } 353 354 #[test] 355 fn unsafe_targets_and_absent_rotation_files_are_handled() { 356 let directory = tempfile::tempdir().expect("temporary directory"); 357 assert!(reject_unsafe_target(directory.path()).is_err()); 358 let regular = directory.path().join("regular"); 359 std::fs::write(®ular, b"regular").expect("regular file"); 360 assert!(reject_unsafe_target(®ular).is_ok()); 361 let missing = directory.path().join("missing"); 362 assert!(reject_unsafe_target(&missing).is_ok()); 363 assert!(remove_if_present(&missing).is_ok()); 364 assert!(rename_if_present(&missing, &directory.path().join("target")).is_ok()); 365 assert!(remove_if_present(directory.path()).is_err()); 366 367 let source = directory.path().join("source"); 368 std::fs::write(&source, b"source").expect("source"); 369 assert!(rename_if_present(&source, directory.path()).is_err()); 370 371 #[cfg(unix)] 372 { 373 std::os::unix::fs::symlink(directory.path(), &missing).expect("symlink"); 374 assert!(reject_unsafe_target(&missing).is_err()); 375 } 376 } 377 378 #[cfg(unix)] 379 #[test] 380 fn descriptor_relative_open_rejects_symlinks_and_multiple_links() { 381 let directory = tempfile::tempdir().expect("temporary directory"); 382 let outside = tempfile::NamedTempFile::new().expect("outside file"); 383 let symlink = directory.path().join("radroots.log"); 384 std::os::unix::fs::symlink(outside.path(), &symlink).expect("symlink"); 385 assert!(SizeRotatingWriter::new(symlink.clone(), LogRotation::default()).is_err()); 386 387 std::fs::remove_file(&symlink).expect("remove symlink"); 388 std::fs::hard_link(outside.path(), &symlink).expect("hard link"); 389 assert!(SizeRotatingWriter::new(symlink, LogRotation::default()).is_err()); 390 391 let link_holder = tempfile::tempdir().expect("link holder"); 392 let parent_link = link_holder.path().join("parent-link"); 393 std::os::unix::fs::symlink(directory.path(), &parent_link).expect("parent symlink"); 394 assert!( 395 SizeRotatingWriter::new(parent_link.join("other.log"), LogRotation::default()).is_err() 396 ); 397 398 use std::os::unix::fs::PermissionsExt; 399 let insecure = tempfile::tempdir().expect("insecure parent"); 400 std::fs::set_permissions(insecure.path(), std::fs::Permissions::from_mode(0o777)) 401 .expect("insecure permissions"); 402 assert!( 403 SizeRotatingWriter::new(insecure.path().join("radroots.log"), LogRotation::default()) 404 .is_err() 405 ); 406 } 407 408 #[cfg(unix)] 409 #[test] 410 fn descriptor_relative_rotation_propagates_non_missing_errors() { 411 let directory = tempfile::tempdir().expect("temporary directory"); 412 let mut writer = SizeRotatingWriter::new( 413 directory.path().join("radroots.log"), 414 LogRotation::default(), 415 ) 416 .expect("writer"); 417 writer.flush().expect("flush"); 418 419 std::fs::create_dir(directory.path().join("blocked")).expect("blocked directory"); 420 assert!(writer.remove_if_present(OsStr::new("blocked")).is_err()); 421 std::fs::write(directory.path().join("source"), b"source").expect("source"); 422 assert!( 423 writer 424 .rename_if_present(OsStr::new("source"), OsStr::new("blocked")) 425 .is_err() 426 ); 427 } 428 429 #[test] 430 fn rotation_without_an_open_file_recreates_the_target() { 431 let directory = tempfile::tempdir().expect("temporary directory"); 432 let path = directory.path().join("radroots.log"); 433 let mut writer = SizeRotatingWriter::new( 434 path, 435 LogRotation { 436 max_file_bytes: 3, 437 retained_files: 2, 438 }, 439 ) 440 .expect("writer"); 441 writer.file = None; 442 writer.rotate().expect("rotation"); 443 writer.write_all(b"ok").expect("write after rotation"); 444 } 445 }