1use alloc::boxed::Box;
11use alloc::collections::{BTreeMap, VecDeque};
12use alloc::vec::Vec;
13
14use crate::Limits;
15use crate::error::{ArchiveError, Error, ErrorKind, Result};
16use crate::meta::{EntryKind, Timestamp, default_mode};
17use crate::metadata::{ArchivePath, Device, EntryMetadata, EntryTimes, Owner};
18use crate::protocol::{
19 ArchiveDecoder, ArchiveEncoder, Chunk, DecodeEvent, DecodeStep, EncodeCommand, EncodeStatus,
20 EncodeStep, EndOfInput, ProbeResult,
21};
22
23const NEWC_MAGIC: &[u8] = b"070701";
24const NEWC_CRC_MAGIC: &[u8] = b"070702";
25const ODC_MAGIC: &[u8] = b"070707";
26const NEWC_HEADER: usize = 110;
27const ODC_HEADER: usize = 76;
28const TRAILER: &[u8] = b"TRAILER!!!";
29
30const BIN_MAGIC_LE: [u8; 2] = [0xc7, 0x71];
32const BIN_MAGIC_BE: [u8; 2] = [0x71, 0xc7];
33
34#[derive(Debug, Clone, Copy, PartialEq, Eq)]
36#[non_exhaustive]
37pub enum CpioDialect {
38 Newc,
40 Crc,
42 Odc,
44 BinaryLittleEndian,
46 BinaryBigEndian,
48}
49
50fn mode_bits(kind: EntryKind) -> u64 {
52 match kind {
53 EntryKind::Dir => S_IFDIR,
54 EntryKind::Symlink => S_IFLNK,
55 EntryKind::Char => S_IFCHR,
56 EntryKind::Block => S_IFBLK,
57 EntryKind::Fifo => S_IFIFO,
58 EntryKind::Socket => S_IFSOCK,
59 _ => S_IFREG,
60 }
61}
62
63fn lo32(v: u64) -> u32 {
65 u32::try_from(v & 0xFFFF_FFFF).unwrap_or(0)
66}
67
68fn put_hex8(field: &mut [u8], val: u32) {
70 let mut v = val;
71 for slot in field.iter_mut().rev() {
72 let d = u8::try_from(v & 0xf).unwrap_or(0);
73 *slot = if d < 10 { b'0' + d } else { b'A' + (d - 10) };
74 v >>= 4;
75 }
76}
77
78fn put_octal(field: &mut [u8], mut value: u64) -> core::result::Result<(), ArchiveError> {
79 for slot in field.iter_mut().rev() {
80 *slot = b'0' + u8::try_from(value & 7).unwrap_or(0);
81 value >>= 3;
82 }
83 if value != 0 {
84 return Err(ArchiveError::new(ErrorKind::Unsupported)
85 .with_format("cpio")
86 .with_context("odc numeric value exceeds its field"));
87 }
88 Ok(())
89}
90
91fn cpio_u32(value: u64, context: &'static str) -> core::result::Result<u32, ArchiveError> {
92 u32::try_from(value).map_err(|_| {
93 ArchiveError::new(ErrorKind::Unsupported)
94 .with_format("cpio")
95 .with_context(context)
96 })
97}
98
99fn cpio_u16(value: u64, context: &'static str) -> core::result::Result<u16, ArchiveError> {
100 u16::try_from(value).map_err(|_| {
101 ArchiveError::new(ErrorKind::Unsupported)
102 .with_format("cpio")
103 .with_context(context)
104 })
105}
106
107fn write_binary_word(header: &mut [u8], index: usize, value: u16, little: bool) {
108 let bytes = if little {
109 value.to_le_bytes()
110 } else {
111 value.to_be_bytes()
112 };
113 let offset = index * 2;
114 header[offset..offset + 2].copy_from_slice(&bytes);
115}
116
117fn newc_field(data: &[u8], pos: usize, i: usize) -> Result<u64> {
119 let start = pos + 6 + i * 8;
120 let field = data
121 .get(start..start + 8)
122 .ok_or(Error::Malformed("cpio: truncated newc field"))?;
123 parse_radix(field, 16)
124}
125
126fn odc_field(data: &[u8], pos: usize, off: usize, width: usize) -> Result<u64> {
128 let start = pos + off;
129 let field = data
130 .get(start..start + width)
131 .ok_or(Error::Malformed("cpio: truncated odc field"))?;
132 parse_radix(field, 8)
133}
134
135fn parse_radix(field: &[u8], radix: u32) -> Result<u64> {
137 let mut val: u64 = 0;
138 for &b in field {
139 if b == b' ' || b == 0 {
140 continue;
141 }
142 let digit = u64::from(
143 (b as char)
144 .to_digit(radix)
145 .ok_or(Error::Malformed("cpio: invalid digit"))?,
146 );
147 val = val
148 .checked_mul(u64::from(radix))
149 .and_then(|v| v.checked_add(digit))
150 .ok_or(Error::Malformed("cpio: numeric overflow"))?;
151 }
152 Ok(val)
153}
154
155const S_IFMT: u64 = 0o170_000;
157const S_IFREG: u64 = 0o100_000;
158const S_IFDIR: u64 = 0o040_000;
159const S_IFCHR: u64 = 0o020_000;
160const S_IFBLK: u64 = 0o060_000;
161const S_IFIFO: u64 = 0o010_000;
162const S_IFLNK: u64 = 0o120_000;
163const S_IFSOCK: u64 = 0o140_000;
164
165fn kind_from_mode(mode: u64) -> EntryKind {
167 match mode & S_IFMT {
168 S_IFDIR => EntryKind::Dir,
169 S_IFLNK => EntryKind::Symlink,
170 S_IFCHR => EntryKind::Char,
171 S_IFBLK => EntryKind::Block,
172 S_IFIFO => EntryKind::Fifo,
173 S_IFSOCK => EntryKind::Socket,
174 _ => EntryKind::File,
175 }
176}
177
178fn usize_of(v: u64) -> Result<usize> {
180 usize::try_from(v).map_err(|_| Error::LimitExceeded("cpio: size exceeds usize"))
181}
182
183#[derive(Debug)]
184enum DecoderState {
185 Header,
186 Data {
187 remaining: u64,
188 padding: usize,
189 checksum: Option<u32>,
190 checksum_actual: u32,
191 emit_end: bool,
192 },
193 EndEntry {
194 padding: usize,
195 checksum: Option<u32>,
196 checksum_actual: u32,
197 emit_end: bool,
198 },
199 Done,
200}
201
202#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
203struct HardlinkKey {
204 device_major: u64,
205 device_minor: u64,
206 inode: u64,
207}
208
209#[derive(Debug)]
210struct HardlinkGroup {
211 expected: u64,
212 seen: u64,
213 target: Option<ArchivePath>,
214 pending: Vec<EntryMetadata>,
215}
216
217#[derive(Debug)]
218enum QueuedEvent {
219 Entry(Box<EntryMetadata>),
220 EndEntry,
221}
222
223#[derive(Debug)]
224struct ParsedHeader {
225 metadata: EntryMetadata,
226 size: u64,
227 padding: usize,
228 checksum: Option<u32>,
229 trailer: bool,
230}
231
232#[derive(Debug)]
237pub struct CpioDecoder {
238 limits: Limits,
239 state: DecoderState,
240 header: Vec<u8>,
241 header_target: Option<usize>,
242 entries: u64,
243 total: u64,
244 hardlinks: BTreeMap<HardlinkKey, HardlinkGroup>,
245 queued: VecDeque<QueuedEvent>,
246 hardlink_metadata: usize,
247}
248
249impl CpioDecoder {
250 #[must_use]
252 pub const fn new(limits: Limits) -> Self {
253 Self {
254 limits,
255 state: DecoderState::Header,
256 header: Vec::new(),
257 header_target: None,
258 entries: 0,
259 total: 0,
260 hardlinks: BTreeMap::new(),
261 queued: VecDeque::new(),
262 hardlink_metadata: 0,
263 }
264 }
265
266 #[must_use]
268 pub fn probe(prefix: &[u8]) -> ProbeResult<()> {
269 if prefix.len() < 2 {
270 return ProbeResult::NeedMore { minimum: 2 };
271 }
272 if prefix.starts_with(&BIN_MAGIC_LE) || prefix.starts_with(&BIN_MAGIC_BE) {
273 return ProbeResult::Match(());
274 }
275 if prefix.len() < 6 {
276 return ProbeResult::NeedMore { minimum: 6 };
277 }
278 if prefix.starts_with(NEWC_MAGIC)
279 || prefix.starts_with(NEWC_CRC_MAGIC)
280 || prefix.starts_with(ODC_MAGIC)
281 {
282 ProbeResult::Match(())
283 } else {
284 ProbeResult::NoMatch
285 }
286 }
287
288 fn target_from_prefix(&self) -> core::result::Result<Option<usize>, ArchiveError> {
289 if self.header.len() < 2 {
290 return Ok(None);
291 }
292 let (fixed, namesize, alignment) =
293 if self.header.starts_with(&BIN_MAGIC_LE) || self.header.starts_with(&BIN_MAGIC_BE) {
294 if self.header.len() < 26 {
295 return Ok(Some(26));
296 }
297 let little = self.header.starts_with(&BIN_MAGIC_LE);
298 let namesize = usize::from(binary_word(&self.header, 10, little)?);
299 (26, namesize, 2)
300 } else {
301 if self.header.len() < 6 {
302 return Ok(Some(6));
303 }
304 if self.header.starts_with(NEWC_MAGIC) || self.header.starts_with(NEWC_CRC_MAGIC) {
305 if self.header.len() < NEWC_HEADER {
306 return Ok(Some(NEWC_HEADER));
307 }
308 let namesize = usize_of(newc_field(&self.header, 0, 11)?)?;
309 (NEWC_HEADER, namesize, 4)
310 } else if self.header.starts_with(ODC_MAGIC) {
311 if self.header.len() < ODC_HEADER {
312 return Ok(Some(ODC_HEADER));
313 }
314 let namesize = usize_of(odc_field(&self.header, 0, 59, 6)?)?;
315 (ODC_HEADER, namesize, 1)
316 } else {
317 return Err(ArchiveError::new(ErrorKind::Malformed)
318 .with_format("cpio")
319 .with_context("unrecognized cpio magic"));
320 }
321 };
322 if namesize == 0 {
323 return Err(ArchiveError::new(ErrorKind::Malformed)
324 .with_format("cpio")
325 .with_context("zero-length pathname"));
326 }
327 if self
328 .limits
329 .path_bytes()
330 .is_some_and(|limit| namesize.saturating_sub(1) > limit)
331 {
332 return Err(ArchiveError::new(ErrorKind::Limit)
333 .with_format("cpio")
334 .with_context("pathname exceeds configured limit"));
335 }
336 let unaligned = fixed.checked_add(namesize).ok_or_else(|| {
337 ArchiveError::new(ErrorKind::Malformed)
338 .with_format("cpio")
339 .with_context("header size overflow")
340 })?;
341 let target = match alignment {
342 4 => unaligned.checked_add(3).map(|value| value & !3),
343 2 => unaligned.checked_add(1).map(|value| value & !1),
344 _ => Some(unaligned),
345 }
346 .ok_or_else(|| {
347 ArchiveError::new(ErrorKind::Malformed)
348 .with_format("cpio")
349 .with_context("header alignment overflow")
350 })?;
351 if self
352 .limits
353 .metadata_bytes()
354 .is_some_and(|limit| target > limit)
355 {
356 return Err(ArchiveError::new(ErrorKind::Limit)
357 .with_format("cpio")
358 .with_context("header metadata exceeds configured limit"));
359 }
360 Ok(Some(target))
361 }
362
363 #[allow(clippy::too_many_lines)]
364 fn parse_header(&self) -> core::result::Result<ParsedHeader, ArchiveError> {
365 let bytes = &self.header;
366 let (
367 fixed,
368 namesize,
369 size,
370 mode,
371 uid,
372 gid,
373 mtime,
374 inode,
375 links,
376 device,
377 referenced_device,
378 checksum,
379 data_alignment,
380 ) = if bytes.starts_with(NEWC_MAGIC) || bytes.starts_with(NEWC_CRC_MAGIC) {
381 let namesize = usize_of(newc_field(bytes, 0, 11)?)?;
382 let size = newc_field(bytes, 0, 6)?;
383 let device = Device {
384 major: newc_field(bytes, 0, 7)?,
385 minor: newc_field(bytes, 0, 8)?,
386 };
387 let referenced = Device {
388 major: newc_field(bytes, 0, 9)?,
389 minor: newc_field(bytes, 0, 10)?,
390 };
391 (
392 NEWC_HEADER,
393 namesize,
394 size,
395 newc_field(bytes, 0, 1)?,
396 newc_field(bytes, 0, 2)?,
397 newc_field(bytes, 0, 3)?,
398 newc_field(bytes, 0, 5)?,
399 newc_field(bytes, 0, 0)?,
400 newc_field(bytes, 0, 4)?,
401 Some(device),
402 Some(referenced),
403 bytes
404 .starts_with(NEWC_CRC_MAGIC)
405 .then(|| newc_field(bytes, 0, 12))
406 .transpose()?
407 .map(lo32),
408 4,
409 )
410 } else if bytes.starts_with(ODC_MAGIC) {
411 (
412 ODC_HEADER,
413 usize_of(odc_field(bytes, 0, 59, 6)?)?,
414 odc_field(bytes, 0, 65, 11)?,
415 odc_field(bytes, 0, 18, 6)?,
416 odc_field(bytes, 0, 24, 6)?,
417 odc_field(bytes, 0, 30, 6)?,
418 odc_field(bytes, 0, 48, 11)?,
419 odc_field(bytes, 0, 12, 6)?,
420 odc_field(bytes, 0, 36, 6)?,
421 Some(Device {
422 major: 0,
423 minor: odc_field(bytes, 0, 6, 6)?,
424 }),
425 Some(Device {
426 major: 0,
427 minor: odc_field(bytes, 0, 42, 6)?,
428 }),
429 None,
430 1,
431 )
432 } else {
433 let little = bytes.starts_with(&BIN_MAGIC_LE);
434 let word = |index| binary_word(bytes, index, little);
435 (
436 26,
437 usize::from(word(10)?),
438 (u64::from(word(11)?) << 16) | u64::from(word(12)?),
439 u64::from(word(3)?),
440 u64::from(word(4)?),
441 u64::from(word(5)?),
442 (u64::from(word(8)?) << 16) | u64::from(word(9)?),
443 u64::from(word(2)?),
444 u64::from(word(6)?),
445 Some(Device {
446 major: 0,
447 minor: u64::from(word(1)?),
448 }),
449 Some(Device {
450 major: 0,
451 minor: u64::from(word(7)?),
452 }),
453 None,
454 2,
455 )
456 };
457 if self.limits.entry_bytes().is_some_and(|limit| size > limit) {
458 return Err(ArchiveError::new(ErrorKind::Limit)
459 .with_format("cpio")
460 .with_context("entry exceeds configured size limit"));
461 }
462 let name = bytes
463 .get(fixed..fixed + namesize)
464 .ok_or_else(|| {
465 ArchiveError::new(ErrorKind::Malformed)
466 .with_format("cpio")
467 .with_context("truncated pathname")
468 })?
469 .strip_suffix(&[0])
470 .ok_or_else(|| {
471 ArchiveError::new(ErrorKind::Malformed)
472 .with_format("cpio")
473 .with_context("pathname is not NUL terminated")
474 })?;
475 let metadata =
476 EntryMetadata::builder(kind_from_mode(mode), ArchivePath::from_bytes(name.to_vec()))
477 .size(Some(size))
478 .mode(Some(u32::try_from(mode & 0o7777).unwrap_or(0)))
479 .owner(Owner {
480 uid: Some(uid),
481 gid: Some(gid),
482 user: None,
483 group: None,
484 })
485 .times(EntryTimes {
486 modified: Some(Timestamp {
487 secs: i64::try_from(mtime).unwrap_or(i64::MAX),
488 nanos: 0,
489 }),
490 ..EntryTimes::default()
491 })
492 .inode_and_links(Some(inode), Some(links))
493 .devices(device, referenced_device)
494 .checksum(checksum.map(u32::to_be_bytes).map(Vec::from))
495 .build();
496 let size_usize = usize::try_from(size).map_err(|_| {
497 ArchiveError::new(ErrorKind::Limit)
498 .with_format("cpio")
499 .with_context("entry size exceeds address space")
500 })?;
501 let padding = match data_alignment {
502 4 => (4 - (size_usize & 3)) & 3,
503 2 => size_usize & 1,
504 _ => 0,
505 };
506 Ok(ParsedHeader {
507 trailer: name == TRAILER,
508 metadata,
509 size,
510 padding,
511 checksum,
512 })
513 }
514
515 fn hardlink_metadata(metadata: EntryMetadata, target: ArchivePath) -> EntryMetadata {
516 metadata
517 .into_builder()
518 .kind(EntryKind::Hardlink)
519 .size(Some(0))
520 .link_target(Some(target))
521 .build()
522 }
523
524 fn queue_entry(&mut self, metadata: EntryMetadata) {
525 self.queued
526 .push_back(QueuedEvent::Entry(Box::new(metadata)));
527 self.queued.push_back(QueuedEvent::EndEntry);
528 }
529
530 fn charge_hardlink_metadata(
531 &mut self,
532 metadata: &EntryMetadata,
533 ) -> core::result::Result<(), ArchiveError> {
534 let charge = core::mem::size_of::<EntryMetadata>()
535 .checked_add(metadata.path().as_bytes().len())
536 .ok_or_else(|| {
537 ArchiveError::new(ErrorKind::Limit)
538 .with_format("cpio")
539 .with_context("hardlink metadata accounting overflow")
540 })?;
541 self.hardlink_metadata = self.hardlink_metadata.checked_add(charge).ok_or_else(|| {
542 ArchiveError::new(ErrorKind::Limit)
543 .with_format("cpio")
544 .with_context("hardlink metadata accounting overflow")
545 })?;
546 if self
547 .limits
548 .metadata_bytes()
549 .is_some_and(|limit| self.hardlink_metadata > limit)
550 {
551 return Err(ArchiveError::new(ErrorKind::Limit)
552 .with_format("cpio")
553 .with_context("hardlink metadata exceeds configured limit"));
554 }
555 Ok(())
556 }
557
558 fn classify_hardlink(
559 &mut self,
560 metadata: EntryMetadata,
561 size: u64,
562 ) -> core::result::Result<Option<EntryMetadata>, ArchiveError> {
563 let links = metadata.links().unwrap_or(1);
564 if metadata.kind() != EntryKind::File || links <= 1 {
565 return Ok(Some(metadata));
566 }
567 self.charge_hardlink_metadata(&metadata)?;
568 let device = metadata.device().unwrap_or_default();
569 let key = HardlinkKey {
570 device_major: device.major,
571 device_minor: device.minor,
572 inode: metadata.inode().unwrap_or(0),
573 };
574 let mut group = self.hardlinks.remove(&key).unwrap_or(HardlinkGroup {
575 expected: links,
576 seen: 0,
577 target: None,
578 pending: Vec::new(),
579 });
580 if group.expected != links {
581 return Err(ArchiveError::new(ErrorKind::Malformed)
582 .with_format("cpio")
583 .with_context("hardlink group disagrees on link count"));
584 }
585 group.seen = group.seen.checked_add(1).ok_or_else(|| {
586 ArchiveError::new(ErrorKind::Limit)
587 .with_format("cpio")
588 .with_context("hardlink count overflow")
589 })?;
590 if group.seen > group.expected {
591 return Err(ArchiveError::new(ErrorKind::Malformed)
592 .with_format("cpio")
593 .with_context("hardlink group has more records than nlink"));
594 }
595
596 let result = if size != 0 {
597 if group.target.is_some() {
598 return Err(ArchiveError::new(ErrorKind::Malformed)
599 .with_format("cpio")
600 .with_context("hardlink group contains multiple payload records"));
601 }
602 let target = metadata.path().clone();
603 group.target = Some(target.clone());
604 for pending in core::mem::take(&mut group.pending) {
605 self.queue_entry(Self::hardlink_metadata(pending, target.clone()));
606 }
607 Some(metadata)
608 } else if let Some(target) = group.target.clone() {
609 Some(Self::hardlink_metadata(metadata, target))
610 } else {
611 group.pending.push(metadata);
612 if group.seen == group.expected {
613 let mut pending = core::mem::take(&mut group.pending).into_iter();
614 let first = pending.next().ok_or_else(|| {
615 ArchiveError::new(ErrorKind::Protocol)
616 .with_format("cpio")
617 .with_context("empty hardlink group lost its first record")
618 })?;
619 let target = first.path().clone();
620 group.target = Some(target.clone());
621 self.queue_entry(first);
622 for metadata in pending {
623 self.queue_entry(Self::hardlink_metadata(metadata, target.clone()));
624 }
625 }
626 None
627 };
628 self.hardlinks.insert(key, group);
629 Ok(result)
630 }
631
632 fn resolve_incomplete_hardlinks(&mut self) -> core::result::Result<(), ArchiveError> {
633 let mut queued = Vec::new();
634 for group in self.hardlinks.values_mut() {
635 if group.target.is_some() || group.pending.is_empty() {
636 continue;
637 }
638 let mut pending = core::mem::take(&mut group.pending).into_iter();
639 let first = pending.next().ok_or_else(|| {
640 ArchiveError::new(ErrorKind::Protocol)
641 .with_format("cpio")
642 .with_context("pending hardlink group disappeared")
643 })?;
644 let target = first.path().clone();
645 group.target = Some(target.clone());
646 queued.push(first);
647 for metadata in pending {
648 queued.push(Self::hardlink_metadata(metadata, target.clone()));
649 }
650 }
651 for metadata in queued {
652 self.queue_entry(metadata);
653 }
654 Ok(())
655 }
656
657 fn pop_queued<'a>(&mut self, consumed: usize) -> Option<DecodeStep<'a>> {
658 self.queued.pop_front().map(|event| DecodeStep {
659 consumed,
660 produced: 0,
661 event: match event {
662 QueuedEvent::Entry(metadata) => DecodeEvent::Entry(*metadata),
663 QueuedEvent::EndEntry => DecodeEvent::EndEntry,
664 },
665 })
666 }
667}
668
669impl ArchiveDecoder for CpioDecoder {
670 #[allow(clippy::too_many_lines)]
671 fn step<'a>(
672 &'a mut self,
673 input: &'a [u8],
674 _output: &'a mut [u8],
675 end: EndOfInput,
676 ) -> core::result::Result<DecodeStep<'a>, ArchiveError> {
677 if matches!(self.state, DecoderState::Header | DecoderState::Done) {
678 if let Some(step) = self.pop_queued(0) {
679 return Ok(step);
680 }
681 }
682 match self.state {
683 DecoderState::Done => {
684 if !input.is_empty() {
685 return Err(ArchiveError::new(ErrorKind::Protocol)
686 .with_format("cpio")
687 .with_context("input supplied after archive completion"));
688 }
689 return Ok(DecodeStep {
690 consumed: 0,
691 produced: 0,
692 event: DecodeEvent::Done,
693 });
694 },
695 DecoderState::Data {
696 remaining,
697 padding,
698 checksum,
699 checksum_actual,
700 emit_end,
701 } => {
702 if remaining == 0 {
703 self.state = DecoderState::EndEntry {
704 padding,
705 checksum,
706 checksum_actual,
707 emit_end,
708 };
709 return self.step(input, &mut [], end);
710 }
711 if input.is_empty() {
712 if matches!(end, EndOfInput::End) {
713 return Err(ArchiveError::new(ErrorKind::Malformed)
714 .with_format("cpio")
715 .with_context("truncated entry data"));
716 }
717 return Ok(DecodeStep {
718 consumed: 0,
719 produced: 0,
720 event: DecodeEvent::NeedInput,
721 });
722 }
723 let count = input
724 .len()
725 .min(usize::try_from(remaining).unwrap_or(usize::MAX));
726 let bytes = &input[..count];
727 let actual = bytes.iter().fold(checksum_actual, |sum, byte| {
728 sum.wrapping_add(u32::from(*byte))
729 });
730 self.total = self.total.checked_add(count as u64).ok_or_else(|| {
731 ArchiveError::new(ErrorKind::Limit)
732 .with_format("cpio")
733 .with_context("decoded byte count overflow")
734 })?;
735 if self
736 .limits
737 .decoded_total()
738 .is_some_and(|limit| self.total > limit)
739 {
740 return Err(ArchiveError::new(ErrorKind::Limit)
741 .with_format("cpio")
742 .with_context("decoded total exceeds configured limit"));
743 }
744 self.state = DecoderState::Data {
745 remaining: remaining - count as u64,
746 padding,
747 checksum,
748 checksum_actual: actual,
749 emit_end,
750 };
751 return Ok(DecodeStep {
752 consumed: count,
753 produced: 0,
754 event: DecodeEvent::Data(Chunk::new(bytes)),
755 });
756 },
757 DecoderState::EndEntry {
758 padding,
759 checksum,
760 checksum_actual,
761 emit_end,
762 } => {
763 if input.len() < padding {
764 if matches!(end, EndOfInput::End) {
765 return Err(ArchiveError::new(ErrorKind::Malformed)
766 .with_format("cpio")
767 .with_context("truncated entry padding"));
768 }
769 return Ok(DecodeStep {
770 consumed: 0,
771 produced: 0,
772 event: DecodeEvent::NeedInput,
773 });
774 }
775 if checksum.is_some_and(|expected| expected != checksum_actual) {
776 return Err(ArchiveError::new(ErrorKind::Integrity)
777 .with_format("cpio")
778 .with_context("crc payload checksum mismatch"));
779 }
780 self.state = DecoderState::Header;
781 if emit_end {
782 return Ok(DecodeStep {
783 consumed: padding,
784 produced: 0,
785 event: DecodeEvent::EndEntry,
786 });
787 }
788 let mut step = self.step(&input[padding..], &mut [], end)?;
789 step.consumed = step.consumed.checked_add(padding).ok_or_else(|| {
790 ArchiveError::new(ErrorKind::Limit)
791 .with_format("cpio")
792 .with_context("decoder progress overflow")
793 })?;
794 return Ok(step);
795 },
796 DecoderState::Header => {},
797 }
798
799 let mut consumed = 0;
800 loop {
801 let target = self.header_target.unwrap_or_else(|| {
802 if self.header.len() < 2 {
803 2
804 } else if self.header.starts_with(&BIN_MAGIC_LE)
805 || self.header.starts_with(&BIN_MAGIC_BE)
806 {
807 26
808 } else if self.header.len() < 6 {
809 6
810 } else if self.header.starts_with(ODC_MAGIC) {
811 ODC_HEADER
812 } else {
813 NEWC_HEADER
814 }
815 });
816 if self.header.len() < target {
817 let count = (target - self.header.len()).min(input.len() - consumed);
818 self.header
819 .extend_from_slice(&input[consumed..consumed + count]);
820 consumed += count;
821 if self.header.len() < target {
822 if matches!(end, EndOfInput::End) {
823 return Err(ArchiveError::new(ErrorKind::Malformed)
824 .with_format("cpio")
825 .with_context("truncated entry header"));
826 }
827 return Ok(DecodeStep {
828 consumed,
829 produced: 0,
830 event: DecodeEvent::NeedInput,
831 });
832 }
833 }
834 let next = self.target_from_prefix()?;
835 self.header_target = next;
836 if next.is_some_and(|needed| self.header.len() < needed) {
837 if consumed == input.len() {
838 return Ok(DecodeStep {
839 consumed,
840 produced: 0,
841 event: DecodeEvent::NeedInput,
842 });
843 }
844 continue;
845 }
846 break;
847 }
848
849 let parsed = self.parse_header()?;
850 self.header.clear();
851 self.header_target = None;
852 if parsed.trailer {
853 self.resolve_incomplete_hardlinks()?;
854 self.state = DecoderState::Done;
855 if let Some(step) = self.pop_queued(consumed) {
856 return Ok(step);
857 }
858 return Ok(DecodeStep {
859 consumed,
860 produced: 0,
861 event: DecodeEvent::Done,
862 });
863 }
864 self.entries = self.entries.checked_add(1).ok_or_else(|| {
865 ArchiveError::new(ErrorKind::Limit)
866 .with_format("cpio")
867 .with_context("entry count overflow")
868 })?;
869 if self
870 .limits
871 .entries()
872 .is_some_and(|limit| self.entries > limit)
873 {
874 return Err(ArchiveError::new(ErrorKind::Limit)
875 .with_format("cpio")
876 .with_context("entry count exceeds configured limit"));
877 }
878 let metadata = self.classify_hardlink(parsed.metadata, parsed.size)?;
879 self.state = DecoderState::Data {
880 remaining: parsed.size,
881 padding: parsed.padding,
882 checksum: parsed.checksum,
883 checksum_actual: 0,
884 emit_end: metadata.is_some(),
885 };
886 if let Some(metadata) = metadata {
887 Ok(DecodeStep {
888 consumed,
889 produced: 0,
890 event: DecodeEvent::Entry(metadata),
891 })
892 } else {
893 let mut step = self.step(&input[consumed..], &mut [], end)?;
894 step.consumed = step.consumed.checked_add(consumed).ok_or_else(|| {
895 ArchiveError::new(ErrorKind::Limit)
896 .with_format("cpio")
897 .with_context("decoder progress overflow")
898 })?;
899 Ok(step)
900 }
901 }
902}
903
904fn binary_word(
905 bytes: &[u8],
906 index: usize,
907 little: bool,
908) -> core::result::Result<u16, ArchiveError> {
909 let offset = index.checked_mul(2).ok_or_else(|| {
910 ArchiveError::new(ErrorKind::Malformed)
911 .with_format("cpio")
912 .with_context("binary header offset overflow")
913 })?;
914 let pair: [u8; 2] = bytes
915 .get(offset..offset + 2)
916 .and_then(|value| value.try_into().ok())
917 .ok_or_else(|| {
918 ArchiveError::new(ErrorKind::Malformed)
919 .with_format("cpio")
920 .with_context("truncated binary header")
921 })?;
922 Ok(if little {
923 u16::from_le_bytes(pair)
924 } else {
925 u16::from_be_bytes(pair)
926 })
927}
928
929#[derive(Debug, Clone, Copy)]
931struct LinkIdentity {
932 inode: u64,
933 links: u64,
934 device: Device,
935}
936
937#[derive(Debug, Clone, Copy)]
938struct StagedHeader {
939 size: u64,
940 identity: LinkIdentity,
941 alignment: usize,
942 checksum: Option<u32>,
943}
944
945#[derive(Debug)]
947pub struct CpioEncoder {
948 limits: Limits,
949 dialect: CpioDialect,
950 pending: Vec<u8>,
951 pending_pos: usize,
952 inode: u32,
953 open: bool,
954 entry_size: u64,
955 entry_alignment: usize,
956 remaining: u64,
957 expected_checksum: Option<u32>,
958 checksum_actual: u32,
959 finishing: bool,
960 done: bool,
961 entries: u64,
962 link_targets: BTreeMap<Vec<u8>, LinkIdentity>,
963}
964
965impl CpioEncoder {
966 #[must_use]
968 pub const fn new(limits: Limits) -> Self {
969 Self {
970 limits,
971 dialect: CpioDialect::Newc,
972 pending: Vec::new(),
973 pending_pos: 0,
974 inode: 0,
975 open: false,
976 entry_size: 0,
977 entry_alignment: 4,
978 remaining: 0,
979 expected_checksum: None,
980 checksum_actual: 0,
981 finishing: false,
982 done: false,
983 entries: 0,
984 link_targets: BTreeMap::new(),
985 }
986 }
987
988 #[must_use]
990 pub const fn with_dialect(limits: Limits, dialect: CpioDialect) -> Self {
991 let mut encoder = Self::new(limits);
992 encoder.dialect = dialect;
993 encoder
994 }
995
996 fn drain_pending(&mut self, output: &mut [u8]) -> usize {
997 let count = (self.pending.len() - self.pending_pos).min(output.len());
998 output[..count].copy_from_slice(&self.pending[self.pending_pos..self.pending_pos + count]);
999 self.pending_pos += count;
1000 if self.pending_pos == self.pending.len() {
1001 self.pending.clear();
1002 self.pending_pos = 0;
1003 }
1004 count
1005 }
1006
1007 #[allow(clippy::too_many_lines)]
1008 fn stage_header(
1009 &mut self,
1010 name: &[u8],
1011 metadata: Option<&EntryMetadata>,
1012 ) -> core::result::Result<StagedHeader, ArchiveError> {
1013 let size = metadata.and_then(EntryMetadata::size).unwrap_or(0);
1014 let namesize = u64::try_from(name.len())
1015 .ok()
1016 .and_then(|value| value.checked_add(1))
1017 .ok_or_else(|| {
1018 ArchiveError::new(ErrorKind::Limit)
1019 .with_format("cpio")
1020 .with_context("pathname size overflow")
1021 })?;
1022 let mode = metadata.map_or(0, |meta| {
1023 mode_bits(meta.kind())
1024 | u64::from(meta.mode().unwrap_or_else(|| default_mode(meta.kind())) & 0o7777)
1025 });
1026 let uid = metadata.and_then(|meta| meta.owner().uid).unwrap_or(0);
1027 let gid = metadata.and_then(|meta| meta.owner().gid).unwrap_or(0);
1028 let links = metadata.and_then(EntryMetadata::links).unwrap_or(1);
1029 let mtime = metadata
1030 .and_then(|meta| meta.times().modified)
1031 .map_or(0, |time| u64::try_from(time.secs.max(0)).unwrap_or(0));
1032 let device = metadata.and_then(EntryMetadata::device).unwrap_or_default();
1033 let referenced = metadata
1034 .and_then(EntryMetadata::referenced_device)
1035 .unwrap_or_default();
1036 let inode = metadata
1037 .and_then(EntryMetadata::inode)
1038 .unwrap_or(u64::from(self.inode));
1039 let checksum = if self.dialect == CpioDialect::Crc {
1040 match metadata.and_then(EntryMetadata::checksum) {
1041 Some(bytes) if bytes.len() == 4 => {
1042 Some(u32::from_be_bytes(bytes.try_into().map_err(|_| {
1043 ArchiveError::new(ErrorKind::Protocol)
1044 .with_format("cpio")
1045 .with_context("CRC checksum conversion failed")
1046 })?))
1047 },
1048 None if size == 0 => Some(0),
1049 _ => {
1050 return Err(ArchiveError::new(ErrorKind::Unsupported)
1051 .with_format("cpio")
1052 .with_context(
1053 "crc output requires a four-byte big-endian payload byte sum",
1054 ));
1055 },
1056 }
1057 } else {
1058 None
1059 };
1060 let alignment = match self.dialect {
1061 CpioDialect::Newc | CpioDialect::Crc => {
1062 let fields = [
1063 cpio_u32(inode, "newc inode exceeds 32-bit field")?,
1064 cpio_u32(mode, "newc mode exceeds 32-bit field")?,
1065 cpio_u32(uid, "newc uid exceeds 32-bit field")?,
1066 cpio_u32(gid, "newc gid exceeds 32-bit field")?,
1067 cpio_u32(links, "newc nlink exceeds 32-bit field")?,
1068 cpio_u32(mtime, "newc mtime exceeds 32-bit field")?,
1069 cpio_u32(size, "newc entry size exceeds 32-bit field")?,
1070 cpio_u32(device.major, "newc device major exceeds 32-bit field")?,
1071 cpio_u32(device.minor, "newc device minor exceeds 32-bit field")?,
1072 cpio_u32(
1073 referenced.major,
1074 "newc referenced device major exceeds 32-bit field",
1075 )?,
1076 cpio_u32(
1077 referenced.minor,
1078 "newc referenced device minor exceeds 32-bit field",
1079 )?,
1080 cpio_u32(namesize, "newc pathname exceeds 32-bit field")?,
1081 checksum.unwrap_or(0),
1082 ];
1083 self.pending.resize(NEWC_HEADER, 0);
1084 self.pending[..6].copy_from_slice(if self.dialect == CpioDialect::Crc {
1085 NEWC_CRC_MAGIC
1086 } else {
1087 NEWC_MAGIC
1088 });
1089 for (index, value) in fields.iter().enumerate() {
1090 let offset = 6 + index * 8;
1091 put_hex8(&mut self.pending[offset..offset + 8], *value);
1092 }
1093 4
1094 },
1095 CpioDialect::Odc => {
1096 if device.major != 0 || referenced.major != 0 {
1097 return Err(ArchiveError::new(ErrorKind::Unsupported)
1098 .with_format("cpio")
1099 .with_context("odc cannot preserve split device major numbers"));
1100 }
1101 self.pending.resize(ODC_HEADER, b'0');
1102 self.pending[..6].copy_from_slice(ODC_MAGIC);
1103 for (offset, width, value) in [
1104 (6, 6, device.minor),
1105 (12, 6, inode),
1106 (18, 6, mode),
1107 (24, 6, uid),
1108 (30, 6, gid),
1109 (36, 6, links),
1110 (42, 6, referenced.minor),
1111 (48, 11, mtime),
1112 (59, 6, namesize),
1113 (65, 11, size),
1114 ] {
1115 put_octal(&mut self.pending[offset..offset + width], value)?;
1116 }
1117 1
1118 },
1119 CpioDialect::BinaryLittleEndian | CpioDialect::BinaryBigEndian => {
1120 if device.major != 0 || referenced.major != 0 {
1121 return Err(ArchiveError::new(ErrorKind::Unsupported)
1122 .with_format("cpio")
1123 .with_context("binary cpio cannot preserve split device major numbers"));
1124 }
1125 let little = self.dialect == CpioDialect::BinaryLittleEndian;
1126 let mtime = cpio_u32(mtime, "binary cpio mtime exceeds 32 bits")?;
1127 let size = cpio_u32(size, "binary cpio size exceeds 32 bits")?;
1128 let fields = [
1129 0o070_707,
1130 cpio_u16(device.minor, "binary cpio device exceeds 16 bits")?,
1131 cpio_u16(inode, "binary cpio inode exceeds 16 bits")?,
1132 cpio_u16(mode, "binary cpio mode exceeds 16 bits")?,
1133 cpio_u16(uid, "binary cpio uid exceeds 16 bits")?,
1134 cpio_u16(gid, "binary cpio gid exceeds 16 bits")?,
1135 cpio_u16(links, "binary cpio nlink exceeds 16 bits")?,
1136 cpio_u16(
1137 referenced.minor,
1138 "binary cpio referenced device exceeds 16 bits",
1139 )?,
1140 u16::try_from(mtime >> 16).unwrap_or(0),
1141 u16::try_from(mtime & 0xffff).unwrap_or(0),
1142 cpio_u16(namesize, "binary cpio pathname exceeds 16 bits")?,
1143 u16::try_from(size >> 16).unwrap_or(0),
1144 u16::try_from(size & 0xffff).unwrap_or(0),
1145 ];
1146 self.pending.resize(26, 0);
1147 for (index, value) in fields.iter().enumerate() {
1148 write_binary_word(&mut self.pending, index, *value, little);
1149 }
1150 2
1151 },
1152 };
1153 self.pending.extend_from_slice(name);
1154 self.pending.push(0);
1155 let aligned = self
1156 .pending
1157 .len()
1158 .checked_add(alignment - 1)
1159 .ok_or_else(|| {
1160 ArchiveError::new(ErrorKind::Limit)
1161 .with_format("cpio")
1162 .with_context("header size overflow")
1163 })?
1164 / alignment
1165 * alignment;
1166 self.pending.resize(aligned, 0);
1167 self.inode = self.inode.wrapping_add(1);
1168 Ok(StagedHeader {
1169 size,
1170 identity: LinkIdentity {
1171 inode,
1172 links,
1173 device,
1174 },
1175 alignment,
1176 checksum,
1177 })
1178 }
1179}
1180
1181impl ArchiveEncoder for CpioEncoder {
1182 #[allow(clippy::too_many_lines)]
1183 fn step(
1184 &mut self,
1185 command: EncodeCommand<'_>,
1186 output: &mut [u8],
1187 ) -> core::result::Result<EncodeStep, ArchiveError> {
1188 if self.done {
1189 return match command {
1190 EncodeCommand::Finish => Ok(EncodeStep {
1191 consumed: 0,
1192 produced: 0,
1193 status: EncodeStatus::Done,
1194 }),
1195 _ => Err(ArchiveError::new(ErrorKind::Protocol)
1196 .with_format("cpio")
1197 .with_context("command supplied after finish")),
1198 };
1199 }
1200 if !self.pending.is_empty() {
1201 let produced = self.drain_pending(output);
1202 if self.pending.is_empty() && self.finishing {
1203 self.done = true;
1204 return Ok(EncodeStep {
1205 consumed: 0,
1206 produced,
1207 status: EncodeStatus::Done,
1208 });
1209 }
1210 return Ok(EncodeStep {
1211 consumed: 0,
1212 produced,
1213 status: if self.pending.is_empty() {
1214 EncodeStatus::NeedCommand
1215 } else {
1216 EncodeStatus::NeedOutput
1217 },
1218 });
1219 }
1220 match command {
1221 EncodeCommand::BeginEntry(metadata) => {
1222 if self.open {
1223 return Err(ArchiveError::new(ErrorKind::Protocol)
1224 .with_format("cpio")
1225 .with_context("previous entry is still open"));
1226 }
1227 if metadata.size().is_none() {
1228 return Err(ArchiveError::new(ErrorKind::SizeRequired)
1229 .with_format("cpio")
1230 .with_context("cpio requires a declared entry size"));
1231 }
1232 let size = metadata.size().unwrap_or(0);
1233 if self
1234 .limits
1235 .path_bytes()
1236 .is_some_and(|limit| metadata.path().as_bytes().len() > limit)
1237 || self.limits.entry_bytes().is_some_and(|limit| size > limit)
1238 {
1239 return Err(ArchiveError::new(ErrorKind::Limit)
1240 .with_format("cpio")
1241 .with_context("entry exceeds configured limits"));
1242 }
1243 let next_entries = self.entries.checked_add(1).ok_or_else(|| {
1244 ArchiveError::new(ErrorKind::Limit)
1245 .with_format("cpio")
1246 .with_context("entry count overflow")
1247 })?;
1248 if self
1249 .limits
1250 .entries()
1251 .is_some_and(|limit| next_entries > limit)
1252 {
1253 return Err(ArchiveError::new(ErrorKind::Limit)
1254 .with_format("cpio")
1255 .with_context("entry count exceeds configured limit"));
1256 }
1257 let effective;
1258 let metadata = if metadata.kind() == EntryKind::Hardlink {
1259 if size != 0 {
1260 return Err(ArchiveError::new(ErrorKind::Protocol)
1261 .with_format("cpio")
1262 .with_context("cpio hardlink entries must have zero size"));
1263 }
1264 let target = metadata.link_target().ok_or_else(|| {
1265 ArchiveError::new(ErrorKind::Protocol)
1266 .with_format("cpio")
1267 .with_context("cpio hardlink is missing its target")
1268 })?;
1269 let identity = self
1270 .link_targets
1271 .get(target.as_bytes())
1272 .copied()
1273 .ok_or_else(|| {
1274 ArchiveError::new(ErrorKind::Protocol)
1275 .with_format("cpio")
1276 .with_context("cpio hardlink target must precede the link entry")
1277 })?;
1278 if identity.links <= 1 {
1279 return Err(ArchiveError::new(ErrorKind::Protocol)
1280 .with_format("cpio")
1281 .with_context(
1282 "cpio hardlink target must declare nlink greater than one",
1283 ));
1284 }
1285 effective = metadata
1286 .clone()
1287 .into_builder()
1288 .kind(EntryKind::File)
1289 .size(Some(0))
1290 .inode_and_links(Some(identity.inode), Some(identity.links))
1291 .devices(Some(identity.device), metadata.referenced_device())
1292 .build();
1293 &effective
1294 } else {
1295 metadata
1296 };
1297 let staged = self.stage_header(metadata.path().as_bytes(), Some(metadata))?;
1298 if metadata.kind() == EntryKind::File && staged.identity.links > 1 {
1299 self.link_targets
1300 .insert(metadata.path().as_bytes().to_vec(), staged.identity);
1301 }
1302 self.entries = next_entries;
1303 self.entry_size = staged.size;
1304 self.entry_alignment = staged.alignment;
1305 self.remaining = staged.size;
1306 self.expected_checksum = staged.checksum;
1307 self.checksum_actual = 0;
1308 self.open = true;
1309 let produced = self.drain_pending(output);
1310 Ok(EncodeStep {
1311 consumed: 1,
1312 produced,
1313 status: if self.pending.is_empty() {
1314 EncodeStatus::NeedCommand
1315 } else {
1316 EncodeStatus::NeedOutput
1317 },
1318 })
1319 },
1320 EncodeCommand::Data(input) => {
1321 if !self.open {
1322 return Err(ArchiveError::new(ErrorKind::Protocol)
1323 .with_format("cpio")
1324 .with_context("entry data supplied without an open entry"));
1325 }
1326 if input.len() as u64 > self.remaining {
1327 return Err(ArchiveError::new(ErrorKind::Protocol)
1328 .with_format("cpio")
1329 .with_context("entry data exceeds declared size"));
1330 }
1331 let count = input.len().min(output.len());
1332 output[..count].copy_from_slice(&input[..count]);
1333 self.checksum_actual = input[..count]
1334 .iter()
1335 .fold(self.checksum_actual, |sum, byte| {
1336 sum.wrapping_add(u32::from(*byte))
1337 });
1338 self.remaining -= count as u64;
1339 Ok(EncodeStep {
1340 consumed: count,
1341 produced: count,
1342 status: if count == input.len() {
1343 EncodeStatus::NeedCommand
1344 } else {
1345 EncodeStatus::NeedOutput
1346 },
1347 })
1348 },
1349 EncodeCommand::EndEntry => {
1350 if !self.open || self.remaining != 0 {
1351 return Err(ArchiveError::new(ErrorKind::Protocol)
1352 .with_format("cpio")
1353 .with_context("entry ended before its declared size"));
1354 }
1355 let size = usize::try_from(self.entry_size).map_err(|_| {
1356 ArchiveError::new(ErrorKind::Limit)
1357 .with_format("cpio")
1358 .with_context("entry size exceeds address space")
1359 })?;
1360 if self
1361 .expected_checksum
1362 .is_some_and(|expected| expected != self.checksum_actual)
1363 {
1364 return Err(ArchiveError::new(ErrorKind::Integrity)
1365 .with_format("cpio")
1366 .with_context("written payload does not match declared crc byte sum"));
1367 }
1368 let remainder = size % self.entry_alignment;
1369 let padding = if remainder == 0 {
1370 0
1371 } else {
1372 self.entry_alignment - remainder
1373 };
1374 self.pending.resize(padding, 0);
1375 self.open = false;
1376 let produced = self.drain_pending(output);
1377 Ok(EncodeStep {
1378 consumed: 1,
1379 produced,
1380 status: if self.pending.is_empty() {
1381 EncodeStatus::NeedCommand
1382 } else {
1383 EncodeStatus::NeedOutput
1384 },
1385 })
1386 },
1387 EncodeCommand::Finish => {
1388 if self.open {
1389 return Err(ArchiveError::new(ErrorKind::Protocol)
1390 .with_format("cpio")
1391 .with_context("cannot finish with an open entry"));
1392 }
1393 let _ = self.stage_header(TRAILER, None)?;
1394 self.finishing = true;
1395 let produced = self.drain_pending(output);
1396 if self.pending.is_empty() {
1397 self.done = true;
1398 }
1399 Ok(EncodeStep {
1400 consumed: 1,
1401 produced,
1402 status: if self.done {
1403 EncodeStatus::Done
1404 } else {
1405 EncodeStatus::NeedOutput
1406 },
1407 })
1408 },
1409 }
1410 }
1411}
1412
1413#[cfg(test)]
1414#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
1415mod tests {
1416 use super::*;
1417
1418 #[test]
1419 fn radix_parsing() {
1420 assert_eq!(parse_radix(b"000000ff", 16).unwrap(), 255);
1421 assert_eq!(parse_radix(b"000644", 8).unwrap(), 0o644);
1422 }
1423}