| 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 | thread_local! { |
| 12 | // 작업 스레드가 지정한 임시 파일 위치. 없으면 시스템 임시 폴더를 사용함. |
| 13 | static LOCATION: std::cell::RefCell<Option<filesystem::Dir>> = |
| 14 | const { std::cell::RefCell::new(None) }; |
| 15 | // 출력 폴더에 이름 있는 임시 파일을 만든 뒤 이름을 지우지 못했는지 기록함. |
| 16 | static LEFTOVER: std::cell::Cell<bool> = const { std::cell::Cell::new(false) }; |
| 17 | } |
| 18 | |
| 19 | /// 해제 작업의 임시 파일을 출력 폴더에 두도록 지정함. 반환값이 사라지면 해제됨. |
| 20 | /// 작업은 한 스레드에서 실행되므로 다른 작업이나 시험에 섞이지 않음. |
| 21 | pub(crate) struct Location(()); |
| 22 | impl Drop for Location { |
| 23 | fn drop(&mut self) { |
| 24 | LOCATION.with(|location| *location.borrow_mut() = None); |
| 25 | } |
| 26 | } |
| 27 | pub(crate) fn place_in(dir: &filesystem::Dir) -> Result<Location> { |
| 28 | let dir = dir.duplicate()?; |
| 29 | LOCATION.with(|location| *location.borrow_mut() = Some(dir)); |
| 30 | LEFTOVER.with(|leftover| leftover.set(false)); |
| 31 | Ok(Location(())) |
| 32 | } |
| 33 | |
| 34 | /// 출력 폴더에 지우지 못한 임시 파일이 남았음을 기록함. Windows 임시 파일은 닫으면 지워지므로 |
| 35 | /// Linux 대체 이름 경로에서만 사용함. |
| 36 | #[cfg(target_os = "linux")] |
| 37 | pub(crate) fn note_leftover() { |
| 38 | LEFTOVER.with(|leftover| leftover.set(true)); |
| 39 | } |
| 40 | |
| 41 | /// 작업 중 출력 폴더에 임시 파일이 남았는지 확인하고 기록을 비움. |
| 42 | pub(crate) fn take_leftover() -> bool { |
| 43 | LEFTOVER.with(|leftover| leftover.replace(false)) |
| 44 | } |
| 45 | |
| 46 | pub(crate) fn random_name() -> Result<String> { |
| 47 | let mut random = [0; 16]; |
| 48 | crate::crypto::random(&mut random)?; |
| 49 | Ok(random.iter().map(|b| format!("{b:02x}")).collect()) |
| 50 | } |
| 51 | |
| 52 | /// 이름 없는 임시 파일을 만듦. 해제 작업에서는 출력 폴더에, 그 외에는 시스템 임시 폴더에 둠. |
| 53 | /// 출력 폴더에 두면 공간 판단이 실제 출력 디스크와 같아지고 /tmp 크기나 할당량에 묶이지 않음. |
| 54 | /// 출력 폴더에 만들지 못하면(읽기 전용, 공간 부족 등) 이 작업의 남은 임시 파일은 모두 |
| 55 | /// 기존 시스템 임시 폴더에 둠. 그러면 동작과 오류 우선순위가 이전과 같아지며, 출력 폴더 |
| 56 | /// 문제는 원래의 출력 확인 지점에서 보고됨. |
| 57 | pub(crate) fn temporary() -> Result<File> { |
| 58 | let placed = |
| 59 | LOCATION.with(|location| location.borrow().as_ref().map(filesystem::Dir::temporary)); |
| 60 | match placed { |
| 61 | Some(Ok(file)) => return Ok(file), |
| 62 | Some(Err(_)) => LOCATION.with(|location| *location.borrow_mut() = None), |
| 63 | None => {} |
| 64 | } |
| 65 | #[cfg(target_os = "linux")] |
| 66 | { |
| 67 | use std::os::unix::fs::OpenOptionsExt; |
| 68 | // 이름 없는 임시 파일은 마지막 핸들을 닫으면 제거됨. |
| 69 | match OpenOptions::new() |
| 70 | .read(true) |
| 71 | .write(true) |
| 72 | .custom_flags(0x410000 | 0x80) |
| 73 | .mode(0o600) |
| 74 | .open(std::env::temp_dir()) |
| 75 | { |
| 76 | Ok(file) => return Ok(file), |
| 77 | Err(error) => { |
| 78 | if crate::space::io_error(error) == ErrorCode::DiskFull { |
| 79 | return Err(ErrorCode::DiskFull); |
| 80 | } |
| 81 | } |
| 82 | } |
| 83 | let name = random_name()?; |
| 84 | let path = std::env::temp_dir().join(format!("zipelo-{name}.tmp")); |
| 85 | let file = OpenOptions::new() |
| 86 | .read(true) |
| 87 | .write(true) |
| 88 | .create_new(true) |
| 89 | .mode(0o600) |
| 90 | .custom_flags(0x20000) |
| 91 | .open(&path) |
| 92 | .map_err(crate::space::io_error)?; |
| 93 | std::fs::remove_file(path).map_err(|_| ErrorCode::Io)?; |
| 94 | use std::os::unix::fs::MetadataExt; |
| 95 | if file.metadata().map_err(|_| ErrorCode::Io)?.nlink() != 0 { |
| 96 | return Err(ErrorCode::Io); |
| 97 | } |
| 98 | Ok(file) |
| 99 | } |
| 100 | #[cfg(windows)] |
| 101 | { |
| 102 | windows_temporary(&std::env::temp_dir(), "zipelo-", false) |
| 103 | } |
| 104 | } |
| 105 | |
| 106 | /// 닫으면 지워지는 Windows 임시 파일을 지정한 폴더에 만듦. 출력 폴더에서는 숨김 속성을 붙임. |
| 107 | #[cfg(windows)] |
| 108 | pub(crate) fn windows_temporary(parent: &Path, prefix: &str, hidden: bool) -> Result<File> { |
| 109 | use std::os::windows::fs::OpenOptionsExt; |
| 110 | let name = random_name()?; |
| 111 | OpenOptions::new() |
| 112 | .read(true) |
| 113 | .write(true) |
| 114 | .create_new(true) |
| 115 | .share_mode(0) |
| 116 | .access_mode(0xc0010000) |
| 117 | .custom_flags(0x04000000 | 0x00200000) |
| 118 | .attributes(if hidden { 0x100 | 0x2 } else { 0x100 }) |
| 119 | .open(parent.join(format!("{prefix}{name}.tmp"))) |
| 120 | .map_err(crate::space::io_error) |
| 121 | } |
| 122 | |
| 123 | #[derive(Clone, Copy, Debug)] |
| 124 | pub(crate) enum Step { |
| 125 | Check, |
| 126 | Activity, |
| 127 | Read { bytes: u64, total: u64 }, |
| 128 | } |
| 129 | |
| 130 | struct Progress<'a, F>(&'a mut F); |
| 131 | impl<F: FnMut(Step) -> Result<()>> crate::resources::Monitor for Progress<'_, F> { |
| 132 | fn check(&mut self) -> Result<()> { |
| 133 | self.0(Step::Check) |
| 134 | } |
| 135 | fn activity(&mut self) -> Result<()> { |
| 136 | self.0(Step::Activity) |
| 137 | } |
| 138 | } |
| 139 | fn completed<T>(result: Result<T>, step: &mut impl FnMut(Step) -> Result<()>) -> Result<T> { |
| 140 | crate::resources::completed(result, &mut Progress(step)) |
| 141 | } |
| 142 | |
| 143 | pub(crate) struct Snapshot { |
| 144 | pub file: File, |
| 145 | pub len: u64, |
| 146 | pub object: SourceObject, |
| 147 | pub hash: [u8; 32], |
| 148 | } |
| 149 | impl Snapshot { |
| 150 | /// 원본을 임시 파일로 복사하는 동안 읽은 바이트와 전체 크기를 함께 알림. |
| 151 | pub fn open_reporting( |
| 152 | path: &Path, |
| 153 | limit: u64, |
| 154 | step: &mut impl FnMut(Step) -> Result<()>, |
| 155 | ) -> Result<Self> { |
| 156 | let mut options = OpenOptions::new(); |
| 157 | options.read(true); |
| 158 | #[cfg(unix)] |
| 159 | { |
| 160 | use std::os::unix::fs::OpenOptionsExt; |
| 161 | options.custom_flags(0x20000 | 0x800); |
| 162 | } |
| 163 | #[cfg(windows)] |
| 164 | { |
| 165 | use std::os::windows::fs::OpenOptionsExt; |
| 166 | options.share_mode(1); |
| 167 | } |
| 168 | let mut source = completed(options.open(path).map_err(|_| ErrorCode::Io), step)?; |
| 169 | let snapshot = Self::capture_reporting(&mut source, limit, step)?; |
| 170 | let named = completed( |
| 171 | options.open(path).map_err(|_| ErrorCode::SourceChanged), |
| 172 | step, |
| 173 | )?; |
| 174 | if filesystem::object(&named)? != snapshot.object |
| 175 | || !named.metadata().map_err(|_| ErrorCode::Io)?.is_file() |
| 176 | { |
| 177 | return Err(ErrorCode::SourceChanged); |
| 178 | } |
| 179 | completed(Ok(snapshot), step) |
| 180 | } |
| 181 | pub(crate) fn capture( |
| 182 | source: &mut File, |
| 183 | limit: u64, |
| 184 | check: &mut impl crate::resources::Monitor, |
| 185 | ) -> Result<Self> { |
| 186 | Self::capture_reporting(source, limit, &mut |step| match step { |
| 187 | Step::Check => check.check(), |
| 188 | Step::Activity => crate::resources::completed(Ok(()), check), |
| 189 | Step::Read { .. } => check.check(), |
| 190 | }) |
| 191 | } |
| 192 | pub(crate) fn capture_reporting( |
| 193 | source: &mut File, |
| 194 | limit: u64, |
| 195 | step: &mut impl FnMut(Step) -> Result<()>, |
| 196 | ) -> Result<Self> { |
| 197 | let before = completed(source.metadata().map_err(|_| ErrorCode::Io), step)?; |
| 198 | if !before.is_file() { |
| 199 | return Err(ErrorCode::InvalidRequest); |
| 200 | } |
| 201 | if before.len() > limit { |
| 202 | return Err(ErrorCode::Limit); |
| 203 | } |
| 204 | source.rewind().map_err(|_| ErrorCode::Io)?; |
| 205 | let object = filesystem::object(&source)?; |
| 206 | let mut file = completed(temporary(), step)?; |
| 207 | completed(crate::space::ensure(&file, before.len()), step)?; |
| 208 | let mut buffer = zeroize::Zeroizing::new([0; 65536]); |
| 209 | let mut hash = Sha256::new(); |
| 210 | let mut len = 0u64; |
| 211 | let total = before.len(); |
| 212 | let mut reported = std::time::Instant::now(); |
| 213 | loop { |
| 214 | step(Step::Check)?; |
| 215 | let n = completed( |
| 216 | source.read(&mut buffer[..]).map_err(|_| ErrorCode::Io), |
| 217 | step, |
| 218 | )?; |
| 219 | if n == 0 { |
| 220 | break; |
| 221 | } |
| 222 | len = len |
| 223 | .checked_add(n as u64) |
| 224 | .filter(|n| *n <= limit) |
| 225 | .ok_or(ErrorCode::Limit)?; |
| 226 | completed( |
| 227 | file.write_all(&buffer[..n]).map_err(crate::space::io_error), |
| 228 | step, |
| 229 | )?; |
| 230 | hash.update(&buffer[..n]); |
| 231 | // 큰 파일에서도 진행이 보이도록 일정 간격으로만 알림. |
| 232 | if reported.elapsed() >= std::time::Duration::from_millis(200) { |
| 233 | step(Step::Read { bytes: len, total })?; |
| 234 | reported = std::time::Instant::now(); |
| 235 | } |
| 236 | } |
| 237 | step(Step::Read { bytes: len, total })?; |
| 238 | let after = source.metadata().map_err(|_| ErrorCode::Io)?; |
| 239 | if filesystem::object(&source)? != object |
| 240 | || before.len() != len |
| 241 | || after.len() != len |
| 242 | || before.modified().ok() != after.modified().ok() |
| 243 | { |
| 244 | return Err(ErrorCode::SourceChanged); |
| 245 | } |
| 246 | completed( |
| 247 | file.seek(SeekFrom::Start(0)).map_err(|_| ErrorCode::Io), |
| 248 | step, |
| 249 | )?; |
| 250 | Ok(Self { |
| 251 | file, |
| 252 | len, |
| 253 | object, |
| 254 | hash: hash.finalize().into(), |
| 255 | }) |
| 256 | } |
| 257 | } |