team-ljyzipelo

공개
580줄18 KB
1use crate::{
2 create_sources::Input,
3 filesystem,
4 protocol::*,
5 spool::{Snapshot, Step},
6};
7use sha2::{Digest, Sha256};
8use std::{
9 ffi::{OsStr, OsString},
10 fs::{File, Metadata},
11 io::{Read, Seek, Write},
12 path::{Path, PathBuf},
13 time::{Instant, SystemTime},
14};
15
16const MAX_VOLUMES: usize = 999;
17type Result<T> = std::result::Result<T, Failure>;
18
19#[derive(Debug)]
20pub(crate) struct Failure {
21 pub error: ErrorCode,
22 pub problem: Option<(VolumeProblemReason, NativePath)>,
23}
24impl From<ErrorCode> for Failure {
25 fn from(error: ErrorCode) -> Self {
26 Self {
27 error,
28 problem: None,
29 }
30 }
31}
32
33#[cfg(unix)]
34fn units(name: &OsStr) -> Vec<u16> {
35 use std::os::unix::ffi::OsStrExt;
36 name.as_bytes()
37 .iter()
38 .map(|byte| u16::from(*byte))
39 .collect()
40}
41#[cfg(windows)]
42fn units(name: &OsStr) -> Vec<u16> {
43 use std::os::windows::ffi::OsStrExt;
44 name.encode_wide().collect()
45}
46#[cfg(unix)]
47fn native(name: &[u16]) -> OsString {
48 use std::os::unix::ffi::OsStringExt;
49 OsString::from_vec(name.iter().map(|unit| *unit as u8).collect())
50}
51#[cfg(windows)]
52fn native(name: &[u16]) -> OsString {
53 use std::os::windows::ffi::OsStringExt;
54 OsString::from_wide(name)
55}
56fn equal_name(left: &[u16], right: &[u16]) -> bool {
57 #[cfg(unix)]
58 {
59 left == right
60 }
61 #[cfg(windows)]
62 {
63 unsafe extern "system" {
64 fn CompareStringOrdinal(
65 a: *const u16,
66 na: i32,
67 b: *const u16,
68 nb: i32,
69 ignore_case: i32,
70 ) -> i32;
71 }
72 if left.len() > 32768 || right.len() > 32768 {
73 return false;
74 }
75 // Windows의 파일명 비교와 같은 대소문자 규칙을 사용함.
76 unsafe {
77 CompareStringOrdinal(
78 left.as_ptr(),
79 left.len() as i32,
80 right.as_ptr(),
81 right.len() as i32,
82 1,
83 ) == 2
84 }
85 }
86}
87fn number(suffix: &[u16]) -> Option<u32> {
88 if suffix.is_empty() || suffix.iter().any(|unit| !(48..=57).contains(unit)) {
89 return None;
90 }
91 Some(suffix.iter().fold(0u32, |value, digit| {
92 value
93 .saturating_mul(10)
94 .saturating_add(u32::from(*digit - 48))
95 }))
96}
97struct Name {
98 prefix: Vec<u16>,
99 selected: u32,
100 width: usize,
101}
102impl Name {
103 fn parse(path: &Path) -> Option<Self> {
104 let name = units(path.file_name()?);
105 let dot = name.iter().rposition(|unit| *unit == 46)?;
106 let prefix = &name[..=dot];
107 let suffix = &name[dot + 1..];
108 if prefix.len() < 4 || !matches!(&prefix[prefix.len() - 4..], [46, 55, 90 | 122, 46]) {
109 return None;
110 }
111 Some(Self {
112 prefix: prefix.to_vec(),
113 selected: number(suffix)?,
114 width: suffix.len(),
115 })
116 }
117 fn volume(&self, number: usize) -> NativePath {
118 let mut name = self.prefix.clone();
119 name.extend(format!("{number:03}").bytes().map(u16::from));
120 NativePath::from_path(Path::new(&native(&name)))
121 }
122 fn problem(&self, reason: VolumeProblemReason, index: usize) -> Failure {
123 Failure {
124 error: reason.terminal_error(),
125 problem: Some((reason, self.volume(index))),
126 }
127 }
128 fn incomplete(&self) -> Failure {
129 self.problem(VolumeProblemReason::IncompleteSet, 1)
130 }
131}
132pub(crate) fn is_split(path: &Path) -> bool {
133 Name::parse(path).is_some()
134}
135pub(crate) fn unsupported_split(path: &Path) -> bool {
136 let Some(leaf) = path.file_name() else {
137 return false;
138 };
139 let name = units(leaf);
140 let Some(dot) = name.iter().rposition(|unit| *unit == 46) else {
141 return false;
142 };
143 let suffix = &name[dot + 1..];
144 let numeric = number(suffix).is_some();
145 (numeric && dot >= 4 && matches!(&name[dot - 4..dot], [46, 90 | 122, 73 | 105, 80 | 112]))
146 || (suffix.len() == 3 && matches!(suffix[0], 90 | 122) && number(&suffix[1..]).is_some())
147}
148
149struct Part {
150 name: OsString,
151 object: SourceObject,
152 length: u64,
153 modified: SystemTime,
154 hash: [u8; 32],
155}
156pub(crate) struct Group {
157 parent: Input,
158 path: PathBuf,
159 object: SourceObject,
160 name: Name,
161 parts: Vec<Part>,
162 total: u64,
163 metadata_limits: crate::archive::MetadataLimits,
164}
165pub(crate) struct Captured {
166 pub snapshot: Snapshot,
167 pub group: Group,
168}
169fn metadata(file: &File) -> std::result::Result<Metadata, ErrorCode> {
170 let metadata = file.metadata().map_err(crate::space::io_error)?;
171 if !metadata.is_file() {
172 return Err(ErrorCode::UnsafePath);
173 }
174 Ok(metadata)
175}
176fn combined_length(total: u64, next: u64) -> Result<u64> {
177 total
178 .checked_add(next)
179 .ok_or_else(|| ErrorCode::Limit.into())
180}
181impl Group {
182 fn scan(
183 &self,
184 step: &mut impl FnMut(Step) -> std::result::Result<(), ErrorCode>,
185 ) -> Result<Vec<OsString>> {
186 let mut names: Vec<Option<OsString>> = (0..MAX_VOLUMES).map(|_| None).collect();
187 let mut metadata_bytes = 0usize;
188 step(Step::Check)?;
189 let entries = self.parent.children(&self.path)?;
190 step(Step::Activity)?;
191 for entry in entries {
192 step(Step::Check)?;
193 let leaf = entry.map_err(crate::space::io_error)?.file_name();
194 let value = units(&leaf);
195 if value.len() > self.name.prefix.len()
196 && equal_name(&value[..self.name.prefix.len()], &self.name.prefix)
197 {
198 let suffix = &value[self.name.prefix.len()..];
199 if let Some(index) = number(suffix) {
200 if index > MAX_VOLUMES as u32 {
201 return Err(ErrorCode::Limit.into());
202 }
203 if index == 0 || suffix.len() != 3 {
204 return Err(self.name.incomplete());
205 }
206 metadata_bytes = value
207 .len()
208 .checked_mul(8)
209 .and_then(|cost| cost.checked_add(256))
210 .and_then(|cost| metadata_bytes.checked_add(cost))
211 .filter(|cost| *cost <= self.metadata_limits.bytes)
212 .ok_or(ErrorCode::Limit)?;
213 if index as usize > self.metadata_limits.nodes {
214 return Err(ErrorCode::Limit.into());
215 }
216 let slot = &mut names[index as usize - 1];
217 if slot.is_some() {
218 return Err(self.name.incomplete());
219 }
220 *slot = Some(leaf);
221 }
222 }
223 step(Step::Activity)?;
224 }
225 let Some(last) = names.iter().rposition(Option::is_some) else {
226 return Ok(Vec::new());
227 };
228 names.truncate(last + 1);
229 names
230 .into_iter()
231 .enumerate()
232 .map(|(index, name)| {
233 name.ok_or_else(|| {
234 self.name
235 .problem(VolumeProblemReason::MissingVolume, index + 1)
236 })
237 })
238 .collect()
239 }
240 fn parent_unchanged(&self) -> Result<()> {
241 let named = Input::open(&self.path).map_err(|_| ErrorCode::SourceChanged)?;
242 if filesystem::object(&named.file)? != self.object
243 || !named
244 .file
245 .metadata()
246 .map_err(crate::space::io_error)?
247 .is_dir()
248 {
249 return Err(ErrorCode::SourceChanged.into());
250 }
251 Ok(())
252 }
253 fn open_part(
254 &self,
255 name: &OsStr,
256 step: &mut impl FnMut(Step) -> std::result::Result<(), ErrorCode>,
257 ) -> Result<Input> {
258 match self.parent.open_named(&self.path, name) {
259 Ok(file) => {
260 step(Step::Activity)?;
261 Ok(file)
262 }
263 Err(error) => {
264 // 읽기 실패가 확정된 중간 누락인지 먼저 확인함.
265 if error == ErrorCode::Io {
266 let names = self.scan(step)?;
267 if !names.iter().any(|candidate| candidate == name) {
268 return Err(ErrorCode::SourceChanged.into());
269 }
270 }
271 Err(error.into())
272 }
273 }
274 }
275 fn matches(&self, part: &Part, input: &Input) -> Result<()> {
276 let data = metadata(&input.file)?;
277 if filesystem::object(&input.file)? != part.object
278 || data.len() != part.length
279 || data.modified().map_err(crate::space::io_error)? != part.modified
280 {
281 return Err(ErrorCode::SourceChanged.into());
282 }
283 Ok(())
284 }
285 fn read_part(
286 &self,
287 part: &Part,
288 output: &mut Option<&mut File>,
289 whole: &mut Sha256,
290 processed: &mut u64,
291 reported: &mut Instant,
292 step: &mut impl FnMut(Step) -> std::result::Result<(), ErrorCode>,
293 ) -> Result<[u8; 32]> {
294 let mut input = self.open_part(&part.name, step)?;
295 self.matches(part, &input)?;
296 let mut hash = Sha256::new();
297 let mut read = 0u64;
298 let mut buffer = zeroize::Zeroizing::new([0; 65536]);
299 loop {
300 step(Step::Check)?;
301 let length = input
302 .file
303 .read(&mut buffer[..])
304 .map_err(crate::space::io_error)?;
305 step(Step::Activity)?;
306 if length == 0 {
307 break;
308 }
309 read = read
310 .checked_add(length as u64)
311 .filter(|n| *n <= part.length)
312 .ok_or(ErrorCode::SourceChanged)?;
313 if let Some(file) = output {
314 file.write_all(&buffer[..length])
315 .map_err(crate::space::io_error)?;
316 step(Step::Activity)?;
317 }
318 hash.update(&buffer[..length]);
319 whole.update(&buffer[..length]);
320 *processed = processed
321 .checked_add(length as u64)
322 .ok_or(ErrorCode::Limit)?;
323 if reported.elapsed() >= std::time::Duration::from_millis(200) {
324 step(Step::Read {
325 bytes: *processed,
326 total: self.total,
327 })?;
328 *reported = Instant::now();
329 }
330 }
331 if read != part.length {
332 return Err(ErrorCode::SourceChanged.into());
333 }
334 self.matches(part, &input)?;
335 let named = self.open_part(&part.name, step)?;
336 self.matches(part, &named)?;
337 Ok(hash.finalize().into())
338 }
339 fn manifest(&self) -> Result<[u8; 32]> {
340 let mut hash = Sha256::new();
341 hash.update(b"zipelo.split7z.v1\0");
342 hash.update(
343 crate::wire::encode_source_object(&self.object).map_err(|_| ErrorCode::Internal)?,
344 );
345 hash.update((self.parts.len() as u16).to_le_bytes());
346 for (index, part) in self.parts.iter().enumerate() {
347 hash.update(((index + 1) as u16).to_le_bytes());
348 hash.update(
349 crate::wire::encode_native_path(&NativePath::from_path(Path::new(&part.name)))
350 .map_err(|_| ErrorCode::Limit)?,
351 );
352 hash.update(
353 crate::wire::encode_source_object(&part.object).map_err(|_| ErrorCode::Internal)?,
354 );
355 hash.update(part.length.to_le_bytes());
356 hash.update(part.hash);
357 }
358 Ok(hash.finalize().into())
359 }
360 pub fn verify(
361 &self,
362 step: &mut impl FnMut(Step) -> std::result::Result<(), ErrorCode>,
363 ) -> Result<()> {
364 step(Step::Check)?;
365 self.parent_unchanged()?;
366 let names = self.scan(step).map_err(|failure| {
367 if matches!(
368 failure.problem,
369 Some((VolumeProblemReason::IncompleteSet, _))
370 ) {
371 ErrorCode::SourceChanged.into()
372 } else {
373 failure
374 }
375 })?;
376 if names.len() != self.parts.len()
377 || names
378 .iter()
379 .zip(&self.parts)
380 .any(|(name, part)| *name != part.name)
381 {
382 return Err(ErrorCode::SourceChanged.into());
383 }
384 let mut processed = 0;
385 let mut whole = Sha256::new();
386 let mut reported = Instant::now();
387 for part in &self.parts {
388 step(Step::Check)?;
389 if self.read_part(
390 part,
391 &mut None,
392 &mut whole,
393 &mut processed,
394 &mut reported,
395 step,
396 )? != part.hash
397 {
398 return Err(ErrorCode::SourceChanged.into());
399 }
400 step(Step::Activity)?;
401 }
402 step(Step::Read {
403 bytes: processed,
404 total: self.total,
405 })?;
406 let final_names = self.scan(step).map_err(|failure| {
407 if matches!(
408 failure.problem,
409 Some((VolumeProblemReason::IncompleteSet, _))
410 ) {
411 ErrorCode::SourceChanged.into()
412 } else {
413 failure
414 }
415 })?;
416 if final_names != names {
417 return Err(ErrorCode::SourceChanged.into());
418 }
419 self.parent_unchanged()?;
420 Ok(())
421 }
422}
423pub(crate) fn open(
424 path: &Path,
425 expected: Option<&ListId>,
426 limit: u64,
427 metadata_limits: crate::archive::MetadataLimits,
428 step: &mut impl FnMut(Step) -> std::result::Result<(), ErrorCode>,
429) -> Result<Option<Captured>> {
430 if unsupported_split(path) {
431 return Err(ErrorCode::UnsupportedFeature.into());
432 }
433 let Some(name) = Name::parse(path) else {
434 return Ok(None);
435 };
436 if !NativePath::from_path(Path::new(
437 path.file_name().ok_or(ErrorCode::InvalidRequest)?,
438 ))
439 .is_basename()
440 {
441 return Err(ErrorCode::UnsafePath.into());
442 }
443 if name.selected > MAX_VOLUMES as u32 {
444 return Err(ErrorCode::Limit.into());
445 }
446 if name.width != 3 {
447 return Err(ErrorCode::UnsupportedFeature.into());
448 }
449 if name.selected != 1 {
450 return Err(name.problem(VolumeProblemReason::FirstVolumeRequired, 1));
451 }
452 step(Step::Check)?;
453 let parent_path = path
454 .parent()
455 .ok_or(ErrorCode::InvalidRequest)?
456 .to_path_buf();
457 let parent = Input::open(&parent_path)?;
458 if !parent
459 .file
460 .metadata()
461 .map_err(crate::space::io_error)?
462 .is_dir()
463 {
464 return Err(ErrorCode::UnsafePath.into());
465 }
466 let object = filesystem::object(&parent.file)?;
467 let mut group = Group {
468 parent,
469 path: parent_path,
470 object,
471 name,
472 parts: Vec::new(),
473 total: 0,
474 metadata_limits,
475 };
476 let names = group.scan(step)?;
477 if names.is_empty() {
478 return Err(if expected.is_some() {
479 ErrorCode::SourceChanged
480 } else {
481 ErrorCode::Io
482 }
483 .into());
484 }
485 for name in names {
486 step(Step::Check)?;
487 let input = group.open_part(&name, step)?;
488 let data = metadata(&input.file)?;
489 let object = filesystem::object(&input.file)?;
490 if group.parts.iter().any(|part| part.object == object) {
491 return Err(ErrorCode::UnsafePath.into());
492 }
493 group.total = combined_length(group.total, data.len())?;
494 group.parts.push(Part {
495 name,
496 object,
497 length: data.len(),
498 modified: data.modified().map_err(crate::space::io_error)?,
499 hash: [0; 32],
500 });
501 step(Step::Activity)?;
502 }
503 if expected.is_some_and(|id| {
504 id.archive_bytes != group.total
505 || id.catalog_version != 2
506 || id.format != Format::SevenZip
507 || !matches!(id.source_object, SourceObject::SplitSevenZip { .. })
508 }) {
509 return Err(ErrorCode::SourceChanged.into());
510 }
511 if group.total > limit {
512 return Err(ErrorCode::Limit.into());
513 }
514 let mut file = crate::spool::temporary()?;
515 crate::space::ensure(&file, group.total)?;
516 let mut processed = 0;
517 let mut whole = Sha256::new();
518 let mut reported = Instant::now();
519 for index in 0..group.parts.len() {
520 let hash = group.read_part(
521 &group.parts[index],
522 &mut Some(&mut file),
523 &mut whole,
524 &mut processed,
525 &mut reported,
526 step,
527 )?;
528 group.parts[index].hash = hash;
529 step(Step::Activity)?;
530 }
531 step(Step::Read {
532 bytes: processed,
533 total: group.total,
534 })?;
535 let hash = whole.finalize().into();
536 let object = SourceObject::SplitSevenZip {
537 manifest_sha256: group.manifest()?,
538 };
539 if expected.is_some_and(|id| id.source_object != object || id.archive_sha256 != hash) {
540 return Err(ErrorCode::SourceChanged.into());
541 }
542 // 마지막 누락 이름을 추측하지 않고 논리 헤더 끝 위치를 검증함.
543 file.rewind().map_err(crate::space::io_error)?;
544 let mut header = [0; 32];
545 if group.parts.iter().any(|part| part.length == 0) || group.total < 32 {
546 return Err(group.name.incomplete());
547 }
548 file.read_exact(&mut header)
549 .map_err(crate::space::io_error)?;
550 if &header[..6] != b"7z\xbc\xaf\x27\x1c"
551 || zlib_rs::crc32::crc32(0, &header[12..])
552 != u32::from_le_bytes(header[8..12].try_into().unwrap())
553 {
554 return Err(group.name.incomplete());
555 }
556 let offset = u64::from_le_bytes(header[12..20].try_into().unwrap());
557 let length = u64::from_le_bytes(header[20..28].try_into().unwrap());
558 if 32u64
559 .checked_add(offset)
560 .and_then(|start| start.checked_add(length))
561 != Some(group.total)
562 {
563 return Err(group.name.incomplete());
564 }
565 group.verify(step)?;
566 file.rewind().map_err(crate::space::io_error)?;
567 Ok(Some(Captured {
568 snapshot: Snapshot {
569 file,
570 len: group.total,
571 object,
572 hash,
573 },
574 group,
575 }))
576}
577
578#[cfg(test)]
579#[path = "../../../tests/rust-archive-worker/split_capture.rs"]
580mod tests;