team-ljyzipelo

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