Skip to main content

libarchive_oxide_core/format/
ar.rs

1// SPDX-FileCopyrightText: 2026 libarchive_oxide contributors
2//
3// SPDX-License-Identifier: MIT OR Apache-2.0
4
5//! Unix `ar` archive format (used by `.deb`, static libraries).
6//!
7//! Handles the three name conventions: plain `SysV` names (trailing `/` terminator), the GNU
8//! extended-name string table (`//` member plus `/N` offset references), and BSD long names
9//! (`#1/LEN` with the real name stored at the start of the member data). The special GNU symbol
10//! tables (`/` and 64-bit `/SYM64/`) are skipped. Every member is a regular file (`ar` carries no
11//! type info).
12
13use alloc::vec::Vec;
14
15use crate::Limits;
16use crate::error::{ArchiveError, Error, ErrorKind, Result};
17use crate::meta::{EntryKind, Timestamp, default_mode};
18use crate::metadata::{ArchivePath, EntryMetadata, EntryTimes, Extension, Owner};
19use crate::protocol::{
20    ArchiveDecoder, ArchiveEncoder, Chunk, DecodeEvent, DecodeStep, EncodeCommand, EncodeStatus,
21    EncodeStep, EndOfInput, ProbeResult,
22};
23
24const MAGIC: &[u8] = b"!<arch>\n";
25const THIN_MAGIC: &[u8] = b"!<thin>\n";
26const HEADER: usize = 60;
27const F_NAME: (usize, usize) = (0, 16);
28const F_MTIME: (usize, usize) = (16, 28);
29const F_UID: (usize, usize) = (28, 34);
30const F_GID: (usize, usize) = (34, 40);
31const F_MODE: (usize, usize) = (40, 48);
32const F_SIZE: (usize, usize) = (48, 58);
33const F_MAGIC: (usize, usize) = (58, 60);
34
35/// Left-aligns `value` into `field`, space-padding the remainder (ar's ASCII header fields).
36fn put_field(field: &mut [u8], value: &[u8]) {
37    field.fill(b' ');
38    let n = value.len().min(field.len());
39    field[..n].copy_from_slice(&value[..n]);
40}
41
42/// Formats `val` in the given radix (8 or 10) into `buf`, returning the written slice.
43fn radix_bytes(val: u64, radix: u64, buf: &mut [u8; 24]) -> &[u8] {
44    if val == 0 {
45        buf[0] = b'0';
46        return &buf[..1];
47    }
48    let mut i = buf.len();
49    let mut v = val;
50    while v > 0 {
51        i -= 1;
52        buf[i] = b'0' + u8::try_from(v % radix).unwrap_or(0);
53        v /= radix;
54    }
55    &buf[i..]
56}
57
58/// Extracts a fixed header field.
59fn field(hdr: &[u8], (start, end): (usize, usize)) -> &[u8] {
60    &hdr[start..end]
61}
62
63/// Trims trailing occurrences of `b` from a slice.
64fn rtrim(mut s: &[u8], b: u8) -> &[u8] {
65    while let [rest @ .., last] = s {
66        if *last == b {
67            s = rest;
68        } else {
69            break;
70        }
71    }
72    s
73}
74
75/// Looks up a name at `offset` in the GNU string table (names are `\n`-terminated, `/`-suffixed).
76fn gnu_table_name(table: &[u8], offset: usize) -> Result<&[u8]> {
77    let rest = table
78        .get(offset..)
79        .ok_or(Error::Malformed("ar: // offset out of range"))?;
80    let end = rest.iter().position(|&c| c == b'\n').unwrap_or(rest.len());
81    Ok(rest[..end].strip_suffix(b"/").unwrap_or(&rest[..end]))
82}
83
84/// Parses ASCII decimal digits into a `u64`.
85fn parse_decimal(field: &[u8]) -> Result<u64> {
86    if field.is_empty() {
87        return Err(Error::Malformed("ar: empty numeric field"));
88    }
89    let mut val: u64 = 0;
90    for &b in field {
91        if !b.is_ascii_digit() {
92            return Err(Error::Malformed("ar: invalid decimal digit"));
93        }
94        val = val
95            .checked_mul(10)
96            .and_then(|v| v.checked_add(u64::from(b - b'0')))
97            .ok_or(Error::Malformed("ar: numeric overflow"))?;
98    }
99    Ok(val)
100}
101
102/// Parses ASCII octal digits into a `u64` (empty yields 0).
103fn parse_octal(field: &[u8]) -> Result<u64> {
104    let mut val: u64 = 0;
105    for &b in field {
106        if !(b'0'..=b'7').contains(&b) {
107            return Err(Error::Malformed("ar: invalid octal digit"));
108        }
109        val = val
110            .checked_mul(8)
111            .and_then(|v| v.checked_add(u64::from(b - b'0')))
112            .ok_or(Error::Malformed("ar: numeric overflow"))?;
113    }
114    Ok(val)
115}
116
117/// `u64` to `usize`, rejecting oversized values on 32-bit targets.
118fn usize_of(v: u64) -> Result<usize> {
119    usize::try_from(v).map_err(|_| Error::LimitExceeded("ar: size exceeds usize"))
120}
121
122#[derive(Debug, Clone, Copy)]
123struct ArFields {
124    mode: u32,
125    uid: u64,
126    gid: u64,
127    mtime: Option<Timestamp>,
128}
129
130#[derive(Debug)]
131enum ArDecoderState {
132    Magic,
133    Header,
134    Special {
135        remaining: usize,
136        padding: usize,
137        string_table: bool,
138    },
139    BsdName {
140        remaining: usize,
141        body_size: u64,
142        padding: usize,
143        fields: ArFields,
144    },
145    Data {
146        remaining: u64,
147        padding: usize,
148    },
149    EndEntry {
150        padding: usize,
151    },
152    Done,
153}
154
155/// Incremental SysV/GNU/BSD ar decoder, including thin-archive metadata.
156#[derive(Debug)]
157pub struct ArDecoder {
158    limits: Limits,
159    state: ArDecoderState,
160    pending: Vec<u8>,
161    string_table: Vec<u8>,
162    thin: bool,
163    entries: u64,
164    total: u64,
165}
166
167impl ArDecoder {
168    /// Creates a decoder with mandatory resource limits.
169    #[must_use]
170    pub const fn new(limits: Limits) -> Self {
171        Self {
172            limits,
173            state: ArDecoderState::Magic,
174            pending: Vec::new(),
175            string_table: Vec::new(),
176            thin: false,
177            entries: 0,
178            total: 0,
179        }
180    }
181
182    /// Incrementally probes regular and thin ar archives.
183    #[must_use]
184    pub fn probe(prefix: &[u8]) -> ProbeResult<()> {
185        if prefix.len() < MAGIC.len() {
186            return ProbeResult::NeedMore {
187                minimum: MAGIC.len(),
188            };
189        }
190        if prefix.starts_with(MAGIC) || prefix.starts_with(THIN_MAGIC) {
191            ProbeResult::Match(())
192        } else {
193            ProbeResult::NoMatch
194        }
195    }
196
197    fn fill(pending: &mut Vec<u8>, target: usize, input: &[u8]) -> usize {
198        let count = (target - pending.len()).min(input.len());
199        pending.extend_from_slice(&input[..count]);
200        count
201    }
202
203    fn fields(header: &[u8]) -> core::result::Result<ArFields, ArchiveError> {
204        if field(header, F_MAGIC) != b"`\n" {
205            return Err(ArchiveError::new(ErrorKind::Malformed)
206                .with_format("ar")
207                .with_context("bad member header terminator"));
208        }
209        Ok(ArFields {
210            mode: u32::try_from(parse_octal(rtrim(field(header, F_MODE), b' '))? & 0o7777)
211                .unwrap_or(0),
212            uid: parse_decimal(rtrim(field(header, F_UID), b' ')).unwrap_or(0),
213            gid: parse_decimal(rtrim(field(header, F_GID), b' ')).unwrap_or(0),
214            mtime: parse_decimal(rtrim(field(header, F_MTIME), b' '))
215                .ok()
216                .map(|seconds| Timestamp {
217                    secs: i64::try_from(seconds).unwrap_or(i64::MAX),
218                    nanos: 0,
219                }),
220        })
221    }
222
223    fn metadata(
224        &self,
225        name: Vec<u8>,
226        size: u64,
227        fields: ArFields,
228    ) -> core::result::Result<EntryMetadata, ArchiveError> {
229        if self
230            .limits
231            .path_bytes()
232            .is_some_and(|limit| name.len() > limit)
233        {
234            return Err(ArchiveError::new(ErrorKind::Limit)
235                .with_format("ar")
236                .with_context("pathname exceeds configured limit"));
237        }
238        if self.limits.entry_bytes().is_some_and(|limit| size > limit) {
239            return Err(ArchiveError::new(ErrorKind::Limit)
240                .with_format("ar")
241                .with_context("member exceeds configured size limit"));
242        }
243        let mut builder = EntryMetadata::builder(EntryKind::File, ArchivePath::from_bytes(name))
244            .size(Some(size))
245            .mode(Some(fields.mode))
246            .owner(Owner {
247                uid: Some(fields.uid),
248                gid: Some(fields.gid),
249                user: None,
250                group: None,
251            })
252            .times(EntryTimes {
253                modified: fields.mtime,
254                ..EntryTimes::default()
255            });
256        if self.thin {
257            builder = builder.extension(Extension::new(
258                "ar-thin",
259                b"external-reference".to_vec(),
260                Vec::new(),
261            ));
262        }
263        Ok(builder.build())
264    }
265
266    fn count_entry(&mut self) -> core::result::Result<(), ArchiveError> {
267        self.entries = self.entries.checked_add(1).ok_or_else(|| {
268            ArchiveError::new(ErrorKind::Limit)
269                .with_format("ar")
270                .with_context("entry count overflow")
271        })?;
272        if self
273            .limits
274            .entries()
275            .is_some_and(|limit| self.entries > limit)
276        {
277            return Err(ArchiveError::new(ErrorKind::Limit)
278                .with_format("ar")
279                .with_context("entry count exceeds configured limit"));
280        }
281        Ok(())
282    }
283
284    fn resolve_gnu_name(&self, offset: usize) -> core::result::Result<Vec<u8>, ArchiveError> {
285        Ok(gnu_table_name(&self.string_table, offset)?.to_vec())
286    }
287}
288
289impl ArchiveDecoder for ArDecoder {
290    #[allow(clippy::too_many_lines, clippy::only_used_in_recursion)]
291    fn step<'a>(
292        &'a mut self,
293        input: &'a [u8],
294        output: &'a mut [u8],
295        end: EndOfInput,
296    ) -> core::result::Result<DecodeStep<'a>, ArchiveError> {
297        match self.state {
298            ArDecoderState::Done => {
299                if !input.is_empty() {
300                    return Err(ArchiveError::new(ErrorKind::Protocol)
301                        .with_format("ar")
302                        .with_context("input supplied after archive completion"));
303                }
304                return Ok(DecodeStep {
305                    consumed: 0,
306                    produced: 0,
307                    event: DecodeEvent::Done,
308                });
309            },
310            ArDecoderState::Data { remaining, padding } => {
311                if remaining == 0 {
312                    self.state = ArDecoderState::EndEntry { padding };
313                    return self.step(input, output, end);
314                }
315                if input.is_empty() {
316                    if matches!(end, EndOfInput::End) {
317                        return Err(ArchiveError::new(ErrorKind::Malformed)
318                            .with_format("ar")
319                            .with_context("truncated member data"));
320                    }
321                    return Ok(DecodeStep {
322                        consumed: 0,
323                        produced: 0,
324                        event: DecodeEvent::NeedInput,
325                    });
326                }
327                let count = input
328                    .len()
329                    .min(usize::try_from(remaining).unwrap_or(usize::MAX));
330                self.total = self.total.checked_add(count as u64).ok_or_else(|| {
331                    ArchiveError::new(ErrorKind::Limit)
332                        .with_format("ar")
333                        .with_context("decoded byte count overflow")
334                })?;
335                if self
336                    .limits
337                    .decoded_total()
338                    .is_some_and(|limit| self.total > limit)
339                {
340                    return Err(ArchiveError::new(ErrorKind::Limit)
341                        .with_format("ar")
342                        .with_context("decoded total exceeds configured limit"));
343                }
344                self.state = ArDecoderState::Data {
345                    remaining: remaining - count as u64,
346                    padding,
347                };
348                return Ok(DecodeStep {
349                    consumed: count,
350                    produced: 0,
351                    event: DecodeEvent::Data(Chunk::new(&input[..count])),
352                });
353            },
354            ArDecoderState::EndEntry { padding } => {
355                if input.len() < padding {
356                    if matches!(end, EndOfInput::End) {
357                        return Err(ArchiveError::new(ErrorKind::Malformed)
358                            .with_format("ar")
359                            .with_context("truncated member padding"));
360                    }
361                    return Ok(DecodeStep {
362                        consumed: 0,
363                        produced: 0,
364                        event: DecodeEvent::NeedInput,
365                    });
366                }
367                self.state = ArDecoderState::Header;
368                return Ok(DecodeStep {
369                    consumed: padding,
370                    produced: 0,
371                    event: DecodeEvent::EndEntry,
372                });
373            },
374            ArDecoderState::Special {
375                remaining,
376                padding,
377                string_table,
378            } => {
379                let count = remaining.min(input.len());
380                if string_table {
381                    self.string_table.extend_from_slice(&input[..count]);
382                }
383                let left = remaining - count;
384                if left != 0 {
385                    if matches!(end, EndOfInput::End) {
386                        return Err(ArchiveError::new(ErrorKind::Malformed)
387                            .with_format("ar")
388                            .with_context("truncated special member"));
389                    }
390                    self.state = ArDecoderState::Special {
391                        remaining: left,
392                        padding,
393                        string_table,
394                    };
395                    return Ok(DecodeStep {
396                        consumed: count,
397                        produced: 0,
398                        event: DecodeEvent::NeedInput,
399                    });
400                }
401                if input.len() - count < padding {
402                    self.state = ArDecoderState::Special {
403                        remaining: 0,
404                        padding,
405                        string_table,
406                    };
407                    if matches!(end, EndOfInput::End) {
408                        return Err(ArchiveError::new(ErrorKind::Malformed)
409                            .with_format("ar")
410                            .with_context("truncated special-member padding"));
411                    }
412                    return Ok(DecodeStep {
413                        consumed: count,
414                        produced: 0,
415                        event: DecodeEvent::NeedInput,
416                    });
417                }
418                self.state = ArDecoderState::Header;
419                return Ok(DecodeStep {
420                    consumed: count + padding,
421                    produced: 0,
422                    event: DecodeEvent::NeedInput,
423                });
424            },
425            ArDecoderState::BsdName {
426                remaining,
427                body_size,
428                padding,
429                ..
430            } => {
431                let count = remaining.min(input.len());
432                self.pending.extend_from_slice(&input[..count]);
433                let left = remaining - count;
434                if left != 0 {
435                    if matches!(end, EndOfInput::End) {
436                        return Err(ArchiveError::new(ErrorKind::Malformed)
437                            .with_format("ar")
438                            .with_context("truncated BSD inline name"));
439                    }
440                    let ArDecoderState::BsdName { fields, .. } =
441                        core::mem::replace(&mut self.state, ArDecoderState::Done)
442                    else {
443                        return Err(ArchiveError::new(ErrorKind::Protocol)
444                            .with_format("ar")
445                            .with_context("BSD name state changed unexpectedly"));
446                    };
447                    self.state = ArDecoderState::BsdName {
448                        remaining: left,
449                        body_size,
450                        padding,
451                        fields,
452                    };
453                    return Ok(DecodeStep {
454                        consumed: count,
455                        produced: 0,
456                        event: DecodeEvent::NeedInput,
457                    });
458                }
459                let ArDecoderState::BsdName { fields, .. } =
460                    core::mem::replace(&mut self.state, ArDecoderState::Done)
461                else {
462                    return Err(ArchiveError::new(ErrorKind::Protocol)
463                        .with_format("ar")
464                        .with_context("BSD name state changed unexpectedly"));
465                };
466                let name = core::mem::take(&mut self.pending);
467                let metadata = self.metadata(name, body_size, fields)?;
468                self.count_entry()?;
469                self.state = if self.thin {
470                    ArDecoderState::EndEntry { padding: 0 }
471                } else {
472                    ArDecoderState::Data {
473                        remaining: body_size,
474                        padding,
475                    }
476                };
477                return Ok(DecodeStep {
478                    consumed: count,
479                    produced: 0,
480                    event: DecodeEvent::Entry(metadata),
481                });
482            },
483            ArDecoderState::Magic | ArDecoderState::Header => {},
484        }
485
486        let mut consumed = 0;
487        if matches!(self.state, ArDecoderState::Magic) {
488            consumed += Self::fill(&mut self.pending, MAGIC.len(), input);
489            if self.pending.len() < MAGIC.len() {
490                if matches!(end, EndOfInput::End) {
491                    return Err(ArchiveError::new(ErrorKind::Malformed)
492                        .with_format("ar")
493                        .with_context("truncated global magic"));
494                }
495                return Ok(DecodeStep {
496                    consumed,
497                    produced: 0,
498                    event: DecodeEvent::NeedInput,
499                });
500            }
501            self.thin = self.pending.as_slice() == THIN_MAGIC;
502            if self.pending.as_slice() != MAGIC && !self.thin {
503                return Err(ArchiveError::new(ErrorKind::Malformed)
504                    .with_format("ar")
505                    .with_context("bad global magic"));
506            }
507            self.pending.clear();
508            self.state = ArDecoderState::Header;
509        }
510
511        if self.pending.is_empty() && consumed == input.len() && matches!(end, EndOfInput::End) {
512            self.state = ArDecoderState::Done;
513            return Ok(DecodeStep {
514                consumed,
515                produced: 0,
516                event: DecodeEvent::Done,
517            });
518        }
519
520        consumed += Self::fill(&mut self.pending, HEADER, &input[consumed..]);
521        if self.pending.len() < HEADER {
522            if matches!(end, EndOfInput::End) {
523                return Err(ArchiveError::new(ErrorKind::Malformed)
524                    .with_format("ar")
525                    .with_context("truncated member header"));
526            }
527            return Ok(DecodeStep {
528                consumed,
529                produced: 0,
530                event: DecodeEvent::NeedInput,
531            });
532        }
533
534        let header = core::mem::take(&mut self.pending);
535        let fields = Self::fields(&header)?;
536        let size = usize_of(parse_decimal(rtrim(field(&header, F_SIZE), b' '))?)?;
537        let padding = size & 1;
538        let raw_name = rtrim(field(&header, F_NAME), b' ');
539        if raw_name == b"//" || raw_name == b"/" || raw_name == b"/SYM64/" {
540            if raw_name == b"//" {
541                if self
542                    .limits
543                    .metadata_bytes()
544                    .is_some_and(|limit| size > limit)
545                {
546                    return Err(ArchiveError::new(ErrorKind::Limit)
547                        .with_format("ar")
548                        .with_context("GNU string table exceeds metadata budget"));
549                }
550                self.string_table.clear();
551                self.string_table.reserve(size);
552            }
553            self.state = ArDecoderState::Special {
554                remaining: size,
555                padding,
556                string_table: raw_name == b"//",
557            };
558            return Ok(DecodeStep {
559                consumed,
560                produced: 0,
561                event: DecodeEvent::NeedInput,
562            });
563        }
564
565        if let Some(length) = raw_name.strip_prefix(b"#1/") {
566            let name_length = usize_of(parse_decimal(length)?)?;
567            let body_size = size.checked_sub(name_length).ok_or_else(|| {
568                ArchiveError::new(ErrorKind::Malformed)
569                    .with_format("ar")
570                    .with_context("BSD name is longer than member")
571            })?;
572            if self
573                .limits
574                .path_bytes()
575                .is_some_and(|limit| name_length > limit)
576            {
577                return Err(ArchiveError::new(ErrorKind::Limit)
578                    .with_format("ar")
579                    .with_context("BSD pathname exceeds configured limit"));
580            }
581            self.pending.clear();
582            self.pending.reserve(name_length);
583            self.state = ArDecoderState::BsdName {
584                remaining: name_length,
585                body_size: body_size as u64,
586                padding,
587                fields,
588            };
589            return Ok(DecodeStep {
590                consumed,
591                produced: 0,
592                event: DecodeEvent::NeedInput,
593            });
594        }
595
596        let name = if raw_name.len() >= 2 && raw_name[0] == b'/' && raw_name[1].is_ascii_digit() {
597            let offset = usize_of(parse_decimal(&raw_name[1..])?)?;
598            self.resolve_gnu_name(offset)?
599        } else {
600            raw_name.strip_suffix(b"/").unwrap_or(raw_name).to_vec()
601        };
602        let metadata = self.metadata(name, size as u64, fields)?;
603        self.count_entry()?;
604        self.state = if self.thin {
605            ArDecoderState::EndEntry { padding: 0 }
606        } else {
607            ArDecoderState::Data {
608                remaining: size as u64,
609                padding,
610            }
611        };
612        Ok(DecodeStep {
613            consumed,
614            produced: 0,
615            event: DecodeEvent::Entry(metadata),
616        })
617    }
618}
619
620/// Streaming BSD-compatible ar encoder.
621#[derive(Debug)]
622pub struct ArEncoder {
623    limits: Limits,
624    pending: Vec<u8>,
625    pending_pos: usize,
626    started: bool,
627    open: bool,
628    remaining: u64,
629    padding: usize,
630    done: bool,
631    entries: u64,
632}
633
634impl ArEncoder {
635    /// Creates an empty encoder.
636    #[must_use]
637    pub const fn new(limits: Limits) -> Self {
638        Self {
639            limits,
640            pending: Vec::new(),
641            pending_pos: 0,
642            started: false,
643            open: false,
644            remaining: 0,
645            padding: 0,
646            done: false,
647            entries: 0,
648        }
649    }
650
651    fn drain_pending(&mut self, output: &mut [u8]) -> usize {
652        let count = (self.pending.len() - self.pending_pos).min(output.len());
653        output[..count].copy_from_slice(&self.pending[self.pending_pos..self.pending_pos + count]);
654        self.pending_pos += count;
655        if self.pending_pos == self.pending.len() {
656            self.pending.clear();
657            self.pending_pos = 0;
658        }
659        count
660    }
661
662    fn stage_entry(&mut self, metadata: &EntryMetadata) -> core::result::Result<(), ArchiveError> {
663        let size = metadata.size().ok_or_else(|| {
664            ArchiveError::new(ErrorKind::SizeRequired)
665                .with_format("ar")
666                .with_context("ar requires a declared entry size")
667        })?;
668        if !self.started {
669            self.pending.extend_from_slice(MAGIC);
670            self.started = true;
671        }
672        let name = metadata.path().as_bytes();
673        let mut name_field = Vec::new();
674        let inline_name = name.len() > 15;
675        if inline_name {
676            name_field.extend_from_slice(b"#1/");
677            let mut buffer = [0_u8; 24];
678            name_field.extend_from_slice(radix_bytes(name.len() as u64, 10, &mut buffer));
679        } else {
680            name_field.extend_from_slice(name);
681            name_field.push(b'/');
682        }
683        let total = size
684            .checked_add(if inline_name { name.len() as u64 } else { 0 })
685            .ok_or_else(|| {
686                ArchiveError::new(ErrorKind::Limit)
687                    .with_format("ar")
688                    .with_context("member size overflow")
689            })?;
690        let mut header = [b' '; HEADER];
691        let mut buffer = [0_u8; 24];
692        put_field(&mut header[F_NAME.0..F_NAME.1], &name_field);
693        let mtime = metadata
694            .times()
695            .modified
696            .map_or(0, |time| u64::try_from(time.secs.max(0)).unwrap_or(0));
697        put_field(
698            &mut header[F_MTIME.0..F_MTIME.1],
699            radix_bytes(mtime, 10, &mut buffer),
700        );
701        put_field(
702            &mut header[F_UID.0..F_UID.1],
703            radix_bytes(metadata.owner().uid.unwrap_or(0), 10, &mut buffer),
704        );
705        put_field(
706            &mut header[F_GID.0..F_GID.1],
707            radix_bytes(metadata.owner().gid.unwrap_or(0), 10, &mut buffer),
708        );
709        put_field(
710            &mut header[F_MODE.0..F_MODE.1],
711            radix_bytes(
712                0o100_000
713                    | u64::from(
714                        metadata
715                            .mode()
716                            .unwrap_or_else(|| default_mode(metadata.kind()))
717                            & 0o7777,
718                    ),
719                8,
720                &mut buffer,
721            ),
722        );
723        put_field(
724            &mut header[F_SIZE.0..F_SIZE.1],
725            radix_bytes(total, 10, &mut buffer),
726        );
727        header[F_MAGIC.0] = b'`';
728        header[F_MAGIC.0 + 1] = b'\n';
729        self.pending.extend_from_slice(&header);
730        if inline_name {
731            self.pending.extend_from_slice(name);
732        }
733        self.remaining = size;
734        self.padding = usize::from(total & 1 != 0);
735        self.open = true;
736        Ok(())
737    }
738}
739
740impl ArchiveEncoder for ArEncoder {
741    #[allow(clippy::too_many_lines)]
742    fn step(
743        &mut self,
744        command: EncodeCommand<'_>,
745        output: &mut [u8],
746    ) -> core::result::Result<EncodeStep, ArchiveError> {
747        if self.done {
748            return match command {
749                EncodeCommand::Finish => Ok(EncodeStep {
750                    consumed: 0,
751                    produced: 0,
752                    status: EncodeStatus::Done,
753                }),
754                _ => Err(ArchiveError::new(ErrorKind::Protocol)
755                    .with_format("ar")
756                    .with_context("command supplied after finish")),
757            };
758        }
759        if !self.pending.is_empty() {
760            let produced = self.drain_pending(output);
761            return Ok(EncodeStep {
762                consumed: 0,
763                produced,
764                status: if self.pending.is_empty() {
765                    EncodeStatus::NeedCommand
766                } else {
767                    EncodeStatus::NeedOutput
768                },
769            });
770        }
771        match command {
772            EncodeCommand::BeginEntry(metadata) => {
773                if self.open {
774                    return Err(ArchiveError::new(ErrorKind::Protocol)
775                        .with_format("ar")
776                        .with_context("previous entry is still open"));
777                }
778                let size = metadata.size().ok_or_else(|| {
779                    ArchiveError::new(ErrorKind::SizeRequired)
780                        .with_format("ar")
781                        .with_context("ar requires a declared entry size")
782                })?;
783                if self
784                    .limits
785                    .path_bytes()
786                    .is_some_and(|limit| metadata.path().as_bytes().len() > limit)
787                    || self.limits.entry_bytes().is_some_and(|limit| size > limit)
788                {
789                    return Err(ArchiveError::new(ErrorKind::Limit)
790                        .with_format("ar")
791                        .with_context("entry exceeds configured limits"));
792                }
793                let next_entries = self.entries.checked_add(1).ok_or_else(|| {
794                    ArchiveError::new(ErrorKind::Limit)
795                        .with_format("ar")
796                        .with_context("entry count overflow")
797                })?;
798                if self
799                    .limits
800                    .entries()
801                    .is_some_and(|limit| next_entries > limit)
802                {
803                    return Err(ArchiveError::new(ErrorKind::Limit)
804                        .with_format("ar")
805                        .with_context("entry count exceeds configured limit"));
806                }
807                self.stage_entry(metadata)?;
808                self.entries = next_entries;
809                let produced = self.drain_pending(output);
810                Ok(EncodeStep {
811                    consumed: 1,
812                    produced,
813                    status: if self.pending.is_empty() {
814                        EncodeStatus::NeedCommand
815                    } else {
816                        EncodeStatus::NeedOutput
817                    },
818                })
819            },
820            EncodeCommand::Data(input) => {
821                if !self.open {
822                    return Err(ArchiveError::new(ErrorKind::Protocol)
823                        .with_format("ar")
824                        .with_context("entry data supplied without an open entry"));
825                }
826                if input.len() as u64 > self.remaining {
827                    return Err(ArchiveError::new(ErrorKind::Protocol)
828                        .with_format("ar")
829                        .with_context("entry data exceeds declared size"));
830                }
831                let count = input.len().min(output.len());
832                output[..count].copy_from_slice(&input[..count]);
833                self.remaining -= count as u64;
834                Ok(EncodeStep {
835                    consumed: count,
836                    produced: count,
837                    status: if count == input.len() {
838                        EncodeStatus::NeedCommand
839                    } else {
840                        EncodeStatus::NeedOutput
841                    },
842                })
843            },
844            EncodeCommand::EndEntry => {
845                if !self.open || self.remaining != 0 {
846                    return Err(ArchiveError::new(ErrorKind::Protocol)
847                        .with_format("ar")
848                        .with_context("entry ended before its declared size"));
849                }
850                self.pending.resize(self.padding, b'\n');
851                self.padding = 0;
852                self.open = false;
853                let produced = self.drain_pending(output);
854                Ok(EncodeStep {
855                    consumed: 1,
856                    produced,
857                    status: if self.pending.is_empty() {
858                        EncodeStatus::NeedCommand
859                    } else {
860                        EncodeStatus::NeedOutput
861                    },
862                })
863            },
864            EncodeCommand::Finish => {
865                if self.open {
866                    return Err(ArchiveError::new(ErrorKind::Protocol)
867                        .with_format("ar")
868                        .with_context("cannot finish with an open entry"));
869                }
870                if !self.started {
871                    self.pending.extend_from_slice(MAGIC);
872                    self.started = true;
873                    let produced = self.drain_pending(output);
874                    if self.pending.is_empty() {
875                        self.done = true;
876                    }
877                    return Ok(EncodeStep {
878                        consumed: 1,
879                        produced,
880                        status: if self.done {
881                            EncodeStatus::Done
882                        } else {
883                            EncodeStatus::NeedOutput
884                        },
885                    });
886                }
887                self.done = true;
888                Ok(EncodeStep {
889                    consumed: 1,
890                    produced: 0,
891                    status: EncodeStatus::Done,
892                })
893            },
894        }
895    }
896}