team-ljyzipelo

공개

Merge pull request #69 from Team-LJY/features/7z-extract

7z 목록과 LZMA 및 LZMA2 해제 추가
작성자
LeeJunyoung
작성 시각
커밋
e497fac4309018a2824b2f296a366a648f4429bf
이 시점의 파일 보기

변경된 파일 43개

+1,968-26
수정experiments/rust-archive-worker/README.md+12-1
@@ -2,7 +2,7 @@
22
33별도 프로세스의 stdin/stdout으로 revision 2 요청을 처리합니다. 제품 앱 연결과 OS sandbox를 제공하는 단계는 아닙니다. 암호 기능은 capability=true이며 ZipCrypto 해제, WinZip AES-256 AE-1/AE-2 해제와 AE-2 생성을 지원합니다.
44
5삭제: - ZIP32 Store/Deflate 목록, 해제, 생성, 기본 TAR/USTAR, GZ, TAR.GZ 해제를 지원합니다. GZ 연결 멤버는 하나의 논리 스트림으로 합칩니다. ZIP64, 다중 볼륨, 비 UTF-8 ZIP 이름, PAX/GNU 확장과 특수 항목 해제는 미지원입니다.
5추가: - ZIP32 Store/Deflate 목록, 해제, 생성, 기본 TAR/USTAR, GZ, TAR.GZ, 비암호화 7z 해제를 지원합니다. GZ 연결 멤버는 하나의 논리 스트림으로 합칩니다. ZIP64, 다중 볼륨, 비 UTF-8 ZIP 이름, PAX/GNU 확장과 특수 항목 해제는 미지원입니다.
66- 입력은 최대 64 MiB, 해독/생성 출력은 최대 128 MiB, 항목은 최대 10,000개입니다. 요청 limits는 이 값을 낮출 수 있습니다. 입력과 검증 완료 payload를 메모리에 보관해 모든 선택 출력의 CRC, 크기와 경로를 쓰기 전에 검사합니다. checkpoint마다 취소와 300초 한도를 확인합니다.
77- 경로 깊이는 64개 구성 요소, 이름/출력 계획 메타데이터 예산은 8 MiB, 출력 계획 노드는 32,768개로 제한합니다. 이름 복제와 인덱스 비용을 보수적으로 계산해 할당 전에 Limit으로 거부합니다.
88- GZip 내부 형식은 완전한 USTAR magic이 있을 때만 TAR로 판별합니다. magic이 없는 영값 데이터는 길이와 무관하게 raw GZip으로 유지하며 명시 출력명이 필요합니다.
@@ -11,6 +11,17 @@
1111- 파일 sync/close는 게시 전에 확인합니다. 게시 후 부모 sync와 임시 파일 정리 실패는 게시 사실과 따로 보고합니다. Windows의 디렉터리 내구성은 Unconfirmed입니다. hard link의 결과가 불명확하면 CommitUncertain/Uncertain이며 자동 재시도나 rollback은 없습니다.
1212- 생성한 디렉터리와 게시한 파일은 취소 시 유지하고 Output으로 보고합니다. 실패한 임시 파일 정리는 실제 임시 이름과 PartialRetained로 보고합니다. 실파일 close/sync/link 장애 주입과 Windows 실기 검증은 아직 수행하지 않았습니다.
1313
14추가: ## 7z 해제
15추가:
16추가: 비암호화 7z의 단일 입력/출력 coder인 Copy, LZMA와 LZMA2를 Rust 코드로 해독합니다. solid substream, 빈 파일/디렉터리, UTF-16LE 이름과 한 단계 압축 헤더를 처리합니다. 추가 라이브러리나 제품 외부 명령을 사용하지 않습니다. 형식 근거는 [7z 명세](https://www.7-zip.org/7z.html)와 [LZMA SDK 명세 안내](https://www.7-zip.org/sdk.html)입니다.
17추가:
18추가: - 시작 헤더/다음 헤더 CRC, packed/folder/substream CRC가 있을 때 해당 CRC와 크기, 스트림의 끝을 검증합니다. 경로, 충돌과 모든 선택 내용 검증이 끝난 뒤 기존 안전 게시 경로로 넘깁니다. 목록은 데이터 CRC 검증 성공을 뜻하지 않습니다.
19추가: - 입력/출력/항목/이름의 기존 한도를 적용합니다. 압축 해제된 헤더도 최대 8 MiB이고 헤더 중첩은 한 단계입니다. 사전은 최대 64 MiB, LZMA의 lc+lp는 최대 4입니다. 해독 중 checkpoint에서 취소와 시간 한도를 확인합니다.
20추가: - 암호화 7z, 다중 coder 필터 체인(BCJ/BCJ2/Delta 등), PPMd/BZip2, 분할/SFX, external metadata, additional streams와 anti 항목은 미지원입니다. 링크, reparse point와 특수 Unix 항목은 거부합니다. 지원하지 않는 구조를 성공으로 처리하지 않습니다.
21추가: - solid 그룹의 압축 크기는 첫 substream에만 기록하고 나머지는 0으로 표시합니다. 각 파일의 정확한 비압축 크기는 유지합니다.
22추가: - 합성 표본은 Python 표준 lzma로 생성합니다. 별도로 시스템 libarchive가 만든 LZMA1/LZMA2 표본을 해제하고, 합성 표본도 libarchive 읽기 API로 검사합니다. libarchive는 Linux 시험의 독립 참조 도구이며 제품 의존성이 아닙니다. 시험 도구와 표본은 tests/rust-archive-worker 아래에 있습니다.
23추가: - 히나타 님과 합의한 확장은 Format::SevenZip=4뿐입니다. 기존 값 0~3과 필드, 메시지 tag, 프레임 version은 유지합니다. 구버전 앱은 값 4를 거부하므로 앱 Format과 양방향 변환도 갱신해야 합니다. 이 백엔드 변경은 frontend 코드를 수정하지 않습니다.
24추가:
1425## 암호 ZIP
1526
1627- AES는 [WinZip AE-1/AE-2 명세](https://www.winzip.com/en/support/aes-encryption/)의 method 99, 0x9901 추가 필드, PBKDF2-HMAC-SHA1 1000회, 16바이트 salt, AES-256 CTR와 HMAC-SHA1-80 형식을 사용합니다. 새 파일은 CRC를 노출하지 않는 AE-2입니다. AE-1은 인증과 CRC를 모두 검증합니다. AES-128/192와 PKWARE Strong Encryption은 미지원입니다.
수정experiments/rust-archive-worker/contract.json+13-1
@@ -136,5 +136,17 @@
136136 "url": "https://man7.org/linux/man-pages/man2/stat.2.html",
137137 "purpose": "Source metadata from the open file descriptor rather than a later path reopen."
138138 }
139삭제: ]
139추가: ],
140추가: "format_tags": {
141추가: "Zip": 0,
142추가: "Tar": 1,
143추가: "Gzip": 2,
144추가: "TarGzip": 3,
145추가: "SevenZip": 4
146추가: },
147추가: "seven_zip_extension": {
148추가: "agreement_message_id": "5a36fd89-af36-42be-9f79-bca39415e84d",
149추가: "compatibility": "Existing format values 0 through 3, fields, message tags and frame version stay unchanged. Older clients reject format 4. App Format and bidirectional conversion require an update.",
150추가: "regression": "Preserve existing format bytes and round-trip SevenZip in ListEnd/ListId."
151추가: }
140152}
수정experiments/rust-archive-worker/src/archive.rs+8-2
@@ -8,12 +8,12 @@ pub const MAX_METADATA_BYTES: usize = 8 * 1024 * 1024;
88pub const MAX_OUTPUT_NODES: usize = 32_768;
99
1010#[derive(Default)]
11삭제: struct MetadataBudget {
11추가: pub(crate) struct MetadataBudget {
1212 bytes: usize,
1313 nodes: usize,
1414}
1515impl MetadataBudget {
16삭제: fn charge(&mut self, name: &str) -> Result<()> {
16추가: pub(crate) fn charge(&mut self, name: &str) -> Result<()> {
1717 // 이름 복제와 인덱스 노드 비용을 할당 전에 계산함.
1818 let cost = name
1919 .len()
@@ -579,6 +579,12 @@ pub fn parse_with_password(
579579 if !limits.valid() || input.len() as u64 > limits.input {
580580 return Err(ErrorCode::Limit);
581581 }
582추가: if input.starts_with(b"7z\xbc\xaf\x27\x1c") {
583추가: return Ok(Catalog {
584추가: format: Format::SevenZip,
585추가: members: crate::seven_zip::parse(input, limits, decode, check)?,
586추가: });
587추가: }
582588 if input.starts_with(b"PK\x03\x04") || input.starts_with(b"PK\x05\x06") {
583589 return Ok(Catalog {
584590 format: Format::Zip,
수정experiments/rust-archive-worker/src/lib.rs+2-0
@@ -1,6 +1,8 @@
11pub mod archive;
22mod crypto;
33pub mod filesystem;
4추가: mod lzma;
45pub mod protocol;
56pub mod runtime;
7추가: mod seven_zip;
68pub mod wire;
추가experiments/rust-archive-worker/src/lzma.rs+408-0
@@ -0,0 +1,408 @@
1추가: use crate::protocol::ErrorCode;
2추가: type Result<T> = std::result::Result<T, ErrorCode>;
3추가: const MAX_DICT: usize = 64 * 1024 * 1024;
4추가: struct Range<'a> {
5추가: input: &'a [u8],
6추가: at: usize,
7추가: range: u32,
8추가: code: u32,
9추가: }
10추가: impl<'a> Range<'a> {
11추가: fn new(input: &'a [u8]) -> Result<Self> {
12추가: if input.len() < 5 || input[0] != 0 {
13추가: return Err(ErrorCode::Integrity);
14추가: }
15추가: Ok(Self {
16추가: input,
17추가: at: 5,
18추가: range: u32::MAX,
19추가: code: u32::from_be_bytes(input[1..5].try_into().unwrap()),
20추가: })
21추가: }
22추가: fn normalize(&mut self) -> Result<()> {
23추가: if self.range < 1 << 24 {
24추가: self.range <<= 8;
25추가: self.code =
26추가: (self.code << 8) | *self.input.get(self.at).ok_or(ErrorCode::Integrity)? as u32;
27추가: self.at += 1;
28추가: }
29추가: Ok(())
30추가: }
31추가: fn bit(&mut self, probability: &mut u16) -> Result<usize> {
32추가: let bound = (self.range >> 11) * *probability as u32;
33추가: let bit = if self.code < bound {
34추가: self.range = bound;
35추가: *probability += (2048 - *probability) >> 5;
36추가: 0
37추가: } else {
38추가: self.range -= bound;
39추가: self.code -= bound;
40추가: *probability -= *probability >> 5;
41추가: 1
42추가: };
43추가: self.normalize()?;
44추가: Ok(bit)
45추가: }
46추가: fn direct(&mut self, count: usize) -> Result<u32> {
47추가: let mut value = 0;
48추가: for _ in 0..count {
49추가: self.range >>= 1;
50추가: let bit = u32::from(self.code >= self.range);
51추가: if bit != 0 {
52추가: self.code -= self.range;
53추가: }
54추가: value = (value << 1) | bit;
55추가: self.normalize()?;
56추가: }
57추가: Ok(value)
58추가: }
59추가: fn tree(&mut self, p: &mut [u16], bits: usize) -> Result<usize> {
60추가: let mut symbol = 1;
61추가: for _ in 0..bits {
62추가: symbol = (symbol << 1) | self.bit(&mut p[symbol])?;
63추가: }
64추가: Ok(symbol - (1 << bits))
65추가: }
66추가: fn reverse(&mut self, p: &mut [u16], base: isize, bits: usize) -> Result<u32> {
67추가: let mut symbol = 1;
68추가: let mut value = 0;
69추가: for i in 0..bits {
70추가: let index =
71추가: usize::try_from(base + symbol as isize).map_err(|_| ErrorCode::Integrity)?;
72추가: let bit = self.bit(p.get_mut(index).ok_or(ErrorCode::Integrity)?)?;
73추가: symbol = (symbol << 1) | bit;
74추가: value |= (bit as u32) << i;
75추가: }
76추가: Ok(value)
77추가: }
78추가: fn finished(&self) -> bool {
79추가: self.code == 0 && self.at == self.input.len()
80추가: }
81추가: }
82추가: struct Length {
83추가: choice: [u16; 2],
84추가: low: [[u16; 8]; 16],
85추가: middle: [[u16; 8]; 16],
86추가: high: [u16; 256],
87추가: }
88추가: impl Length {
89추가: fn new() -> Self {
90추가: Self {
91추가: choice: [1024; 2],
92추가: low: [[1024; 8]; 16],
93추가: middle: [[1024; 8]; 16],
94추가: high: [1024; 256],
95추가: }
96추가: }
97추가: fn read(&mut self, r: &mut Range<'_>, position: usize) -> Result<usize> {
98추가: if r.bit(&mut self.choice[0])? == 0 {
99추가: r.tree(&mut self.low[position], 3)
100추가: } else if r.bit(&mut self.choice[1])? == 0 {
101추가: Ok(8 + r.tree(&mut self.middle[position], 3)?)
102추가: } else {
103추가: Ok(16 + r.tree(&mut self.high, 8)?)
104추가: }
105추가: }
106추가: }
107추가: struct Model {
108추가: lc: usize,
109추가: lp: usize,
110추가: pb: usize,
111추가: state: usize,
112추가: reps: [u32; 4],
113추가: literal: Vec<u16>,
114추가: matches: [[u16; 16]; 12],
115추가: rep: [u16; 12],
116추가: g0: [u16; 12],
117추가: g1: [u16; 12],
118추가: g2: [u16; 12],
119추가: short: [[u16; 16]; 12],
120추가: slots: [[u16; 64]; 4],
121추가: special: [u16; 114],
122추가: align: [u16; 16],
123추가: length: Length,
124추가: rep_length: Length,
125추가: }
126추가: impl Model {
127추가: fn new(property: u8) -> Result<Self> {
128추가: if property >= 225 {
129추가: return Err(ErrorCode::Integrity);
130추가: }
131추가: let lc = property as usize % 9;
132추가: let lp = (property as usize / 9) % 5;
133추가: let pb = property as usize / 45;
134추가: if lc + lp > 4 {
135추가: return Err(ErrorCode::UnsupportedFeature);
136추가: }
137추가: Ok(Self {
138추가: lc,
139추가: lp,
140추가: pb,
141추가: state: 0,
142추가: reps: [0; 4],
143추가: literal: vec![1024; 0x300 << (lc + lp)],
144추가: matches: [[1024; 16]; 12],
145추가: rep: [1024; 12],
146추가: g0: [1024; 12],
147추가: g1: [1024; 12],
148추가: g2: [1024; 12],
149추가: short: [[1024; 16]; 12],
150추가: slots: [[1024; 64]; 4],
151추가: special: [1024; 114],
152추가: align: [1024; 16],
153추가: length: Length::new(),
154추가: rep_length: Length::new(),
155추가: })
156추가: }
157추가: fn reset(&mut self) -> Result<()> {
158추가: *self = Self::new(((self.pb * 5 + self.lp) * 9 + self.lc) as u8)?;
159추가: Ok(())
160추가: }
161추가: fn previous(out: &[u8], history: usize, distance: u32, dictionary: usize) -> Result<u8> {
162추가: let distance = distance as usize + 1;
163추가: if distance > dictionary || distance > out.len() - history {
164추가: return Err(ErrorCode::Integrity);
165추가: }
166추가: Ok(out[out.len() - distance])
167추가: }
168추가: fn symbol(
169추가: &mut self,
170추가: r: &mut Range<'_>,
171추가: out: &mut Vec<u8>,
172추가: history: usize,
173추가: dictionary: usize,
174추가: target: usize,
175추가: ) -> Result<bool> {
176추가: let pos = out.len() - history;
177추가: let position = pos & ((1 << self.pb) - 1);
178추가: let state = self.state;
179추가: if r.bit(&mut self.matches[state][position])? == 0 {
180추가: if out.len() >= target {
181추가: return Err(ErrorCode::Integrity);
182추가: }
183추가: let previous = if pos == 0 { 0 } else { *out.last().unwrap() };
184추가: let context =
185추가: ((pos & ((1 << self.lp) - 1)) << self.lc) + (previous as usize >> (8 - self.lc));
186추가: let p = &mut self.literal[context * 0x300..(context + 1) * 0x300];
187추가: let mut symbol = 1;
188추가: if state >= 7 {
189추가: let mut matched = Self::previous(out, history, self.reps[0], dictionary)?;
190추가: while symbol < 256 {
191추가: let m = (matched >> 7) as usize;
192추가: matched <<= 1;
193추가: let bit = r.bit(&mut p[((1 + m) << 8) + symbol])?;
194추가: symbol = (symbol << 1) | bit;
195추가: if bit != m {
196추가: break;
197추가: }
198추가: }
199추가: }
200추가: while symbol < 256 {
201추가: symbol = (symbol << 1) | r.bit(&mut p[symbol])?;
202추가: }
203추가: out.push(symbol as u8);
204추가: self.state = if state < 4 {
205추가: 0
206추가: } else if state < 10 {
207추가: state - 3
208추가: } else {
209추가: state - 6
210추가: };
211추가: return Ok(false);
212추가: }
213추가: let length;
214추가: if r.bit(&mut self.rep[state])? != 0 {
215추가: if r.bit(&mut self.g0[state])? == 0 {
216추가: if r.bit(&mut self.short[state][position])? == 0 {
217추가: self.state = if state < 7 { 9 } else { 11 };
218추가: if out.len() >= target {
219추가: return Err(ErrorCode::Integrity);
220추가: }
221추가: out.push(Self::previous(out, history, self.reps[0], dictionary)?);
222추가: return Ok(false);
223추가: }
224추가: } else {
225추가: let index = if r.bit(&mut self.g1[state])? == 0 {
226추가: 1
227추가: } else if r.bit(&mut self.g2[state])? == 0 {
228추가: 2
229추가: } else {
230추가: 3
231추가: };
232추가: let distance = self.reps[index];
233추가: for i in (1..=index).rev() {
234추가: self.reps[i] = self.reps[i - 1];
235추가: }
236추가: self.reps[0] = distance;
237추가: }
238추가: length = self.rep_length.read(r, position)? + 2;
239추가: self.state = if state < 7 { 8 } else { 11 };
240추가: } else {
241추가: length = self.length.read(r, position)? + 2;
242추가: self.state = if state < 7 { 7 } else { 10 };
243추가: let slot = r.tree(&mut self.slots[(length - 2).min(3)], 6)?;
244추가: let distance = if slot < 4 {
245추가: slot as u32
246추가: } else {
247추가: let bits = (slot >> 1) - 1;
248추가: let base = ((2 | (slot & 1)) as u32) << bits;
249추가: if slot < 14 {
250추가: base + r.reverse(&mut self.special, base as isize - slot as isize - 1, bits)?
251추가: } else {
252추가: base + (r.direct(bits - 4)? << 4) + r.reverse(&mut self.align, 0, 4)?
253추가: }
254추가: };
255추가: if distance == u32::MAX {
256추가: if length != 2 {
257추가: return Err(ErrorCode::Integrity);
258추가: }
259추가: return Ok(true);
260추가: }
261추가: self.reps.rotate_right(1);
262추가: self.reps[0] = distance;
263추가: }
264추가: if out.len().checked_add(length).is_none_or(|n| n > target) {
265추가: return Err(ErrorCode::Integrity);
266추가: }
267추가: for _ in 0..length {
268추가: out.push(Self::previous(out, history, self.reps[0], dictionary)?);
269추가: }
270추가: Ok(false)
271추가: }
272추가: fn decode(
273추가: &mut self,
274추가: input: &[u8],
275추가: out: &mut Vec<u8>,
276추가: history: usize,
277추가: dictionary: usize,
278추가: target: usize,
279추가: eos: bool,
280추가: check: &mut impl FnMut() -> Result<()>,
281추가: ) -> Result<()> {
282추가: let mut range = Range::new(input)?;
283추가: let mut next_check = out.len();
284추가: while out.len() < target {
285추가: if out.len() >= next_check {
286추가: check()?;
287추가: next_check = out.len() + 65536;
288추가: }
289추가: if self.symbol(&mut range, out, history, dictionary, target)? {
290추가: return Err(ErrorCode::Integrity);
291추가: }
292추가: }
293추가: if !range.finished() {
294추가: if !eos
295추가: || !self.symbol(&mut range, out, history, dictionary, target)?
296추가: || !range.finished()
297추가: {
298추가: return Err(ErrorCode::Integrity);
299추가: }
300추가: }
301추가: Ok(())
302추가: }
303추가: }
304추가: fn dictionary(size: u64) -> Result<usize> {
305추가: if size > MAX_DICT as u64 {
306추가: return Err(ErrorCode::Limit);
307추가: }
308추가: Ok((size as usize).max(4096))
309추가: }
310추가: pub(crate) fn decode(
311추가: input: &[u8],
312추가: properties: &[u8],
313추가: lzma2: bool,
314추가: size: usize,
315추가: check: &mut impl FnMut() -> Result<()>,
316추가: ) -> Result<Vec<u8>> {
317추가: let mut out = Vec::new();
318추가: out.try_reserve_exact(size).map_err(|_| ErrorCode::Limit)?;
319추가: if !lzma2 {
320추가: if properties.len() != 5 {
321추가: return Err(ErrorCode::Integrity);
322추가: }
323추가: let dictionary =
324추가: dictionary(u32::from_le_bytes(properties[1..5].try_into().unwrap()) as u64)?;
325추가: Model::new(properties[0])?.decode(input, &mut out, 0, dictionary, size, true, check)?;
326추가: return Ok(out);
327추가: }
328추가: if properties.len() != 1 || properties[0] > 40 {
329추가: return Err(ErrorCode::Integrity);
330추가: }
331추가: let prop = properties[0] as u32;
332추가: let dictionary = dictionary(if prop == 40 {
333추가: u32::MAX as u64
334추가: } else {
335추가: ((2 | (prop & 1)) as u64) << (prop / 2 + 11)
336추가: })?;
337추가: let mut at = 0;
338추가: let mut history = 0;
339추가: let mut have_dictionary = false;
340추가: let mut need_state = true;
341추가: let mut model: Option<Model> = None;
342추가: loop {
343추가: check()?;
344추가: let control = *input.get(at).ok_or(ErrorCode::Integrity)?;
345추가: at += 1;
346추가: if control == 0 {
347추가: if at != input.len() || out.len() != size {
348추가: return Err(ErrorCode::Integrity);
349추가: }
350추가: return Ok(out);
351추가: }
352추가: let take16 = |at: &mut usize| -> Result<usize> {
353추가: let bytes = input.get(*at..*at + 2).ok_or(ErrorCode::Integrity)?;
354추가: *at += 2;
355추가: Ok(u16::from_be_bytes(bytes.try_into().unwrap()) as usize + 1)
356추가: };
357추가: if control == 1 || control >= 0xe0 {
358추가: history = out.len();
359추가: have_dictionary = true;
360추가: model = None;
361추가: }
362추가: if !have_dictionary {
363추가: return Err(ErrorCode::Integrity);
364추가: }
365추가: let unpacked = take16(&mut at)?;
366추가: if control <= 2 {
367추가: let end = at.checked_add(unpacked).ok_or(ErrorCode::Integrity)?;
368추가: if out.len().checked_add(unpacked).is_none_or(|n| n > size) {
369추가: return Err(ErrorCode::Integrity);
370추가: }
371추가: out.extend_from_slice(input.get(at..end).ok_or(ErrorCode::Integrity)?);
372추가: at = end;
373추가: need_state = true;
374추가: } else if control >= 0x80 {
375추가: let unpacked = unpacked + ((control as usize & 31) << 16);
376추가: let packed = take16(&mut at)?;
377추가: if control >= 0xc0 {
378추가: model = Some(Model::new(*input.get(at).ok_or(ErrorCode::Integrity)?)?);
379추가: at += 1;
380추가: }
381추가: let model = model.as_mut().ok_or(ErrorCode::Integrity)?;
382추가: if control >= 0xa0 {
383추가: model.reset()?;
384추가: } else if need_state {
385추가: return Err(ErrorCode::Integrity);
386추가: }
387추가: let end = at.checked_add(packed).ok_or(ErrorCode::Integrity)?;
388추가: let target = out
389추가: .len()
390추가: .checked_add(unpacked)
391추가: .filter(|n| *n <= size)
392추가: .ok_or(ErrorCode::Integrity)?;
393추가: model.decode(
394추가: input.get(at..end).ok_or(ErrorCode::Integrity)?,
395추가: &mut out,
396추가: history,
397추가: dictionary,
398추가: target,
399추가: false,
400추가: check,
401추가: )?;
402추가: at = end;
403추가: need_state = false;
404추가: } else {
405추가: return Err(ErrorCode::Integrity);
406추가: }
407추가: }
408추가: }
수정experiments/rust-archive-worker/src/protocol.rs+1-0
@@ -80,6 +80,7 @@ pub enum Format {
8080 Tar,
8181 Gzip,
8282 TarGzip,
83추가: SevenZip,
8384}
8485#[derive(Clone, Debug, PartialEq, Eq)]
8586pub enum SourceObject {
추가experiments/rust-archive-worker/src/seven_zip.rs+587-0
@@ -0,0 +1,587 @@
1추가: use crate::{
2추가: archive::{MAX_METADATA_BYTES, Member, MetadataBudget, valid_name, validate_members},
3추가: protocol::*,
4추가: };
5추가: use std::collections::BTreeSet;
6추가: use zlib_rs::crc32::crc32;
7추가: type Result<T> = std::result::Result<T, ErrorCode>;
8추가: struct Reader<'a> {
9추가: bytes: &'a [u8],
10추가: at: usize,
11추가: }
12추가: impl<'a> Reader<'a> {
13추가: fn new(bytes: &'a [u8]) -> Self {
14추가: Self { bytes, at: 0 }
15추가: }
16추가: fn take(&mut self, n: usize) -> Result<&'a [u8]> {
17추가: let end = self.at.checked_add(n).ok_or(ErrorCode::Integrity)?;
18추가: let bytes = self.bytes.get(self.at..end).ok_or(ErrorCode::Integrity)?;
19추가: self.at = end;
20추가: Ok(bytes)
21추가: }
22추가: fn byte(&mut self) -> Result<u8> {
23추가: Ok(self.take(1)?[0])
24추가: }
25추가: fn expect(&mut self, id: u8) -> Result<()> {
26추가: if self.byte()? == id {
27추가: Ok(())
28추가: } else {
29추가: Err(ErrorCode::Integrity)
30추가: }
31추가: }
32추가: fn integer(&mut self) -> Result<u64> {
33추가: let first = self.byte()?;
34추가: let mut mask = 0x80;
35추가: let mut value = 0;
36추가: for i in 0..8 {
37추가: if first & mask == 0 {
38추가: return Ok(value | (((first & (mask - 1)) as u64) << (8 * i)));
39추가: }
40추가: value |= (self.byte()? as u64) << (8 * i);
41추가: mask >>= 1;
42추가: }
43추가: Ok(value)
44추가: }
45추가: fn number(&mut self, limit: usize) -> Result<usize> {
46추가: usize::try_from(self.integer()?)
47추가: .ok()
48추가: .filter(|n| *n <= limit)
49추가: .ok_or(ErrorCode::Limit)
50추가: }
51추가: fn bits(&mut self, count: usize) -> Result<Vec<bool>> {
52추가: let bytes = self.take(count.div_ceil(8))?;
53추가: Ok((0..count)
54추가: .map(|i| bytes[i / 8] & (0x80 >> (i % 8)) != 0)
55추가: .collect())
56추가: }
57추가: fn defined(&mut self, count: usize) -> Result<Vec<bool>> {
58추가: match self.byte()? {
59추가: 0 => self.bits(count),
60추가: 1 => Ok(vec![true; count]),
61추가: _ => Err(ErrorCode::Integrity),
62추가: }
63추가: }
64추가: fn digests(&mut self, count: usize) -> Result<Vec<Option<u32>>> {
65추가: self.defined(count)?
66추가: .into_iter()
67추가: .map(|set| {
68추가: if set {
69추가: Ok(Some(u32::from_le_bytes(self.take(4)?.try_into().unwrap())))
70추가: } else {
71추가: Ok(None)
72추가: }
73추가: })
74추가: .collect()
75추가: }
76추가: fn end(&self) -> Result<()> {
77추가: if self.at == self.bytes.len() {
78추가: Ok(())
79추가: } else {
80추가: Err(ErrorCode::Integrity)
81추가: }
82추가: }
83추가: }
84추가: struct Folder {
85추가: method: Vec<u8>,
86추가: properties: Vec<u8>,
87추가: size: usize,
88추가: crc: Option<u32>,
89추가: sizes: Vec<usize>,
90추가: crcs: Vec<Option<u32>>,
91추가: }
92추가: struct Streams {
93추가: position: usize,
94추가: packed: Vec<usize>,
95추가: packed_crcs: Vec<Option<u32>>,
96추가: folders: Vec<Folder>,
97추가: }
98추가: impl Streams {
99추가: fn read(r: &mut Reader<'_>, limits: Limits) -> Result<Self> {
100추가: r.expect(6)?;
101추가: let position = r.number(limits.input as usize)?;
102추가: let count = r.number(limits.entries as usize)?;
103추가: r.expect(9)?;
104추가: let packed = (0..count)
105추가: .map(|_| r.number(limits.input as usize))
106추가: .collect::<Result<Vec<_>>>()?;
107추가: let mut tag = r.byte()?;
108추가: let packed_crcs = if tag == 10 {
109추가: tag = 255;
110추가: r.digests(count)?
111추가: } else {
112추가: vec![None; count]
113추가: };
114추가: if tag == 255 {
115추가: tag = r.byte()?;
116추가: }
117추가: if tag != 0 {
118추가: return Err(ErrorCode::Integrity);
119추가: }
120추가: r.expect(7)?;
121추가: r.expect(11)?;
122추가: let num = r.number(limits.entries as usize)?;
123추가: if num != count {
124추가: return Err(ErrorCode::UnsupportedFeature);
125추가: }
126추가: if r.byte()? != 0 {
127추가: return Err(ErrorCode::UnsupportedFeature);
128추가: }
129추가: let mut folders = Vec::new();
130추가: for _ in 0..num {
131추가: if r.integer()? != 1 {
132추가: return Err(ErrorCode::UnsupportedFeature);
133추가: }
134추가: let flags = r.byte()?;
135추가: let len = (flags & 15) as usize;
136추가: if flags & 0xc0 != 0 || len == 0 {
137추가: return Err(ErrorCode::UnsupportedFeature);
138추가: }
139추가: let method = r.take(len)?.to_vec();
140추가: if flags & 0x10 != 0 && (r.integer()? != 1 || r.integer()? != 1) {
141추가: return Err(ErrorCode::UnsupportedFeature);
142추가: }
143추가: let properties = if flags & 0x20 != 0 {
144추가: let n = r.number(64)?;
145추가: r.take(n)?.to_vec()
146추가: } else {
147추가: Vec::new()
148추가: };
149추가: if !matches!(method.as_slice(), [0] | [3, 1, 1] | [0x21]) {
150추가: return Err(ErrorCode::UnsupportedFeature);
151추가: }
152추가: folders.push(Folder {
153추가: method,
154추가: properties,
155추가: size: 0,
156추가: crc: None,
157추가: sizes: Vec::new(),
158추가: crcs: Vec::new(),
159추가: });
160추가: }
161추가: r.expect(12)?;
162추가: let mut total = 0usize;
163추가: for folder in &mut folders {
164추가: folder.size = r.number(limits.output as usize)?;
165추가: total = total
166추가: .checked_add(folder.size)
167추가: .filter(|n| *n <= limits.output as usize)
168추가: .ok_or(ErrorCode::Limit)?;
169추가: }
170추가: let mut tag = r.byte()?;
171추가: if tag == 10 {
172추가: for (f, crc) in folders.iter_mut().zip(r.digests(num)?) {
173추가: f.crc = crc;
174추가: }
175추가: tag = r.byte()?;
176추가: }
177추가: if tag != 0 {
178추가: return Err(ErrorCode::Integrity);
179추가: }
180추가: let mut counts = vec![1usize; num];
181추가: let mut supplied_sizes = false;
182추가: let mut tag = r.byte()?;
183추가: if tag == 8 {
184추가: tag = r.byte()?;
185추가: if tag == 13 {
186추가: let mut total = 0usize;
187추가: for n in &mut counts {
188추가: *n = r.number(limits.entries as usize)?;
189추가: total = total
190추가: .checked_add(*n)
191추가: .filter(|n| *n <= limits.entries as usize)
192추가: .ok_or(ErrorCode::Limit)?;
193추가: }
194추가: tag = r.byte()?;
195추가: }
196추가: if tag == 9 {
197추가: supplied_sizes = true;
198추가: for (folder, count) in folders.iter_mut().zip(&counts) {
199추가: let mut total = 0usize;
200추가: for _ in 1..*count {
201추가: let n = r.number(folder.size)?;
202추가: total = total
203추가: .checked_add(n)
204추가: .filter(|n| *n <= folder.size)
205추가: .ok_or(ErrorCode::Integrity)?;
206추가: folder.sizes.push(n);
207추가: }
208추가: if *count > 0 {
209추가: folder.sizes.push(folder.size - total);
210추가: }
211추가: }
212추가: tag = r.byte()?;
213추가: }
214추가: let digest_count = folders
215추가: .iter()
216추가: .zip(&counts)
217추가: .map(|(f, n)| if *n == 1 && f.crc.is_some() { 0 } else { *n })
218추가: .sum();
219추가: let mut digests = if tag == 10 {
220추가: let d = r.digests(digest_count)?;
221추가: tag = r.byte()?;
222추가: d.into_iter()
223추가: } else {
224추가: vec![None; digest_count].into_iter()
225추가: };
226추가: for (f, n) in folders.iter_mut().zip(&counts) {
227추가: f.crcs = if *n == 1 && f.crc.is_some() {
228추가: vec![f.crc]
229추가: } else {
230추가: (0..*n).map(|_| digests.next().unwrap()).collect()
231추가: };
232추가: }
233추가: if tag != 0 {
234추가: return Err(ErrorCode::Integrity);
235추가: }
236추가: tag = r.byte()?;
237추가: } else {
238추가: for f in &mut folders {
239추가: f.crcs.push(f.crc);
240추가: }
241추가: }
242추가: if tag != 0 {
243추가: return Err(ErrorCode::Integrity);
244추가: }
245추가: for (f, n) in folders.iter_mut().zip(&counts) {
246추가: if !supplied_sizes {
247추가: if *n > 1 {
248추가: return Err(ErrorCode::Integrity);
249추가: }
250추가: if *n == 1 {
251추가: f.sizes.push(f.size);
252추가: }
253추가: }
254추가: if *n == 0 && f.size != 0 {
255추가: return Err(ErrorCode::Integrity);
256추가: }
257추가: }
258추가: Ok(Self {
259추가: position,
260추가: packed,
261추가: packed_crcs,
262추가: folders,
263추가: })
264추가: }
265추가: fn bounds<'a>(&self, input: &'a [u8], data_end: usize) -> Result<Vec<&'a [u8]>> {
266추가: let mut at = 32usize
267추가: .checked_add(self.position)
268추가: .ok_or(ErrorCode::Integrity)?;
269추가: let mut slices = Vec::new();
270추가: for (size, expected) in self.packed.iter().zip(&self.packed_crcs) {
271추가: let end = at
272추가: .checked_add(*size)
273추가: .filter(|end| *end <= data_end)
274추가: .ok_or(ErrorCode::Integrity)?;
275추가: let bytes = input.get(at..end).ok_or(ErrorCode::Integrity)?;
276추가: if expected.is_some_and(|crc| crc32(0, bytes) != crc) {
277추가: return Err(ErrorCode::Integrity);
278추가: }
279추가: slices.push(bytes);
280추가: at = end;
281추가: }
282추가: Ok(slices)
283추가: }
284추가: fn decode(
285추가: &self,
286추가: packed: &[&[u8]],
287추가: check: &mut impl FnMut() -> Result<()>,
288추가: ) -> Result<Vec<Vec<u8>>> {
289추가: self.folders
290추가: .iter()
291추가: .zip(packed)
292추가: .map(|(f, bytes)| {
293추가: check()?;
294추가: let out = match f.method.as_slice() {
295추가: [0] => {
296추가: if !f.properties.is_empty() || bytes.len() != f.size {
297추가: return Err(ErrorCode::Integrity);
298추가: }
299추가: bytes.to_vec()
300추가: }
301추가: [3, 1, 1] => crate::lzma::decode(bytes, &f.properties, false, f.size, check)?,
302추가: [0x21] => crate::lzma::decode(bytes, &f.properties, true, f.size, check)?,
303추가: _ => return Err(ErrorCode::UnsupportedFeature),
304추가: };
305추가: if f.crc.is_some_and(|crc| crc32(0, &out) != crc) {
306추가: return Err(ErrorCode::Integrity);
307추가: }
308추가: let mut at = 0;
309추가: for (size, crc) in f.sizes.iter().zip(&f.crcs) {
310추가: let end = at + *size;
311추가: if crc.is_some_and(|crc| crc32(0, &out[at..end]) != crc) {
312추가: return Err(ErrorCode::Integrity);
313추가: }
314추가: at = end;
315추가: }
316추가: Ok(out)
317추가: })
318추가: .collect()
319추가: }
320추가: }
321추가: fn files(
322추가: r: &mut Reader<'_>,
323추가: limits: Limits,
324추가: streams: Option<&Streams>,
325추가: ) -> Result<(Vec<Member>, Vec<usize>)> {
326추가: let count = r.number(limits.entries as usize)?;
327추가: let mut empty = vec![false; count];
328추가: let mut empty_file = Vec::new();
329추가: let mut names = None;
330추가: let mut attrs = vec![None; count];
331추가: let mut seen = BTreeSet::new();
332추가: loop {
333추가: let property = r.byte()?;
334추가: if property == 0 {
335추가: break;
336추가: }
337추가: if !seen.insert(property) {
338추가: return Err(ErrorCode::Integrity);
339추가: }
340추가: let len = r.number(MAX_METADATA_BYTES)?;
341추가: let mut value = Reader::new(r.take(len)?);
342추가: match property {
343추가: 14 => {
344추가: empty = value.bits(count)?;
345추가: }
346추가: 15 => {
347추가: empty_file = value.bits(empty.iter().filter(|e| **e).count())?;
348추가: }
349추가: 16 => {
350추가: if value
351추가: .bits(empty.iter().filter(|e| **e).count())?
352추가: .iter()
353추가: .any(|b| *b)
354추가: {
355추가: return Err(ErrorCode::UnsupportedFeature);
356추가: }
357추가: }
358추가: 17 => {
359추가: if value.byte()? != 0 {
360추가: return Err(ErrorCode::UnsupportedFeature);
361추가: }
362추가: let mut decoded = Vec::new();
363추가: let mut budget = MetadataBudget::default();
364추가: for _ in 0..count {
365추가: let mut units = Vec::new();
366추가: loop {
367추가: let n = u16::from_le_bytes(value.take(2)?.try_into().unwrap());
368추가: if n == 0 {
369추가: break;
370추가: }
371추가: if units.len() >= 4096 {
372추가: return Err(ErrorCode::Limit);
373추가: }
374추가: units.push(n);
375추가: }
376추가: let name = String::from_utf16(&units).map_err(|_| ErrorCode::Integrity)?;
377추가: budget.charge(&name)?;
378추가: decoded.push(name);
379추가: }
380추가: names = Some(decoded);
381추가: }
382추가: 21 => {
383추가: let defined = value.defined(count)?;
384추가: if value.byte()? != 0 {
385추가: return Err(ErrorCode::UnsupportedFeature);
386추가: }
387추가: for (attr, set) in attrs.iter_mut().zip(defined) {
388추가: if set {
389추가: *attr = Some(u32::from_le_bytes(value.take(4)?.try_into().unwrap()));
390추가: }
391추가: }
392추가: }
393추가: 18..=20 => {
394추가: let defined = value.defined(count)?;
395추가: if value.byte()? != 0 {
396추가: return Err(ErrorCode::UnsupportedFeature);
397추가: }
398추가: value.take(defined.iter().filter(|b| **b).count() * 8)?;
399추가: }
400추가: 25 => {
401추가: if value.take(len)?.iter().any(|b| *b != 0) {
402추가: return Err(ErrorCode::Integrity);
403추가: }
404추가: }
405추가: _ => return Err(ErrorCode::UnsupportedFeature),
406추가: }
407추가: value.end()?;
408추가: }
409추가: let names = names.unwrap_or_default();
410추가: if names.len() != count {
411추가: return Err(ErrorCode::Integrity);
412추가: }
413추가: if !empty_file.is_empty() && empty_file.len() != empty.iter().filter(|e| **e).count() {
414추가: return Err(ErrorCode::Integrity);
415추가: }
416추가: let mut descriptions = Vec::new();
417추가: if let Some(streams) = streams {
418추가: for (folder, compressed) in streams.folders.iter().zip(&streams.packed) {
419추가: for (i, size) in folder.sizes.iter().enumerate() {
420추가: descriptions.push((*size, if i == 0 { *compressed } else { 0 }));
421추가: }
422추가: }
423추가: }
424추가: let mut descriptions = descriptions.into_iter();
425추가: let mut empty_flags = empty_file.into_iter();
426추가: let mut members = Vec::new();
427추가: let mut stream_indices = Vec::new();
428추가: for (index, ((name, empty), attr)) in names.into_iter().zip(empty).zip(attrs).enumerate() {
429추가: let kind = if empty && !empty_flags.next().unwrap_or(false) {
430추가: EntryKind::Directory
431추가: } else {
432추가: EntryKind::File
433추가: };
434추가: if let Some(attr) = attr {
435추가: let mode = attr >> 16;
436추가: if attr & 0x400 != 0
437추가: || (attr & 0x8000 != 0 && !matches!(mode & 0xf000, 0 | 0x4000 | 0x8000))
438추가: {
439추가: return Err(ErrorCode::UnsafePath);
440추가: }
441추가: if (attr & 0x10 != 0 || attr & 0x8000 != 0 && mode & 0xf000 == 0x4000)
442추가: && kind != EntryKind::Directory
443추가: {
444추가: return Err(ErrorCode::Integrity);
445추가: }
446추가: }
447추가: let name = valid_name(&name, kind == EntryKind::Directory)?;
448추가: if !empty {
449추가: stream_indices.push(index);
450추가: }
451추가: let (size, compressed_size) = if empty {
452추가: (0, 0)
453추가: } else {
454추가: descriptions.next().ok_or(ErrorCode::Integrity)?
455추가: };
456추가: members.push(Member {
457추가: entry: Entry {
458추가: entry_id: index as u32,
459추가: name,
460추가: kind,
461추가: size: size as u64,
462추가: compressed_size: compressed_size as u64,
463추가: encrypted: false,
464추가: },
465추가: data: Vec::new(),
466추가: });
467추가: }
468추가: if descriptions.next().is_some() {
469추가: return Err(ErrorCode::Integrity);
470추가: }
471추가: validate_members(&members)?;
472추가: Ok((members, stream_indices))
473추가: }
474추가: pub(crate) fn parse(
475추가: input: &[u8],
476추가: limits: Limits,
477추가: decode: bool,
478추가: check: &mut impl FnMut() -> Result<()>,
479추가: ) -> Result<Vec<Member>> {
480추가: check()?;
481추가: let header = input.get(..32).ok_or(ErrorCode::Integrity)?;
482추가: if header[6] != 0 || header[7] > 4 {
483추가: return Err(ErrorCode::UnsupportedFeature);
484추가: }
485추가: if crc32(0, &header[12..32]) != u32::from_le_bytes(header[8..12].try_into().unwrap()) {
486추가: return Err(ErrorCode::Integrity);
487추가: }
488추가: let offset = u64::from_le_bytes(header[12..20].try_into().unwrap());
489추가: let len = u64::from_le_bytes(header[20..28].try_into().unwrap());
490추가: if len > MAX_METADATA_BYTES as u64 {
491추가: return Err(ErrorCode::Limit);
492추가: }
493추가: let start = usize::try_from(offset)
494추가: .ok()
495추가: .and_then(|n| n.checked_add(32))
496추가: .ok_or(ErrorCode::Integrity)?;
497추가: let end = start
498추가: .checked_add(len as usize)
499추가: .filter(|n| *n == input.len())
500추가: .ok_or(ErrorCode::Integrity)?;
501추가: let bytes = input.get(start..end).ok_or(ErrorCode::Integrity)?;
502추가: if crc32(0, bytes) != u32::from_le_bytes(header[28..32].try_into().unwrap()) {
503추가: return Err(ErrorCode::Integrity);
504추가: }
505추가: if bytes.is_empty() {
506추가: return if start == 32 {
507추가: Ok(Vec::new())
508추가: } else {
509추가: Err(ErrorCode::Integrity)
510추가: };
511추가: }
512추가: let mut data_end = start;
513추가: let decoded_header;
514추가: let bytes = if bytes[0] == 23 {
515추가: let mut r = Reader::new(&bytes[1..]);
516추가: let mut header_limits = limits;
517추가: header_limits.output = MAX_METADATA_BYTES as u64;
518추가: let streams = Streams::read(&mut r, header_limits)?;
519추가: r.end()?;
520추가: if streams.folders.len() != 1 || streams.folders[0].sizes.len() != 1 {
521추가: return Err(ErrorCode::UnsupportedFeature);
522추가: }
523추가: let packed = streams.bounds(input, data_end)?;
524추가: decoded_header = streams
525추가: .decode(&packed, check)?
526추가: .pop()
527추가: .ok_or(ErrorCode::Integrity)?;
528추가: data_end = 32 + streams.position;
529추가: &decoded_header
530추가: } else {
531추가: bytes
532추가: };
533추가: let mut r = Reader::new(bytes);
534추가: r.expect(1)?;
535추가: let mut streams = None;
536추가: let mut tag = r.byte()?;
537추가: if tag == 2 {
538추가: while {
539추가: let tag = r.byte()?;
540추가: tag != 0
541추가: } {
542추가: let len = r.number(MAX_METADATA_BYTES)?;
543추가: r.take(len)?;
544추가: }
545추가: tag = r.byte()?;
546추가: }
547추가: if tag == 3 {
548추가: return Err(ErrorCode::UnsupportedFeature);
549추가: }
550추가: if tag == 4 {
551추가: streams = Some(Streams::read(&mut r, limits)?);
552추가: tag = r.byte()?;
553추가: }
554추가: let (mut members, stream_indices) = if tag == 5 {
555추가: let f = files(&mut r, limits, streams.as_ref())?;
556추가: tag = r.byte()?;
557추가: f
558추가: } else {
559추가: (Vec::new(), Vec::new())
560추가: };
561추가: if tag != 0 {
562추가: return Err(ErrorCode::Integrity);
563추가: }
564추가: r.end()?;
565추가: if let Some(streams) = streams {
566추가: if streams.folders.iter().map(|f| f.sizes.len()).sum::<usize>() != stream_indices.len() {
567추가: return Err(ErrorCode::Integrity);
568추가: }
569추가: let packed = streams.bounds(input, data_end)?;
570추가: if decode {
571추가: let output = streams.decode(&packed, check)?;
572추가: let mut stream_files = stream_indices.into_iter();
573추가: for (folder, bytes) in streams.folders.iter().zip(output) {
574추가: let mut at = 0;
575추가: for size in &folder.sizes {
576추가: let member = &mut members[stream_files.next().ok_or(ErrorCode::Integrity)?];
577추가: if member.entry.size as usize != *size {
578추가: return Err(ErrorCode::Integrity);
579추가: }
580추가: member.data = bytes[at..at + size].to_vec();
581추가: at += size;
582추가: }
583추가: }
584추가: }
585추가: }
586추가: Ok(members)
587추가: }
수정experiments/rust-archive-worker/src/wire.rs+1-1
@@ -125,7 +125,7 @@ macro_rules! enumeration { ($t:ident {$($v:ident=$n:expr),*$(,)?}) => { impl Wir
125125 fn enc(&self,e:&mut Encoder)->io::Result<()> { (match self {$(Self::$v=>$n,)*} as u8).enc(e) }
126126 fn dec(d:&mut Decoder<'_>)->io::Result<Self> { match u8::dec(d)? {$($n=>Ok(Self::$v),)*_=>Err(invalid())} }
127127} }; }
128삭제: enumeration!(Format{Zip=0,Tar=1,Gzip=2,TarGzip=3});
128추가: enumeration!(Format{Zip=0,Tar=1,Gzip=2,TarGzip=3,SevenZip=4});
129129enumeration!(Method{Store=0,Deflate=1});
130130enumeration!(Encryption{None=0,Aes256=1});
131131enumeration!(ActionKind{List=0,Extract=1,CreateZip=2});
수정experiments/rust-ui-memory-app/Cargo.lock+68-0
@@ -116,6 +116,18 @@ version = "2.0.1"
116116source = "registry+https://github.com/rust-lang/crates.io-index"
117117checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"
118118
119추가: [[package]]
120추가: name = "aes"
121추가: version = "0.8.4"
122추가: source = "registry+https://github.com/rust-lang/crates.io-index"
123추가: checksum = "b169f7a6d4742236a0a00c541b845991d0ac43e546831af1249753ab4c3aa3a0"
124추가: dependencies = [
125추가: "cfg-if",
126추가: "cipher",
127추가: "cpufeatures",
128추가: "zeroize",
129추가: ]
130추가:
119131[[package]]
120132name = "ahash"
121133version = "0.8.12"
@@ -555,6 +567,16 @@ dependencies = [
555567 "libc",
556568]
557569
570추가: [[package]]
571추가: name = "cipher"
572추가: version = "0.4.4"
573추가: source = "registry+https://github.com/rust-lang/crates.io-index"
574추가: checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad"
575추가: dependencies = [
576추가: "crypto-common",
577추가: "inout",
578추가: ]
579추가:
558580[[package]]
559581name = "clipboard-win"
560582version = "5.4.3"
@@ -704,6 +726,7 @@ checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
704726dependencies = [
705727 "block-buffer",
706728 "crypto-common",
729추가: "subtle",
707730]
708731
709732[[package]]
@@ -1398,6 +1421,15 @@ version = "0.4.3"
13981421source = "registry+https://github.com/rust-lang/crates.io-index"
13991422checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"
14001423
1424추가: [[package]]
1425추가: name = "hmac"
1426추가: version = "0.12.1"
1427추가: source = "registry+https://github.com/rust-lang/crates.io-index"
1428추가: checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e"
1429추가: dependencies = [
1430추가: "digest",
1431추가: ]
1432추가:
14011433[[package]]
14021434name = "image"
14031435version = "0.25.10"
@@ -1422,6 +1454,15 @@ dependencies = [
14221454 "hashbrown 0.17.1",
14231455]
14241456
1457추가: [[package]]
1458추가: name = "inout"
1459추가: version = "0.1.4"
1460추가: source = "registry+https://github.com/rust-lang/crates.io-index"
1461추가: checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01"
1462추가: dependencies = [
1463추가: "generic-array",
1464추가: ]
1465추가:
14251466[[package]]
14261467name = "itertools"
14271468version = "0.15.0"
@@ -2147,6 +2188,16 @@ version = "0.1.1"
21472188source = "registry+https://github.com/rust-lang/crates.io-index"
21482189checksum = "73072a9470554c8e794778acece2312661218aaabb635600957d952cf01c716e"
21492190
2191추가: [[package]]
2192추가: name = "pbkdf2"
2193추가: version = "0.12.2"
2194추가: source = "registry+https://github.com/rust-lang/crates.io-index"
2195추가: checksum = "f8ed6a7761f76e3b9f92dfb0a60a6a6477c61024b775147ff0973a02653abaf2"
2196추가: dependencies = [
2197추가: "digest",
2198추가: "hmac",
2199추가: ]
2200추가:
21502201[[package]]
21512202name = "peniko"
21522203version = "0.6.1"
@@ -2588,6 +2639,17 @@ dependencies = [
25882639 "syn 3.0.10",
25892640]
25902641
2642추가: [[package]]
2643추가: name = "sha1"
2644추가: version = "0.10.7"
2645추가: source = "registry+https://github.com/rust-lang/crates.io-index"
2646추가: checksum = "a978451301f4db1d02937a4ab3ccce137717b81826e79b7d49ffe3244a13c3b8"
2647추가: dependencies = [
2648추가: "cfg-if",
2649추가: "cpufeatures",
2650추가: "digest",
2651추가: ]
2652추가:
25912653[[package]]
25922654name = "sha2"
25932655version = "0.10.9"
@@ -3952,7 +4014,13 @@ dependencies = [
39524014name = "zipelo-archive-worker"
39534015version = "0.1.0"
39544016dependencies = [
4017추가: "aes",
4018추가: "hmac",
4019추가: "pbkdf2",
4020추가: "sha1",
39554021 "sha2",
4022추가: "subtle",
4023추가: "zeroize",
39564024 "zlib-rs",
39574025]
39584026
수정experiments/rust-ui-memory-app/Cargo.toml+4-0
@@ -38,3 +38,7 @@ path = "../../tests/rust-app-ui/regressions.rs"
3838[[test]]
3939name = "real_worker"
4040path = "../../tests/rust-app-real-worker/flows.rs"
41추가:
42추가: [[test]]
43추가: name = "format_contract"
44추가: path = "../../tests/rust-app-real-worker/formats.rs"
수정experiments/rust-ui-memory-app/src/archive_process.rs+4-2
@@ -29,7 +29,8 @@ convert_enum!(
2929 Zip,
3030 Tar,
3131 Gzip,
32삭제: TarGzip
32추가: TarGzip,
33추가: SevenZip
3334);
3435convert_enum!(
3536 format_to_ui,
@@ -38,7 +39,8 @@ convert_enum!(
3839 Zip,
3940 Tar,
4041 Gzip,
41삭제: TarGzip
42추가: TarGzip,
43추가: SevenZip
4244);
4345convert_enum!(
4446 kind_to_ui,
수정experiments/rust-ui-memory-app/src/archive_ui.rs+1-0
@@ -6,6 +6,7 @@ pub enum Format {
66 Tar,
77 Gzip,
88 TarGzip,
9추가: SevenZip,
910}
1011#[derive(Clone, Debug, Eq, PartialEq)]
1112pub enum SourceObject {
수정tests/rust-app-real-worker/Cargo.lock+80-0
@@ -2,6 +2,18 @@
22# It is not intended for manual editing.
33version = 4
44
5추가: [[package]]
6추가: name = "aes"
7추가: version = "0.8.4"
8추가: source = "registry+https://github.com/rust-lang/crates.io-index"
9추가: checksum = "b169f7a6d4742236a0a00c541b845991d0ac43e546831af1249753ab4c3aa3a0"
10추가: dependencies = [
11추가: "cfg-if",
12추가: "cipher",
13추가: "cpufeatures",
14추가: "zeroize",
15추가: ]
16추가:
517[[package]]
618name = "block-buffer"
719version = "0.10.4"
@@ -17,6 +29,16 @@ version = "1.0.5"
1729source = "registry+https://github.com/rust-lang/crates.io-index"
1830checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"
1931
32추가: [[package]]
33추가: name = "cipher"
34추가: version = "0.4.4"
35추가: source = "registry+https://github.com/rust-lang/crates.io-index"
36추가: checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad"
37추가: dependencies = [
38추가: "crypto-common",
39추가: "inout",
40추가: ]
41추가:
2042[[package]]
2143name = "cpufeatures"
2244version = "0.2.17"
@@ -44,6 +66,7 @@ checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
4466dependencies = [
4567 "block-buffer",
4668 "crypto-common",
69추가: "subtle",
4770]
4871
4972[[package]]
@@ -56,12 +79,51 @@ dependencies = [
5679 "version_check",
5780]
5881
82추가: [[package]]
83추가: name = "hmac"
84추가: version = "0.12.1"
85추가: source = "registry+https://github.com/rust-lang/crates.io-index"
86추가: checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e"
87추가: dependencies = [
88추가: "digest",
89추가: ]
90추가:
91추가: [[package]]
92추가: name = "inout"
93추가: version = "0.1.4"
94추가: source = "registry+https://github.com/rust-lang/crates.io-index"
95추가: checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01"
96추가: dependencies = [
97추가: "generic-array",
98추가: ]
99추가:
59100[[package]]
60101name = "libc"
61102version = "0.2.191"
62103source = "registry+https://github.com/rust-lang/crates.io-index"
63104checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a"
64105
106추가: [[package]]
107추가: name = "pbkdf2"
108추가: version = "0.12.2"
109추가: source = "registry+https://github.com/rust-lang/crates.io-index"
110추가: checksum = "f8ed6a7761f76e3b9f92dfb0a60a6a6477c61024b775147ff0973a02653abaf2"
111추가: dependencies = [
112추가: "digest",
113추가: "hmac",
114추가: ]
115추가:
116추가: [[package]]
117추가: name = "sha1"
118추가: version = "0.10.7"
119추가: source = "registry+https://github.com/rust-lang/crates.io-index"
120추가: checksum = "a978451301f4db1d02937a4ab3ccce137717b81826e79b7d49ffe3244a13c3b8"
121추가: dependencies = [
122추가: "cfg-if",
123추가: "cpufeatures",
124추가: "digest",
125추가: ]
126추가:
65127[[package]]
66128name = "sha2"
67129version = "0.10.9"
@@ -73,6 +135,12 @@ dependencies = [
73135 "digest",
74136]
75137
138추가: [[package]]
139추가: name = "subtle"
140추가: version = "2.6.1"
141추가: source = "registry+https://github.com/rust-lang/crates.io-index"
142추가: checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"
143추가:
76144[[package]]
77145name = "typenum"
78146version = "1.20.1"
@@ -85,11 +153,23 @@ version = "0.9.5"
85153source = "registry+https://github.com/rust-lang/crates.io-index"
86154checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
87155
156추가: [[package]]
157추가: name = "zeroize"
158추가: version = "1.9.1"
159추가: source = "registry+https://github.com/rust-lang/crates.io-index"
160추가: checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879"
161추가:
88162[[package]]
89163name = "zipelo-archive-worker"
90164version = "0.1.0"
91165dependencies = [
166추가: "aes",
167추가: "hmac",
168추가: "pbkdf2",
169추가: "sha1",
92170 "sha2",
171추가: "subtle",
172추가: "zeroize",
93173 "zlib-rs",
94174]
95175
수정tests/rust-app-real-worker/README.md+6-0
@@ -50,3 +50,9 @@ fixtures/는 generate.py의 Python 표준 라이브러리로 생성한 작은
5050암호 ZIP, 대용량 성능, OS sandbox, 악성 파일 전체 검증과 Windows 실기는 이 시험의 범위 밖임.
5151
5252취소와 종료 경합 회귀 시험은 실제 작업자에 List를 보낸 뒤 화면 poll 전에 취소하는 흐름을 100회 확인함. 취소 파이프 쓰기가 실패해도 검증된 Terminal과 성공 종료가 있으면 원래 결과를 보존하며, Terminal이 없는 조기 종료는 계속 실패로 처리함. 취소 쓰기 오류 판단을 미루어도 EOF와 child wait 전에는 닫기나 작업 교체를 허용하지 않음.
53추가:
54추가: 7z 앱 연동은 revision 2의 기존 Format 값 0~3을 유지하고 SevenZip 값 4를 추가함.
55추가: formats.rs는 전체 ListEnd 프레임을 고정 바이트와 비교하고 Unix/Windows 식별자가
56추가: 목록 응답과 해제 요청 사이에서 보존되는지 확인함. 화면 흐름 시험은 PR69의 LZMA와
57추가: LZMA2 표본을 실제 작업자로 열고, 받은 ListId로 풀어 원본 바이트를 확인함.
58추가: 구버전 앱은 새 형식 값을 해석할 수 없으므로 앱과 작업자를 함께 갱신해야 함.
수정tests/rust-app-real-worker/flows.rs+38-1
@@ -144,7 +144,12 @@ fn wait(model: &mut Model) {
144144}
145145fn completed(model: &Model) {
146146 assert!(model.confirmed, "{}", model.status());
147삭제: assert_eq!(model.terminal.as_ref().unwrap().outcome, Outcome::Completed);
147추가: assert_eq!(
148추가: model.terminal.as_ref().unwrap().outcome,
149추가: Outcome::Completed,
150추가: "terminal: {:?}",
151추가: model.terminal
152추가: );
148153}
149154#[cfg(feature = "ui")]
150155mod screen {
@@ -290,6 +295,38 @@ mod screen {
290295 assert_reaped(&observed);
291296 }
292297 #[test]
298추가: fn seven_zip_open_and_extract_via_actual_widgets_and_worker() {
299추가: for name in ["lzma.7z", "lzma2.7z"] {
300추가: let scratch = Scratch::new();
301추가: let archive = scratch.path(name);
302추가: fs::copy(
303추가: Path::new(env!("CARGO_MANIFEST_DIR"))
304추가: .join("../../tests/rust-archive-worker/fixtures/7z")
305추가: .join(name),
306추가: &archive,
307추가: )
308추가: .unwrap();
309추가: let original = fs::read(&archive).unwrap();
310추가: let output = make_directory(&scratch.path("output"));
311추가: let (factory, observed) = observed_factory();
312추가: let mut screen = Screen::new(factory);
313추가: screen.open(&archive);
314추가: assert_eq!(
315추가: screen.app.model.list_id.as_ref().unwrap().format,
316추가: Format::SevenZip
317추가: );
318추가: assert!(screen.app.model.can_extract());
319추가: screen.extract(&output);
320추가: assert_eq!(
321추가: fs::read(output.join("folder/hello.txt")).unwrap(),
322추가: b"Zipelo 7z interoperability\n".repeat(100)
323추가: );
324추가: assert_eq!(fs::read(archive).unwrap(), original);
325추가: assert_eq!(observed.borrow().jobs.len(), 2);
326추가: assert_reaped(&observed);
327추가: }
328추가: }
329추가: #[test]
293330 fn zip_open_and_extract_via_actual_widgets_and_worker() {
294331 archive_flow("sample.zip", Format::Zip);
295332 }
추가tests/rust-app-real-worker/formats.rs+130-0
@@ -0,0 +1,130 @@
1추가: #![allow(dead_code)]
2추가: #[path = "../../experiments/rust-ui-memory-app/src/archive_ui.rs"]
3추가: mod archive_ui;
4추가: mod adapter {
5추가: include!("../../experiments/rust-ui-memory-app/src/archive_process.rs");
6추가:
7추가: fn token(format: ui::Format, source_object: ui::SourceObject) -> ui::ListId {
8추가: ui::ListId {
9추가: catalog_version: 1,
10추가: format,
11추가: source_object,
12추가: archive_bytes: 33,
13추가: archive_sha256: [44; 32],
14추가: }
15추가: }
16추가: fn formats() -> [ui::Format; 5] {
17추가: [
18추가: ui::Format::Zip,
19추가: ui::Format::Tar,
20추가: ui::Format::Gzip,
21추가: ui::Format::TarGzip,
22추가: ui::Format::SevenZip,
23추가: ]
24추가: }
25추가: #[test]
26추가: fn list_end_preserves_existing_tags_and_assigns_four_to_seven_zip() {
27추가: for (tag, format) in formats().into_iter().enumerate() {
28추가: let id = token(
29추가: format,
30추가: ui::SourceObject::Unix {
31추가: device: 11,
32추가: inode: 22,
33추가: },
34추가: );
35추가: let mut actual = Vec::new();
36추가: codec::Writer::new(&mut actual, 99)
37추가: .send(&wire::Message::ListEnd {
38추가: entry_count: 7,
39추가: list_id: list_to_wire(id.clone()),
40추가: })
41추가: .unwrap();
42추가: let mut body = Vec::new();
43추가: body.extend(7u32.to_le_bytes());
44추가: body.extend(1u16.to_le_bytes());
45추가: body.push(tag as u8);
46추가: body.push(1);
47추가: body.extend(11u64.to_le_bytes());
48추가: body.extend(22u64.to_le_bytes());
49추가: body.extend(33u64.to_le_bytes());
50추가: body.extend([44; 32]);
51추가: let mut expected = Vec::from(*b"ZAW1");
52추가: expected.extend(1u16.to_le_bytes());
53추가: expected.extend(102u16.to_le_bytes());
54추가: expected.extend((body.len() as u32).to_le_bytes());
55추가: expected.extend([0; 4]);
56추가: expected.extend(99u64.to_le_bytes());
57추가: expected.extend(0u64.to_le_bytes());
58추가: expected.extend(body);
59추가: assert_eq!(actual, expected);
60추가: let (_, _, message) = codec::Reader::new(actual.as_slice())
61추가: .read()
62추가: .unwrap()
63추가: .unwrap();
64추가: match event_to_ui(message, None).unwrap() {
65추가: ui::Event::ListEnd {
66추가: entry_count,
67추가: list_id,
68추가: } => {
69추가: assert_eq!(entry_count, 7);
70추가: assert_eq!(list_id, id);
71추가: }
72추가: _ => panic!("목록 완료 응답이 아님"),
73추가: }
74추가: }
75추가: }
76추가: #[test]
77추가: fn extraction_roundtrip_preserves_both_platform_identities_and_all_formats() {
78추가: for source in [
79추가: ui::SourceObject::Unix {
80추가: device: 11,
81추가: inode: 22,
82추가: },
83추가: ui::SourceObject::Windows {
84추가: volume: 55,
85추가: file_id: [66; 16],
86추가: },
87추가: ] {
88추가: for format in formats() {
89추가: let id = token(format, source.clone());
90추가: assert_eq!(list_to_ui(list_to_wire(id.clone())), id);
91추가: let start = start_to_wire(ui::Start::Extract {
92추가: archive: PathBuf::from("input.7z"),
93추가: destination: PathBuf::from("output"),
94추가: selection: ui::Selection::EntryIds(vec![7]),
95추가: list_id: id.clone(),
96추가: gzip_output_name: if format == ui::Format::Gzip {
97추가: Some("content".into())
98추가: } else {
99추가: None
100추가: },
101추가: });
102추가: let mut bytes = Vec::new();
103추가: codec::Writer::new(&mut bytes, 99)
104추가: .send(&wire::Message::Start(start))
105추가: .unwrap();
106추가: assert_eq!(&bytes[6..8], &1u16.to_le_bytes());
107추가: match codec::Reader::new(bytes.as_slice())
108추가: .read()
109추가: .unwrap()
110추가: .unwrap()
111추가: .2
112추가: {
113추가: wire::Message::Start(wire::Start {
114추가: action:
115추가: wire::Action::Extract {
116추가: list_id: Some(decoded),
117추가: selection,
118추가: ..
119추가: },
120추가: ..
121추가: }) => {
122추가: assert_eq!(list_to_ui(decoded), id);
123추가: assert_eq!(selection, wire::Selection::EntryIds(vec![7]));
124추가: }
125추가: _ => panic!("압축 해제 요청이 아님"),
126추가: }
127추가: }
128추가: }
129추가: }
130추가: }
수정tests/rust-app-ui/validation.json+27-18
@@ -1,20 +1,20 @@
11{
22 "command": "python3 tests/ci/run_rust.py local",
33 "platform": "linux-desktop-2",
4삭제: "base_remote_main": "3f51510fcc613c3f72e29c3b421aab178bf94186",
5삭제: "local_baseline_head": "3ef6f50",
6삭제: "source_state": "Tested committed integration source. Only this evidence JSON was updated after the full runner completed; hashes identify the tested code and fixtures.",
4추가: "base_remote_main": "4160fcc4e80070b6ab9ea50c78705c0458b2384a",
5추가: "local_baseline_head": "b8811fa1bcb169c1ec8e5b14dbe6a46c510da0d1",
6추가: "source_state": "최신 PR69와 기존 SevenZip 앱 변환 및 암호 의존성 lockfile을 통합한 커밋에서 전체 검증함. 검증 후 이 증거 JSON만 갱신함.",
77 "linux_build_crates": 19,
88 "linux_test_targets": 19,
9삭제: "rust_tests_passed": 870,
9추가: "rust_tests_passed": 895,
1010 "new_archive_ui_tests_passed": 22,
1111 "windows_cross_build_crates": 19,
1212 "windows_runtime_tested": false,
1313 "native_visual_check": "Headless egui Context used actual widget pointer/key events and the real OS worker process on Linux. Native OS window/input automation and Windows execution were not performed.",
14삭제: "prior_failures": "Retained locally: first build drop API/legacy harness references; second and third egui renderer harness texture/first-frame setup; final runner passed.",
14추가: "prior_failures": "최초 실행은 공유 캐시의 기존 7z 미지원 작업자로 화면 시험 1개가 실패함. 추출 소스의 타임스탬프를 갱신하여 다시 빌드한 뒤 LZMA/LZMA2 화면 시험과 전체 실행이 통과함.",
1515 "limitations": [
16삭제: "Normal ZIP/TAR.GZ listing and extraction plus ZIP creation/reopen/extraction use the actual worker executable and OS pipes.",
17삭제: "The three successful screen tests run headless egui widgets, not a native OS GUI automation session.",
16추가: "Normal ZIP/TAR.GZ/7z listing and extraction plus ZIP creation/reopen/extraction use the actual worker executable and OS pipes.",
17추가: "Four successful screen tests run headless egui widgets, including LZMA/LZMA2 7z fixtures, not native OS GUI automation.",
1818 "Malformed, wrong-action, early-exit and disposal fault cases use a separate test-only probe; serialization failure and late cancellation use the actual worker.",
1919 "No Windows runtime, encryption ZIP, large-file performance, OS sandbox or exhaustive malicious-input validation in this frontend integration.",
2020 "Manual path text is UTF-8; native archive CLI/drop paths retain PathBuf and NativePath."
@@ -22,15 +22,15 @@
2222 "tested_files": [
2323 {
2424 "path": "experiments/rust-ui-memory-app/Cargo.lock",
25삭제: "sha256": "791935d3b7eb17f68ccd08e35e6839e3ff42fecf9fd51cce4ce69fb7bb717197"
25추가: "sha256": "f5515522ce9eebb3918f9bb4905a4aa8ae5e299c544ad5a14327ce1fcda3ec1f"
2626 },
2727 {
2828 "path": "experiments/rust-ui-memory-app/Cargo.toml",
29삭제: "sha256": "dd23a3958123c9271f8201793d655b99b28f055cfd94ac22288ee56408d093a4"
29추가: "sha256": "d2ba4202c0920af4b090fb59245f92b59c14f0590930ca4c6d8874d77057a577"
3030 },
3131 {
3232 "path": "experiments/rust-ui-memory-app/src/archive_process.rs",
33삭제: "sha256": "52cebb8d1ec237dfbf56d2bb4449d6fce26dc66c594767ac086a9a6577fe2767"
33추가: "sha256": "a75457134618ba7c8b0e8ee7800e14ec5c77fadac5c62fdac2ccf1fa663bd142"
3434 },
3535 {
3636 "path": "experiments/rust-ui-memory-app/src/archive_screen.rs",
@@ -38,7 +38,7 @@
3838 },
3939 {
4040 "path": "experiments/rust-ui-memory-app/src/archive_ui.rs",
41삭제: "sha256": "e37e59f6abe56e19551b5de1b5a95e56c5a1448c0aa4387bff38c4f18d319d46"
41추가: "sha256": "f26557645cea07350843c7e88225e07bb4316ab673dc2581b036567f01d66d6e"
4242 },
4343 {
4444 "path": "experiments/rust-ui-memory-app/src/desktop.rs",
@@ -54,7 +54,7 @@
5454 },
5555 {
5656 "path": "tests/rust-app-real-worker/Cargo.lock",
57삭제: "sha256": "6fce2f154d57e28e975582755ca13d9ebb4d2d6927a53c42f03e8a9b5f78f78c"
57추가: "sha256": "2b47293130e0653e22b4b40f821e58aa2e0dc2441e56b2278679664060e5b0e9"
5858 },
5959 {
6060 "path": "tests/rust-app-real-worker/Cargo.toml",
@@ -62,7 +62,7 @@
6262 },
6363 {
6464 "path": "tests/rust-app-real-worker/README.md",
65삭제: "sha256": "7902bca8e72fc9599492bfe022b123a60b1ae6cad6fbbd8094bb3c5512268a98"
65추가: "sha256": "7253cd2a765dc594e3a27970fd3811eb50645d1179c2728b57eee2d440b3e367"
6666 },
6767 {
6868 "path": "tests/rust-app-real-worker/fixtures/sample.tar.gz",
@@ -74,7 +74,7 @@
7474 },
7575 {
7676 "path": "tests/rust-app-real-worker/flows.rs",
77삭제: "sha256": "d2510f60db64cc373a8affd4b7102d16e3733f82e224905e18b7c5633134e8ff"
77추가: "sha256": "23501dfcfcefa5404d1587d5295915a227a18ba53ccbdf56eaa35b101011d115"
7878 },
7979 {
8080 "path": "tests/rust-app-real-worker/generate.py",
@@ -99,6 +99,10 @@
9999 {
100100 "path": "tests/rust-app-ui/regressions.rs",
101101 "sha256": "a4c3685a380cb73fd506a290270b2a5308529ef4f843c203127c2bc9a2df2a80"
102추가: },
103추가: {
104추가: "path": "tests/rust-app-real-worker/formats.rs",
105추가: "sha256": "50532a4ee144ab533a43e1fefa5d1baf1131638892b585c20c9d4715a904e006"
102106 }
103107 ],
104108 "review_regressions": [
@@ -113,8 +117,13 @@
113117 ],
114118 "before_review_fix": "Earlier PR62 fixes reproduced 3 failures before repair. Integration tests additionally reproduced normal channel shutdown and late-cancel races before repair. PR68 review race reproduced with the new test before repair; all 100 iterations passed after repair.",
115119 "approved_ui_head": "423a7c80c9d7182e07d29adee03a97d09a19b11f",
116삭제: "tested_local_head": "b7e558cd8afbb8bb54b55ebd4c463641cc2129e5",
117삭제: "real_worker_tests_passed": 10,
118삭제: "runner_tests_passed": 17,
119삭제: "merge_validation": "Approved UI logic unchanged from 2174031; main malicious fixtures integrated and full local runner passed."
120추가: "tested_local_head": "496415fbd6fa6bc359f85775a88ed56cd71fa2e5",
121추가: "real_worker_tests_passed": 11,
122추가: "runner_tests_passed": 23,
123추가: "format_contract_tests_passed": 2,
124추가: "prerequisite_heads": {
125추가: "PR69": "8614f8431a6d7f1967822c233a812d383e574000"
126추가: },
127추가: "format_extension": "Existing tags 0..3 unchanged; SevenZip=4. Full ListEnd golden frame, both platform identities and Extract codec roundtrip verified.",
128추가: "lockfile_update": "PR71 159d51a의 앱 및 probe 암호 의존성 고정과 동일함. 기존 패키지 버전을 변경하지 않음."
120129}
추가tests/rust-archive-worker/fixtures/7z/bad-crc.7z

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

파일 내려받기
추가tests/rust-archive-worker/fixtures/7z/bad-dictionary.7z

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

파일 내려받기
추가tests/rust-archive-worker/fixtures/7z/bad-payload.7z

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

파일 내려받기
추가tests/rust-archive-worker/fixtures/7z/bad-trailing.7z

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

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

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

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

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

파일 내려받기
추가tests/rust-archive-worker/fixtures/7z/encoded-solid.7z

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

파일 내려받기
추가tests/rust-archive-worker/fixtures/7z/libarchive-lzma1.7z

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

파일 내려받기
추가tests/rust-archive-worker/fixtures/7z/libarchive-lzma2.7z

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

파일 내려받기
추가tests/rust-archive-worker/fixtures/7z/long-match.7z

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

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

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

파일 내려받기
추가tests/rust-archive-worker/fixtures/7z/lzma2-chunks.7z

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

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

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

파일 내려받기
추가tests/rust-archive-worker/fixtures/7z/properties-0.7z

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

파일 내려받기
추가tests/rust-archive-worker/fixtures/7z/properties-1.7z

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

파일 내려받기
추가tests/rust-archive-worker/fixtures/7z/properties-2.7z

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

파일 내려받기
추가tests/rust-archive-worker/fixtures/7z/properties-3.7z

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

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

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

파일 내려받기
추가tests/rust-archive-worker/fixtures/7z/unsafe-absolute.7z

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

파일 내려받기
추가tests/rust-archive-worker/fixtures/7z/unsafe-backslash.7z

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

파일 내려받기
추가tests/rust-archive-worker/fixtures/7z/unsafe-deep.7z

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

파일 내려받기
추가tests/rust-archive-worker/fixtures/7z/unsafe-dotdot.7z

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

파일 내려받기
추가tests/rust-archive-worker/fixtures/7z/unsafe-drive.7z

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

파일 내려받기
수정tests/rust-archive-worker/main.rs+352-0
@@ -1198,3 +1198,355 @@ fn empty_encryption_password_never_creates_zip() {
11981198 assert_eq!(terminal(&events).publication, Publication::None);
11991199 assert!(!s.0.join("empty.zip").exists());
12001200}
1201추가:
1202추가: const SEVEN_PAYLOAD: &[u8] = b"Zipelo 7z interoperability\n";
1203추가: fn seven_fixture(name: &str) -> Vec<u8> {
1204추가: fs::read(
1205추가: PathBuf::from(env!("CARGO_MANIFEST_DIR"))
1206추가: .join("../../tests/rust-archive-worker/fixtures/7z")
1207추가: .join(name),
1208추가: )
1209추가: .unwrap()
1210추가: }
1211추가: #[test]
1212추가: fn seven_zip_lzma_lzma2_and_copy_interoperate() {
1213추가: for name in [
1214추가: "copy.7z",
1215추가: "lzma.7z",
1216추가: "lzma2.7z",
1217추가: "properties-0.7z",
1218추가: "properties-1.7z",
1219추가: "properties-2.7z",
1220추가: "properties-3.7z",
1221추가: "libarchive-lzma1.7z",
1222추가: "libarchive-lzma2.7z",
1223추가: ] {
1224추가: let bytes = seven_fixture(name);
1225추가: let catalog = archive::parse(&bytes, Limits::default(), true, &mut || Ok(()))
1226추가: .unwrap_or_else(|e| panic!("{name}: {e:?}"));
1227추가: assert_eq!(catalog.format, Format::SevenZip);
1228추가: assert_eq!(catalog.members[0].data, SEVEN_PAYLOAD.repeat(100), "{name}");
1229추가: let s = Scratch::new();
1230추가: let events = extract(&s, &bytes, None, Selection::All, None, Limits::default());
1231추가: assert_eq!(
1232추가: terminal(&events).outcome,
1233추가: Outcome::Completed,
1234추가: "{name}: {events:?}"
1235추가: );
1236추가: assert_eq!(
1237추가: fs::read(s.0.join("output/folder/hello.txt")).unwrap(),
1238추가: SEVEN_PAYLOAD.repeat(100)
1239추가: );
1240추가: }
1241추가: }
1242추가: #[test]
1243추가: fn seven_zip_encoded_header_solid_and_empty_entries() {
1244추가: let s = Scratch::new();
1245추가: let bytes = seven_fixture("encoded-solid.7z");
1246추가: let catalog = archive::parse(&bytes, Limits::default(), false, &mut || Ok(())).unwrap();
1247추가: assert_eq!(catalog.members.len(), 4);
1248추가: let events = extract(&s, &bytes, None, Selection::All, None, Limits::default());
1249추가: assert_eq!(terminal(&events).outcome, Outcome::Completed, "{events:?}");
1250추가: assert_eq!(fs::read(s.0.join("output/folder/empty")).unwrap(), b"");
1251추가: assert_eq!(
1252추가: fs::read(s.0.join("output/folder/hello.txt")).unwrap(),
1253추가: SEVEN_PAYLOAD.repeat(100)
1254추가: );
1255추가: let mut reverse = SEVEN_PAYLOAD.repeat(100);
1256추가: reverse.reverse();
1257추가: assert_eq!(fs::read(s.0.join("output/한글.txt")).unwrap(), reverse);
1258추가: }
1259추가: #[test]
1260추가: fn seven_zip_long_matches_and_lzma2_chunks() {
1261추가: for name in ["long-match.7z", "lzma2-chunks.7z"] {
1262추가: let bytes = seven_fixture(name);
1263추가: let catalog = archive::parse(&bytes, Limits::default(), true, &mut || Ok(()))
1264추가: .unwrap_or_else(|e| panic!("{name}: {e:?}"));
1265추가: if name == "long-match.7z" {
1266추가: assert_eq!(catalog.members[0].data, SEVEN_PAYLOAD.repeat(10000));
1267추가: } else {
1268추가: let expected = (0..100000u64)
1269추가: .map(|i| (((i * 1103515245 + (i >> 2) * 12345) >> ((i % 4) * 8)) & 255) as u8)
1270추가: .collect::<Vec<_>>();
1271추가: assert_eq!(catalog.members[0].data, expected);
1272추가: }
1273추가: }
1274추가: }
1275추가: #[test]
1276추가: fn seven_zip_malicious_inputs_never_write() {
1277추가: for name in [
1278추가: "unsafe-dotdot.7z",
1279추가: "unsafe-absolute.7z",
1280추가: "unsafe-drive.7z",
1281추가: "unsafe-backslash.7z",
1282추가: "unsafe-deep.7z",
1283추가: "symlink.7z",
1284추가: "collision.7z",
1285추가: "bad-payload.7z",
1286추가: "bad-crc.7z",
1287추가: "bad-dictionary.7z",
1288추가: ] {
1289추가: let s = Scratch::new();
1290추가: let bytes = seven_fixture(name);
1291추가: let events = extract(&s, &bytes, None, Selection::All, None, Limits::default());
1292추가: assert_eq!(
1293추가: terminal(&events).outcome,
1294추가: Outcome::Failed,
1295추가: "{name}: {events:?}"
1296추가: );
1297추가: assert_eq!(terminal(&events).publication, Publication::None);
1298추가: assert_eq!(terminal(&events).created_count, 0);
1299추가: assert!(!events.iter().any(|e| matches!(e, Message::Output { .. })));
1300추가: assert_eq!(fs::read_dir(s.0.join("output")).unwrap().count(), 0);
1301추가: assert!(!s.0.join("outside.txt").exists());
1302추가: }
1303추가: }
1304추가:
1305추가: #[test]
1306추가: fn seven_zip_format_wire_tag_preserves_existing_encodings() {
1307추가: for (tag, format) in [
1308추가: Format::Zip,
1309추가: Format::Tar,
1310추가: Format::Gzip,
1311추가: Format::TarGzip,
1312추가: Format::SevenZip,
1313추가: ]
1314추가: .into_iter()
1315추가: .enumerate()
1316추가: {
1317추가: let token = ListId {
1318추가: catalog_version: 1,
1319추가: format,
1320추가: source_object: SourceObject::Unix {
1321추가: device: 1,
1322추가: inode: 2,
1323추가: },
1324추가: archive_bytes: 3,
1325추가: archive_sha256: [4; 32],
1326추가: };
1327추가: let mut bytes = Vec::new();
1328추가: Writer::new(&mut bytes, 17)
1329추가: .send(&Message::ListEnd {
1330추가: entry_count: 5,
1331추가: list_id: token.clone(),
1332추가: })
1333추가: .unwrap();
1334추가: assert_eq!(bytes[38], tag as u8);
1335추가: match Reader::new(bytes.as_slice()).read().unwrap().unwrap().2 {
1336추가: Message::ListEnd {
1337추가: entry_count,
1338추가: list_id,
1339추가: } => {
1340추가: assert_eq!(entry_count, 5);
1341추가: assert_eq!(list_id, token);
1342추가: }
1343추가: _ => panic!("expected ListEnd"),
1344추가: }
1345추가: }
1346추가: }
1347추가: #[test]
1348추가: fn seven_zip_listing_token_and_selection() {
1349추가: let s = Scratch::new();
1350추가: let bytes = seven_fixture("encoded-solid.7z");
1351추가: fs::write(s.0.join("input"), &bytes).unwrap();
1352추가: let events = execute(Start {
1353추가: action: Action::List {
1354추가: archive: s.path("input"),
1355추가: },
1356추가: limits: Limits::default(),
1357추가: });
1358추가: assert_eq!(terminal(&events).outcome, Outcome::Completed);
1359추가: let list_id = events
1360추가: .into_iter()
1361추가: .find_map(|e| {
1362추가: if let Message::ListEnd { list_id, .. } = e {
1363추가: Some(list_id)
1364추가: } else {
1365추가: None
1366추가: }
1367추가: })
1368추가: .unwrap();
1369추가: assert_eq!(list_id.format, Format::SevenZip);
1370추가: let events = extract(
1371추가: &s,
1372추가: &bytes,
1373추가: None,
1374추가: Selection::EntryIds(vec![3]),
1375추가: Some(list_id),
1376추가: Limits::default(),
1377추가: );
1378추가: assert_eq!(terminal(&events).outcome, Outcome::Completed);
1379추가: assert_eq!(terminal(&events).created_count, 1);
1380추가: assert!(!s.0.join("output/folder").exists());
1381추가: assert_eq!(fs::read_dir(s.0.join("output")).unwrap().count(), 1);
1382추가: }
1383추가: #[test]
1384추가: fn seven_zip_limits_truncation_and_existing_files_are_preserved() {
1385추가: let bytes = seven_fixture("lzma2.7z");
1386추가: for cut in [0, 1, 6, 12, 31, 32, bytes.len() - 1] {
1387추가: let s = Scratch::new();
1388추가: let events = extract(
1389추가: &s,
1390추가: &bytes[..cut],
1391추가: None,
1392추가: Selection::All,
1393추가: None,
1394추가: Limits::default(),
1395추가: );
1396추가: assert_eq!(terminal(&events).outcome, Outcome::Failed);
1397추가: assert_eq!(terminal(&events).publication, Publication::None);
1398추가: assert_eq!(fs::read_dir(s.0.join("output")).unwrap().count(), 0);
1399추가: }
1400추가: let s = Scratch::new();
1401추가: let events = extract(
1402추가: &s,
1403추가: &bytes,
1404추가: None,
1405추가: Selection::All,
1406추가: None,
1407추가: Limits {
1408추가: output: 100,
1409추가: ..Limits::default()
1410추가: },
1411추가: );
1412추가: assert_eq!(terminal(&events).error, ErrorCode::Limit);
1413추가: assert_eq!(fs::read_dir(s.0.join("output")).unwrap().count(), 0);
1414추가: fs::create_dir(s.0.join("output/folder")).unwrap();
1415추가: #[cfg(unix)]
1416추가: {
1417추가: use std::os::unix::fs::PermissionsExt;
1418추가: fs::set_permissions(s.0.join("output/folder"), fs::Permissions::from_mode(0o700)).unwrap();
1419추가: }
1420추가: fs::write(s.0.join("output/folder/hello.txt"), b"preserve").unwrap();
1421추가: let events = extract(&s, &bytes, None, Selection::All, None, Limits::default());
1422추가: assert_eq!(terminal(&events).error, ErrorCode::Conflict);
1423추가: assert_eq!(
1424추가: fs::read(s.0.join("output/folder/hello.txt")).unwrap(),
1425추가: b"preserve"
1426추가: );
1427추가: let s = Scratch::new();
1428추가: let events = extract(
1429추가: &s,
1430추가: &seven_fixture("bad-trailing.7z"),
1431추가: None,
1432추가: Selection::All,
1433추가: None,
1434추가: Limits::default(),
1435추가: );
1436추가: assert_eq!(terminal(&events).error, ErrorCode::Integrity);
1437추가: assert_eq!(fs::read_dir(s.0.join("output")).unwrap().count(), 0);
1438추가: }
1439추가: #[test]
1440추가: fn seven_zip_parser_honors_cancellation_checkpoints() {
1441추가: let bytes = seven_fixture("long-match.7z");
1442추가: let mut calls = 0;
1443추가: let result = archive::parse(&bytes, Limits::default(), true, &mut || {
1444추가: calls += 1;
1445추가: if calls >= 5 {
1446추가: Err(ErrorCode::None)
1447추가: } else {
1448추가: Ok(())
1449추가: }
1450추가: });
1451추가: assert!(matches!(result, Err(ErrorCode::None)));
1452추가: }
1453추가: #[test]
1454추가: fn pr64_malicious_corpus_is_rejected_without_writes() {
1455추가: let root = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
1456추가: .join("../../tests/malicious-archive-fixtures/fixtures");
1457추가: let cases = [
1458추가: ("zip-dotdot.zip", ErrorCode::UnsafePath, 131072, None),
1459추가: (
1460추가: "zip-absolute-posix.zip",
1461추가: ErrorCode::UnsafePath,
1462추가: 131072,
1463추가: None,
1464추가: ),
1465추가: (
1466추가: "zip-absolute-drive.zip",
1467추가: ErrorCode::UnsafePath,
1468추가: 131072,
1469추가: None,
1470추가: ),
1471추가: (
1472추가: "zip-backslash-dotdot.zip",
1473추가: ErrorCode::UnsafePath,
1474추가: 131072,
1475추가: None,
1476추가: ),
1477추가: ("tar-dotdot.tar", ErrorCode::UnsafePath, 131072, None),
1478추가: ("targz-dotdot.tar.gz", ErrorCode::UnsafePath, 131072, None),
1479추가: (
1480추가: "tar-absolute-posix.tar",
1481추가: ErrorCode::UnsafePath,
1482추가: 131072,
1483추가: None,
1484추가: ),
1485추가: ("zip-symlink-escape.zip", ErrorCode::Conflict, 131072, None),
1486추가: ("tar-symlink-escape.tar", ErrorCode::Conflict, 131072, None),
1487추가: ("zip-output-limit.zip", ErrorCode::Limit, 1024, None),
1488추가: (
1489추가: "gzip-output-limit.gz",
1490추가: ErrorCode::Limit,
1491추가: 1024,
1492추가: Some("payload.bin"),
1493추가: ),
1494추가: ("targz-output-limit.tar.gz", ErrorCode::Limit, 1024, None),
1495추가: (
1496추가: "zip-bad-local-header.zip",
1497추가: ErrorCode::Integrity,
1498추가: 131072,
1499추가: None,
1500추가: ),
1501추가: ("tar-bad-checksum.tar", ErrorCode::Integrity, 131072, None),
1502추가: (
1503추가: "gzip-reserved-flags.gz",
1504추가: ErrorCode::Integrity,
1505추가: 131072,
1506추가: Some("payload.bin"),
1507추가: ),
1508추가: ];
1509추가: for (name, expected, output, gzip) in cases {
1510추가: let s = Scratch::new();
1511추가: let bytes = fs::read(root.join(name)).unwrap();
1512추가: fs::write(s.0.join("outside.txt"), b"preserve").unwrap();
1513추가: let events = extract(
1514추가: &s,
1515추가: &bytes,
1516추가: gzip,
1517추가: Selection::All,
1518추가: None,
1519추가: Limits {
1520추가: input: 1048576,
1521추가: output,
1522추가: entries: 64,
1523추가: },
1524추가: );
1525추가: assert_eq!(
1526추가: terminal(&events).outcome,
1527추가: Outcome::Failed,
1528추가: "{name}: {events:?}"
1529추가: );
1530추가: assert_eq!(terminal(&events).error, expected, "{name}");
1531추가: assert_eq!(terminal(&events).publication, Publication::None);
1532추가: assert_eq!(terminal(&events).created_count, 0);
1533추가: assert_eq!(terminal(&events).retained_partial_count, 0);
1534추가: assert!(!events.iter().any(|e| matches!(e, Message::Output { .. })));
1535추가: assert_eq!(fs::read_dir(s.0.join("output")).unwrap().count(), 0);
1536추가: assert_eq!(fs::read(s.0.join("outside.txt")).unwrap(), b"preserve");
1537추가: assert_eq!(fs::read(s.0.join("input")).unwrap(), bytes);
1538추가: }
1539추가: }
1540추가: #[cfg(target_os = "linux")]
1541추가: #[test]
1542추가: fn seven_zip_reference_reader_accepts_synthetic_fixtures() {
1543추가: let helper = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
1544추가: .join("../../tests/rust-archive-worker/seven_zip_reference.py");
1545추가: assert!(
1546추가: Command::new("python3")
1547추가: .arg(helper)
1548추가: .status()
1549추가: .unwrap()
1550추가: .success()
1551추가: );
1552추가: }
추가tests/rust-archive-worker/seven_zip_fixtures.py+116-0
@@ -0,0 +1,116 @@
1추가: """Python 표준 LZMA 구현으로 합성 7z 표본을 생성함."""
2추가: import lzma
3추가: from pathlib import Path
4추가: import struct
5추가: import zlib
6추가:
7추가: ROOT = Path(__file__).resolve().parent / "fixtures" / "7z"
8추가: SIGNATURE = b"7z\xbc\xaf\x27\x1c\x00\x04"
9추가: PAYLOAD = b"Zipelo 7z interoperability\n" * 100
10추가:
11추가:
12추가: def integer(n):
13추가: for i in range(8):
14추가: if n < 1 << (7 + 7 * i):
15추가: return bytes([(0xFF << (8 - i) & 255) | (n >> (8 * i))]) + n.to_bytes(8, "little")[:i]
16추가: return b"\xff" + struct.pack("<Q", n)
17추가:
18추가:
19추가: def bits(values):
20추가: return bytes(sum((128 >> bit) if i + bit < len(values) and values[i + bit] else 0
21추가: for bit in range(8)) for i in range(0, len(values), 8))
22추가:
23추가:
24추가: def property_bytes(tag, value):
25추가: return bytes([tag]) + integer(len(value)) + value
26추가:
27추가:
28추가: def packed(data, method, lc=3, lp=0, pb=2):
29추가: if method == "copy":
30추가: return data, b"\x01\x00"
31추가: is_lzma2 = method == "lzma2"
32추가: settings = {"id": lzma.FILTER_LZMA2 if is_lzma2 else lzma.FILTER_LZMA1,
33추가: "dict_size": 4096, "lc": lc, "lp": lp, "pb": pb}
34추가: stream = lzma.compress(data, format=lzma.FORMAT_RAW, filters=[settings])
35추가: assert lzma.decompress(stream, format=lzma.FORMAT_RAW, filters=[settings]) == data
36추가: props = b"\x00" if is_lzma2 else bytes([(pb * 5 + lp) * 9 + lc]) + struct.pack("<I", 4096)
37추가: method_id = b"\x21" if is_lzma2 else b"\x03\x01\x01"
38추가: return stream, bytes([0x20 | len(method_id)]) + method_id + integer(len(props)) + props
39추가:
40추가:
41추가: def streams(position, packed_bytes, coder, data, substreams):
42추가: info = b"\x06" + integer(position) + b"\x01\x09" + integer(len(packed_bytes))
43추가: info += b"\x0a\x01" + struct.pack("<I", zlib.crc32(packed_bytes)) + b"\x00"
44추가: info += b"\x07\x0b\x01\x00\x01" + coder + b"\x0c" + integer(len(data))
45추가: info += b"\x0a\x01" + struct.pack("<I", zlib.crc32(data)) + b"\x00"
46추가: if len(substreams) != 1:
47추가: info += b"\x08\x0d" + integer(len(substreams))
48추가: if substreams:
49추가: info += b"\x09" + b"".join(integer(len(part)) for part in substreams[:-1])
50추가: info += b"\x0a\x01" + b"".join(struct.pack("<I", zlib.crc32(part)) for part in substreams)
51추가: info += b"\x00"
52추가: else:
53추가: info += b"\x08\x00"
54추가: return info + b"\x00"
55추가:
56추가:
57추가: def archive(entries, method="lzma2", encoded=False, properties=(3, 0, 2), damage=None):
58추가: parts = [data for _, data, _ in entries if data]
59추가: data = b"".join(parts)
60추가: compressed, coder = packed(data, method, *properties)
61추가: if damage == "payload":
62추가: compressed = compressed[:len(compressed) // 2]
63추가: if damage == "trailing":
64추가: compressed += b"unexpected"
65추가: if damage == "dictionary":
66추가: coder = b"\x21\x21\x01\x28"
67추가: info = b"\x01\x04" + streams(0, compressed, coder, data, parts)
68추가: files = b"\x05" + integer(len(entries))
69추가: empties = [not content for _, content, _ in entries]
70추가: if any(empties):
71추가: files += property_bytes(14, bits(empties))
72추가: files += property_bytes(15, bits([attr & 0x10 == 0 for _, content, attr in entries if not content]))
73추가: files += property_bytes(17, b"\x00" + b"".join(name.encode("utf-16le") + b"\x00\x00" for name, _, _ in entries))
74추가: files += property_bytes(21, b"\x01\x00" + b"".join(struct.pack("<I", attr) for _, _, attr in entries))
75추가: header = info + files + b"\x00\x00"
76추가: if damage == "crc":
77추가: # 데이터 CRC만 틀리게 하며 헤더와 packed CRC는 다시 계산함.
78추가: good = struct.pack("<I", zlib.crc32(data))
79추가: at = header.index(good)
80추가: header = header[:at] + bytes([header[at] ^ 1]) + header[at + 1:]
81추가: if encoded:
82추가: encoded_bytes, encoded_coder = packed(header, "lzma")
83추가: next_header = b"\x17" + streams(len(compressed), encoded_bytes, encoded_coder, header, [header])
84추가: compressed += encoded_bytes
85추가: header = next_header
86추가: start = struct.pack("<QQI", len(compressed), len(header), zlib.crc32(header))
87추가: return SIGNATURE + struct.pack("<I", zlib.crc32(start)) + start + compressed + header
88추가:
89추가:
90추가: def build():
91추가: result = {}
92추가: entries = [("folder/hello.txt", PAYLOAD, 0x20)]
93추가: for method in ("copy", "lzma", "lzma2"):
94추가: result[f"{method}.7z"] = archive(entries, method)
95추가: result["encoded-solid.7z"] = archive([("folder", b"", 0x10), ("folder/empty", b"", 0x20),
96추가: ("folder/hello.txt", PAYLOAD, 0x20), ("한글.txt", PAYLOAD[::-1], 0x20)], encoded=True)
97추가: for i, params in enumerate(((0, 0, 0), (4, 0, 4), (1, 2, 1), (2, 2, 3))):
98추가: result[f"properties-{i}.7z"] = archive(entries, "lzma", properties=params)
99추가: result["long-match.7z"] = archive([("folder/hello.txt", PAYLOAD * 100, 0x20)])
100추가: noise = bytes(((i * 1103515245 + (i >> 2) * 12345) >> ((i % 4) * 8)) & 255 for i in range(100000))
101추가: result["lzma2-chunks.7z"] = archive([("noise", noise, 0x20)])
102추가: for name, hostile in (("dotdot", "../outside.txt"), ("absolute", "/outside.txt"),
103추가: ("drive", "C:/outside.txt"), ("backslash", "..\\outside.txt"),
104추가: ("deep", "a/" * 65 + "file")):
105추가: result[f"unsafe-{name}.7z"] = archive([("before.txt", PAYLOAD, 0x20), (hostile, PAYLOAD, 0x20)])
106추가: result["symlink.7z"] = archive([("before.txt", PAYLOAD, 0x20), ("link", b"../outside", (0o120777 << 16) | 0x8000)])
107추가: result["collision.7z"] = archive([("hello", PAYLOAD, 0x20), ("HELLO", PAYLOAD, 0x20)])
108추가: for damage in ("payload", "crc", "dictionary", "trailing"):
109추가: result[f"bad-{damage}.7z"] = archive(entries, damage=damage)
110추가: return result
111추가:
112추가:
113추가: if __name__ == "__main__":
114추가: ROOT.mkdir(exist_ok=False)
115추가: for name, data in build().items():
116추가: (ROOT / name).write_bytes(data)
추가tests/rust-archive-worker/seven_zip_reference.py+110-0
@@ -0,0 +1,110 @@
1추가: """시스템 libarchive를 시험에서만 사용해 7z 상호 운용을 확인함."""
2추가: import ctypes as c
3추가: import ctypes.util
4추가: from pathlib import Path
5추가: import sys
6추가:
7추가:
8추가: def library():
9추가: lib = c.CDLL(ctypes.util.find_library("archive"))
10추가: functions = {
11추가: "archive_write_new": (c.c_void_p, []),
12추가: "archive_read_new": (c.c_void_p, []),
13추가: "archive_entry_new": (c.c_void_p, []),
14추가: "archive_error_string": (c.c_char_p, [c.c_void_p]),
15추가: "archive_write_set_format_7zip": (c.c_int, [c.c_void_p]),
16추가: "archive_write_set_format_option": (c.c_int, [c.c_void_p, c.c_char_p, c.c_char_p, c.c_char_p]),
17추가: "archive_write_open_memory": (c.c_int, [c.c_void_p, c.c_void_p, c.c_size_t, c.POINTER(c.c_size_t)]),
18추가: "archive_entry_set_pathname": (None, [c.c_void_p, c.c_char_p]),
19추가: "archive_entry_set_filetype": (None, [c.c_void_p, c.c_uint]),
20추가: "archive_entry_set_perm": (None, [c.c_void_p, c.c_uint]),
21추가: "archive_entry_set_size": (None, [c.c_void_p, c.c_longlong]),
22추가: "archive_entry_set_mtime": (None, [c.c_void_p, c.c_longlong, c.c_long]),
23추가: "archive_write_header": (c.c_int, [c.c_void_p, c.c_void_p]),
24추가: "archive_write_data": (c.c_ssize_t, [c.c_void_p, c.c_void_p, c.c_size_t]),
25추가: "archive_entry_free": (None, [c.c_void_p]),
26추가: "archive_write_close": (c.c_int, [c.c_void_p]),
27추가: "archive_write_free": (c.c_int, [c.c_void_p]),
28추가: "archive_read_support_filter_all": (c.c_int, [c.c_void_p]),
29추가: "archive_read_support_format_7zip": (c.c_int, [c.c_void_p]),
30추가: "archive_read_open_filename": (c.c_int, [c.c_void_p, c.c_char_p, c.c_size_t]),
31추가: "archive_read_next_header": (c.c_int, [c.c_void_p, c.POINTER(c.c_void_p)]),
32추가: "archive_entry_pathname": (c.c_char_p, [c.c_void_p]),
33추가: "archive_read_data": (c.c_ssize_t, [c.c_void_p, c.c_void_p, c.c_size_t]),
34추가: "archive_read_free": (c.c_int, [c.c_void_p]),
35추가: }
36추가: for name, (result, args) in functions.items():
37추가: function = getattr(lib, name)
38추가: function.restype = result
39추가: function.argtypes = args
40추가: return lib
41추가:
42추가:
43추가: def create(method, entries):
44추가: lib = library()
45추가: archive = lib.archive_write_new()
46추가: buffer = c.create_string_buffer(4 * 1024 * 1024)
47추가: used = c.c_size_t()
48추가: def check(result):
49추가: assert result == 0, lib.archive_error_string(archive)
50추가: try:
51추가: check(lib.archive_write_set_format_7zip(archive))
52추가: check(lib.archive_write_set_format_option(archive, b"7zip", b"compression", method.encode()))
53추가: check(lib.archive_write_open_memory(archive, buffer, len(buffer), c.byref(used)))
54추가: for name, data in entries:
55추가: entry = lib.archive_entry_new()
56추가: try:
57추가: lib.archive_entry_set_pathname(entry, name.encode())
58추가: lib.archive_entry_set_filetype(entry, 0o100000)
59추가: lib.archive_entry_set_perm(entry, 0o600)
60추가: lib.archive_entry_set_size(entry, len(data))
61추가: lib.archive_entry_set_mtime(entry, 0, 0)
62추가: check(lib.archive_write_header(archive, entry))
63추가: assert lib.archive_write_data(archive, data, len(data)) == len(data)
64추가: finally:
65추가: lib.archive_entry_free(entry)
66추가: check(lib.archive_write_close(archive))
67추가: return buffer.raw[:used.value]
68추가: finally:
69추가: lib.archive_write_free(archive)
70추가:
71추가:
72추가: def verify(path):
73추가: lib = library()
74추가: archive = lib.archive_read_new()
75추가: result = {}
76추가: try:
77추가: assert lib.archive_read_support_filter_all(archive) == 0
78추가: assert lib.archive_read_support_format_7zip(archive) == 0
79추가: assert lib.archive_read_open_filename(archive, str(path).encode(), 65536) == 0
80추가: entry = c.c_void_p()
81추가: while True:
82추가: status = lib.archive_read_next_header(archive, c.byref(entry))
83추가: if status == 1:
84추가: return result
85추가: assert status == 0, lib.archive_error_string(archive)
86추가: name = lib.archive_entry_pathname(entry).decode()
87추가: data = bytearray()
88추가: buffer = c.create_string_buffer(65536)
89추가: while True:
90추가: size = lib.archive_read_data(archive, buffer, len(buffer))
91추가: assert size >= 0, lib.archive_error_string(archive)
92추가: if size == 0:
93추가: break
94추가: data.extend(buffer.raw[:size])
95추가: result[name] = bytes(data)
96추가: finally:
97추가: lib.archive_read_free(archive)
98추가:
99추가:
100추가: if __name__ == "__main__":
101추가: root = Path(__file__).resolve().parent / "fixtures/7z"
102추가: payload = b"Zipelo 7z interoperability\n" * 100
103추가: if sys.argv[1:] == ["--generate"]:
104추가: for method in ("lzma1", "lzma2"):
105추가: path = root / f"libarchive-{method}.7z"
106추가: path.write_bytes(create(method, [("folder/hello.txt", payload), ("second", payload[::-1])]))
107추가: assert verify(path) == {"folder/hello.txt": payload, "second": payload[::-1]}
108추가: else:
109추가: for name in ("copy.7z", "lzma.7z", "lzma2.7z", "encoded-solid.7z", "long-match.7z", "lzma2-chunks.7z"):
110추가: assert verify(root / name)