team-ljyzipelo

공개
207줄6.7 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
11pub(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)]
74pub(crate) enum Step {
75 Check,
76 Activity,
77 Read { bytes: u64, total: u64 },
78}
79
80struct Progress<'a, F>(&'a mut F);
81impl<F: FnMut(Step) -> Result<()>> crate::resources::Monitor for Progress<'_, F> {
82 fn check(&mut self) -> Result<()> {
83 self.0(Step::Check)
84 }
85 fn activity(&mut self) -> Result<()> {
86 self.0(Step::Activity)
87 }
88}
89fn completed<T>(result: Result<T>, step: &mut impl FnMut(Step) -> Result<()>) -> Result<T> {
90 crate::resources::completed(result, &mut Progress(step))
91}
92
93pub(crate) struct Snapshot {
94 pub file: File,
95 pub len: u64,
96 pub object: SourceObject,
97 pub hash: [u8; 32],
98}
99impl Snapshot {
100 /// 원본을 임시 파일로 복사하는 동안 읽은 바이트와 전체 크기를 함께 알림.
101 pub fn open_reporting(
102 path: &Path,
103 limit: u64,
104 step: &mut impl FnMut(Step) -> Result<()>,
105 ) -> Result<Self> {
106 let mut options = OpenOptions::new();
107 options.read(true);
108 #[cfg(unix)]
109 {
110 use std::os::unix::fs::OpenOptionsExt;
111 options.custom_flags(0x20000 | 0x800);
112 }
113 #[cfg(windows)]
114 {
115 use std::os::windows::fs::OpenOptionsExt;
116 options.share_mode(1);
117 }
118 let mut source = completed(options.open(path).map_err(|_| ErrorCode::Io), step)?;
119 let snapshot = Self::capture_reporting(&mut source, limit, step)?;
120 let named = completed(
121 options.open(path).map_err(|_| ErrorCode::SourceChanged),
122 step,
123 )?;
124 if filesystem::object(&named)? != snapshot.object
125 || !named.metadata().map_err(|_| ErrorCode::Io)?.is_file()
126 {
127 return Err(ErrorCode::SourceChanged);
128 }
129 completed(Ok(snapshot), step)
130 }
131 pub(crate) fn capture(
132 source: &mut File,
133 limit: u64,
134 check: &mut impl crate::resources::Monitor,
135 ) -> Result<Self> {
136 Self::capture_reporting(source, limit, &mut |step| match step {
137 Step::Check => check.check(),
138 Step::Activity => crate::resources::completed(Ok(()), check),
139 Step::Read { .. } => check.check(),
140 })
141 }
142 pub(crate) fn capture_reporting(
143 source: &mut File,
144 limit: u64,
145 step: &mut impl FnMut(Step) -> Result<()>,
146 ) -> Result<Self> {
147 let before = completed(source.metadata().map_err(|_| ErrorCode::Io), step)?;
148 if !before.is_file() {
149 return Err(ErrorCode::InvalidRequest);
150 }
151 if before.len() > limit {
152 return Err(ErrorCode::Limit);
153 }
154 source.rewind().map_err(|_| ErrorCode::Io)?;
155 let object = filesystem::object(&source)?;
156 let mut file = completed(temporary(), step)?;
157 completed(crate::space::ensure(&file, before.len()), step)?;
158 let mut buffer = zeroize::Zeroizing::new([0; 65536]);
159 let mut hash = Sha256::new();
160 let mut len = 0u64;
161 let total = before.len();
162 let mut reported = std::time::Instant::now();
163 loop {
164 step(Step::Check)?;
165 let n = completed(
166 source.read(&mut buffer[..]).map_err(|_| ErrorCode::Io),
167 step,
168 )?;
169 if n == 0 {
170 break;
171 }
172 len = len
173 .checked_add(n as u64)
174 .filter(|n| *n <= limit)
175 .ok_or(ErrorCode::Limit)?;
176 completed(
177 file.write_all(&buffer[..n]).map_err(crate::space::io_error),
178 step,
179 )?;
180 hash.update(&buffer[..n]);
181 // 큰 파일에서도 진행이 보이도록 일정 간격으로만 알림.
182 if reported.elapsed() >= std::time::Duration::from_millis(200) {
183 step(Step::Read { bytes: len, total })?;
184 reported = std::time::Instant::now();
185 }
186 }
187 step(Step::Read { bytes: len, total })?;
188 let after = source.metadata().map_err(|_| ErrorCode::Io)?;
189 if filesystem::object(&source)? != object
190 || before.len() != len
191 || after.len() != len
192 || before.modified().ok() != after.modified().ok()
193 {
194 return Err(ErrorCode::SourceChanged);
195 }
196 completed(
197 file.seek(SeekFrom::Start(0)).map_err(|_| ErrorCode::Io),
198 step,
199 )?;
200 Ok(Self {
201 file,
202 len,
203 object,
204 hash: hash.finalize().into(),
205 })
206 }
207}