team-ljyzipelo

공개

분할 7z의 목록과 해제를 검증된 묶음으로 처리한다

작성자
시로사키 하나
작성 시각
커밋
8ac2ccf31e74cbb28a519e617789e996a4390fce
부모
d480c49
이 시점의 파일 보기

변경된 파일 41개

+1,969-10
수정experiments/rust-archive-worker/README.md+7-1
@@ -178,7 +178,7 @@ Python 표준 bz2, lzma와 tarfile로 독립 생성 및 해제한 결과의 SHA2
178178
179179## 분할 7z 계약
180180
181삭제: 상태: 2026-11-14 frontend 합의 완료. [PLANS 8.8](../../docs/PLANS.md)의 공용 타입과 코덱에 묶음 ListId, MissingVolume 및 VolumeProblem을 반영했다. 조각 탐색과 캡처 및 실제 목록/해제, 앱 수신과 화면 연동은 구현 대기다. 기준은 main ecad460이며 frontend가 같은 PR에서 화면과 상황별 디버깅 명령을 연결한다.
181추가: 상태: 2026-11-14 frontend 합의 완료. [PLANS 8.8](../../docs/PLANS.md)의 묶음 ListId, MissingVolume 및 VolumeProblem과 조각 탐색, 캡처, 재검증 및 실제 목록/해제를 구현했다. 같은 PR에서 앱 수신, 화면과 상황별 디버깅 명령을 연결했으며 실제 분할 파일의 Windows/Wayland 화면 통합 검증과 독립 리뷰는 남아 있다. 기준은 main ecad460이다.
182182
183183### 지원 범위와 조각 탐색
184184
@@ -224,3 +224,9 @@ Python 표준 bz2, lzma와 tarfile로 독립 생성 및 해제한 결과의 SHA2
224224- backend는 조각 탐색과 캡처, 묶음 동일성, 공용 타입 및 wire와 작업자 회귀 시험을 담당한다. frontend는 .001 열기와 제외 형식 및 조각 오류 안내, 묶음 ListId 보존, 분할 미리보기 실행 제한, 수신 검증, --ui-scenario와 가이드 및 Windows/Wayland 실기를 담당한다. 구현 변경은 계약 합의와 공용 타입 반영 뒤 파일 소유 범위를 나눠 연결한다.
225225- 독립 도구 표본의 목록과 해제 해시, 헤더 및 데이터의 조각 경계, .009/.010, 서로 다른 조각 길이, 999개와 초과, 중간 및 마지막 누락, 잘림, 검출 가능한 혼입과 순서 변경을 시험한다. 목록 후 중간/마지막 조각의 같은 길이 교체와 내용 변경, 실행 중 변경, 링크 및 부모 교체, 길이 오버플로와 합산 예산, 승인 후 한도, 암호, 취소와 충돌도 회귀로 확인한다.
226226- 새 시험 코드는 저장소 루트 tests/에만 둔다. 작업 파일과 캐시 및 일회성 로그는 프로젝트의 tests/work/split7z 한 곳에 두고 clone 안에 다시 tests/work나 생성용 tests/ci 캐시를 만들지 않는다. PR 병합 또는 종료 뒤 담당자가 해당 작업 폴더와 캐시를 정리한다.
227추가:
228추가: ### 독립 분할 표본
229추가:
230추가: - `tests/rust-archive-worker/fixtures/split7z/`는 Ubuntu `7zip 26.00+dfsg-1`의 7-Zip 26.00이 `-v64b`로 직접 만든 조각이다. 일반 solid LZMA2, 헤더 암호화와 본문 암호화 묶음을 포함한다. 테스트에만 쓰는 독립 실행 도구이며 제품 의존성이나 배포 파일에 추가하지 않는다.
231추가: - 생성기 `tests/rust-archive-worker/split_fixtures.py`가 독립 도구로 다시 풀어 원본 바이트와 비교하고 `manifest.json`에 도구 버전, 옵션, 각 조각과 논리 입력 및 해제 결과의 SHA256을 기록한다. 암호 표본의 공개 시험 암호는 `zipelo-split-test`다. 새 표본을 만들 때 `--tool`에 7-Zip 실행 파일을, `--work`와 `--output`에는 `tests/work/split7z` 아래의 비어 있는 별도 하위 폴더를 지정한다.
232추가: - 작업자 회귀 시험은 추적된 일반 표본의 두 파일을 풀어 기준 바이트와 해시를 대조한다. 암호화 표본은 기존 7z 정책대로 UnsupportedFeature이며 새 암호 지원이나 암호 질문을 추가하지 않는다. 목록 성공은 패킹 데이터 전체의 무결성 검증을 뜻하지 않는다.
수정experiments/rust-archive-worker/src/create_sources.rs+8-2
@@ -142,10 +142,16 @@ impl Input {
142142 Ok(())
143143 }
144144 fn open_child(&self, path: &Path, name: &str) -> Result<Self> {
145추가: self.open_named(path, std::ffi::OsStr::new(name))
146추가: }
147추가: pub(crate) fn open_named(&self, path: &Path, name: &std::ffi::OsStr) -> Result<Self> {
148추가: if !NativePath::from_path(Path::new(name)).is_basename() {
149추가: return Err(ErrorCode::UnsafePath);
150추가: }
145151 #[cfg(target_os = "linux")]
146152 {
147153 let _ = path;
148삭제: let file = Self::read(Self::child(&self.file, std::ffi::OsStr::new(name))?)?;
154추가: let file = Self::read(Self::child(&self.file, name)?)?;
149155 Self::validate(&file)?;
150156 Ok(Self { file })
151157 }
@@ -154,7 +160,7 @@ impl Input {
154160 Self::open(&path.join(name))
155161 }
156162 }
157삭제: fn children(&self, path: &Path) -> Result<fs::ReadDir> {
163추가: pub(crate) fn children(&self, path: &Path) -> Result<fs::ReadDir> {
158164 #[cfg(target_os = "linux")]
159165 {
160166 use std::os::fd::AsRawFd;
수정experiments/rust-archive-worker/src/lib.rs+1-0
@@ -12,6 +12,7 @@ pub mod resources;
1212pub mod runtime;
1313mod seven_zip;
1414mod space;
15추가: mod split_seven_zip;
1516mod spool;
1617mod streaming;
1718pub mod wire;
수정experiments/rust-archive-worker/src/runtime.rs+89-7
@@ -39,6 +39,7 @@ struct Job<W> {
3939 budget: Option<Budget>,
4040 watchdog: Watchdog,
4141 remaining_choice: Option<ConflictChoice>,
42추가: source_group: Option<crate::split_seven_zip::Group>,
4243 started: Instant,
4344 terminal: Terminal,
4445 parent: crate::parent::Parent,
@@ -249,6 +250,38 @@ impl<W: Write> Job<W> {
249250 ErrorCode::Io
250251 })
251252 }
253추가: fn split_result<T>(
254추가: &mut self,
255추가: result: std::result::Result<T, crate::split_seven_zip::Failure>,
256추가: ) -> Result<T> {
257추가: match result {
258추가: Ok(value) => Ok(value),
259추가: Err(failure) => {
260추가: self.check()?;
261추가: if let Some((reason, volume)) = failure.problem {
262추가: self.event(Message::VolumeProblem { reason, volume })?;
263추가: }
264추가: Err(failure.error)
265추가: }
266추가: }
267추가: }
268추가: fn verify_split(&mut self) -> Result<()> {
269추가: let Some(group) = self.source_group.take() else {
270추가: return Ok(());
271추가: };
272추가: let result = (|| {
273추가: self.progress(Stage::Verify, 0, None, 0)?;
274추가: group.verify(&mut |step| match step {
275추가: crate::spool::Step::Check => self.check(),
276추가: crate::spool::Step::Activity => completed(Ok(()), self),
277추가: crate::spool::Step::Read { bytes, total } => {
278추가: self.progress(Stage::Verify, bytes, Some(total), 0)
279추가: }
280추가: })
281추가: })();
282추가: self.source_group = Some(group);
283추가: self.split_result(result)
284추가: }
252285 fn check(&mut self) -> Result<()> {
253286 self.parent.check()?;
254287 let state = self.state.lock().map_err(|_| ErrorCode::Internal)?;
@@ -304,8 +337,12 @@ impl<W: Write> Job<W> {
304337 match step {
305338 filesystem::PublishStep::Check => self.check(),
306339 filesystem::PublishStep::Activity => completed(Ok(()), self),
307삭제: filesystem::PublishStep::Commit if last => self.cutoff(),
308삭제: filesystem::PublishStep::Commit => self.check(),
340추가: filesystem::PublishStep::Commit => {
341추가: if self.terminal.created_count == 0 {
342추가: self.verify_split()?;
343추가: }
344추가: if last { self.cutoff() } else { self.check() }
345추가: }
309346 }
310347 });
311348 self.terminal.retained_partial_count += p.retained;
@@ -362,6 +399,12 @@ impl<W: Write> Job<W> {
362399 use sha2::{Digest, Sha256};
363400 use std::io::{Read, Seek, SeekFrom};
364401 let path = archive.to_path()?;
402추가: if crate::split_seven_zip::is_split(&path)
403추가: || crate::split_seven_zip::unsupported_split(&path)
404추가: || matches!(expected.source_object, SourceObject::SplitSevenZip { .. })
405추가: {
406추가: return Err(ErrorCode::UnsupportedFeature);
407추가: }
365408 self.progress(Stage::Read, 0, None, 0)?;
366409 let mut snapshot =
367410 crate::spool::Snapshot::open_reporting(&path, limits.input, &mut |step| match step {
@@ -517,8 +560,38 @@ impl<W: Write> Job<W> {
517560 } => {
518561 let extract = matches!(start.action, Action::Extract { .. });
519562 let path = source.to_path()?;
520삭제: self.progress(Stage::Read, 0, None, 0)?;
521삭제: let mut snapshot =
563추가: self.progress(
564추가: if crate::split_seven_zip::is_split(&path) {
565추가: Stage::Scan
566추가: } else {
567추가: Stage::Read
568추가: },
569추가: 0,
570추가: None,
571추가: 0,
572추가: )?;
573추가: let expected = match &start.action {
574추가: Action::Extract { list_id, .. } => list_id.as_ref(),
575추가: _ => None,
576추가: };
577추가: let metadata_limits = self.metadata_limits();
578추가: let captured = crate::split_seven_zip::open(
579추가: &path,
580추가: expected,
581추가: limits.input,
582추가: metadata_limits,
583추가: &mut |step| match step {
584추가: crate::spool::Step::Check => self.check(),
585추가: crate::spool::Step::Activity => completed(Ok(()), self),
586추가: crate::spool::Step::Read { bytes, total } => {
587추가: self.progress(Stage::Read, bytes, Some(total), 0)
588추가: }
589추가: },
590추가: );
591추가: let mut snapshot = if let Some(captured) = self.split_result(captured)? {
592추가: self.source_group = Some(captured.group);
593추가: captured.snapshot
594추가: } else {
522595 crate::spool::Snapshot::open_reporting(&path, limits.input, &mut |step| {
523596 match step {
524597 crate::spool::Step::Check => self.check(),
@@ -527,13 +600,14 @@ impl<W: Write> Job<W> {
527600 self.progress(Stage::Read, bytes, Some(total), 0)
528601 }
529602 }
530삭제: })?;
603추가: })?
604추가: };
531605 if let Action::Extract {
532606 list_id: Some(expected),
533607 ..
534608 } = &start.action
535609 {
536삭제: if expected.catalog_version != 1
610추가: if expected.catalog_version != if self.source_group.is_some() { 2 } else { 1 }
537611 || expected.source_object != snapshot.object
538612 || expected.archive_bytes != snapshot.len
539613 || expected.archive_sha256 != snapshot.hash
@@ -551,7 +625,7 @@ impl<W: Write> Job<W> {
551625 self,
552626 )?;
553627 let list_id = ListId {
554삭제: catalog_version: 1,
628추가: catalog_version: if self.source_group.is_some() { 2 } else { 1 },
555629 format: catalog.format,
556630 source_object: snapshot.object,
557631 archive_bytes: snapshot.len,
@@ -562,6 +636,7 @@ impl<W: Write> Job<W> {
562636 self.check()?;
563637 completed(self.event(Message::Entry(member.entry.clone())), self)?;
564638 }
639추가: self.verify_split()?;
565640 completed(
566641 self.event(Message::ListEnd {
567642 entry_count: catalog.members.len() as u32,
@@ -707,6 +782,9 @@ impl<W: Write> Job<W> {
707782 .collect::<Result<BTreeSet<_>>>()?;
708783 for name in dirs {
709784 self.check()?;
785추가: if self.terminal.created_count == 0 {
786추가: self.verify_split()?;
787추가: }
710788 let (created, durability, sync_error) =
711789 filesystem::directory_with(&root, &name, self)?;
712790 if created {
@@ -778,6 +856,9 @@ impl<W: Write> Job<W> {
778856 replace,
779857 )?;
780858 }
859추가: if self.terminal.created_count == 0 {
860추가: self.verify_split()?;
861추가: }
781862 if !self.interactive || self.terminal.created_count != 0 {
782863 self.terminal.publication = Publication::Complete;
783864 }
@@ -1018,6 +1099,7 @@ pub fn serve<R: Read + Send + 'static, W: Write + Send + 'static>(
10181099 budget,
10191100 watchdog: Watchdog::new(),
10201101 remaining_choice: None,
1102추가: source_group: None,
10211103 parent,
10221104 started: Instant::now(),
10231105 terminal: Terminal {
추가experiments/rust-archive-worker/src/split_seven_zip.rs+580-0
@@ -0,0 +1,580 @@
1추가: use crate::{
2추가: create_sources::Input,
3추가: filesystem,
4추가: protocol::*,
5추가: spool::{Snapshot, Step},
6추가: };
7추가: use sha2::{Digest, Sha256};
8추가: use std::{
9추가: ffi::{OsStr, OsString},
10추가: fs::{File, Metadata},
11추가: io::{Read, Seek, Write},
12추가: path::{Path, PathBuf},
13추가: time::{Instant, SystemTime},
14추가: };
15추가:
16추가: const MAX_VOLUMES: usize = 999;
17추가: type Result<T> = std::result::Result<T, Failure>;
18추가:
19추가: #[derive(Debug)]
20추가: pub(crate) struct Failure {
21추가: pub error: ErrorCode,
22추가: pub problem: Option<(VolumeProblemReason, NativePath)>,
23추가: }
24추가: impl From<ErrorCode> for Failure {
25추가: fn from(error: ErrorCode) -> Self {
26추가: Self {
27추가: error,
28추가: problem: None,
29추가: }
30추가: }
31추가: }
32추가:
33추가: #[cfg(unix)]
34추가: fn 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)]
42추가: fn units(name: &OsStr) -> Vec<u16> {
43추가: use std::os::windows::ffi::OsStrExt;
44추가: name.encode_wide().collect()
45추가: }
46추가: #[cfg(unix)]
47추가: fn 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)]
52추가: fn native(name: &[u16]) -> OsString {
53추가: use std::os::windows::ffi::OsStringExt;
54추가: OsString::from_wide(name)
55추가: }
56추가: fn 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추가: }
87추가: fn 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추가: }
97추가: struct Name {
98추가: prefix: Vec<u16>,
99추가: selected: u32,
100추가: width: usize,
101추가: }
102추가: impl 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추가: }
132추가: pub(crate) fn is_split(path: &Path) -> bool {
133추가: Name::parse(path).is_some()
134추가: }
135추가: pub(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추가:
149추가: struct Part {
150추가: name: OsString,
151추가: object: SourceObject,
152추가: length: u64,
153추가: modified: SystemTime,
154추가: hash: [u8; 32],
155추가: }
156추가: pub(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추가: }
165추가: pub(crate) struct Captured {
166추가: pub snapshot: Snapshot,
167추가: pub group: Group,
168추가: }
169추가: fn 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추가: }
176추가: fn combined_length(total: u64, next: u64) -> Result<u64> {
177추가: total
178추가: .checked_add(next)
179추가: .ok_or_else(|| ErrorCode::Limit.into())
180추가: }
181추가: impl 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추가: }
423추가: pub(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"]
580추가: mod tests;
수정experiments/rust-archive-worker/src/wire.rs+14-0
@@ -310,6 +310,20 @@ impl Wire for SourceObject {
310310 }
311311 }
312312}
313추가: pub(crate) fn encode_source_object(value: &SourceObject) -> io::Result<Vec<u8>> {
314추가: encode_component(value)
315추가: }
316추가: pub(crate) fn encode_native_path(value: &NativePath) -> io::Result<Vec<u8>> {
317추가: encode_component(value)
318추가: }
319추가: fn encode_component(value: &impl Wire) -> io::Result<Vec<u8>> {
320추가: let mut encoder = Encoder {
321추가: bytes: Vec::new(),
322추가: selection_limit: LEGACY_VECTOR_ITEMS,
323추가: };
324추가: value.enc(&mut encoder)?;
325추가: Ok(encoder.bytes)
326추가: }
313327impl Wire for Selection {
314328 fn enc(&self, e: &mut Encoder) -> io::Result<()> {
315329 match self {
추가tests/rust-archive-worker/fixtures/split7z/encrypted-body.7z.001

바이너리 파일이라 Diff를 표시하지 않아요.

파일 내려받기
추가tests/rust-archive-worker/fixtures/split7z/encrypted-body.7z.002

바이너리 파일이라 Diff를 표시하지 않아요.

파일 내려받기
추가tests/rust-archive-worker/fixtures/split7z/encrypted-body.7z.003

바이너리 파일이라 Diff를 표시하지 않아요.

파일 내려받기
추가tests/rust-archive-worker/fixtures/split7z/encrypted-body.7z.004

바이너리 파일이라 Diff를 표시하지 않아요.

파일 내려받기
추가tests/rust-archive-worker/fixtures/split7z/encrypted-body.7z.005

바이너리 파일이라 Diff를 표시하지 않아요.

파일 내려받기
추가tests/rust-archive-worker/fixtures/split7z/encrypted-body.7z.006

바이너리 파일이라 Diff를 표시하지 않아요.

파일 내려받기
추가tests/rust-archive-worker/fixtures/split7z/encrypted-body.7z.007

바이너리 파일이라 Diff를 표시하지 않아요.

파일 내려받기
추가tests/rust-archive-worker/fixtures/split7z/encrypted-body.7z.008

바이너리 파일이라 Diff를 표시하지 않아요.

파일 내려받기
추가tests/rust-archive-worker/fixtures/split7z/encrypted-body.7z.009

바이너리 파일이라 Diff를 표시하지 않아요.

파일 내려받기
추가tests/rust-archive-worker/fixtures/split7z/encrypted-body.7z.010

바이너리 파일이라 Diff를 표시하지 않아요.

파일 내려받기
추가tests/rust-archive-worker/fixtures/split7z/encrypted-header.7z.001

바이너리 파일이라 Diff를 표시하지 않아요.

파일 내려받기
추가tests/rust-archive-worker/fixtures/split7z/encrypted-header.7z.002

바이너리 파일이라 Diff를 표시하지 않아요.

파일 내려받기
추가tests/rust-archive-worker/fixtures/split7z/encrypted-header.7z.003

바이너리 파일이라 Diff를 표시하지 않아요.

파일 내려받기
추가tests/rust-archive-worker/fixtures/split7z/encrypted-header.7z.004

바이너리 파일이라 Diff를 표시하지 않아요.

파일 내려받기
추가tests/rust-archive-worker/fixtures/split7z/encrypted-header.7z.005

바이너리 파일이라 Diff를 표시하지 않아요.

파일 내려받기
추가tests/rust-archive-worker/fixtures/split7z/encrypted-header.7z.006

바이너리 파일이라 Diff를 표시하지 않아요.

파일 내려받기
추가tests/rust-archive-worker/fixtures/split7z/encrypted-header.7z.007

바이너리 파일이라 Diff를 표시하지 않아요.

파일 내려받기
추가tests/rust-archive-worker/fixtures/split7z/encrypted-header.7z.008

바이너리 파일이라 Diff를 표시하지 않아요.

파일 내려받기
추가tests/rust-archive-worker/fixtures/split7z/encrypted-header.7z.009

바이너리 파일이라 Diff를 표시하지 않아요.

파일 내려받기
추가tests/rust-archive-worker/fixtures/split7z/encrypted-header.7z.010

바이너리 파일이라 Diff를 표시하지 않아요.

파일 내려받기
추가tests/rust-archive-worker/fixtures/split7z/encrypted-header.7z.011

바이너리 파일이라 Diff를 표시하지 않아요.

파일 내려받기
추가tests/rust-archive-worker/fixtures/split7z/manifest.json+215-0
@@ -0,0 +1,215 @@
1추가: {
2추가: "tool": "7-Zip (a) 26.00 (x64) : Copyright (c) 1999-2026 Igor Pavlov : 2026-02-12",
3추가: "source": "Ubuntu 7zip 26.00+dfsg-1",
4추가: "payload_sha256": {
5추가: "folder/hello.txt": "8f4e947bcb198177be3ee37336bcfad91ea6ac7e8ba574822ad9992594e25402",
6추가: "second.bin": "689388892d665f3bd6fcfbd95b3e92bb101ef323d81e85d55b8f2ac0dc341686"
7추가: },
8추가: "fixtures": {
9추가: "reference": {
10추가: "arguments": [
11추가: "a",
12추가: "-t7z",
13추가: "-m0=LZMA2",
14추가: "-md=1m",
15추가: "-ms=on",
16추가: "-mhc=off",
17추가: "-mta=off",
18추가: "-mtc=off",
19추가: "-mtm=off",
20추가: "-v64b"
21추가: ],
22추가: "parts": [
23추가: {
24추가: "name": "reference.7z.001",
25추가: "bytes": 64,
26추가: "sha256": "926cc1eccf417dc04de359b88be8e45f988a69de1cec76e1b996b04658b6a839"
27추가: },
28추가: {
29추가: "name": "reference.7z.002",
30추가: "bytes": 64,
31추가: "sha256": "dcbe0ab8bb6e25fd65917ecd2fee5bd433cacd8b446b8dcac3b4b74e2bf0b48a"
32추가: },
33추가: {
34추가: "name": "reference.7z.003",
35추가: "bytes": 64,
36추가: "sha256": "221ab44a6acbb1f1dfcf61b3b591ecf97b6b539fe54affdcf1e69f467a5a6386"
37추가: },
38추가: {
39추가: "name": "reference.7z.004",
40추가: "bytes": 64,
41추가: "sha256": "8f5574b9e8ce6ed7e8279c7ef3cc4ef95a1a798fef34e7b46dcc5f03b4d07f8f"
42추가: },
43추가: {
44추가: "name": "reference.7z.005",
45추가: "bytes": 64,
46추가: "sha256": "75abd8ed00ba5456353886a0fba0c8b84e80779bb739c2367f8e326ab7d064d6"
47추가: },
48추가: {
49추가: "name": "reference.7z.006",
50추가: "bytes": 64,
51추가: "sha256": "c25b47c4c2dba64e4b29d6f404d2b56e4588547beaf270fa05af256daad480e6"
52추가: },
53추가: {
54추가: "name": "reference.7z.007",
55추가: "bytes": 64,
56추가: "sha256": "81f2ee1ab21b6e102cb9b1ea2d22f94214bd77876b2e1ff9cecff47f9d02b805"
57추가: },
58추가: {
59추가: "name": "reference.7z.008",
60추가: "bytes": 64,
61추가: "sha256": "c0577df6e2af28ea14628147893be75d11c653e10a0df1281c234c87d6edf5e9"
62추가: },
63추가: {
64추가: "name": "reference.7z.009",
65추가: "bytes": 41,
66추가: "sha256": "509db208d2a0370d94cff9348cba5342752a0e4af32bf254acc281a0866a4cce"
67추가: }
68추가: ],
69추가: "logical_sha256": "66f0c5bba96b0eaa53b15c12cc233f2954df4ea5f3a7c01ae096f911dd2bfd6b"
70추가: },
71추가: "encrypted-header": {
72추가: "arguments": [
73추가: "a",
74추가: "-t7z",
75추가: "-m0=LZMA2",
76추가: "-md=1m",
77추가: "-ms=on",
78추가: "-mhc=off",
79추가: "-mta=off",
80추가: "-mtc=off",
81추가: "-mtm=off",
82추가: "-v64b",
83추가: "-pzipelo-split-test",
84추가: "-mhe=on"
85추가: ],
86추가: "parts": [
87추가: {
88추가: "name": "encrypted-header.7z.001",
89추가: "bytes": 64,
90추가: "sha256": "f1e82f9bc81de9f7930353e2ea3405e1861079a928b7293a8131d540ea44605c"
91추가: },
92추가: {
93추가: "name": "encrypted-header.7z.002",
94추가: "bytes": 64,
95추가: "sha256": "ef59571335763e52ab8c05cc902d10889a963b3ac9496c3bb397d6b0bd54a761"
96추가: },
97추가: {
98추가: "name": "encrypted-header.7z.003",
99추가: "bytes": 64,
100추가: "sha256": "f9dc1be239cf45306bf8980fa7ad63e89260f0f4502085688c028905eeada0f5"
101추가: },
102추가: {
103추가: "name": "encrypted-header.7z.004",
104추가: "bytes": 64,
105추가: "sha256": "4b64ed14cd8e659cbd154796ead55384bab5ab8a88f94ce308720f649b03cf48"
106추가: },
107추가: {
108추가: "name": "encrypted-header.7z.005",
109추가: "bytes": 64,
110추가: "sha256": "204ac069bcabfc0420450a619e4fd37d620bc1e25269162069c9c0978688a9ef"
111추가: },
112추가: {
113추가: "name": "encrypted-header.7z.006",
114추가: "bytes": 64,
115추가: "sha256": "698d9f22cfb818f6ffa7da166e763a0189f652d8fd765c4549cf2512c3869d17"
116추가: },
117추가: {
118추가: "name": "encrypted-header.7z.007",
119추가: "bytes": 64,
120추가: "sha256": "5c76cc10923601e5512ac60092945890cabe57112242d5c06c834353f9490966"
121추가: },
122추가: {
123추가: "name": "encrypted-header.7z.008",
124추가: "bytes": 64,
125추가: "sha256": "c08af61ef1f3c549e6c5bccc581549054e724ef02b5369dc152596bb1e4c6018"
126추가: },
127추가: {
128추가: "name": "encrypted-header.7z.009",
129추가: "bytes": 64,
130추가: "sha256": "f31af00c7cf084ce7be451f12e5deb4e6a32d843b49666e1dadf59dcd0c9bacf"
131추가: },
132추가: {
133추가: "name": "encrypted-header.7z.010",
134추가: "bytes": 64,
135추가: "sha256": "76ba20a1b63b7d2dbf59553bd923d621f190d18594732e0ac823d47b5d243b07"
136추가: },
137추가: {
138추가: "name": "encrypted-header.7z.011",
139추가: "bytes": 1,
140추가: "sha256": "6e340b9cffb37a989ca544e6bb780a2c78901d3fb33738768511a30617afa01d"
141추가: }
142추가: ],
143추가: "logical_sha256": "d194a02a1d24154c6e2f7e3c959b23c20a330955c6496247d57412f262d278ae"
144추가: },
145추가: "encrypted-body": {
146추가: "arguments": [
147추가: "a",
148추가: "-t7z",
149추가: "-m0=LZMA2",
150추가: "-md=1m",
151추가: "-ms=on",
152추가: "-mhc=off",
153추가: "-mta=off",
154추가: "-mtc=off",
155추가: "-mtm=off",
156추가: "-v64b",
157추가: "-pzipelo-split-test",
158추가: "-mhe=off"
159추가: ],
160추가: "parts": [
161추가: {
162추가: "name": "encrypted-body.7z.001",
163추가: "bytes": 64,
164추가: "sha256": "e3e135f63bd6e4c5fb2a463987811ca0e295745904b4876f2d41e90be1edbd9b"
165추가: },
166추가: {
167추가: "name": "encrypted-body.7z.002",
168추가: "bytes": 64,
169추가: "sha256": "aedca6078c99f24c83f83b03f1fa48b1c2be5477871f0b16d23baa00c6237d3c"
170추가: },
171추가: {
172추가: "name": "encrypted-body.7z.003",
173추가: "bytes": 64,
174추가: "sha256": "0b812094951519250385c46d51e8ec25f78cd2343f659db517c45c592a0b25cf"
175추가: },
176추가: {
177추가: "name": "encrypted-body.7z.004",
178추가: "bytes": 64,
179추가: "sha256": "0e6a28d1553cb74fd3c7a2870332b6d49b98bf9357d3bfd48b04712fc7e105ca"
180추가: },
181추가: {
182추가: "name": "encrypted-body.7z.005",
183추가: "bytes": 64,
184추가: "sha256": "2bee9f4c138ae71ad35af650253768a778c3aacc0d34f6f1319213c59627cb5e"
185추가: },
186추가: {
187추가: "name": "encrypted-body.7z.006",
188추가: "bytes": 64,
189추가: "sha256": "6ceacdee4bff8191c4d0d96e8c59ba9a8d73a77c66aea0cf883019800dec175f"
190추가: },
191추가: {
192추가: "name": "encrypted-body.7z.007",
193추가: "bytes": 64,
194추가: "sha256": "73e7ce72aeee468967c3f4e5985eff4c650fa28082a715b5b229bdbc0c94f9ac"
195추가: },
196추가: {
197추가: "name": "encrypted-body.7z.008",
198추가: "bytes": 64,
199추가: "sha256": "dfee6881d0d0d06b6c90ac6afc38ea346e8577466963530d634bb51afd398848"
200추가: },
201추가: {
202추가: "name": "encrypted-body.7z.009",
203추가: "bytes": 64,
204추가: "sha256": "6744ff37e50ff527da6ce80515b582028e5a72e248a0aa1823737f56e6989a9e"
205추가: },
206추가: {
207추가: "name": "encrypted-body.7z.010",
208추가: "bytes": 10,
209추가: "sha256": "87d64a26149d54109ecd0e122979863a0488ab35e468dce5f061084480d5a1a8"
210추가: }
211추가: ],
212추가: "logical_sha256": "931110c31e093301c19ed6fc40fa18f58fc9502b14d4a0fd9fdbb1f7879e5a93"
213추가: }
214추가: }
215추가: }
추가tests/rust-archive-worker/fixtures/split7z/reference.7z.001

바이너리 파일이라 Diff를 표시하지 않아요.

파일 내려받기
추가tests/rust-archive-worker/fixtures/split7z/reference.7z.002

바이너리 파일이라 Diff를 표시하지 않아요.

파일 내려받기
추가tests/rust-archive-worker/fixtures/split7z/reference.7z.003

바이너리 파일이라 Diff를 표시하지 않아요.

파일 내려받기
추가tests/rust-archive-worker/fixtures/split7z/reference.7z.004

바이너리 파일이라 Diff를 표시하지 않아요.

파일 내려받기
추가tests/rust-archive-worker/fixtures/split7z/reference.7z.005

바이너리 파일이라 Diff를 표시하지 않아요.

파일 내려받기
추가tests/rust-archive-worker/fixtures/split7z/reference.7z.006

바이너리 파일이라 Diff를 표시하지 않아요.

파일 내려받기
추가tests/rust-archive-worker/fixtures/split7z/reference.7z.007

바이너리 파일이라 Diff를 표시하지 않아요.

파일 내려받기
추가tests/rust-archive-worker/fixtures/split7z/reference.7z.008

바이너리 파일이라 Diff를 표시하지 않아요.

파일 내려받기
추가tests/rust-archive-worker/fixtures/split7z/reference.7z.009

바이너리 파일이라 Diff를 표시하지 않아요.

파일 내려받기
수정tests/rust-archive-worker/main.rs+2-0
@@ -1623,3 +1623,5 @@ mod conflicts;
16231623mod compressed_tar;
16241624
16251625mod guarded;
1626추가:
1627추가: mod split_runtime;
추가tests/rust-archive-worker/split_capture.rs+406-0
@@ -0,0 +1,406 @@
1추가: use super::*;
2추가: use std::sync::atomic::{AtomicU64, Ordering};
3추가: static NEXT: AtomicU64 = AtomicU64::new(0);
4추가: struct Scratch(PathBuf);
5추가: impl Scratch {
6추가: fn new() -> Self {
7추가: let path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
8추가: .join("../../tests/rust-archive-worker/split-runs")
9추가: .join(format!(
10추가: "{}-{}",
11추가: std::process::id(),
12추가: NEXT.fetch_add(1, Ordering::Relaxed)
13추가: ));
14추가: std::fs::create_dir_all(&path).unwrap();
15추가: Self(path.canonicalize().unwrap())
16추가: }
17추가: fn split(&self, count: usize) -> Vec<u8> {
18추가: let bytes = include_bytes!("fixtures/7z/copy.7z");
19추가: for index in (0..count).rev() {
20추가: std::fs::write(
21추가: self.0.join(format!("sample.7z.{:03}", index + 1)),
22추가: &bytes[index * bytes.len() / count..(index + 1) * bytes.len() / count],
23추가: )
24추가: .unwrap();
25추가: }
26추가: bytes.to_vec()
27추가: }
28추가: fn first(&self) -> PathBuf {
29추가: self.0.join("sample.7z.001")
30추가: }
31추가: fn capture(&self) -> Captured {
32추가: open(
33추가: &self.first(),
34추가: None,
35추가: u64::MAX,
36추가: crate::archive::MetadataLimits::default(),
37추가: &mut |_| Ok(()),
38추가: )
39추가: .unwrap()
40추가: .unwrap()
41추가: }
42추가: }
43추가: impl Drop for Scratch {
44추가: fn drop(&mut self) {
45추가: let _ = std::fs::remove_dir_all(&self.0);
46추가: }
47추가: }
48추가: fn code<T>(result: Result<T>) -> ErrorCode {
49추가: match result {
50추가: Err(failure) => failure.error,
51추가: Ok(_) => panic!("오류가 필요함"),
52추가: }
53추가: }
54추가: fn token(capture: &Captured) -> ListId {
55추가: ListId {
56추가: catalog_version: 2,
57추가: format: Format::SevenZip,
58추가: source_object: capture.snapshot.object.clone(),
59추가: archive_bytes: capture.snapshot.len,
60추가: archive_sha256: capture.snapshot.hash,
61추가: }
62추가: }
63추가:
64추가: #[test]
65추가: fn concatenated_snapshot_and_manifest_include_every_native_component() {
66추가: let s = Scratch::new();
67추가: let original = s.split(11);
68추가: let mut captured = s.capture();
69추가: let mut actual = Vec::new();
70추가: captured.snapshot.file.read_to_end(&mut actual).unwrap();
71추가: assert_eq!(actual, original);
72추가: assert_eq!(
73추가: captured.snapshot.hash,
74추가: <[u8; 32]>::from(Sha256::digest(&original))
75추가: );
76추가: let group = &captured.group;
77추가: let mut bytes = b"zipelo.split7z.v1\0".to_vec();
78추가: fn object(bytes: &mut Vec<u8>, object: &SourceObject) {
79추가: match object {
80추가: SourceObject::Unix { device, inode } => {
81추가: bytes.push(1);
82추가: bytes.extend(device.to_le_bytes());
83추가: bytes.extend(inode.to_le_bytes());
84추가: }
85추가: SourceObject::Windows {
86추가: volume_serial,
87추가: file_id,
88추가: } => {
89추가: bytes.push(2);
90추가: bytes.extend(volume_serial.to_le_bytes());
91추가: bytes.extend(file_id);
92추가: }
93추가: _ => panic!("단일 객체가 필요함"),
94추가: }
95추가: }
96추가: object(&mut bytes, &group.object);
97추가: bytes.extend(11u16.to_le_bytes());
98추가: for (index, part) in group.parts.iter().enumerate() {
99추가: bytes.extend(((index + 1) as u16).to_le_bytes());
100추가: match NativePath::from_path(Path::new(&part.name)) {
101추가: NativePath::Unix(name) => {
102추가: bytes.push(1);
103추가: bytes.extend((name.len() as u32).to_le_bytes());
104추가: bytes.extend(name);
105추가: }
106추가: NativePath::Windows(name) => {
107추가: bytes.push(2);
108추가: bytes.extend((name.len() as u32).to_le_bytes());
109추가: for unit in name {
110추가: bytes.extend(unit.to_le_bytes());
111추가: }
112추가: }
113추가: }
114추가: object(&mut bytes, &part.object);
115추가: bytes.extend(part.length.to_le_bytes());
116추가: bytes.extend(part.hash);
117추가: }
118추가: assert_eq!(
119추가: captured.snapshot.object,
120추가: SourceObject::SplitSevenZip {
121추가: manifest_sha256: Sha256::digest(&bytes).into()
122추가: }
123추가: );
124추가: }
125추가:
126추가: #[test]
127추가: fn verification_hashes_middle_and_tail_even_when_size_and_time_are_restored() {
128추가: for index in [2, 3] {
129추가: let s = Scratch::new();
130추가: s.split(3);
131추가: let captured = s.capture();
132추가: let path = s.0.join(format!("sample.7z.{index:03}"));
133추가: let file = File::options().read(true).write(true).open(&path).unwrap();
134추가: let modified = file.metadata().unwrap().modified().unwrap();
135추가: let mut changed = std::fs::read(&path).unwrap();
136추가: changed[0] ^= 1;
137추가: std::fs::write(&path, changed).unwrap();
138추가: file.set_times(std::fs::FileTimes::new().set_modified(modified))
139추가: .unwrap();
140추가: assert_eq!(
141추가: code(captured.group.verify(&mut |_| Ok(()))),
142추가: ErrorCode::SourceChanged
143추가: );
144추가: }
145추가: }
146추가:
147추가: #[test]
148추가: fn capture_rechecks_parts_after_the_last_read() {
149추가: let s = Scratch::new();
150추가: s.split(3);
151추가: let mut changed = false;
152추가: let result = open(
153추가: &s.first(),
154추가: None,
155추가: u64::MAX,
156추가: crate::archive::MetadataLimits::default(),
157추가: &mut |step| {
158추가: if matches!(step, Step::Read { .. }) && !changed {
159추가: changed = true;
160추가: let p = s.0.join("sample.7z.002");
161추가: let mut bytes = std::fs::read(&p).unwrap();
162추가: bytes[0] ^= 1;
163추가: std::fs::write(p, bytes).unwrap();
164추가: }
165추가: Ok(())
166추가: },
167추가: );
168추가: assert!(changed);
169추가: assert_eq!(code(result), ErrorCode::SourceChanged);
170추가: }
171추가:
172추가: #[test]
173추가: fn verification_detects_parent_replacement_and_new_part_names() {
174추가: let s = Scratch::new();
175추가: s.split(3);
176추가: let captured = s.capture();
177추가: std::fs::write(s.0.join("sample.7z.004"), [0]).unwrap();
178추가: assert_eq!(
179추가: code(captured.group.verify(&mut |_| Ok(()))),
180추가: ErrorCode::SourceChanged
181추가: );
182추가: std::fs::remove_file(s.0.join("sample.7z.004")).unwrap();
183추가: let renamed = s.0.with_extension("old");
184추가: #[cfg(unix)]
185추가: {
186추가: std::fs::rename(&s.0, &renamed).unwrap();
187추가: std::fs::create_dir(&s.0).unwrap();
188추가: assert_eq!(
189추가: code(captured.group.verify(&mut |_| Ok(()))),
190추가: ErrorCode::SourceChanged
191추가: );
192추가: std::fs::remove_dir_all(renamed).unwrap();
193추가: }
194추가: #[cfg(windows)]
195추가: {
196추가: // 고정한 디렉터리는 Windows 공유 모드로 이름 변경을 차단함.
197추가: assert!(std::fs::rename(&s.0, &renamed).is_err());
198추가: captured.group.verify(&mut |_| Ok(())).unwrap();
199추가: }
200추가: }
201추가:
202추가: #[test]
203추가: fn scan_and_rehash_keep_cancellation_and_deadline_errors() {
204추가: for error in [ErrorCode::None, ErrorCode::Limit] {
205추가: let s = Scratch::new();
206추가: s.split(9);
207추가: for at in [1, 10, 50] {
208추가: let mut checks = 0;
209추가: assert_eq!(
210추가: code(open(
211추가: &s.first(),
212추가: None,
213추가: u64::MAX,
214추가: crate::archive::MetadataLimits::default(),
215추가: &mut |step| {
216추가: if matches!(step, Step::Check) {
217추가: checks += 1;
218추가: if checks == at {
219추가: return Err(error);
220추가: }
221추가: }
222추가: Ok(())
223추가: }
224추가: )),
225추가: error
226추가: );
227추가: }
228추가: let captured = s.capture();
229추가: for at in [1, 10, 40] {
230추가: let mut checks = 0;
231추가: assert_eq!(
232추가: code(captured.group.verify(&mut |step| {
233추가: if matches!(step, Step::Check) {
234추가: checks += 1;
235추가: if checks == at {
236추가: return Err(error);
237추가: }
238추가: }
239추가: Ok(())
240추가: })),
241추가: error
242추가: );
243추가: }
244추가: }
245추가: }
246추가:
247추가: #[test]
248추가: fn aggregate_input_and_metadata_limits_are_not_reset_per_part() {
249추가: let s = Scratch::new();
250추가: let bytes = s.split(11);
251추가: assert_eq!(
252추가: code(open(
253추가: &s.first(),
254추가: None,
255추가: bytes.len() as u64 - 1,
256추가: crate::archive::MetadataLimits::default(),
257추가: &mut |_| Ok(())
258추가: )),
259추가: ErrorCode::Limit
260추가: );
261추가: assert!(
262추가: open(
263추가: &s.first(),
264추가: None,
265추가: bytes.len() as u64,
266추가: crate::archive::MetadataLimits::default(),
267추가: &mut |_| Ok(())
268추가: )
269추가: .unwrap()
270추가: .is_some()
271추가: );
272추가: let metadata = crate::archive::MetadataLimits {
273추가: bytes: 512,
274추가: ..Default::default()
275추가: };
276추가: assert_eq!(
277추가: code(open(&s.first(), None, u64::MAX, metadata, &mut |_| Ok(()))),
278추가: ErrorCode::Limit
279추가: );
280추가: }
281추가:
282추가: #[cfg(unix)]
283추가: #[test]
284추가: fn capture_rejects_symlinks_hard_link_aliases_and_special_files() {
285추가: use std::os::unix::fs::symlink;
286추가: let s = Scratch::new();
287추가: s.split(3);
288추가: let first = s.first();
289추가: let second = s.0.join("sample.7z.002");
290추가: std::fs::remove_file(&second).unwrap();
291추가: symlink(&first, &second).unwrap();
292추가: assert_eq!(
293추가: code(open(
294추가: &first,
295추가: None,
296추가: u64::MAX,
297추가: Default::default(),
298추가: &mut |_| Ok(())
299추가: )),
300추가: ErrorCode::UnsafePath
301추가: );
302추가: std::fs::remove_file(&second).unwrap();
303추가: std::fs::hard_link(&first, &second).unwrap();
304추가: assert_eq!(
305추가: code(open(
306추가: &first,
307추가: None,
308추가: u64::MAX,
309추가: Default::default(),
310추가: &mut |_| Ok(())
311추가: )),
312추가: ErrorCode::UnsafePath
313추가: );
314추가: std::fs::remove_file(&second).unwrap();
315추가: std::fs::create_dir(&second).unwrap();
316추가: assert_eq!(
317추가: code(open(
318추가: &first,
319추가: None,
320추가: u64::MAX,
321추가: Default::default(),
322추가: &mut |_| Ok(())
323추가: )),
324추가: ErrorCode::UnsafePath
325추가: );
326추가: }
327추가:
328추가: #[test]
329추가: fn same_logical_data_with_different_part_boundaries_changes_group_identity() {
330추가: let s = Scratch::new();
331추가: s.split(3);
332추가: let captured = s.capture();
333추가: let expected = token(&captured);
334추가: let first = s.first();
335추가: let second = s.0.join("sample.7z.002");
336추가: let mut a = std::fs::read(&first).unwrap();
337추가: let mut b = std::fs::read(&second).unwrap();
338추가: a.push(b.remove(0));
339추가: std::fs::write(first, a).unwrap();
340추가: std::fs::write(second, b).unwrap();
341추가: let next = s.capture();
342추가: assert_eq!(next.snapshot.hash, captured.snapshot.hash);
343추가: assert_ne!(next.snapshot.object, captured.snapshot.object);
344추가: assert_eq!(
345추가: code(open(
346추가: &s.first(),
347추가: Some(&expected),
348추가: u64::MAX,
349추가: Default::default(),
350추가: &mut |_| Ok(())
351추가: )),
352추가: ErrorCode::SourceChanged
353추가: );
354추가: }
355추가:
356추가: #[test]
357추가: fn combined_lengths_reject_u64_overflow_without_changing_the_limit() {
358추가: assert_eq!(combined_length(u64::MAX - 1, 1).unwrap(), u64::MAX);
359추가: assert_eq!(code(combined_length(u64::MAX, 1)), ErrorCode::Limit);
360추가: assert_eq!(code(combined_length(u64::MAX - 1, 2)), ErrorCode::Limit);
361추가: }
362추가:
363추가: #[cfg(unix)]
364추가: #[test]
365추가: fn native_non_utf8_part_names_are_preserved_without_lossy_matching() {
366추가: use std::os::unix::ffi::OsStringExt;
367추가: let s = Scratch::new();
368추가: let original = s.split(3);
369추가: for index in 1..=3 {
370추가: let mut name = b"\xff\x01.7z.".to_vec();
371추가: name.extend(format!("{index:03}").bytes());
372추가: std::fs::rename(
373추가: s.0.join(format!("sample.7z.{index:03}")),
374추가: s.0.join(OsString::from_vec(name)),
375추가: )
376추가: .unwrap();
377추가: }
378추가: let path = s.0.join(OsString::from_vec(b"\xff\x01.7z.001".to_vec()));
379추가: let captured = open(&path, None, u64::MAX, Default::default(), &mut |_| Ok(()))
380추가: .unwrap()
381추가: .unwrap();
382추가: assert_eq!(
383추가: captured.snapshot.hash,
384추가: <[u8; 32]>::from(Sha256::digest(original))
385추가: );
386추가: assert_eq!(
387추가: NativePath::from_path(Path::new(&captured.group.parts[0].name)),
388추가: NativePath::Unix(b"\xff\x01.7z.001".to_vec())
389추가: );
390추가: }
391추가:
392추가: #[test]
393추가: fn disappearing_known_tail_is_a_source_change_before_reopen() {
394추가: let s = Scratch::new();
395추가: s.split(3);
396추가: let captured = s.capture();
397추가: std::fs::remove_file(s.0.join("sample.7z.003")).unwrap();
398추가: assert_eq!(
399추가: code(
400추가: captured
401추가: .group
402추가: .open_part(&captured.group.parts[2].name, &mut |_| Ok(()))
403추가: ),
404추가: ErrorCode::SourceChanged
405추가: );
406추가: }
추가tests/rust-archive-worker/split_fixtures.py+92-0
@@ -0,0 +1,92 @@
1추가: """독립 7-Zip으로 분할 표본을 만들고 해제 해시를 대조함."""
2추가:
3추가: import argparse
4추가: import hashlib
5추가: import json
6추가: from pathlib import Path
7추가: import subprocess
8추가:
9추가:
10추가: def main():
11추가: parser = argparse.ArgumentParser()
12추가: parser.add_argument("--tool", type=Path, required=True)
13추가: parser.add_argument("--work", type=Path, required=True)
14추가: parser.add_argument("--output", type=Path, required=True)
15추가: args = parser.parse_args()
16추가: tool = args.tool.resolve()
17추가: work = args.work.resolve()
18추가: output = args.output.resolve()
19추가: work.mkdir(parents=True, exist_ok=True)
20추가: output.mkdir(parents=True, exist_ok=True)
21추가: assert not any(work.iterdir()) and not any(output.iterdir())
22추가: source = work / "source"
23추가: (source / "folder").mkdir(parents=True)
24추가: expected = {
25추가: "folder/hello.txt": b"Zipelo 7z interoperability\n" * 100,
26추가: "second.bin": bytes((index * 37 + (index >> 3)) % 256 for index in range(4096)),
27추가: }
28추가: for name, data in expected.items():
29추가: (source / name).write_bytes(data)
30추가:
31추가: def run(arguments, cwd):
32추가: return subprocess.check_output([str(tool), *arguments], cwd=cwd, text=True)
33추가:
34추가: version = run([], source).splitlines()[1]
35추가: fixtures = {}
36추가: variants = [
37추가: ("reference", []),
38추가: ("encrypted-header", ["-pzipelo-split-test", "-mhe=on"]),
39추가: ("encrypted-body", ["-pzipelo-split-test", "-mhe=off"]),
40추가: ]
41추가: for name, encryption in variants:
42추가: options = [
43추가: "a", "-t7z", "-m0=LZMA2", "-md=1m", "-ms=on", "-mhc=off",
44추가: "-mta=off", "-mtc=off", "-mtm=off", "-v64b", *encryption,
45추가: ]
46추가: run([*options, str(output / f"{name}.7z"), "folder", "second.bin"], source)
47추가: parts = sorted(output.glob(f"{name}.7z.[0-9][0-9][0-9]"))
48추가: assert len(parts) > 1
49추가: extracted = work / name
50추가: run(
51추가: ["x", "-y", "-pzipelo-split-test", f"-o{extracted}", str(parts[0])],
52추가: source,
53추가: )
54추가: actual = {
55추가: entry.relative_to(extracted).as_posix(): entry.read_bytes()
56추가: for entry in extracted.rglob("*") if entry.is_file()
57추가: }
58추가: assert actual == expected
59추가: digest = hashlib.sha256()
60추가: for part in parts:
61추가: digest.update(part.read_bytes())
62추가: fixtures[name] = {
63추가: "arguments": options,
64추가: "parts": [
65추가: {
66추가: "name": part.name,
67추가: "bytes": part.stat().st_size,
68추가: "sha256": hashlib.sha256(part.read_bytes()).hexdigest(),
69추가: }
70추가: for part in parts
71추가: ],
72추가: "logical_sha256": digest.hexdigest(),
73추가: }
74추가: manifest = {
75추가: "tool": version,
76추가: "source": "Ubuntu 7zip 26.00+dfsg-1",
77추가: "payload_sha256": {
78추가: name: hashlib.sha256(data).hexdigest() for name, data in expected.items()
79추가: },
80추가: "fixtures": fixtures,
81추가: }
82추가: (output / "manifest.json").write_text(
83추가: json.dumps(manifest, ensure_ascii=False, indent=4) + "\n", encoding="utf-8"
84추가: )
85추가: print(json.dumps({
86추가: "tool": version,
87추가: "parts": {name: len(data["parts"]) for name, data in fixtures.items()},
88추가: }, ensure_ascii=False))
89추가:
90추가:
91추가: if __name__ == "__main__":
92추가: main()
추가tests/rust-archive-worker/split_runtime.rs+555-0
@@ -0,0 +1,555 @@
1추가: use super::*;
2추가: use sha2::{Digest, Sha256};
3추가:
4추가: fn directory(s: &Scratch, name: &str) {
5추가: let path = s.0.join(name);
6추가: fs::create_dir_all(&path).unwrap();
7추가: #[cfg(unix)]
8추가: {
9추가: use std::os::unix::fs::PermissionsExt;
10추가: let mut current = path.as_path();
11추가: while current != s.0 {
12추가: fs::set_permissions(current, fs::Permissions::from_mode(0o700)).unwrap();
13추가: current = current.parent().unwrap();
14추가: }
15추가: }
16추가: }
17추가: fn pieces(s: &Scratch, bytes: &[u8], ends: &[usize]) -> Vec<PathBuf> {
18추가: let mut begin = 0;
19추가: let mut paths = Vec::new();
20추가: for (index, end) in ends.iter().copied().chain(Some(bytes.len())).enumerate() {
21추가: assert!(begin <= end && end <= bytes.len());
22추가: let path = s.0.join(format!("sample.7z.{:03}", index + 1));
23추가: fs::write(&path, &bytes[begin..end]).unwrap();
24추가: paths.push(path);
25추가: begin = end;
26추가: }
27추가: paths
28추가: }
29추가: fn setup(s: &Scratch, count: usize, fixture: &str) -> (Vec<u8>, Vec<PathBuf>) {
30추가: let bytes = seven_fixture(fixture);
31추가: let ends = (1..count)
32추가: .map(|i| i * bytes.len() / count)
33추가: .collect::<Vec<_>>();
34추가: let paths = pieces(s, &bytes, &ends);
35추가: (bytes, paths)
36추가: }
37추가: fn list(s: &Scratch) -> Vec<Message> {
38추가: execute(Start {
39추가: action: Action::List {
40추가: archive: s.path("sample.7z.001"),
41추가: },
42추가: limits: Limits::default(),
43추가: })
44추가: }
45추가: fn id(events: &[Message]) -> ListId {
46추가: assert_eq!(terminal(events).outcome, Outcome::Completed, "{events:?}");
47추가: events
48추가: .iter()
49추가: .find_map(|event| match event {
50추가: Message::ListEnd { list_id, .. } => Some(list_id.clone()),
51추가: _ => None,
52추가: })
53추가: .unwrap()
54추가: }
55추가: fn request(s: &Scratch, list_id: Option<ListId>, selection: Selection) -> Start {
56추가: Start {
57추가: action: Action::Extract {
58추가: archive: s.path("sample.7z.001"),
59추가: destination: s.path("output"),
60추가: selection,
61추가: list_id,
62추가: gzip_output_name: None,
63추가: },
64추가: limits: Limits::default(),
65추가: }
66추가: }
67추가: fn failure(events: &[Message], error: ErrorCode) {
68추가: assert_eq!(terminal(events).outcome, Outcome::Failed, "{events:?}");
69추가: assert_eq!(terminal(events).error, error, "{events:?}");
70추가: assert_eq!(terminal(events).created_count, 0, "{events:?}");
71추가: assert_eq!(
72추가: terminal(events).publication,
73추가: Publication::None,
74추가: "{events:?}"
75추가: );
76추가: assert!(
77추가: !events
78추가: .iter()
79추가: .any(|event| matches!(event, Message::Output { .. } | Message::ListEnd { .. })),
80추가: "{events:?}"
81추가: );
82추가: }
83추가: fn hashes(paths: &[PathBuf]) -> Vec<[u8; 32]> {
84추가: paths
85추가: .iter()
86추가: .map(|p| Sha256::digest(fs::read(p).unwrap()).into())
87추가: .collect()
88추가: }
89추가: fn problem(events: &[Message], reason: VolumeProblemReason, leaf: &str) {
90추가: let problems = events
91추가: .iter()
92추가: .filter_map(|event| match event {
93추가: Message::VolumeProblem { reason, volume } => Some((reason, volume)),
94추가: _ => None,
95추가: })
96추가: .collect::<Vec<_>>();
97추가: assert_eq!(problems.len(), 1, "{events:?}");
98추가: assert_eq!(
99추가: problems[0],
100추가: (&reason, &NativePath::from_path(std::path::Path::new(leaf)))
101추가: );
102추가: let accepted = events
103추가: .iter()
104추가: .position(|event| matches!(event, Message::Accepted { .. }))
105추가: .unwrap();
106추가: let reported = events
107추가: .iter()
108추가: .position(|event| matches!(event, Message::VolumeProblem { .. }))
109추가: .unwrap();
110추가: assert!(accepted < reported && reported < events.len() - 1);
111추가: }
112추가:
113추가: #[test]
114추가: fn headers_and_data_cross_variable_part_boundaries_for_reference_archives() {
115추가: for fixture in [
116추가: "copy.7z",
117추가: "lzma.7z",
118추가: "lzma2.7z",
119추가: "libarchive-lzma1.7z",
120추가: "libarchive-lzma2.7z",
121추가: ] {
122추가: let s = Scratch::new();
123추가: let bytes = seven_fixture(fixture);
124추가: let paths = pieces(&s, &bytes, &[1, 6, 13, 31, 32, 40]);
125추가: let before = hashes(&paths);
126추가: let listed = list(&s);
127추가: let token = id(&listed);
128추가: assert_eq!(token.catalog_version, 2);
129추가: assert_eq!(token.format, Format::SevenZip);
130추가: assert!(matches!(
131추가: token.source_object,
132추가: SourceObject::SplitSevenZip { .. }
133추가: ));
134추가: assert_eq!(token.archive_bytes, bytes.len() as u64);
135추가: assert_eq!(
136추가: token.archive_sha256,
137추가: <[u8; 32]>::from(Sha256::digest(&bytes))
138추가: );
139추가: directory(&s, "output");
140추가: let result = execute(request(&s, Some(token), Selection::EntryIds(vec![0])));
141추가: assert_eq!(
142추가: terminal(&result).outcome,
143추가: Outcome::Completed,
144추가: "{fixture}: {result:?}"
145추가: );
146추가: assert_eq!(
147추가: fs::read(s.0.join("output/folder/hello.txt")).unwrap(),
148추가: SEVEN_PAYLOAD.repeat(100)
149추가: );
150추가: assert_eq!(hashes(&paths), before);
151추가: }
152추가: }
153추가:
154추가: #[test]
155추가: fn numeric_order_crosses_009_010_and_accepts_exactly_999_parts() {
156추가: for count in [11, 999] {
157추가: let s = Scratch::new();
158추가: let (bytes, paths) = setup(&s, count, "copy.7z");
159추가: let before = hashes(&paths);
160추가: let token = id(&list(&s));
161추가: assert_eq!(token.archive_bytes, bytes.len() as u64);
162추가: directory(&s, "output");
163추가: let result = execute(request(&s, Some(token), Selection::All));
164추가: assert_eq!(
165추가: terminal(&result).outcome,
166추가: Outcome::Completed,
167추가: "{count}: {result:?}"
168추가: );
169추가: assert_eq!(
170추가: fs::read(s.0.join("output/folder/hello.txt")).unwrap(),
171추가: SEVEN_PAYLOAD.repeat(100)
172추가: );
173추가: assert_eq!(hashes(&paths), before);
174추가: fs::write(s.0.join("sample.7z.1000"), [0]).unwrap();
175추가: failure(&list(&s), ErrorCode::Limit);
176추가: }
177추가: }
178추가:
179추가: #[test]
180추가: fn nonfirst_selection_and_definite_middle_gaps_name_the_exact_required_part() {
181추가: let s = Scratch::new();
182추가: let (_, paths) = setup(&s, 11, "copy.7z");
183추가: let result = execute(Start {
184추가: action: Action::List {
185추가: archive: s.path("sample.7z.002"),
186추가: },
187추가: limits: Limits::default(),
188추가: });
189추가: failure(&result, ErrorCode::InvalidRequest);
190추가: problem(
191추가: &result,
192추가: VolumeProblemReason::FirstVolumeRequired,
193추가: "sample.7z.001",
194추가: );
195추가: fs::remove_file(&paths[8]).unwrap();
196추가: let result = list(&s);
197추가: failure(&result, ErrorCode::MissingVolume);
198추가: problem(&result, VolumeProblemReason::MissingVolume, "sample.7z.009");
199추가: }
200추가:
201추가: #[test]
202추가: fn missing_tail_truncated_empty_and_extra_bytes_never_guess_a_missing_name() {
203추가: for mode in 0..4 {
204추가: let s = Scratch::new();
205추가: let (_, paths) = setup(&s, 3, "copy.7z");
206추가: match mode {
207추가: 0 => fs::remove_file(&paths[2]).unwrap(),
208추가: 1 => {
209추가: let mut bytes = fs::read(&paths[2]).unwrap();
210추가: bytes.pop();
211추가: fs::write(&paths[2], bytes).unwrap();
212추가: }
213추가: 2 => fs::write(&paths[1], []).unwrap(),
214추가: _ => {
215추가: let mut bytes = fs::read(&paths[2]).unwrap();
216추가: bytes.push(0);
217추가: fs::write(&paths[2], bytes).unwrap();
218추가: }
219추가: }
220추가: let result = list(&s);
221추가: failure(&result, ErrorCode::Integrity);
222추가: problem(&result, VolumeProblemReason::IncompleteSet, "sample.7z.001");
223추가: }
224추가: }
225추가:
226추가: #[test]
227추가: fn detectable_mixed_reordered_and_corrupt_payloads_never_publish() {
228추가: for mode in 0..3 {
229추가: let s = Scratch::new();
230추가: let (_, paths) = setup(&s, 11, "copy.7z");
231추가: if mode == 0 {
232추가: let a = fs::read(&paths[4]).unwrap();
233추가: let b = fs::read(&paths[5]).unwrap();
234추가: fs::write(&paths[4], b).unwrap();
235추가: fs::write(&paths[5], a).unwrap();
236추가: } else {
237추가: let mut bytes = fs::read(&paths[4]).unwrap();
238추가: if mode == 1 {
239추가: bytes.fill(0x5a);
240추가: } else {
241추가: bytes[0] ^= 1;
242추가: }
243추가: fs::write(&paths[4], bytes).unwrap();
244추가: }
245추가: directory(&s, "output");
246추가: let result = execute(request(&s, None, Selection::All));
247추가: failure(&result, ErrorCode::Integrity);
248추가: assert_eq!(fs::read_dir(s.0.join("output")).unwrap().count(), 0);
249추가: }
250추가: }
251추가:
252추가: #[test]
253추가: fn changing_middle_tail_length_object_or_count_after_listing_invalidates_the_token() {
254추가: for mode in 0..8 {
255추가: let s = Scratch::new();
256추가: let (_, paths) = setup(&s, 3, "copy.7z");
257추가: let token = id(&list(&s));
258추가: let selected = if mode == 0 { &paths[1] } else { &paths[2] };
259추가: match mode {
260추가: 0 | 1 => {
261추가: let mut data = fs::read(selected).unwrap();
262추가: data[0] ^= 1;
263추가: fs::write(selected, data).unwrap();
264추가: }
265추가: 2 => {
266추가: let data = fs::read(selected).unwrap();
267추가: fs::rename(selected, s.0.join("old-part")).unwrap();
268추가: fs::write(selected, data).unwrap();
269추가: }
270추가: 3 => {
271추가: let mut data = fs::read(selected).unwrap();
272추가: data.pop();
273추가: fs::write(selected, data).unwrap();
274추가: }
275추가: 4 => fs::remove_file(selected).unwrap(),
276추가: 5 => fs::write(s.0.join("sample.7z.004"), [0]).unwrap(),
277추가: 6 => fs::remove_file(&paths[1]).unwrap(),
278추가: _ => {
279추가: for path in &paths {
280추가: fs::remove_file(path).unwrap();
281추가: }
282추가: }
283추가: }
284추가: directory(&s, "output");
285추가: let result = execute(request(&s, Some(token), Selection::All));
286추가: failure(
287추가: &result,
288추가: if mode == 6 {
289추가: ErrorCode::MissingVolume
290추가: } else {
291추가: ErrorCode::SourceChanged
292추가: },
293추가: );
294추가: if mode == 6 {
295추가: problem(&result, VolumeProblemReason::MissingVolume, "sample.7z.002");
296추가: } else {
297추가: assert!(
298추가: !result
299추가: .iter()
300추가: .any(|event| matches!(event, Message::VolumeProblem { .. }))
301추가: );
302추가: }
303추가: assert_eq!(fs::read_dir(s.0.join("output")).unwrap().count(), 0);
304추가: }
305추가: }
306추가:
307추가: #[test]
308추가: fn replacement_or_gap_during_conflict_wait_is_rechecked_before_first_file_commit() {
309추가: for mode in 0..3 {
310추가: let s = Scratch::new();
311추가: let (_, paths) = setup(&s, 3, "copy.7z");
312추가: let token = id(&list(&s));
313추가: directory(&s, "output/folder");
314추가: fs::write(s.0.join("output/folder/hello.txt"), b"keep").unwrap();
315추가: let mut changed = false;
316추가: let result = guarded::run(
317추가: &s,
318추가: GuardedStart {
319추가: start: request(&s, Some(token), Selection::All),
320추가: ceiling: Limits::default(),
321추가: interactive: true,
322추가: },
323추가: |event| {
324추가: if let Message::ConflictRequired { challenge_id, .. } = event {
325추가: changed = true;
326추가: if mode == 2 {
327추가: fs::remove_file(&paths[1]).unwrap();
328추가: } else {
329추가: let target = &paths[if mode == 0 { 1 } else { 2 }];
330추가: let mut bytes = fs::read(target).unwrap();
331추가: bytes[0] ^= 1;
332추가: fs::write(target, bytes).unwrap();
333추가: }
334추가: return Some(vec![Message::ConflictReply {
335추가: challenge_id: *challenge_id,
336추가: choice: ConflictChoice::Overwrite,
337추가: apply_to_remaining: false,
338추가: }]);
339추가: }
340추가: None
341추가: },
342추가: );
343추가: assert!(changed, "{result:?}");
344추가: failure(
345추가: &result,
346추가: if mode == 2 {
347추가: ErrorCode::MissingVolume
348추가: } else {
349추가: ErrorCode::SourceChanged
350추가: },
351추가: );
352추가: assert_eq!(
353추가: fs::read(s.0.join("output/folder/hello.txt")).unwrap(),
354추가: b"keep"
355추가: );
356추가: assert_eq!(terminal(&result).cleanup, Cleanup::Complete);
357추가: assert_eq!(fs::read_dir(s.0.join("output/folder")).unwrap().count(), 1);
358추가: }
359추가: }
360추가:
361추가: #[test]
362추가: fn split_capture_uses_aggregate_input_budget_and_existing_output_permission() {
363추가: for allow in [false, true] {
364추가: let s = Scratch::new();
365추가: let (bytes, paths) = setup(&s, 11, "copy.7z");
366추가: let before = hashes(&paths);
367추가: directory(&s, "output");
368추가: let mut start = request(&s, None, Selection::All);
369추가: start.limits.input = bytes.len() as u64;
370추가: start.limits.output = 1;
371추가: let ceiling = Limits {
372추가: input: bytes.len() as u64,
373추가: output: 8192,
374추가: ..Limits::default()
375추가: };
376추가: let mut questions = 0;
377추가: let result = guarded::run(
378추가: &s,
379추가: GuardedStart {
380추가: start,
381추가: ceiling,
382추가: interactive: true,
383추가: },
384추가: |event| {
385추가: if let Message::ResourceRequired {
386추가: challenge_id,
387추가: scope,
388추가: ..
389추가: } = event
390추가: {
391추가: questions += 1;
392추가: return Some(vec![Message::ResourceReply {
393추가: challenge_id: *challenge_id,
394추가: scope: *scope,
395추가: allow,
396추가: }]);
397추가: }
398추가: None
399추가: },
400추가: );
401추가: assert_eq!(questions, 1);
402추가: assert_eq!(
403추가: terminal(&result).outcome,
404추가: if allow {
405추가: Outcome::Completed
406추가: } else {
407추가: Outcome::Cancelled
408추가: },
409추가: "{result:?}"
410추가: );
411추가: if allow {
412추가: assert_eq!(
413추가: fs::read(s.0.join("output/folder/hello.txt")).unwrap(),
414추가: SEVEN_PAYLOAD.repeat(100)
415추가: );
416추가: } else {
417추가: assert_eq!(terminal(&result).created_count, 0);
418추가: assert_eq!(fs::read_dir(s.0.join("output")).unwrap().count(), 0);
419추가: }
420추가: assert_eq!(hashes(&paths), before);
421추가: }
422추가: let s = Scratch::new();
423추가: let (bytes, _) = setup(&s, 11, "copy.7z");
424추가: directory(&s, "output");
425추가: let mut start = request(&s, None, Selection::All);
426추가: start.limits.input = bytes.len() as u64 - 1;
427추가: failure(&execute(start), ErrorCode::Limit);
428추가: }
429추가:
430추가: #[test]
431추가: fn cancellation_at_conflict_keeps_source_and_existing_output() {
432추가: let s = Scratch::new();
433추가: let (_, paths) = setup(&s, 3, "copy.7z");
434추가: let before = hashes(&paths);
435추가: directory(&s, "output/folder");
436추가: fs::write(s.0.join("output/folder/hello.txt"), b"keep").unwrap();
437추가: let result = guarded::run(
438추가: &s,
439추가: GuardedStart {
440추가: start: request(&s, None, Selection::All),
441추가: ceiling: Limits::default(),
442추가: interactive: true,
443추가: },
444추가: |event| matches!(event, Message::ConflictRequired { .. }).then(|| vec![Message::Cancel]),
445추가: );
446추가: assert_eq!(terminal(&result).outcome, Outcome::Cancelled);
447추가: assert_eq!(terminal(&result).created_count, 0);
448추가: assert_eq!(
449추가: fs::read(s.0.join("output/folder/hello.txt")).unwrap(),
450추가: b"keep"
451추가: );
452추가: assert_eq!(hashes(&paths), before);
453추가: }
454추가:
455추가: #[test]
456추가: fn split_preview_and_excluded_zip_volume_names_are_not_retried_as_single_inputs() {
457추가: let s = Scratch::new();
458추가: let (_, paths) = setup(&s, 3, "copy.7z");
459추가: let token = id(&list(&s));
460추가: let preview = Start {
461추가: action: Action::Preview {
462추가: archive: s.path("sample.7z.001"),
463추가: entry_id: 0,
464추가: list_id: token,
465추가: },
466추가: limits: Limits::default(),
467추가: };
468추가: let result = guarded::run(
469추가: &s,
470추가: GuardedStart {
471추가: start: preview,
472추가: ceiling: Limits::default(),
473추가: interactive: true,
474추가: },
475추가: |_| None,
476추가: );
477추가: failure(&result, ErrorCode::UnsupportedFeature);
478추가: assert!(
479추가: !result
480추가: .iter()
481추가: .any(|event| matches!(event, Message::PreviewBegin(_)))
482추가: );
483추가: for name in ["sample.zip.001", "sample.z01"] {
484추가: fs::write(s.0.join(name), include_bytes!("fixtures/store.zip")).unwrap();
485추가: let result = execute(Start {
486추가: action: Action::List {
487추가: archive: s.path(name),
488추가: },
489추가: limits: Limits::default(),
490추가: });
491추가: failure(&result, ErrorCode::UnsupportedFeature);
492추가: }
493추가: assert_eq!(paths.len(), 3);
494추가: }
495추가:
496추가: fn reference_fixture(s: &Scratch, name: &str) -> Vec<PathBuf> {
497추가: let root = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
498추가: .join("../../tests/rust-archive-worker/fixtures/split7z");
499추가: let mut paths = Vec::new();
500추가: for index in 1..=999 {
501추가: let source = root.join(format!("{name}.7z.{index:03}"));
502추가: match fs::read(source) {
503추가: Ok(data) => {
504추가: let destination = s.0.join(format!("sample.7z.{index:03}"));
505추가: fs::write(&destination, data).unwrap();
506추가: paths.push(destination);
507추가: }
508추가: Err(error) if error.kind() == std::io::ErrorKind::NotFound => break,
509추가: Err(error) => panic!("{error:?}"),
510추가: }
511추가: }
512추가: assert!(paths.len() > 1);
513추가: paths
514추가: }
515추가:
516추가: #[test]
517추가: fn seven_zip_created_volumes_list_and_extract_with_matching_reference_hashes() {
518추가: let s = Scratch::new();
519추가: let paths = reference_fixture(&s, "reference");
520추가: let before = hashes(&paths);
521추가: let token = id(&list(&s));
522추가: directory(&s, "output");
523추가: let result = execute(request(&s, Some(token), Selection::All));
524추가: assert_eq!(terminal(&result).outcome, Outcome::Completed, "{result:?}");
525추가: let expected = SEVEN_PAYLOAD.repeat(100);
526추가: let actual = fs::read(s.0.join("output/folder/hello.txt")).unwrap();
527추가: assert_eq!(Sha256::digest(&actual), Sha256::digest(&expected));
528추가: assert_eq!(actual, expected);
529추가: let expected = (0..4096usize)
530추가: .map(|index| ((index * 37 + (index >> 3)) % 256) as u8)
531추가: .collect::<Vec<_>>();
532추가: let actual = fs::read(s.0.join("output/second.bin")).unwrap();
533추가: assert_eq!(Sha256::digest(&actual), Sha256::digest(&expected));
534추가: assert_eq!(actual, expected);
535추가: assert_eq!(hashes(&paths), before);
536추가: }
537추가:
538추가: #[test]
539추가: fn encrypted_seven_zip_volumes_keep_the_existing_unsupported_policy() {
540추가: for name in ["encrypted-header", "encrypted-body"] {
541추가: let s = Scratch::new();
542추가: let paths = reference_fixture(&s, name);
543추가: let before = hashes(&paths);
544추가: directory(&s, "output");
545추가: let result = execute(request(&s, None, Selection::All));
546추가: failure(&result, ErrorCode::UnsupportedFeature);
547추가: assert!(
548추가: !result
549추가: .iter()
550추가: .any(|event| matches!(event, Message::PasswordRequired { .. }))
551추가: );
552추가: assert_eq!(fs::read_dir(s.0.join("output")).unwrap().count(), 0);
553추가: assert_eq!(hashes(&paths), before);
554추가: }
555추가: }