team-ljyzipelo

공개

Merge pull request #146 from Team-LJY/fix/worker-real-path-tests

작업자 시험을 실제 경로로 옮기고 ZIP 확장 해석 통합
작성자
LeeJunyoung
작성 시각
커밋
463b0dae6844f8ba89adfe0d70c27f144bdf3a3d
이 시점의 파일 보기

변경된 파일 20개

+686-805
수정experiments/rust-archive-worker/src/archive.rs+2-483
@@ -1,6 +1,6 @@
11use crate::protocol::*;
22use std::collections::{BTreeMap, BTreeSet};
3삭제: use zlib_rs::{Deflate, DeflateFlush, Inflate, InflateFlush, Status, crc32::crc32};
3추가: use zlib_rs::{Deflate, DeflateFlush, Status, crc32::crc32};
44
55type Result<T> = std::result::Result<T, ErrorCode>;
66pub const MAX_PATH_DEPTH: usize = 64;
@@ -56,9 +56,6 @@ impl MetadataBudget {
5656 pub(crate) fn charge_bytes(&mut self, bytes: usize, limits: MetadataLimits) -> Result<()> {
5757 self.charge_cost(bytes, 0, limits)
5858 }
59삭제: pub(crate) fn charge(&mut self, name: &str) -> Result<()> {
60삭제: self.charge_with(name, MetadataLimits::default())
61삭제: }
6259 pub(crate) fn charge_with(&mut self, name: &str, limits: MetadataLimits) -> Result<()> {
6360 // 이름 복제와 인덱스 노드 비용을 할당 전에 계산함.
6461 let cost = name
@@ -90,17 +87,6 @@ pub struct Catalog {
9087 pub format: Format,
9188 pub members: Vec<Member>,
9289}
93삭제: fn part(b: &[u8], at: usize, n: usize) -> Result<&[u8]> {
94삭제: b.get(at..at.checked_add(n).ok_or(ErrorCode::Integrity)?)
95삭제: .ok_or(ErrorCode::Integrity)
96삭제: }
97삭제: fn u16at(b: &[u8], at: usize) -> Result<u16> {
98삭제: Ok(u16::from_le_bytes(part(b, at, 2)?.try_into().unwrap()))
99삭제: }
100삭제: fn u32at(b: &[u8], at: usize) -> Result<u32> {
101삭제: Ok(u32::from_le_bytes(part(b, at, 4)?.try_into().unwrap()))
102삭제: }
103삭제:
10490pub fn valid_name(name: &str, directory: bool) -> Result<String> {
10591 let name = if directory {
10692 name.strip_suffix('/').unwrap_or(name)
@@ -218,61 +204,6 @@ fn bounded_append(output: &mut Vec<u8>, data: &[u8], limit: u64) -> Result<()> {
218204 output.extend_from_slice(data);
219205 Ok(())
220206}
221삭제: fn inflate(
222삭제: input: &[u8],
223삭제: gzip: bool,
224삭제: limit: u64,
225삭제: check: &mut impl crate::resources::Monitor,
226삭제: ) -> Result<(Vec<u8>, usize)> {
227삭제: let mut stream = Inflate::new(gzip, if gzip { 31 } else { 15 });
228삭제: let mut out = Vec::new();
229삭제: let mut buffer = [0; 65536];
230삭제: loop {
231삭제: check.check()?;
232삭제: let before_in = stream.total_in();
233삭제: let before_out = stream.total_out();
234삭제: let status = stream
235삭제: .decompress(
236삭제: &input[before_in as usize..],
237삭제: &mut buffer,
238삭제: InflateFlush::NoFlush,
239삭제: )
240삭제: .map_err(|_| ErrorCode::Integrity)?;
241삭제: let written = (stream.total_out() - before_out) as usize;
242삭제: bounded_append(&mut out, &buffer[..written], limit)?;
243삭제: if status == Status::StreamEnd {
244삭제: return Ok((out, stream.total_in() as usize));
245삭제: }
246삭제: if stream.total_in() == before_in && stream.total_out() == before_out {
247삭제: return Err(ErrorCode::Integrity);
248삭제: }
249삭제: }
250삭제: }
251삭제: fn gzip(
252삭제: input: &[u8],
253삭제: limits: Limits,
254삭제: check: &mut impl crate::resources::Monitor,
255삭제: ) -> Result<Vec<u8>> {
256삭제: let mut at = 0;
257삭제: let mut result = Vec::new();
258삭제: while at < input.len() {
259삭제: if !input[at..].starts_with(&[31, 139, 8]) {
260삭제: return Err(ErrorCode::Integrity);
261삭제: }
262삭제: let (out, used) = inflate(
263삭제: &input[at..],
264삭제: true,
265삭제: limits.output - result.len() as u64,
266삭제: check,
267삭제: )?;
268삭제: if used == 0 {
269삭제: return Err(ErrorCode::Integrity);
270삭제: }
271삭제: bounded_append(&mut result, &out, limits.output)?;
272삭제: at += used;
273삭제: }
274삭제: Ok(result)
275삭제: }
276207pub(crate) fn tar_string(b: &[u8]) -> Result<String> {
277208 let n = b.iter().position(|v| *v == 0).unwrap_or(b.len());
278209 if b[n..].iter().any(|v| *v != 0) {
@@ -294,128 +225,6 @@ pub(crate) fn octal(b: &[u8]) -> Result<u64> {
294225 }
295226 u64::from_str_radix(text, 8).map_err(|_| ErrorCode::Integrity)
296227}
297삭제: fn tar(
298삭제: input: &[u8],
299삭제: limits: Limits,
300삭제: decode: bool,
301삭제: check: &mut impl crate::resources::Monitor,
302삭제: ) -> Result<Vec<Member>> {
303삭제: let mut at = 0;
304삭제: let mut members = Vec::new();
305삭제: let mut total = 0u64;
306삭제: let mut metadata = MetadataBudget::default();
307삭제: loop {
308삭제: check.check()?;
309삭제: let header = part(input, at, 512)?;
310삭제: if header.iter().all(|b| *b == 0) {
311삭제: if part(input, at + 512, 512)?.iter().any(|b| *b != 0)
312삭제: || input[at..].iter().any(|b| *b != 0)
313삭제: || input.len() % 512 != 0
314삭제: {
315삭제: return Err(ErrorCode::Integrity);
316삭제: }
317삭제: break;
318삭제: }
319삭제: if members.len() >= limits.entries as usize {
320삭제: return Err(ErrorCode::Limit);
321삭제: }
322삭제: let expected = octal(&header[148..156])?;
323삭제: let checksum = header
324삭제: .iter()
325삭제: .enumerate()
326삭제: .map(|(i, b)| {
327삭제: if (148..156).contains(&i) {
328삭제: 32u64
329삭제: } else {
330삭제: *b as u64
331삭제: }
332삭제: })
333삭제: .sum::<u64>();
334삭제: if checksum != expected {
335삭제: return Err(ErrorCode::Integrity);
336삭제: }
337삭제: let mut name = tar_string(&header[..100])?;
338삭제: if &header[257..263] == b"ustar\0" || &header[257..263] == b"ustar " {
339삭제: let prefix = tar_string(&header[345..500])?;
340삭제: if !prefix.is_empty() {
341삭제: name = format!("{prefix}/{name}");
342삭제: }
343삭제: } else if header[257..263].iter().any(|b| *b != 0) {
344삭제: return Err(ErrorCode::UnsupportedFeature);
345삭제: }
346삭제: let kind = match header[156] {
347삭제: 0 | b'0' => EntryKind::File,
348삭제: b'5' => EntryKind::Directory,
349삭제: b'1' | b'2' => EntryKind::Link,
350삭제: b'x' | b'g' | b'L' | b'K' => return Err(ErrorCode::UnsupportedFeature),
351삭제: _ => EntryKind::Other,
352삭제: };
353삭제: let size = octal(&header[124..136])?;
354삭제: if kind != EntryKind::File && size != 0 {
355삭제: return Err(ErrorCode::Integrity);
356삭제: }
357삭제: total = total
358삭제: .checked_add(size)
359삭제: .filter(|n| *n <= limits.output)
360삭제: .ok_or(ErrorCode::Limit)?;
361삭제: let size = usize::try_from(size).map_err(|_| ErrorCode::Limit)?;
362삭제: let bytes = part(input, at + 512, size)?;
363삭제: metadata.charge(&name)?;
364삭제: let name = valid_name(&name, kind == EntryKind::Directory)?;
365삭제: let data = if decode { bytes.to_vec() } else { Vec::new() };
366삭제: members.push(Member {
367삭제: entry: Entry {
368삭제: entry_id: members.len() as u32,
369삭제: name,
370삭제: kind,
371삭제: size: size as u64,
372삭제: compressed_size: size as u64,
373삭제: encrypted: false,
374삭제: },
375삭제: data,
376삭제: });
377삭제: at = at
378삭제: .checked_add(512)
379삭제: .and_then(|n| n.checked_add(size.div_ceil(512) * 512))
380삭제: .ok_or(ErrorCode::Integrity)?;
381삭제: }
382삭제: validate_members(&members)?;
383삭제: Ok(members)
384삭제: }
385삭제: #[derive(Clone, Copy, PartialEq, Eq)]
386삭제: pub(crate) struct AesExtra {
387삭제: pub version: u16,
388삭제: pub method: u16,
389삭제: }
390삭제: pub(crate) fn aes_extra(extra: &[u8]) -> Result<Option<AesExtra>> {
391삭제: let mut at = 0;
392삭제: let mut found = None;
393삭제: while at < extra.len() {
394삭제: let tag = u16at(extra, at)?;
395삭제: let len = u16at(extra, at + 2)? as usize;
396삭제: let value = part(extra, at + 4, len)?;
397삭제: if tag == 1 {
398삭제: return Err(ErrorCode::UnsupportedFeature);
399삭제: }
400삭제: if tag == 0x9901 {
401삭제: if found.is_some() || len < 7 {
402삭제: return Err(ErrorCode::Integrity);
403삭제: }
404삭제: let version = u16at(value, 0)?;
405삭제: let method = u16at(value, 5)?;
406삭제: if !matches!(version, 1 | 2)
407삭제: || &value[2..4] != b"AE"
408삭제: || value[4] != 3
409삭제: || !matches!(method, 0 | 8)
410삭제: {
411삭제: return Err(ErrorCode::UnsupportedFeature);
412삭제: }
413삭제: found = Some(AesExtra { version, method });
414삭제: }
415삭제: at += 4 + len;
416삭제: }
417삭제: Ok(found)
418삭제: }
419228/// ZIP 항목 이름을 해석함.
420229///
421230/// - UTF-8 플래그(비트 11)가 있으면 이름은 UTF-8이어야 하며 아니면 손상으로 봄.
@@ -431,20 +240,7 @@ pub(crate) fn zip_name(raw: &[u8], flags: u16, extra: &[u8]) -> Result<String> {
431240 .map(str::to_owned)
432241 .map_err(|_| ErrorCode::Integrity);
433242 }
434삭제: let mut at = 0;
435삭제: let mut unicode = None;
436삭제: while at < extra.len() {
437삭제: let tag = u16at(extra, at)?;
438삭제: let len = u16at(extra, at + 2)? as usize;
439삭제: let value = part(extra, at + 4, len)?;
440삭제: if tag == 0x7075 {
441삭제: if unicode.is_some() || len < 5 {
442삭제: return Err(ErrorCode::Integrity);
443삭제: }
444삭제: unicode = Some(value);
445삭제: }
446삭제: at += 4 + len;
447삭제: }
243추가: let unicode = crate::zip_extra::parse(extra, crate::zip_extra::Policy::Names)?.unicode;
448244 if let Some(value) = unicode
449245 && value[0] == 1
450246 && u32::from_le_bytes(value[1..5].try_into().unwrap()) == crc32(0, raw)
@@ -457,283 +253,6 @@ pub(crate) fn zip_name(raw: &[u8], flags: u16, extra: &[u8]) -> Result<String> {
457253 .map(str::to_owned)
458254 .map_err(|_| ErrorCode::UnsupportedFeature)
459255}
460삭제: fn zip(
461삭제: input: &[u8],
462삭제: limits: Limits,
463삭제: decode: bool,
464삭제: password: Option<&[u8]>,
465삭제: check: &mut impl crate::resources::Monitor,
466삭제: ) -> Result<Vec<Member>> {
467삭제: if input.len() < 22 {
468삭제: return Err(ErrorCode::Integrity);
469삭제: }
470삭제: let end = (input.len().saturating_sub(65557)..=input.len() - 22)
471삭제: .rev()
472삭제: .find(|&i| {
473삭제: input.get(i..i + 4) == Some(b"PK\x05\x06")
474삭제: && u16at(input, i + 20)
475삭제: .ok()
476삭제: .is_some_and(|n| i + 22 + n as usize == input.len())
477삭제: })
478삭제: .ok_or(ErrorCode::Integrity)?;
479삭제: let count = u16at(input, end + 10)? as usize;
480삭제: if u16at(input, end + 4)? != 0
481삭제: || u16at(input, end + 6)? != 0
482삭제: || count != u16at(input, end + 8)? as usize
483삭제: {
484삭제: return Err(ErrorCode::UnsupportedFeature);
485삭제: }
486삭제: if count == 65535 || u32at(input, end + 12)? == u32::MAX || u32at(input, end + 16)? == u32::MAX
487삭제: {
488삭제: return Err(ErrorCode::UnsupportedFeature);
489삭제: }
490삭제: if count > limits.entries as usize {
491삭제: return Err(ErrorCode::Limit);
492삭제: }
493삭제: let central = u32at(input, end + 16)? as usize;
494삭제: if central.checked_add(u32at(input, end + 12)? as usize) != Some(end) {
495삭제: return Err(ErrorCode::Integrity);
496삭제: }
497삭제: let mut at = central;
498삭제: let mut members = Vec::new();
499삭제: let mut spans = Vec::new();
500삭제: let mut total = 0u64;
501삭제: let mut metadata = MetadataBudget::default();
502삭제: for id in 0..count {
503삭제: check.check()?;
504삭제: let h = part(input, at, 46)?;
505삭제: if &h[..4] != b"PK\x01\x02" {
506삭제: return Err(ErrorCode::Integrity);
507삭제: }
508삭제: let flags = u16at(h, 8)?;
509삭제: let method = u16at(h, 10)?;
510삭제: if flags & !0x080f != 0 || !matches!(method, 0 | 8 | 99) || u16at(h, 34)? != 0 {
511삭제: return Err(ErrorCode::UnsupportedFeature);
512삭제: }
513삭제: let crc = u32at(h, 16)?;
514삭제: let compressed = u32at(h, 20)? as usize;
515삭제: let size = u32at(h, 24)? as usize;
516삭제: if compressed == u32::MAX as usize || size == u32::MAX as usize {
517삭제: return Err(ErrorCode::UnsupportedFeature);
518삭제: }
519삭제: total = total
520삭제: .checked_add(size as u64)
521삭제: .filter(|n| *n <= limits.output)
522삭제: .ok_or(ErrorCode::Limit)?;
523삭제: let name_len = u16at(h, 28)? as usize;
524삭제: let extra_len = u16at(h, 30)? as usize;
525삭제: let comment_len = u16at(h, 32)? as usize;
526삭제: let extra = aes_extra(part(input, at + 46 + name_len, extra_len)?)?;
527삭제: let encrypted = flags & 1 != 0;
528삭제: if (method == 99) != extra.is_some() || (method == 99 && !encrypted) {
529삭제: return Err(ErrorCode::Integrity);
530삭제: }
531삭제: if extra.is_some_and(|e| e.version == 2) && crc != 0 {
532삭제: return Err(ErrorCode::Integrity);
533삭제: }
534삭제: let raw = part(input, at + 46, name_len)?;
535삭제: let name = zip_name(raw, flags, part(input, at + 46 + name_len, extra_len)?)?;
536삭제: let name = name.as_str();
537삭제: let mode = u32at(h, 38)? >> 16;
538삭제: let kind = match mode & 0xf000 {
539삭제: 0xa000 => EntryKind::Link,
540삭제: 0x4000 => EntryKind::Directory,
541삭제: 0 | 0x8000 => {
542삭제: if name.ends_with('/') {
543삭제: EntryKind::Directory
544삭제: } else {
545삭제: EntryKind::File
546삭제: }
547삭제: }
548삭제: _ => EntryKind::Other,
549삭제: };
550삭제: metadata.charge(name)?;
551삭제: let name = valid_name(name, kind == EntryKind::Directory)?;
552삭제: let local = u32at(h, 42)? as usize;
553삭제: let lh = part(input, local, 30)?;
554삭제: if &lh[..4] != b"PK\x03\x04" || u16at(lh, 6)? != flags || u16at(lh, 8)? != method {
555삭제: return Err(ErrorCode::Integrity);
556삭제: }
557삭제: let ln = u16at(lh, 26)? as usize;
558삭제: let le = u16at(lh, 28)? as usize;
559삭제: if aes_extra(part(input, local + 30 + ln, le)?)? != extra
560삭제: || u16at(lh, 10)? != u16at(h, 12)?
561삭제: || part(input, local + 30, ln)? != raw
562삭제: {
563삭제: return Err(ErrorCode::Integrity);
564삭제: }
565삭제: if flags & 8 == 0
566삭제: && (u32at(lh, 14)? != crc
567삭제: || u32at(lh, 18)? as usize != compressed
568삭제: || u32at(lh, 22)? as usize != size)
569삭제: {
570삭제: return Err(ErrorCode::Integrity);
571삭제: }
572삭제: let start = local
573삭제: .checked_add(30 + ln + le)
574삭제: .ok_or(ErrorCode::Integrity)?;
575삭제: let packed = part(input, start, compressed)?;
576삭제: let mut stop = start + compressed;
577삭제: if flags & 8 != 0 {
578삭제: if input.get(stop..stop + 4) == Some(b"PK\x07\x08") {
579삭제: stop += 4;
580삭제: }
581삭제: if u32at(input, stop)? != crc
582삭제: || u32at(input, stop + 4)? as usize != compressed
583삭제: || u32at(input, stop + 8)? as usize != size
584삭제: {
585삭제: return Err(ErrorCode::Integrity);
586삭제: }
587삭제: stop += 12;
588삭제: }
589삭제: if stop > central {
590삭제: return Err(ErrorCode::Integrity);
591삭제: }
592삭제: spans.push((local, stop));
593삭제: if encrypted && compressed < if extra.is_some() { 28 } else { 12 } {
594삭제: return Err(ErrorCode::Integrity);
595삭제: }
596삭제: let data = if decode {
597삭제: let decrypted;
598삭제: let packed = if encrypted {
599삭제: let password = password.ok_or(ErrorCode::WrongPassword)?;
600삭제: decrypted = if extra.is_some() {
601삭제: crate::crypto::aes_decrypt(packed, password, check)?
602삭제: } else {
603삭제: let verifier = if flags & 8 != 0 {
604삭제: (u16at(h, 12)? >> 8) as u8
605삭제: } else {
606삭제: (crc >> 24) as u8
607삭제: };
608삭제: crate::crypto::zipcrypto_decrypt(packed, password, verifier, check)?
609삭제: };
610삭제: decrypted.as_slice()
611삭제: } else {
612삭제: packed
613삭제: };
614삭제: let actual_method = extra.map_or(method, |e| e.method);
615삭제: let bytes = if actual_method == 0 {
616삭제: if packed.len() != size {
617삭제: return Err(ErrorCode::Integrity);
618삭제: }
619삭제: packed.to_vec()
620삭제: } else {
621삭제: let (out, used) = inflate(packed, false, size as u64, check)?;
622삭제: if used != packed.len() {
623삭제: return Err(ErrorCode::Integrity);
624삭제: }
625삭제: out
626삭제: };
627삭제: if bytes.len() != size
628삭제: || (extra.is_none_or(|e| e.version == 1) && crc32(0, &bytes) != crc)
629삭제: {
630삭제: return Err(ErrorCode::Integrity);
631삭제: }
632삭제: bytes
633삭제: } else {
634삭제: Vec::new()
635삭제: };
636삭제: if kind == EntryKind::Directory && size != 0 {
637삭제: return Err(ErrorCode::Integrity);
638삭제: }
639삭제: members.push(Member {
640삭제: entry: Entry {
641삭제: entry_id: id as u32,
642삭제: name,
643삭제: kind,
644삭제: size: size as u64,
645삭제: compressed_size: compressed as u64,
646삭제: encrypted,
647삭제: },
648삭제: data,
649삭제: });
650삭제: at = at
651삭제: .checked_add(46 + name_len + extra_len + comment_len)
652삭제: .ok_or(ErrorCode::Integrity)?;
653삭제: }
654삭제: if at != end {
655삭제: return Err(ErrorCode::Integrity);
656삭제: }
657삭제: spans.sort_unstable();
658삭제: let mut next = 0;
659삭제: for (start, stop) in spans {
660삭제: if start != next {
661삭제: return Err(ErrorCode::Integrity);
662삭제: }
663삭제: next = stop;
664삭제: }
665삭제: if next != central {
666삭제: return Err(ErrorCode::Integrity);
667삭제: }
668삭제: validate_members(&members)?;
669삭제: Ok(members)
670삭제: }
671삭제: pub fn parse(
672삭제: input: &[u8],
673삭제: limits: Limits,
674삭제: decode: bool,
675삭제: check: &mut impl crate::resources::Monitor,
676삭제: ) -> Result<Catalog> {
677삭제: parse_with_password(input, limits, decode, None, check)
678삭제: }
679삭제: pub fn parse_with_password(
680삭제: input: &[u8],
681삭제: limits: Limits,
682삭제: decode: bool,
683삭제: password: Option<&[u8]>,
684삭제: check: &mut impl crate::resources::Monitor,
685삭제: ) -> Result<Catalog> {
686삭제: if !limits.valid() {
687삭제: return Err(ErrorCode::Limit);
688삭제: }
689삭제: let limits = limits.legacy();
690삭제: if input.len() as u64 > limits.input {
691삭제: return Err(ErrorCode::Limit);
692삭제: }
693삭제: if input.starts_with(b"7z\xbc\xaf\x27\x1c") {
694삭제: return Ok(Catalog {
695삭제: format: Format::SevenZip,
696삭제: members: crate::seven_zip::parse(input, limits, decode, check)?,
697삭제: });
698삭제: }
699삭제: if input.starts_with(b"PK\x03\x04") || input.starts_with(b"PK\x05\x06") {
700삭제: return Ok(Catalog {
701삭제: format: Format::Zip,
702삭제: members: zip(input, limits, decode, password, check)?,
703삭제: });
704삭제: }
705삭제: if input.starts_with(&[31, 139]) {
706삭제: let bytes = gzip(input, limits, check)?;
707삭제: if bytes.len() >= 512 && matches!(&bytes[257..263], b"ustar\0" | b"ustar ") {
708삭제: return Ok(Catalog {
709삭제: format: Format::TarGzip,
710삭제: members: tar(&bytes, limits, decode, check)?,
711삭제: });
712삭제: }
713삭제: let len = bytes.len() as u64;
714삭제: return Ok(Catalog {
715삭제: format: Format::Gzip,
716삭제: members: vec![Member {
717삭제: entry: Entry {
718삭제: entry_id: 0,
719삭제: name: "GZip stream".to_owned(),
720삭제: kind: EntryKind::File,
721삭제: size: len,
722삭제: compressed_size: input.len() as u64,
723삭제: encrypted: false,
724삭제: },
725삭제: data: if decode { bytes } else { Vec::new() },
726삭제: }],
727삭제: });
728삭제: }
729삭제: if input.len() >= 512 {
730삭제: return Ok(Catalog {
731삭제: format: Format::Tar,
732삭제: members: tar(input, limits, decode, check)?,
733삭제: });
734삭제: }
735삭제: Err(ErrorCode::UnsupportedFormat)
736삭제: }
737256fn deflate(
738257 input: &[u8],
739258 limit: u64,
수정experiments/rust-archive-worker/src/crypto.rs+0-53
@@ -44,28 +44,6 @@ fn authenticate(
4444 }
4545 Ok(mac)
4646}
47삭제: pub(crate) fn aes_decrypt(
48삭제: packed: &[u8],
49삭제: password: &[u8],
50삭제: check: &mut impl crate::resources::Monitor,
51삭제: ) -> Result<Zeroizing<Vec<u8>>> {
52삭제: if packed.len() < 28 {
53삭제: return Err(ErrorCode::Integrity);
54삭제: }
55삭제: check.check()?;
56삭제: let key = keys(password, &packed[..16]);
57삭제: if !bool::from(key[64..].ct_eq(&packed[16..18])) {
58삭제: return Err(ErrorCode::WrongPassword);
59삭제: }
60삭제: let end = packed.len() - 10;
61삭제: // 인증이 성공하기 전에는 복호화나 압축 해제를 시작하지 않음.
62삭제: authenticate(&key[32..64], &packed[18..end], check)?
63삭제: .verify_truncated_left(&packed[end..])
64삭제: .map_err(|_| ErrorCode::Integrity)?;
65삭제: let mut bytes = Zeroizing::new(packed[18..end].to_vec());
66삭제: ctr(&mut bytes, &key[..32], check)?;
67삭제: Ok(bytes)
68삭제: }
6947pub(crate) fn aes_encrypt(
7048 packed: &[u8],
7149 password: &[u8],
@@ -134,37 +112,6 @@ const CRC_TABLE: [u32; 256] = {
134112 }
135113 table
136114};
137삭제: pub(crate) fn zipcrypto_decrypt(
138삭제: packed: &[u8],
139삭제: password: &[u8],
140삭제: verifier: u8,
141삭제: check: &mut impl crate::resources::Monitor,
142삭제: ) -> Result<Zeroizing<Vec<u8>>> {
143삭제: if packed.len() < 12 {
144삭제: return Err(ErrorCode::Integrity);
145삭제: }
146삭제: let mut key = Zeroizing::new([0x12345678u32, 0x23456789, 0x34567890]);
147삭제: for &byte in password {
148삭제: zip_update(&mut key, byte);
149삭제: }
150삭제: let mut out = Zeroizing::new(Vec::with_capacity(packed.len() - 12));
151삭제: for (index, &byte) in packed.iter().enumerate() {
152삭제: if index % 65536 == 0 {
153삭제: check.check()?;
154삭제: }
155삭제: let temp = key[2] | 2;
156삭제: let plain = byte ^ ((temp.wrapping_mul(temp ^ 1) >> 8) as u8);
157삭제: zip_update(&mut key, plain);
158삭제: if index == 11 && plain != verifier {
159삭제: return Err(ErrorCode::WrongPassword);
160삭제: }
161삭제: if index >= 12 {
162삭제: out.push(plain);
163삭제: }
164삭제: }
165삭제: Ok(out)
166삭제: }
167삭제:
168115pub(crate) enum Decryptor {
169116 Plain,
170117 Zip(Zeroizing<[u32; 3]>),
수정experiments/rust-archive-worker/src/lib.rs+1-0
@@ -17,4 +17,5 @@ mod split_seven_zip;
1717mod spool;
1818mod streaming;
1919pub mod wire;
20추가: mod zip_extra;
2021mod zip_recovery;
수정experiments/rust-archive-worker/src/seven_zip.rs+0-30
@@ -773,33 +773,3 @@ pub(crate) fn open_selected(
773773 data,
774774 })
775775}
776삭제: pub(crate) fn parse(
777삭제: input: &[u8],
778삭제: limits: Limits,
779삭제: decode: bool,
780삭제: check: &mut impl crate::resources::Monitor,
781삭제: ) -> Result<Vec<Member>> {
782삭제: use std::io::{Read, Seek, SeekFrom, Write};
783삭제: let mut source = crate::spool::temporary()?;
784삭제: crate::space::ensure(&source, input.len() as u64)?;
785삭제: source.write_all(input).map_err(crate::space::io_error)?;
786삭제: let mut catalog = open(&mut source, input.len() as u64, limits, decode, check)?;
787삭제: if decode {
788삭제: for (member, offset) in catalog.members.iter_mut().zip(catalog.offsets) {
789삭제: catalog
790삭제: .data
791삭제: .seek(SeekFrom::Start(offset))
792삭제: .map_err(crate::space::io_error)?;
793삭제: member
794삭제: .data
795삭제: .try_reserve_exact(member.entry.size as usize)
796삭제: .map_err(|_| ErrorCode::Limit)?;
797삭제: (&mut catalog.data)
798삭제: .take(member.entry.size)
799삭제: .read_to_end(&mut member.data)
800삭제: .map_err(crate::space::io_error)?;
801삭제: crate::resources::completed(Ok(()), check)?;
802삭제: }
803삭제: }
804삭제: Ok(catalog.members)
805삭제: }
수정experiments/rust-archive-worker/src/streaming.rs+9-75
@@ -3,6 +3,7 @@ use crate::{
33 crypto,
44 protocol::*,
55 spool,
6추가: zip_extra::{self, Policy, disk_start, expanded, large_value, local_sizes},
67};
78use std::{
89 fs::File,
@@ -357,77 +358,6 @@ struct Packed {
357358 aes: bool,
358359}
359360
360삭제: fn extra(bytes: &[u8]) -> Result<(Option<archive::AesExtra>, Option<Vec<u8>>)> {
361삭제: let mut at = 0;
362삭제: let mut aes = Vec::new();
363삭제: let mut large = None;
364삭제: while at < bytes.len() {
365삭제: if bytes.len() - at < 4 {
366삭제: return Err(ErrorCode::Integrity);
367삭제: }
368삭제: let tag = u16at(bytes, at);
369삭제: let len = u16at(bytes, at + 2) as usize;
370삭제: let end = at + 4 + len;
371삭제: if end > bytes.len() {
372삭제: return Err(ErrorCode::Integrity);
373삭제: }
374삭제: if tag == 1 {
375삭제: if large.is_some() {
376삭제: return Err(ErrorCode::Integrity);
377삭제: }
378삭제: large = Some(bytes[at + 4..end].to_vec());
379삭제: } else {
380삭제: aes.extend_from_slice(&bytes[at..end]);
381삭제: }
382삭제: at = end;
383삭제: }
384삭제: Ok((archive::aes_extra(&aes)?, large))
385삭제: }
386삭제: fn large_value(value: u32, extra: &mut &[u8]) -> Result<u64> {
387삭제: if value != u32::MAX {
388삭제: return Ok(value as u64);
389삭제: }
390삭제: if extra.len() < 8 {
391삭제: return Err(ErrorCode::Integrity);
392삭제: }
393삭제: let result = u64at(extra, 0);
394삭제: *extra = &extra[8..];
395삭제: Ok(result)
396삭제: }
397삭제: fn expanded(value: u64, maximum: u64, large: u64) -> Result<u64> {
398삭제: if value == maximum || value == large {
399삭제: Ok(large)
400삭제: } else {
401삭제: Err(ErrorCode::Integrity)
402삭제: }
403삭제: }
404삭제: fn disk_start(value: u16, extra: &mut &[u8]) -> Result<u32> {
405삭제: if value != u16::MAX {
406삭제: return Ok(value as u32);
407삭제: }
408삭제: if extra.len() < 4 {
409삭제: return Err(ErrorCode::Integrity);
410삭제: }
411삭제: let result = u32at(extra, 0);
412삭제: *extra = &extra[4..];
413삭제: Ok(result)
414삭제: }
415삭제: fn local_sizes(size: u32, compressed: u32, extra: Option<&[u8]>) -> Result<(u64, u64)> {
416삭제: if let Some(extra) = extra {
417삭제: // 로컬 ZIP64 추가 필드에는 두 크기가 함께 들어감.
418삭제: if extra.len() < 16 {
419삭제: return Err(ErrorCode::Integrity);
420삭제: }
421삭제: Ok((
422삭제: expanded(size as u64, u32::MAX as u64, u64at(extra, 0))?,
423삭제: expanded(compressed as u64, u32::MAX as u64, u64at(extra, 8))?,
424삭제: ))
425삭제: } else if size == u32::MAX || compressed == u32::MAX {
426삭제: Err(ErrorCode::Integrity)
427삭제: } else {
428삭제: Ok((size as u64, compressed as u64))
429삭제: }
430삭제: }
431361fn descriptor_size(
432362 bytes: &[u8],
433363 crc: u32,
@@ -572,10 +502,12 @@ fn zip(
572502 }
573503 let raw = bytes(source, cursor + 46, nn as usize)?;
574504 let central_extra = bytes(source, cursor + 46 + nn, ne as usize)?;
575삭제: let (aes, large) = extra(&central_extra)?;
505추가: let parsed_extra = zip_extra::parse(&central_extra, Policy::Streaming)?;
506추가: let aes = parsed_extra.aes;
507추가: let large = parsed_extra.zip64;
576508 let name = archive::zip_name(&raw, flags, &central_extra)?;
577509 let name = name.as_str();
578삭제: let mut large = large.as_deref().unwrap_or(&[]);
510추가: let mut large = large.unwrap_or(&[]);
579511 let size = large_value(u32at(&h, 24), &mut large)?;
580512 let compressed = large_value(u32at(&h, 20), &mut large)?;
581513 let local = large_value(u32at(&h, 42), &mut large)?;
@@ -653,7 +585,9 @@ fn zip(
653585 if bytes(source, local + 30, ln as usize)? != raw {
654586 return Err(ErrorCode::Integrity);
655587 }
656삭제: let (local_aes, local_large) = extra(&bytes(source, local + 30 + ln, le as usize)?)?;
588추가: let local_extra = bytes(source, local + 30 + ln, le as usize)?;
589추가: let parsed_local = zip_extra::parse(&local_extra, Policy::Streaming)?;
590추가: let (local_aes, local_large) = (parsed_local.aes, parsed_local.zip64);
657591 if local_aes != aes || local_large.as_ref().is_some_and(|values| values.len() < 16) {
658592 return Err(ErrorCode::Integrity);
659593 }
@@ -664,7 +598,7 @@ fn zip(
664598 || local_large.is_some();
665599 if flags & 8 == 0 {
666600 let (local_size, local_compressed) =
667삭제: local_sizes(u32at(&lh, 22), u32at(&lh, 18), local_large.as_deref())?;
601추가: local_sizes(u32at(&lh, 22), u32at(&lh, 18), local_large)?;
668602 if u32at(&lh, 14) != crc || local_size != size || local_compressed != compressed {
669603 return Err(ErrorCode::Integrity);
670604 }
추가experiments/rust-archive-worker/src/zip_extra.rs+149-0
@@ -0,0 +1,149 @@
1추가: use crate::protocol::ErrorCode;
2추가:
3추가: type Result<T> = std::result::Result<T, ErrorCode>;
4추가:
5추가: #[derive(Clone, Copy, PartialEq, Eq)]
6추가: pub(crate) enum Policy {
7추가: Streaming,
8추가: Recovery,
9추가: Names,
10추가: }
11추가:
12추가: #[derive(Clone, Copy, Debug, PartialEq, Eq)]
13추가: pub(crate) struct AesExtra {
14추가: pub version: u16,
15추가: pub method: u16,
16추가: }
17추가:
18추가: #[derive(Default, Debug)]
19추가: pub(crate) struct Extra<'a> {
20추가: pub aes: Option<AesExtra>,
21추가: pub zip64: Option<&'a [u8]>,
22추가: pub unicode: Option<&'a [u8]>,
23추가: }
24추가:
25추가: fn u16at(bytes: &[u8], at: usize) -> u16 {
26추가: u16::from_le_bytes(bytes[at..at + 2].try_into().unwrap())
27추가: }
28추가: fn u32at(bytes: &[u8], at: usize) -> u32 {
29추가: u32::from_le_bytes(bytes[at..at + 4].try_into().unwrap())
30추가: }
31추가: fn u64at(bytes: &[u8], at: usize) -> u64 {
32추가: u64::from_le_bytes(bytes[at..at + 8].try_into().unwrap())
33추가: }
34추가:
35추가: fn aes(value: &[u8]) -> Result<AesExtra> {
36추가: if value.len() < 7 {
37추가: return Err(ErrorCode::Integrity);
38추가: }
39추가: let version = u16at(value, 0);
40추가: let method = u16at(value, 5);
41추가: if !matches!(version, 1 | 2)
42추가: || &value[2..4] != b"AE"
43추가: || value[4] != 3
44추가: || !matches!(method, 0 | 8)
45추가: {
46추가: return Err(ErrorCode::UnsupportedFeature);
47추가: }
48추가: Ok(AesExtra { version, method })
49추가: }
50추가:
51추가: pub(crate) fn parse(bytes: &[u8], policy: Policy) -> Result<Extra<'_>> {
52추가: let mut found = Extra::default();
53추가: let mut deferred_aes = None;
54추가: let mut duplicate_aes = false;
55추가: let mut at = 0;
56추가: while at < bytes.len() {
57추가: if bytes.len() - at < 4 {
58추가: return Err(ErrorCode::Integrity);
59추가: }
60추가: let tag = u16at(bytes, at);
61추가: let length = u16at(bytes, at + 2) as usize;
62추가: // 복구 경로는 확장 크기와 강한 암호화를 해석하지 않음.
63추가: if policy == Policy::Recovery && matches!(tag, 1 | 0x0017 | 0x0018) {
64추가: return Err(ErrorCode::UnsupportedFeature);
65추가: }
66추가: let end = at.checked_add(4 + length).ok_or(ErrorCode::Integrity)?;
67추가: let value = bytes.get(at + 4..end).ok_or(ErrorCode::Integrity)?;
68추가: match (policy, tag) {
69추가: (Policy::Streaming, 1) => {
70추가: if found.zip64.replace(value).is_some() {
71추가: return Err(ErrorCode::Integrity);
72추가: }
73추가: }
74추가: (Policy::Streaming, 0x9901) => {
75추가: if deferred_aes.is_some() {
76추가: duplicate_aes = true;
77추가: } else {
78추가: deferred_aes = Some(value);
79추가: }
80추가: }
81추가: (Policy::Names, 0x7075) => {
82추가: if found.unicode.is_some() || length < 5 {
83추가: return Err(ErrorCode::Integrity);
84추가: }
85추가: found.unicode = Some(value);
86추가: }
87추가: _ => {}
88추가: }
89추가: at = end;
90추가: }
91추가: // 스트리밍은 전체 필드 경계를 확인한 뒤 AES 지원 여부를 판단함.
92추가: if let Some(value) = deferred_aes {
93추가: found.aes = Some(aes(value)?);
94추가: if duplicate_aes {
95추가: return Err(ErrorCode::Integrity);
96추가: }
97추가: }
98추가: Ok(found)
99추가: }
100추가:
101추가: pub(crate) fn large_value(value: u32, extra: &mut &[u8]) -> Result<u64> {
102추가: if value != u32::MAX {
103추가: return Ok(value as u64);
104추가: }
105추가: if extra.len() < 8 {
106추가: return Err(ErrorCode::Integrity);
107추가: }
108추가: let result = u64at(extra, 0);
109추가: *extra = &extra[8..];
110추가: Ok(result)
111추가: }
112추가: pub(crate) fn expanded(value: u64, maximum: u64, large: u64) -> Result<u64> {
113추가: if value == maximum || value == large {
114추가: Ok(large)
115추가: } else {
116추가: Err(ErrorCode::Integrity)
117추가: }
118추가: }
119추가: pub(crate) fn disk_start(value: u16, extra: &mut &[u8]) -> Result<u32> {
120추가: if value != u16::MAX {
121추가: return Ok(value as u32);
122추가: }
123추가: if extra.len() < 4 {
124추가: return Err(ErrorCode::Integrity);
125추가: }
126추가: let result = u32at(extra, 0);
127추가: *extra = &extra[4..];
128추가: Ok(result)
129추가: }
130추가: pub(crate) fn local_sizes(size: u32, compressed: u32, extra: Option<&[u8]>) -> Result<(u64, u64)> {
131추가: if let Some(extra) = extra {
132추가: // 로컬 ZIP64 추가 필드에는 두 크기가 함께 들어감.
133추가: if extra.len() < 16 {
134추가: return Err(ErrorCode::Integrity);
135추가: }
136추가: Ok((
137추가: expanded(size as u64, u32::MAX as u64, u64at(extra, 0))?,
138추가: expanded(compressed as u64, u32::MAX as u64, u64at(extra, 8))?,
139추가: ))
140추가: } else if size == u32::MAX || compressed == u32::MAX {
141추가: Err(ErrorCode::Integrity)
142추가: } else {
143추가: Ok((size as u64, compressed as u64))
144추가: }
145추가: }
146추가:
147추가: #[cfg(test)]
148추가: #[path = "../../../tests/rust-archive-worker/zip_extra.rs"]
149추가: mod tests;
수정experiments/rust-archive-worker/src/zip_recovery.rs+2-20
@@ -38,24 +38,6 @@ fn bytes(source: &mut File, offset: u64, size: usize, end: u64) -> Result<Vec<u8
3838 io(source.read_exact(&mut data))?;
3939 Ok(data)
4040}
41삭제: fn extra(data: &[u8]) -> Result<()> {
42삭제: let mut at = 0;
43삭제: while at < data.len() {
44삭제: if data.len() - at < 4 {
45삭제: return Err(ErrorCode::Integrity);
46삭제: }
47삭제: let tag = u16at(data, at);
48삭제: let size = u16at(data, at + 2) as usize;
49삭제: if matches!(tag, 1 | 0x0017 | 0x0018) {
50삭제: return Err(ErrorCode::UnsupportedFeature);
51삭제: }
52삭제: at = at
53삭제: .checked_add(4 + size)
54삭제: .filter(|n| *n <= data.len())
55삭제: .ok_or(ErrorCode::Integrity)?;
56삭제: }
57삭제: Ok(())
58삭제: }
5941struct Candidate {
6042 finding: RecoveryEntry,
6143 start: u64,
@@ -438,7 +420,7 @@ fn central(
438420 charge(&mut metadata, nn, ne, check)?;
439421 let raw = bytes(source, at + 46, nn, cd_end)?;
440422 let ext = bytes(source, at + 46 + nn as u64, ne, cd_end)?;
441삭제: extra(&ext)?;
423추가: crate::zip_extra::parse(&ext, crate::zip_extra::Policy::Recovery)?;
442424 let (size, packed) = declared(u32at(&h, 24), u32at(&h, 20))?;
443425 let unix_kind = (u32at(&h, 38) >> 16) & 0xf000;
444426 let kind = match unix_kind {
@@ -579,7 +561,7 @@ fn local(
579561 }
580562 let raw = bytes(source, at + 30, nn, len)?;
581563 let ext = bytes(source, at + 30 + nn as u64, ne, len)?;
582삭제: extra(&ext)?;
564추가: crate::zip_extra::parse(&ext, crate::zip_extra::Policy::Recovery)?;
583565 let kind = if raw.ends_with(b"/") {
584566 EntryKind::Directory
585567 } else {
수정tests/ci/README.md+1-0
@@ -17,6 +17,7 @@ python3 tests/ci/run_rust.py local --job rust-local
1717- 추적된 fixture를 Git blob과 대조합니다. Windows checkout 시 core.autocrlf=false를 사용해야 하며 기대값의 바이트를 바꾸지 않습니다.
1818- 개별 단계는 `build`, `test`, `cross-build`로 실행할 수 있습니다. 한 crate가 실패해도 다른 crate 결과를 수집합니다.
1919- GUI 앱은 컴파일하며 실제 화면 시나리오는 실행하지 않습니다. C# 시험과 역사적 hash 검사는 포함하지 않습니다.
20추가: - Linux 작업자의 작은 임시 공간 시험은 기본 실행에 포함합니다. 자식 프로세스에만 적용한 LD_PRELOAD 보조 코드로 2MiB 공유 용량, 부분 쓰기와 ENOSPC 및 핸들 종료 후 공간 반환을 재현합니다. 커널 tmpfs를 직접 마운트한 실기 검증은 아닙니다.
2021
2122## 출시 전 Windows 실기 확인
2223
수정tests/rust-archive-worker/folder_inputs.rs+1-1
@@ -149,7 +149,7 @@ fn empty_root_folder_is_preserved() {
149149 let events = execute(start);
150150 assert_eq!(terminal(&events).outcome, Outcome::Completed, "{events:?}");
151151 let bytes = fs::read(s.0.join("created.zip")).unwrap();
152삭제: let catalog = archive::parse(&bytes, Limits::default(), true, &mut || Ok(())).unwrap();
152추가: let catalog = worker_catalog(&bytes, Limits::default(), true, None).unwrap();
153153 assert_eq!(catalog.members.len(), 1);
154154 assert_eq!(catalog.members[0].entry.kind, EntryKind::Directory);
155155 assert_eq!(catalog.members[0].entry.name, "documents");
수정tests/rust-archive-worker/guarded.rs+1-1
@@ -828,7 +828,7 @@ fn created_empty_files_and_directories_refresh_idle_deadline() {
828828 assert_eq!(terminal(&events).publication, Publication::Complete);
829829 assert_eq!(terminal(&events).created_count, 1);
830830 let bytes = fs::read(s.0.join("new.zip")).unwrap();
831삭제: let parsed = archive::parse(&bytes, Limits::default(), true, &mut || Ok(())).unwrap();
831추가: let parsed = worker_catalog(&bytes, Limits::default(), true, None).unwrap();
832832 assert_eq!(parsed.members.len(), 37);
833833 assert!(parsed.members.iter().any(|member| {
834834 member.entry.name == "source" && member.entry.kind == EntryKind::Directory
수정tests/rust-archive-worker/main.rs+19-44
@@ -10,17 +10,21 @@ use zipelo_archive_worker::{
1010 protocol::*,
1111 wire::{Reader, Writer},
1212};
13추가: mod real_catalog;
14추가: use real_catalog::worker_catalog;
15추가:
1316static NEXT: AtomicU64 = AtomicU64::new(0);
1417struct Scratch(PathBuf);
1518impl Scratch {
1619 fn new() -> Self {
17삭제: let path = PathBuf::from(std::env::var_os("ZIPELO_TEST_WORK_DIR").expect("runner 작업 경로 필요"))
18삭제: .join("fixtures/rust-archive-worker")
19삭제: .join(format!(
20삭제: "{}-{}",
21삭제: std::process::id(),
22삭제: NEXT.fetch_add(1, Ordering::Relaxed)
23삭제: ));
20추가: let path =
21추가: PathBuf::from(std::env::var_os("ZIPELO_TEST_WORK_DIR").expect("runner 작업 경로 필요"))
22추가: .join("fixtures/rust-archive-worker")
23추가: .join(format!(
24추가: "{}-{}",
25추가: std::process::id(),
26추가: NEXT.fetch_add(1, Ordering::Relaxed)
27추가: ));
2428 fs::create_dir_all(path.parent().unwrap()).unwrap();
2529 let builder = fs::DirBuilder::new();
2630 #[cfg(unix)]
@@ -414,7 +418,7 @@ fn create_store_and_deflate_zip() {
414418 });
415419 assert_eq!(terminal(&e).outcome, Outcome::Completed, "{e:?}");
416420 let bytes = fs::read(s.0.join("result.zip")).unwrap();
417삭제: let parsed = archive::parse(&bytes, Limits::default(), true, &mut || Ok(())).unwrap();
421추가: let parsed = worker_catalog(&bytes, Limits::default(), true, None).unwrap();
418422 assert_eq!(parsed.members[0].data, PAYLOAD);
419423 }
420424}
@@ -723,15 +727,7 @@ fn shallow_zip_parent_metadata_is_bounded() {
723727 .iter()
724728 .all(|n| n.split('/').count() <= archive::MAX_PATH_DEPTH)
725729 );
726삭제: assert!(
727삭제: archive::parse(
728삭제: &path_fixture_zip(&names),
729삭제: Limits::default(),
730삭제: false,
731삭제: &mut || Ok(())
732삭제: )
733삭제: .is_ok()
734삭제: );
730추가: assert!(worker_catalog(&path_fixture_zip(&names), Limits::default(), false, None).is_ok());
735731 assert_metadata_limit(&names);
736732}
737733
@@ -749,7 +745,7 @@ fn aggregate_archive_name_metadata_is_bounded() {
749745 let bytes = path_fixture_zip(&names);
750746 assert!((bytes.len() as u64) < Limits::default().input);
751747 assert!(matches!(
752삭제: archive::parse(&bytes, Limits::default(), false, &mut || Ok(())),
748추가: worker_catalog(&bytes, Limits::default(), false, None),
753749 Err(ErrorCode::Limit)
754750 ));
755751 assert_metadata_limit(&names);
@@ -787,7 +783,7 @@ fn zero_payload_gzip_is_not_tar() {
787783 for length in [512, 1024, 1536] {
788784 let scratch = Scratch::new();
789785 let bytes = zeros_gzip(length);
790삭제: let parsed = archive::parse(&bytes, Limits::default(), true, &mut || Ok(())).unwrap();
786추가: let parsed = worker_catalog(&bytes, Limits::default(), true, None).unwrap();
791787 assert_eq!(parsed.format, Format::Gzip);
792788 let events = extract(
793789 &scratch,
@@ -1160,14 +1156,7 @@ fn empty_aes_members_and_random_salts_round_trip() {
11601156 )
11611157 .unwrap();
11621158 assert_ne!(a, b);
1163삭제: let decoded = archive::parse_with_password(
1164삭제: &a,
1165삭제: Limits::default(),
1166삭제: true,
1167삭제: Some(TEST_PASSWORD),
1168삭제: &mut || Ok(()),
1169삭제: )
1170삭제: .unwrap();
1159추가: let decoded = worker_catalog(&a, Limits::default(), true, Some(TEST_PASSWORD)).unwrap();
11711160 assert!(decoded.members[0].data.is_empty());
11721161}
11731162
@@ -1230,7 +1219,7 @@ fn seven_zip_lzma_lzma2_and_copy_interoperate() {
12301219 "libarchive-lzma2.7z",
12311220 ] {
12321221 let bytes = seven_fixture(name);
1233삭제: let catalog = archive::parse(&bytes, Limits::default(), true, &mut || Ok(()))
1222추가: let catalog = worker_catalog(&bytes, Limits::default(), true, None)
12341223 .unwrap_or_else(|e| panic!("{name}: {e:?}"));
12351224 assert_eq!(catalog.format, Format::SevenZip);
12361225 assert_eq!(catalog.members[0].data, SEVEN_PAYLOAD.repeat(100), "{name}");
@@ -1251,7 +1240,7 @@ fn seven_zip_lzma_lzma2_and_copy_interoperate() {
12511240fn seven_zip_encoded_header_solid_and_empty_entries() {
12521241 let s = Scratch::new();
12531242 let bytes = seven_fixture("encoded-solid.7z");
1254삭제: let catalog = archive::parse(&bytes, Limits::default(), false, &mut || Ok(())).unwrap();
1243추가: let catalog = worker_catalog(&bytes, Limits::default(), false, None).unwrap();
12551244 assert_eq!(catalog.members.len(), 4);
12561245 let events = extract(&s, &bytes, None, Selection::All, None, Limits::default());
12571246 assert_eq!(terminal(&events).outcome, Outcome::Completed, "{events:?}");
@@ -1268,7 +1257,7 @@ fn seven_zip_encoded_header_solid_and_empty_entries() {
12681257fn seven_zip_long_matches_and_lzma2_chunks() {
12691258 for name in ["long-match.7z", "lzma2-chunks.7z"] {
12701259 let bytes = seven_fixture(name);
1271삭제: let catalog = archive::parse(&bytes, Limits::default(), true, &mut || Ok(()))
1260추가: let catalog = worker_catalog(&bytes, Limits::default(), true, None)
12721261 .unwrap_or_else(|e| panic!("{name}: {e:?}"));
12731262 if name == "long-match.7z" {
12741263 assert_eq!(catalog.members[0].data, SEVEN_PAYLOAD.repeat(10000));
@@ -1445,20 +1434,6 @@ fn seven_zip_limits_truncation_and_existing_files_are_preserved() {
14451434 assert_eq!(fs::read_dir(s.0.join("output")).unwrap().count(), 0);
14461435}
14471436#[test]
1448삭제: fn seven_zip_parser_honors_cancellation_checkpoints() {
1449삭제: let bytes = seven_fixture("long-match.7z");
1450삭제: let mut calls = 0;
1451삭제: let result = archive::parse(&bytes, Limits::default(), true, &mut || {
1452삭제: calls += 1;
1453삭제: if calls >= 5 {
1454삭제: Err(ErrorCode::None)
1455삭제: } else {
1456삭제: Ok(())
1457삭제: }
1458삭제: });
1459삭제: assert!(matches!(result, Err(ErrorCode::None)));
1460삭제: }
1461삭제: #[test]
14621437fn pr64_malicious_corpus_is_rejected_without_writes() {
14631438 let root = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
14641439 .join("../../tests/malicious-archive-fixtures/fixtures");
추가tests/rust-archive-worker/real_catalog.rs+76-0
@@ -0,0 +1,76 @@
1추가: use super::*;
2추가:
3추가: pub(super) fn worker_catalog(
4추가: bytes: &[u8],
5추가: limits: Limits,
6추가: decode: bool,
7추가: password: Option<&[u8]>,
8추가: ) -> Result<archive::Catalog, ErrorCode> {
9추가: let scratch = Scratch::new();
10추가: fs::write(scratch.0.join("input"), bytes).unwrap();
11추가: let events = execute(Start {
12추가: action: Action::List {
13추가: archive: scratch.path("input"),
14추가: },
15추가: limits,
16추가: });
17추가: if terminal(&events).outcome != Outcome::Completed {
18추가: return Err(terminal(&events).error);
19추가: }
20추가: let list_id = events
21추가: .iter()
22추가: .find_map(|event| match event {
23추가: Message::ListEnd { list_id, .. } => Some(list_id.clone()),
24추가: _ => None,
25추가: })
26추가: .expect("작업자의 목록 식별자가 필요함");
27추가: let entries: Vec<_> = events
28추가: .into_iter()
29추가: .filter_map(|event| match event {
30추가: Message::Entry(entry) => Some(entry),
31추가: _ => None,
32추가: })
33추가: .collect();
34추가: if decode {
35추가: let builder = fs::DirBuilder::new();
36추가: #[cfg(unix)]
37추가: let mut builder = builder;
38추가: #[cfg(unix)]
39추가: {
40추가: use std::os::unix::fs::DirBuilderExt;
41추가: builder.mode(0o700);
42추가: }
43추가: builder.create(scratch.0.join("output")).unwrap();
44추가: let action = Action::Extract {
45추가: archive: scratch.path("input"),
46추가: destination: scratch.path("output"),
47추가: selection: Selection::All,
48추가: gzip_output_name: (list_id.format == Format::Gzip).then(|| entries[0].name.clone()),
49추가: list_id: Some(list_id.clone()),
50추가: };
51추가: let start = Start { action, limits };
52추가: let extracted = if let Some(password) = password {
53추가: interactive(start, |id, _, _| password_reply(id, password))
54추가: } else {
55추가: execute(start)
56추가: };
57추가: if terminal(&extracted).outcome != Outcome::Completed {
58추가: return Err(terminal(&extracted).error);
59추가: }
60추가: }
61추가: let members = entries
62추가: .into_iter()
63추가: .map(|entry| {
64추가: let data = if decode && entry.kind == EntryKind::File {
65추가: fs::read(scratch.0.join("output").join(&entry.name)).unwrap()
66추가: } else {
67추가: Vec::new()
68추가: };
69추가: archive::Member { entry, data }
70추가: })
71추가: .collect();
72추가: Ok(archive::Catalog {
73추가: format: list_id.format,
74추가: members,
75추가: })
76추가: }
수정tests/rust-archive-worker/recovery.rs+1-1
@@ -141,7 +141,7 @@ fn six_damaged_corpora_preserve_source_and_independent_expected_hashes() {
141141 assert_eq!(t.created_count, 1);
142142 assert_eq!(t.publication, Publication::Complete);
143143 let bytes = fs::read(s.0.join("recovered.zip")).unwrap();
144삭제: let catalog = archive::parse(&bytes, Limits::default(), true, &mut || Ok(())).unwrap();
144추가: let catalog = worker_catalog(&bytes, Limits::default(), true, None).unwrap();
145145 assert_eq!(catalog.members.len(), count);
146146 for member in &catalog.members {
147147 let (_, sha) = expected
수정tests/rust-archive-worker/recovery_checks.rs+30-0
@@ -410,3 +410,33 @@ fn central_zip64_fields_and_extra_remain_unsupported() {
410410 Err(ErrorCode::UnsupportedFeature)
411411 ));
412412}
413추가:
414추가: #[test]
415추가: fn central_rejects_extra_crossing_only_the_next_local_file() {
416추가: let mut damaged = include_bytes!("../zip-recovery-fixtures/control.zip").to_vec();
417추가: let cd = u32at(&damaged, damaged.len() - 6) as usize;
418추가: let second = cd
419추가: + 46
420추가: + u16at(&damaged, cd + 28) as usize
421추가: + u16at(&damaged, cd + 30) as usize
422추가: + u16at(&damaged, cd + 32) as usize;
423추가: let next_local = u32at(&damaged, second + 42) as usize;
424추가: let names_end = 30 + u16at(&damaged, 26) as usize;
425추가: let extra = next_local - names_end + 1;
426추가: let data_start = names_end + extra;
427추가: assert!(data_start > next_local);
428추가: assert!(data_start + u32at(&damaged, cd + 20) as usize <= cd);
429추가: damaged[28..30].copy_from_slice(&(extra as u16).to_le_bytes());
430추가: let scratch = Scratch::new(&damaged);
431추가: let mut source = File::open(scratch.path()).unwrap();
432추가: assert!(matches!(
433추가: central(
434추가: &mut source,
435추가: damaged.len() as u64,
436추가: Limits::default(),
437추가: &mut || Ok(())
438추가: ),
439추가: Err(ErrorCode::Integrity)
440추가: ));
441추가: assert_eq!(std::fs::read(scratch.path()).unwrap(), damaged);
442추가: }
수정tests/rust-archive-worker/resource_budget.rs+7-2
@@ -174,9 +174,14 @@ fn granted_entry_policy_keeps_independent_metadata_budget() {
174174 );
175175 let mut metadata = crate::archive::MetadataBudget::default();
176176 for _ in 0..32768 {
177삭제: metadata.charge("").unwrap();
177추가: metadata
178추가: .charge_with("", crate::archive::MetadataLimits::default())
179추가: .unwrap();
178180 }
179삭제: assert_eq!(metadata.charge(""), Err(ErrorCode::Limit));
181추가: assert_eq!(
182추가: metadata.charge_with("", crate::archive::MetadataLimits::default()),
183추가: Err(ErrorCode::Limit)
184추가: );
180185}
181186
182187#[test]
수정tests/rust-archive-worker/spool_fallback.rs+136-69
@@ -59,19 +59,31 @@ impl Case {
5959 self.archive_names.sort();
6060 (self.scratch.path("archive/split.7z.001"), originals)
6161 }
62추가: fn library(&self) -> PathBuf {
63추가: let library = self.scratch.0.join("location.so");
64추가: if !library.exists() {
65추가: assert!(
66추가: Command::new("cc")
67추가: .args(["-shared", "-fPIC", "-O2", "-Wall", "-Wextra", "-Werror"])
68추가: .arg(
69추가: PathBuf::from(env!("CARGO_MANIFEST_DIR"))
70추가: .join("../../tests/rust-archive-worker/spool_location_fault.c")
71추가: )
72추가: .args(["-ldl", "-o"])
73추가: .arg(&library)
74추가: .status()
75추가: .unwrap()
76추가: .success()
77추가: );
78추가: }
79추가: library
80추가: }
6281 fn run(&self, action: Action, phase: &str, mask: u8, named: bool) -> Vec<Message> {
6382 let s = &self.scratch;
6483 let mut command = s.worker();
6584 command
6685 .env("XDG_CACHE_HOME", s.0.join("cache"))
67삭제: .env(
68삭제: "TMPDIR",
69삭제: if phase == "real" {
70삭제: PathBuf::from(std::env::var_os("ZIPELO_SPOOL_REAL_TMP").unwrap())
71삭제: } else {
72삭제: s.0.join("system")
73삭제: },
74삭제: )
86추가: .env("TMPDIR", s.0.join("system"))
7587 .env("HOME", &s.0);
7688 if phase == "home" {
7789 command.env_remove("XDG_CACHE_HOME");
@@ -87,31 +99,14 @@ impl Case {
8799 },
88100 );
89101 }
90삭제: if phase != "real" {
91삭제: let library = s.0.join("location.so");
92삭제: if !library.exists() {
93삭제: assert!(
94삭제: Command::new("cc")
95삭제: .args(["-shared", "-fPIC", "-O2", "-Wall", "-Wextra", "-Werror"])
96삭제: .arg(
97삭제: PathBuf::from(env!("CARGO_MANIFEST_DIR"))
98삭제: .join("../../tests/rust-archive-worker/spool_location_fault.c")
99삭제: )
100삭제: .args(["-ldl", "-o"])
101삭제: .arg(&library)
102삭제: .status()
103삭제: .unwrap()
104삭제: .success()
105삭제: );
106삭제: }
107삭제: command
108삭제: .env("LD_PRELOAD", library)
109삭제: .env("ZIPELO_SPOOL_PHASE", phase)
110삭제: .env("ZIPELO_SPOOL_MASK", mask.to_string())
111삭제: .env("ZIPELO_SPOOL_TRACE", s.0.join("trace"));
112삭제: if named {
113삭제: command.env("ZIPELO_SPOOL_NAMED", "1");
114삭제: }
102추가: let library = self.library();
103추가: command
104추가: .env("LD_PRELOAD", library)
105추가: .env("ZIPELO_SPOOL_PHASE", phase)
106추가: .env("ZIPELO_SPOOL_MASK", mask.to_string())
107추가: .env("ZIPELO_SPOOL_TRACE", s.0.join("trace"));
108추가: if named {
109추가: command.env("ZIPELO_SPOOL_NAMED", "1");
115110 }
116111 let mut child = Running(
117112 command
@@ -689,45 +684,117 @@ fn source_change_during_direct_read_prevents_success() {
689684}
690685
691686#[test]
692삭제: #[ignore = "별도 VM의 작은 tmpfs 경로를 ZIPELO_SPOOL_REAL_TMP로 지정해야 함"]
693삭제: fn actual_tmpfs_quota_lists_and_previews_large_zip_and_seven_zip() {
694삭제: let path = PathBuf::from(std::env::var_os("ZIPELO_SPOOL_REAL_TMP").unwrap());
695삭제: let filesystem = Command::new("stat")
696삭제: .args(["-f", "-c", "%T"])
697삭제: .arg(&path)
687추가: fn small_temporary_quota_counts_closed_files_until_unlinked() {
688추가: let scratch = Scratch::new();
689추가: fs::create_dir(scratch.0.join("system")).unwrap();
690추가: let c = Case {
691추가: scratch,
692추가: archive_names: Vec::new(),
693추가: };
694추가: let library = c.library();
695추가: let probe = Command::new("python3")
696추가: .arg("-B")
697추가: .arg("-c")
698추가: .arg(
699추가: r#"
700추가: import errno, os, sys
701추가: from pathlib import Path
702추가: root = Path(sys.argv[1])
703추가: def assert_full(fd):
704추가: try:
705추가: os.write(fd, b"x")
706추가: except OSError as error:
707추가: assert error.errno == errno.ENOSPC
708추가: else:
709추가: raise AssertionError("임시 용량이 너무 일찍 반환됨")
710추가: a = os.open(root / "quota-a", os.O_CREAT | os.O_RDWR, 0o600)
711추가: b = os.open(root / "quota-b", os.O_CREAT | os.O_RDWR, 0o600)
712추가: duplicate = os.dup(a)
713추가: try:
714추가: assert os.write(a, bytes(1024 * 1024)) == 1024 * 1024
715추가: os.close(duplicate)
716추가: duplicate = -1
717추가: os.close(a)
718추가: a = -1
719추가: assert os.write(b, bytes(2 * 1024 * 1024)) == 1024 * 1024
720추가: try:
721추가: os.write(b, b"x")
722추가: except OSError as error:
723추가: assert error.errno == errno.ENOSPC
724추가: else:
725추가: raise AssertionError("닫힌 파일의 용량이 반환됨")
726추가: assert (root / "quota-a").stat().st_size == 1024 * 1024
727추가: os.link(root / "quota-a", root / "quota-alias")
728추가: (root / "quota-a").unlink()
729추가: assert_full(b)
730추가: (root / "quota-alias").unlink()
731추가: assert os.write(b, bytes(1024 * 1024)) == 1024 * 1024
732추가: duplicate = os.dup(b)
733추가: (root / "quota-b").unlink()
734추가: assert_full(b)
735추가: os.close(b)
736추가: b = -1
737추가: assert_full(duplicate)
738추가: os.close(duplicate)
739추가: duplicate = -1
740추가: b = os.open(root / "quota-b", os.O_CREAT | os.O_RDWR, 0o600)
741추가: assert os.write(b, bytes(2 * 1024 * 1024)) == 2 * 1024 * 1024
742추가: finally:
743추가: if duplicate >= 0:
744추가: os.close(duplicate)
745추가: if a >= 0:
746추가: os.close(a)
747추가: if b >= 0:
748추가: os.close(b)
749추가: for name in ["quota-a", "quota-b", "quota-alias"]:
750추가: (root / name).unlink(missing_ok=True)
751추가: "#,
752추가: )
753추가: .arg(c.scratch.0.join("system"))
754추가: .env("TMPDIR", c.scratch.0.join("system"))
755추가: .env("LD_PRELOAD", library)
756추가: .env("ZIPELO_SPOOL_PHASE", "tiny-tmpfs")
757추가: .env("ZIPELO_SPOOL_TRACE", c.scratch.0.join("trace"))
698758 .output()
699759 .unwrap();
700삭제: assert_eq!(
701삭제: String::from_utf8(filesystem.stdout).unwrap().trim(),
702삭제: "tmpfs"
760추가: assert!(
761추가: probe.status.success(),
762추가: "{}",
763추가: String::from_utf8_lossy(&probe.stderr)
703764 );
704삭제: let capacity = Command::new("stat")
705삭제: .args(["-f", "-c", "%S %b"])
706삭제: .arg(&path)
707삭제: .output()
708삭제: .unwrap();
709삭제: let fields: Vec<u64> = String::from_utf8(capacity.stdout)
710삭제: .unwrap()
711삭제: .split_whitespace()
712삭제: .map(|value| value.parse().unwrap())
713삭제: .collect();
714삭제: let bytes = fields[0] * fields[1];
715삭제: assert!(bytes > 0 && bytes < 16 * 1024 * 1024, "{bytes}");
716삭제: let probe = path.join("capacity-probe");
717삭제: let error = fs::write(&probe, vec![0; bytes as usize + 4096]).unwrap_err();
718삭제: assert_eq!(error.kind(), std::io::ErrorKind::StorageFull);
719삭제: fs::remove_file(probe).unwrap();
720삭제: let c = Case::new();
721삭제: for format in ["zip", "7z"] {
722삭제: c.assert_preview(format, "real", 0, false);
723삭제: }
724삭제: assert_eq!(fs::read_dir(path).unwrap().count(), 0);
725삭제: assert_eq!(
726삭제: fs::metadata(c.scratch.0.join("cache/zipelo"))
765추가: assert!(
766추가: fs::read_to_string(c.scratch.0.join("trace"))
727767 .unwrap()
728삭제: .permissions()
729삭제: .mode()
730삭제: & 0o777,
731삭제: 0o700
768추가: .contains('F')
732769 );
733770}
771추가:
772추가: #[test]
773추가: fn small_temporary_quota_lists_and_previews_large_zip_and_seven_zip() {
774추가: for named in [false, true] {
775추가: let c = Case::new();
776추가: for format in ["zip", "7z"] {
777추가: c.assert_preview(format, "tiny-tmpfs", 0, named);
778추가: }
779추가: assert!(
780추가: Command::new("python3")
781추가: .arg("-B")
782추가: .arg(
783추가: PathBuf::from(env!("CARGO_MANIFEST_DIR"))
784추가: .join("../../tests/rust-archive-worker/spool_fallback_cases.py")
785추가: )
786추가: .arg(&c.scratch.0)
787추가: .arg("non-solid")
788추가: .status()
789추가: .unwrap()
790추가: .success()
791추가: );
792추가: for format in ["zip", "7z"] {
793추가: c.assert_preview(format, "tiny-tmpfs", 3, named);
794추가: }
795추가: let trace = fs::read_to_string(c.scratch.0.join("trace")).unwrap();
796추가: assert!(trace.contains('2'), "{trace}");
797추가: assert_eq!(fs::read_dir(c.scratch.0.join("system")).unwrap().count(), 0);
798추가: c.clean();
799추가: }
800추가: }
수정tests/rust-archive-worker/spool_location_fault.c+94-0
@@ -1,5 +1,6 @@
11#define _GNU_SOURCE
22#include <dlfcn.h>
3추가: #include <dirent.h>
34#include <errno.h>
45#include <fcntl.h>
56#include <stdarg.h>
@@ -60,10 +61,83 @@ static void trace(int at) {
6061 close(fd);
6162 }
6263}
64추가: struct usage {
65추가: struct stat seen[256];
66추가: size_t count;
67추가: unsigned long long bytes;
68추가: };
69추가: static void count_file(struct usage *usage, const struct stat *value) {
70추가: if (!S_ISREG(value->st_mode)) return;
71추가: for (size_t i = 0; i < usage->count; i++) {
72추가: if (usage->seen[i].st_dev == value->st_dev
73추가: && usage->seen[i].st_ino == value->st_ino) return;
74추가: }
75추가: if (usage->count == 256) _exit(97);
76추가: usage->seen[usage->count++] = *value;
77추가: usage->bytes += value->st_size;
78추가: }
79추가: static void count_directory(DIR *directory, struct usage *usage, unsigned depth) {
80추가: if (depth > 64) _exit(97);
81추가: struct dirent *entry;
82추가: while ((entry = readdir(directory))) {
83추가: if (!strcmp(entry->d_name, ".") || !strcmp(entry->d_name, "..")) continue;
84추가: struct stat value;
85추가: if (fstatat(dirfd(directory), entry->d_name, &value, AT_SYMLINK_NOFOLLOW)) _exit(98);
86추가: count_file(usage, &value);
87추가: if (S_ISDIR(value.st_mode)) {
88추가: int fd = original_openat(dirfd(directory), entry->d_name,
89추가: O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC);
90추가: if (fd < 0) _exit(98);
91추가: DIR *child = fdopendir(fd);
92추가: if (!child) _exit(98);
93추가: count_directory(child, usage, depth + 1);
94추가: closedir(child);
95추가: }
96추가: }
97추가: }
98추가: static unsigned long long temporary_usage(void) {
99추가: struct usage usage = {0};
100추가: const char *root = getenv("TMPDIR");
101추가: if (!root) _exit(98);
102추가: DIR *directory = opendir(root);
103추가: if (!directory) _exit(98);
104추가: // 닫혀도 이름이 남은 파일은 계속 용량을 사용함.
105추가: count_directory(directory, &usage, 0);
106추가: closedir(directory);
107추가: directory = opendir("/proc/self/fd");
108추가: if (!directory) _exit(98);
109추가: struct dirent *entry;
110추가: // 이름이 지워진 열린 파일도 마지막 핸들을 닫기 전까지 집계함.
111추가: while ((entry = readdir(directory))) {
112추가: if (entry->d_name[0] == '.') continue;
113추가: int fd = atoi(entry->d_name);
114추가: char path[4096];
115추가: struct stat value;
116추가: if (descriptor(fd, path, sizeof(path)) == 2 && !fstat(fd, &value)) {
117추가: count_file(&usage, &value);
118추가: }
119추가: }
120추가: closedir(directory);
121추가: return usage.bytes;
122추가: }
123추가: static void exhausted(void) {
124추가: const char *path = getenv("ZIPELO_SPOOL_TRACE");
125추가: if (!path) return;
126추가: int fd = original_openat(AT_FDCWD, path, O_CREAT | O_WRONLY | O_APPEND, 0600);
127추가: if (fd >= 0) {
128추가: original_write(fd, "F", 1);
129추가: close(fd);
130추가: }
131추가: }
132추가: #define TEMPORARY_CAPACITY (2ULL * 1024 * 1024)
63133static int reject(int at, int flags) {
64134 if ((flags & O_TMPFILE) != O_TMPFILE && !(flags & O_CREAT)) return 0;
65135 trace(at);
66136 const char *phase = getenv("ZIPELO_SPOOL_PHASE");
137추가: if (affected(at) && at < 2 && phase && !strcmp(phase, "tiny-tmpfs")) {
138추가: errno = EDQUOT;
139추가: return 1;
140추가: }
67141 if (affected(at) && phase && (!strcmp(phase, "create") || !strcmp(phase, "denied"))) {
68142 errno = !strcmp(phase, "denied") ? EACCES : EDQUOT;
69143 return 1;
@@ -115,6 +189,20 @@ ssize_t write(int fd, const void *bytes, size_t count) {
115189 char path[4096];
116190 int at = descriptor(fd, path, sizeof(path));
117191 const char *phase = getenv("ZIPELO_SPOOL_PHASE");
192추가: if (phase && !strcmp(phase, "tiny-tmpfs") && at == 2) {
193추가: struct stat value;
194추가: off_t position = lseek(fd, 0, SEEK_CUR);
195추가: if (position < 0 || fstat(fd, &value)) _exit(96);
196추가: unsigned long long used = temporary_usage();
197추가: unsigned long long room = used < TEMPORARY_CAPACITY ? TEMPORARY_CAPACITY - used : 0;
198추가: unsigned long long end = (unsigned long long)value.st_size + room;
199추가: if ((unsigned long long)position >= end) {
200추가: exhausted();
201추가: errno = ENOSPC;
202추가: return -1;
203추가: }
204추가: if (count > end - position) count = end - position;
205추가: }
118206 int stage = phase && !strcmp(phase, "stage-write") && fd != snapshot_fd;
119207 if (affected(at) && phase && (stage || !strcmp(phase, "write")
120208 || !strcmp(phase, "changed") || !strcmp(phase, "io"))) {
@@ -140,6 +228,12 @@ int fstatvfs(int fd, struct statvfs *value) {
140228 value->f_frsize = 1;
141229 value->f_bavail = 65536;
142230 }
231추가: if (!result && at == 2 && phase && !strcmp(phase, "tiny-tmpfs")) {
232추가: unsigned long long used = temporary_usage();
233추가: value->f_frsize = 1;
234추가: value->f_blocks = TEMPORARY_CAPACITY;
235추가: value->f_bavail = value->f_bfree = used < TEMPORARY_CAPACITY ? TEMPORARY_CAPACITY - used : 0;
236추가: }
143237 return result;
144238}
145239
수정tests/rust-archive-worker/streaming_bounds.rs+24-0
@@ -122,3 +122,27 @@ fn descriptor_width_uses_sizes_and_crc() {
122122 );
123123 }
124124}
125추가:
126추가: #[test]
127추가: fn seven_zip_parser_honors_cancellation_checkpoints() {
128추가: let bytes = include_bytes!("fixtures/7z/long-match.7z");
129추가: let mut source = spool::temporary().unwrap();
130추가: source.write_all(bytes).unwrap();
131추가: let mut calls = 0;
132추가: let result = Catalog::open(
133추가: &mut source,
134추가: bytes.len() as u64,
135추가: Limits::default(),
136추가: true,
137추가: None,
138추가: &mut || {
139추가: calls += 1;
140추가: if calls >= 5 {
141추가: Err(ErrorCode::None)
142추가: } else {
143추가: Ok(())
144추가: }
145추가: },
146추가: );
147추가: assert!(matches!(result, Err(ErrorCode::None)));
148추가: }
추가tests/rust-archive-worker/zip_extra.rs+113-0
@@ -0,0 +1,113 @@
1추가: use super::*;
2추가:
3추가: fn field(tag: u16, value: &[u8]) -> Vec<u8> {
4추가: [
5추가: tag.to_le_bytes().as_slice(),
6추가: &(value.len() as u16).to_le_bytes(),
7추가: value,
8추가: ]
9추가: .concat()
10추가: }
11추가:
12추가: #[test]
13추가: fn truncated_headers_and_values_are_rejected_by_every_policy() {
14추가: for policy in [Policy::Streaming, Policy::Recovery, Policy::Names] {
15추가: for bytes in [vec![0], vec![0, 0], vec![0, 0, 0], vec![2, 0, 1, 0]] {
16추가: assert!(matches!(parse(&bytes, policy), Err(ErrorCode::Integrity)));
17추가: }
18추가: assert!(parse(&field(2, &[]), policy).is_ok());
19추가: }
20추가: }
21추가:
22추가: #[test]
23추가: fn zip64_is_borrowed_only_for_normal_streaming() {
24추가: let bytes = field(1, &[0; 16]);
25추가: assert_eq!(
26추가: parse(&bytes, Policy::Streaming).unwrap().zip64,
27추가: Some(&bytes[4..])
28추가: );
29추가: assert!(matches!(
30추가: parse(&bytes, Policy::Recovery),
31추가: Err(ErrorCode::UnsupportedFeature)
32추가: ));
33추가: assert!(matches!(
34추가: parse(
35추가: &[bytes.as_slice(), bytes.as_slice()].concat(),
36추가: Policy::Streaming
37추가: ),
38추가: Err(ErrorCode::Integrity)
39추가: ));
40추가: for tag in [1, 0x0017, 0x0018] {
41추가: assert!(matches!(
42추가: parse(&field(tag, &[]), Policy::Recovery),
43추가: Err(ErrorCode::UnsupportedFeature)
44추가: ));
45추가: }
46추가: }
47추가:
48추가: #[test]
49추가: fn aes_policy_keeps_support_and_duplicate_checks() {
50추가: let value = [2, 0, b'A', b'E', 3, 8, 0];
51추가: let bytes = field(0x9901, &value);
52추가: let policy = Policy::Streaming;
53추가: assert_eq!(
54추가: parse(&bytes, policy).unwrap().aes,
55추가: Some(AesExtra {
56추가: version: 2,
57추가: method: 8
58추가: })
59추가: );
60추가: assert!(matches!(
61추가: parse(&[bytes.as_slice(), bytes.as_slice()].concat(), policy),
62추가: Err(ErrorCode::Integrity)
63추가: ));
64추가: assert!(matches!(
65추가: parse(&field(0x9901, &value[..6]), policy),
66추가: Err(ErrorCode::Integrity)
67추가: ));
68추가: let mut unsupported = value;
69추가: unsupported[4] = 2;
70추가: assert!(matches!(
71추가: parse(&field(0x9901, &unsupported), policy),
72추가: Err(ErrorCode::UnsupportedFeature)
73추가: ));
74추가: assert!(parse(&bytes, Policy::Recovery).unwrap().aes.is_none());
75추가: }
76추가:
77추가: #[test]
78추가: fn unicode_and_aes_fields_can_share_the_same_extra() {
79추가: let bytes = [
80추가: field(0x7075, &[1, 0, 0, 0, 0]),
81추가: field(0x9901, &[2, 0, b'A', b'E', 3, 0, 0]),
82추가: ]
83추가: .concat();
84추가: assert_eq!(
85추가: parse(&bytes, Policy::Names).unwrap().unicode,
86추가: Some(&bytes[4..9])
87추가: );
88추가: assert!(parse(&bytes, Policy::Streaming).unwrap().aes.is_some());
89추가: assert!(matches!(
90추가: parse(&field(0x7075, &[0; 4]), Policy::Names),
91추가: Err(ErrorCode::Integrity)
92추가: ));
93추가: }
94추가:
95추가: #[test]
96추가: fn mixed_invalid_fields_keep_error_precedence() {
97추가: let unsupported_aes = field(0x9901, &[3, 0, b'A', b'E', 3, 0, 0]);
98추가: let duplicate_zip64 = [field(1, &[]), field(1, &[])].concat();
99추가: let extra = [unsupported_aes.as_slice(), duplicate_zip64.as_slice()].concat();
100추가: assert!(matches!(
101추가: parse(&extra, Policy::Streaming),
102추가: Err(ErrorCode::Integrity)
103추가: ));
104추가: let truncated = [unsupported_aes.as_slice(), &[2, 0, 1, 0]].concat();
105추가: assert!(matches!(
106추가: parse(&truncated, Policy::Streaming),
107추가: Err(ErrorCode::Integrity)
108추가: ));
109추가: assert!(matches!(
110추가: parse(&[1, 0, 8, 0], Policy::Recovery),
111추가: Err(ErrorCode::UnsupportedFeature)
112추가: ));
113추가: }
수정tests/rust-archive-worker/zip_names.rs+20-26
@@ -107,20 +107,11 @@ fn listed_names(bytes: &[u8]) -> std::result::Result<Vec<String>, ErrorCode> {
107107 .collect())
108108}
109109
110삭제: /// 스트리밍 목록과 메모리 파서가 같은 이름 또는 같은 오류를 내는지 확인함.
111삭제: fn names_agree(bytes: &[u8]) -> std::result::Result<Vec<String>, ErrorCode> {
112삭제: let streamed = listed_names(bytes);
113삭제: let parsed = archive::parse(bytes, Limits::default(), false, &mut || Ok(()))
114삭제: .map(|c| c.members.into_iter().map(|m| m.entry.name).collect());
115삭제: assert_eq!(streamed, parsed);
116삭제: streamed
117삭제: }
118삭제:
119110#[test]
120111fn infozip_utf8_names_without_flag_list_and_extract() {
121삭제: assert_eq!(names_agree(KOREAN).unwrap(), ["README.md", "회의록.txt"]);
112추가: assert_eq!(listed_names(KOREAN).unwrap(), ["README.md", "회의록.txt"]);
122113 assert_eq!(
123삭제: names_agree(KOREAN_TREE).unwrap(),
114추가: listed_names(KOREAN_TREE).unwrap(),
124115 ["README.md", "회의록.txt", "폴더", "폴더/메모.txt"]
125116 );
126117 for bytes in [KOREAN, KOREAN_TREE] {
@@ -149,7 +140,7 @@ fn infozip_multi_entry_zipcrypto_trees_list_and_extract() {
149140 (ZIPCRYPTO_ASCII_TREE, "docs/notes.txt"),
150141 (ZIPCRYPTO_KOREAN_TREE, "폴더/메모.txt"),
151142 ] {
152삭제: let names = names_agree(bytes).unwrap();
143추가: let names = listed_names(bytes).unwrap();
153144 assert!(names.iter().any(|n| n == file), "{names:?}");
154145 let s = Scratch::new();
155146 let events = interactive(encrypted_start(&s, bytes), |id, _, purpose| {
@@ -168,7 +159,7 @@ fn unicode_path_extra_is_used_only_when_its_crc_matches() {
168159 let cp949 = b"\xc8\xb8\xc0\xc7\xb7\xcf.txt";
169160 let extra = unicode_path(cp949, "회의록.txt");
170161 assert_eq!(
171삭제: names_agree(&single_entry_zip(cp949, 0, &extra, b"hi\n")).unwrap(),
162추가: listed_names(&single_entry_zip(cp949, 0, &extra, b"hi\n")).unwrap(),
172163 ["회의록.txt"]
173164 );
174165 let s = Scratch::new();
@@ -180,24 +171,24 @@ fn unicode_path_extra_is_used_only_when_its_crc_matches() {
180171 // CRC가 다른 확장 필드는 이름이 바뀐 뒤 남은 낡은 값이므로 무시함.
181172 let stale = unicode_path(b"old.txt", "회의록.txt");
182173 assert_eq!(
183삭제: names_agree(&single_entry_zip(b"new.txt", 0, &stale, b"hi\n")).unwrap(),
174추가: listed_names(&single_entry_zip(b"new.txt", 0, &stale, b"hi\n")).unwrap(),
184175 ["new.txt"]
185176 );
186177 let stale = unicode_path(b"other", "회의록.txt");
187178 assert_eq!(
188삭제: names_agree(&single_entry_zip(cp949, 0, &stale, b"hi\n")),
179추가: listed_names(&single_entry_zip(cp949, 0, &stale, b"hi\n")),
189180 Err(ErrorCode::UnsupportedFeature)
190181 );
191182 // UTF-8 플래그가 있으면 이름 자체가 UTF-8이므로 확장 필드를 보지 않음.
192183 let ignored = unicode_path("a.txt".as_bytes(), "b.txt");
193184 assert_eq!(
194삭제: names_agree(&single_entry_zip(b"a.txt", 0x0800, &ignored, b"hi\n")).unwrap(),
185추가: listed_names(&single_entry_zip(b"a.txt", 0x0800, &ignored, b"hi\n")).unwrap(),
195186 ["a.txt"]
196187 );
197188}
198189
199190fn assert_rejected_without_output(bytes: &[u8], error: ErrorCode) {
200삭제: assert_eq!(names_agree(bytes), Err(error));
191추가: assert_eq!(listed_names(bytes), Err(error));
201192 let s = Scratch::new();
202193 let events = extract(&s, bytes, None, Selection::All, None, Limits::default());
203194 let result = terminal(&events);
@@ -223,7 +214,10 @@ fn converted_names_colliding_with_other_paths_are_rejected_before_writes() {
223214 let first = b"first.txt";
224215 let second = b"second.txt";
225216 let original = stored_entries_zip(&[(first, 0, &[], b"first"), (second, 0, &[], b"second")]);
226삭제: assert_eq!(names_agree(&original).unwrap(), ["first.txt", "second.txt"]);
217추가: assert_eq!(
218추가: listed_names(&original).unwrap(),
219추가: ["first.txt", "second.txt"]
220추가: );
227221 for (first_name, second_name) in [
228222 ("회의록.txt", "회의록.txt"),
229223 ("폴더/Memo.txt", "폴더/memo.txt"),
@@ -236,7 +230,7 @@ fn converted_names_colliding_with_other_paths_are_rejected_before_writes() {
236230 (second.as_slice(), &second_extra, second_name),
237231 ] {
238232 let bytes = single_entry_zip(raw, 0, extra, b"hi\n");
239삭제: assert_eq!(names_agree(&bytes).unwrap(), [name]);
233추가: assert_eq!(listed_names(&bytes).unwrap(), [name]);
240234 }
241235 let bytes = stored_entries_zip(&[
242236 (first, 0, &first_extra, b"first"),
@@ -251,26 +245,26 @@ fn legacy_and_hostile_names_stay_rejected() {
251245 let cp949 = b"\xc8\xb8\xc0\xc7\xb7\xcf.txt";
252246 // 코드 페이지를 추측하지 않음.
253247 assert_eq!(
254삭제: names_agree(&single_entry_zip(cp949, 0, &[], b"hi\n")),
248추가: listed_names(&single_entry_zip(cp949, 0, &[], b"hi\n")),
255249 Err(ErrorCode::UnsupportedFeature)
256250 );
257251 // UTF-8 플래그와 맞지 않는 이름은 손상으로 봄.
258252 assert_eq!(
259삭제: names_agree(&single_entry_zip(cp949, 0x0800, &[], b"hi\n")),
253추가: listed_names(&single_entry_zip(cp949, 0x0800, &[], b"hi\n")),
260254 Err(ErrorCode::Integrity)
261255 );
262256 // 확장 필드로 들어온 이름도 같은 경로 검사를 거침.
263257 for hostile in ["../escape.txt", "/absolute.txt", "C:drive.txt", "CON.txt"] {
264258 let extra = unicode_path(b"safe.txt", hostile);
265259 assert_eq!(
266삭제: names_agree(&single_entry_zip(b"safe.txt", 0, &extra, b"hi\n")),
260추가: listed_names(&single_entry_zip(b"safe.txt", 0, &extra, b"hi\n")),
267261 Err(ErrorCode::UnsafePath),
268262 "{hostile}"
269263 );
270264 }
271265 for hostile in ["../회의록.txt", "폴더/../../x"] {
272266 assert_eq!(
273삭제: names_agree(&single_entry_zip(hostile.as_bytes(), 0, &[], b"hi\n")),
267추가: listed_names(&single_entry_zip(hostile.as_bytes(), 0, &[], b"hi\n")),
274268 Err(ErrorCode::UnsafePath),
275269 "{hostile}"
276270 );
@@ -280,20 +274,20 @@ fn legacy_and_hostile_names_stay_rejected() {
280274 let len = broken.len();
281275 broken[len - 1] = 0xff;
282276 assert_eq!(
283삭제: names_agree(&single_entry_zip(b"safe.txt", 0, &broken, b"hi\n")),
277추가: listed_names(&single_entry_zip(b"safe.txt", 0, &broken, b"hi\n")),
284278 Err(ErrorCode::Integrity)
285279 );
286280 let mut short = 0x7075u16.to_le_bytes().to_vec();
287281 short.extend([4, 0, 1, 0, 0, 0]);
288282 assert_eq!(
289삭제: names_agree(&single_entry_zip(b"safe.txt", 0, &short, b"hi\n")),
283추가: listed_names(&single_entry_zip(b"safe.txt", 0, &short, b"hi\n")),
290284 Err(ErrorCode::Integrity)
291285 );
292286 // APPNOTE 4.6.9에 따라 모르는 버전의 확장 필드는 무시함.
293287 let mut version = unicode_path(b"safe.txt", "x");
294288 version[4] = 2;
295289 assert_eq!(
296삭제: names_agree(&single_entry_zip(b"safe.txt", 0, &version, b"hi\n")).unwrap(),
290추가: listed_names(&single_entry_zip(b"safe.txt", 0, &version, b"hi\n")).unwrap(),
297291 ["safe.txt"]
298292 );
299293}