team-ljyzipelo

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