| 1 | use crate::{filesystem, protocol::*}; |
| 2 | use sha2::{Digest, Sha256}; |
| 3 | use std::{ |
| 4 | fs::{File, OpenOptions}, |
| 5 | io::{Read, Seek, SeekFrom, Write}, |
| 6 | path::Path, |
| 7 | }; |
| 8 | |
| 9 | type Result<T> = std::result::Result<T, ErrorCode>; |
| 10 | |
| 11 | pub(crate) fn temporary() -> Result<File> { |
| 12 | #[cfg(target_os = "linux")] |
| 13 | { |
| 14 | use std::os::unix::fs::OpenOptionsExt; |
| 15 | // 이름 없는 임시 파일은 마지막 핸들을 닫으면 제거됨. |
| 16 | match OpenOptions::new() |
| 17 | .read(true) |
| 18 | .write(true) |
| 19 | .custom_flags(0x410000 | 0x80) |
| 20 | .mode(0o600) |
| 21 | .open(std::env::temp_dir()) |
| 22 | { |
| 23 | Ok(file) => return Ok(file), |
| 24 | Err(ref error) if error.kind() == std::io::ErrorKind::StorageFull => { |
| 25 | return Err(ErrorCode::DiskFull); |
| 26 | } |
| 27 | Err(_) => {} |
| 28 | } |
| 29 | let mut random = [0; 16]; |
| 30 | crate::crypto::random(&mut random)?; |
| 31 | let name = random |
| 32 | .iter() |
| 33 | .map(|b| format!("{b:02x}")) |
| 34 | .collect::<String>(); |
| 35 | let path = std::env::temp_dir().join(format!("zipelo-{name}.tmp")); |
| 36 | let file = OpenOptions::new() |
| 37 | .read(true) |
| 38 | .write(true) |
| 39 | .create_new(true) |
| 40 | .mode(0o600) |
| 41 | .custom_flags(0x20000) |
| 42 | .open(&path) |
| 43 | .map_err(crate::space::io_error)?; |
| 44 | std::fs::remove_file(path).map_err(|_| ErrorCode::Io)?; |
| 45 | use std::os::unix::fs::MetadataExt; |
| 46 | if file.metadata().map_err(|_| ErrorCode::Io)?.nlink() != 0 { |
| 47 | return Err(ErrorCode::Io); |
| 48 | } |
| 49 | Ok(file) |
| 50 | } |
| 51 | #[cfg(windows)] |
| 52 | { |
| 53 | use std::os::windows::fs::OpenOptionsExt; |
| 54 | let mut random = [0; 16]; |
| 55 | crate::crypto::random(&mut random)?; |
| 56 | let name = random |
| 57 | .iter() |
| 58 | .map(|b| format!("{b:02x}")) |
| 59 | .collect::<String>(); |
| 60 | OpenOptions::new() |
| 61 | .read(true) |
| 62 | .write(true) |
| 63 | .create_new(true) |
| 64 | .share_mode(0) |
| 65 | .access_mode(0xc0010000) |
| 66 | .custom_flags(0x04000000 | 0x00200000) |
| 67 | .attributes(0x100) |
| 68 | .open(std::env::temp_dir().join(format!("zipelo-{name}.tmp"))) |
| 69 | .map_err(crate::space::io_error) |
| 70 | } |
| 71 | } |
| 72 | |
| 73 | #[derive(Clone, Copy, Debug)] |
| 74 | pub(crate) enum Step { |
| 75 | Check, |
| 76 | Read { bytes: u64, total: u64 }, |
| 77 | } |
| 78 | |
| 79 | pub(crate) struct Snapshot { |
| 80 | pub file: File, |
| 81 | pub len: u64, |
| 82 | pub object: SourceObject, |
| 83 | pub hash: [u8; 32], |
| 84 | } |
| 85 | impl Snapshot { |
| 86 | /// 원본을 임시 파일로 복사하는 동안 읽은 바이트와 전체 크기를 함께 알림. |
| 87 | pub fn open_reporting( |
| 88 | path: &Path, |
| 89 | limit: u64, |
| 90 | step: &mut impl FnMut(Step) -> Result<()>, |
| 91 | ) -> Result<Self> { |
| 92 | let mut options = OpenOptions::new(); |
| 93 | options.read(true); |
| 94 | #[cfg(unix)] |
| 95 | { |
| 96 | use std::os::unix::fs::OpenOptionsExt; |
| 97 | options.custom_flags(0x20000 | 0x800); |
| 98 | } |
| 99 | #[cfg(windows)] |
| 100 | { |
| 101 | use std::os::windows::fs::OpenOptionsExt; |
| 102 | options.share_mode(1); |
| 103 | } |
| 104 | let mut source = options.open(path).map_err(|_| ErrorCode::Io)?; |
| 105 | let snapshot = Self::capture_reporting(&mut source, limit, step)?; |
| 106 | let named = options.open(path).map_err(|_| ErrorCode::SourceChanged)?; |
| 107 | if filesystem::object(&named)? != snapshot.object |
| 108 | || !named.metadata().map_err(|_| ErrorCode::Io)?.is_file() |
| 109 | { |
| 110 | return Err(ErrorCode::SourceChanged); |
| 111 | } |
| 112 | Ok(snapshot) |
| 113 | } |
| 114 | pub(crate) fn capture( |
| 115 | source: &mut File, |
| 116 | limit: u64, |
| 117 | check: &mut impl FnMut() -> Result<()>, |
| 118 | ) -> Result<Self> { |
| 119 | Self::capture_reporting(source, limit, &mut |step| match step { |
| 120 | Step::Check => check(), |
| 121 | Step::Read { .. } => Ok(()), |
| 122 | }) |
| 123 | } |
| 124 | fn capture_reporting( |
| 125 | source: &mut File, |
| 126 | limit: u64, |
| 127 | step: &mut impl FnMut(Step) -> Result<()>, |
| 128 | ) -> Result<Self> { |
| 129 | let before = source.metadata().map_err(|_| ErrorCode::Io)?; |
| 130 | if !before.is_file() { |
| 131 | return Err(ErrorCode::InvalidRequest); |
| 132 | } |
| 133 | if before.len() > limit { |
| 134 | return Err(ErrorCode::Limit); |
| 135 | } |
| 136 | source.rewind().map_err(|_| ErrorCode::Io)?; |
| 137 | let object = filesystem::object(&source)?; |
| 138 | let mut file = temporary()?; |
| 139 | crate::space::ensure(&file, before.len())?; |
| 140 | let mut buffer = zeroize::Zeroizing::new([0; 65536]); |
| 141 | let mut hash = Sha256::new(); |
| 142 | let mut len = 0u64; |
| 143 | let total = before.len(); |
| 144 | let mut reported = std::time::Instant::now(); |
| 145 | loop { |
| 146 | step(Step::Check)?; |
| 147 | let n = source.read(&mut buffer[..]).map_err(|_| ErrorCode::Io)?; |
| 148 | if n == 0 { |
| 149 | break; |
| 150 | } |
| 151 | len = len |
| 152 | .checked_add(n as u64) |
| 153 | .filter(|n| *n <= limit) |
| 154 | .ok_or(ErrorCode::Limit)?; |
| 155 | file.write_all(&buffer[..n]) |
| 156 | .map_err(crate::space::io_error)?; |
| 157 | hash.update(&buffer[..n]); |
| 158 | // 큰 파일에서도 진행이 보이도록 일정 간격으로만 알림. |
| 159 | if reported.elapsed() >= std::time::Duration::from_millis(200) { |
| 160 | step(Step::Read { bytes: len, total })?; |
| 161 | reported = std::time::Instant::now(); |
| 162 | } |
| 163 | } |
| 164 | step(Step::Read { bytes: len, total })?; |
| 165 | let after = source.metadata().map_err(|_| ErrorCode::Io)?; |
| 166 | if filesystem::object(&source)? != object |
| 167 | || before.len() != len |
| 168 | || after.len() != len |
| 169 | || before.modified().ok() != after.modified().ok() |
| 170 | { |
| 171 | return Err(ErrorCode::SourceChanged); |
| 172 | } |
| 173 | file.seek(SeekFrom::Start(0)).map_err(|_| ErrorCode::Io)?; |
| 174 | Ok(Self { |
| 175 | file, |
| 176 | len, |
| 177 | object, |
| 178 | hash: hash.finalize().into(), |
| 179 | }) |
| 180 | } |
| 181 | } |