Skip to main content

ninep_proto/
slice_codec.rs

1//! Allocation-free 9P codec shared by the server, userspace, and kernel clients.
2//!
3//! [`decode_frame`] and [`encode_frame`] support all implemented 9P messages,
4//! including negotiated mutation envelopes. [`Request`],
5//! [`encode_request`], and [`decode_response`] are native-client convenience
6//! APIs over that same codec. Variable fields borrow caller-owned storage.
7//!
8//! A frame is `size[4] type[1] tag[2] body[size - 7]`, all little-endian.
9//! Negotiated ZeroFS mutations insert `op_id[16] flags[1] origin_writer_epoch[8]`
10//! after the tag. Responses and durability barriers have no envelope.
11
12#![cfg_attr(MODULE, allow(dead_code, unreachable_pub))]
13
14#[cfg(MODULE)]
15#[path = "wire_types.rs"]
16mod wire_types;
17
18#[cfg(not(MODULE))]
19pub use crate::wire_types::*;
20#[cfg(MODULE)]
21pub use wire_types::*;
22
23#[cfg(MODULE)]
24#[path = "wire_messages.rs"]
25mod wire_messages;
26#[cfg(not(MODULE))]
27use crate::{wire_messages, wire_types};
28#[path = "slice_messages.rs"]
29mod messages;
30#[cfg_attr(MODULE, allow(unused_imports))]
31pub use messages::{
32    DirectoryEntry, Frame, LockType, Message, Names, QidList, carries_op_id, decode_entry,
33    decode_frame, encode_entry, encode_frame, encoded_frame_size,
34};
35
36pub const MAX_MSIZE: u32 = P9_MAX_MSIZE;
37
38/// Reserved tag required by `Tversion`.
39pub const NOTAG: u16 = u16::MAX;
40
41/// `Tunlinkat.flags` bit distinguishing rmdir from unlink.
42pub const AT_REMOVEDIR: u32 = 0x200;
43
44/// Maximum component length accepted by the ZeroFS server.
45pub const MAX_NAME_LEN: usize = P9_MAX_NAME_LEN as usize;
46
47/// `Tlock.lock_type`: shared read lock.
48pub const LOCK_TYPE_RDLCK: u8 = 0;
49
50/// `Tlock.lock_type`: exclusive write lock.
51pub const LOCK_TYPE_WRLCK: u8 = 1;
52
53/// `Tlock.lock_type`: release the named range. `Rgetlock` reports it when no
54/// lock conflicts with the probe.
55pub const LOCK_TYPE_UNLCK: u8 = 2;
56
57/// `Tlock.flags`: report a conflict as [`LOCK_BLOCKED`] instead of `EAGAIN`.
58/// The server never waits, so the caller owns the retry loop either way.
59pub const LOCK_FLAGS_BLOCK: u32 = 1;
60
61/// `Rlock.status`: the range is held by the requesting fid.
62pub const LOCK_SUCCESS: u8 = LockStatus::Success.as_wire();
63
64/// `Rlock.status`: a conflicting lock exists and the request wanted to block.
65pub const LOCK_BLOCKED: u8 = LockStatus::Blocked.as_wire();
66
67/// `Rlock.status`: the server refused the lock.
68pub const LOCK_ERROR: u8 = LockStatus::LockError.as_wire();
69
70/// `Rlock.status`: the server is in its post-restart grace period.
71pub const LOCK_GRACE: u8 = LockStatus::Grace.as_wire();
72
73/// `Trebind` restores a previously recorded fid after reconnection.
74pub const REBIND_REPLAY: u8 = P9_REBIND_REPLAY;
75
76/// `Trebind` marks a fid for a forthcoming in-place replay reopen. The flag
77/// grants neither access nor an inode pin.
78pub const REBIND_OPENED: u8 = P9_REBIND_OPENED;
79
80/// All currently defined `Trebind.flags` bits.
81pub const REBIND_KNOWN_FLAGS: u8 = P9_REBIND_KNOWN_FLAGS;
82pub const REBIND_CREDENTIAL_SENTINEL: u8 = P9_REBIND_CREDENTIAL_SENTINEL;
83pub const REBIND_CREDENTIAL_VERSION: u8 = P9_REBIND_CREDENTIAL_VERSION;
84pub const REBIND_CREDENTIAL_GROUPS_INCOMPLETE: u8 = P9_REBIND_CREDENTIAL_GROUPS_INCOMPLETE;
85pub const REBIND_CREDENTIAL_HEADER_SIZE: usize = P9_REBIND_CREDENTIAL_HEADER_SIZE;
86pub const REBIND_CREDENTIAL_MAX_SIZE: usize = P9_REBIND_CREDENTIAL_MAX_SIZE;
87
88/// Exclusive end of a 9P lock range. A zero length extends to EOF.
89///
90/// This is the single source of truth for 9P lock arithmetic.
91/// `lock_range.rs` wraps it for the server's allocating API.
92pub fn lock_range_end(start: u64, length: u64) -> u64 {
93    if length == 0 {
94        u64::MAX
95    } else {
96        start.saturating_add(length)
97    }
98}
99
100/// Remove one range from another, returning the surviving left and right
101/// fragments as `(start, length)`. A zero length extends to EOF, both on input
102/// and on a right fragment that reaches it.
103///
104/// At most two fragments survive, so the fixed array is exact rather than a
105/// bound.
106pub fn subtract_lock_range(
107    held_start: u64,
108    held_length: u64,
109    remove_start: u64,
110    remove_length: u64,
111) -> [Option<(u64, u64)>; 2] {
112    let held_end = lock_range_end(held_start, held_length);
113    let remove_end = lock_range_end(remove_start, remove_length);
114    if held_start >= remove_end || remove_start >= held_end {
115        return [Some((held_start, held_length)), None];
116    }
117
118    let mut left = None;
119    if held_start < remove_start {
120        let left_end = remove_start.min(held_end);
121        if held_start < left_end {
122            left = Some((held_start, left_end - held_start));
123        }
124    }
125
126    let mut right = None;
127    if remove_end < held_end {
128        let right_start = remove_end.max(held_start);
129        if right_start < held_end {
130            // Re-encode an open-ended survivor as EOF rather than as the
131            // distance to u64::MAX, which would bound a lock that is not.
132            let right_length = if held_end == u64::MAX {
133                0
134            } else {
135                held_end - right_start
136            };
137            right = Some((right_start, right_length));
138        }
139    }
140
141    [left, right]
142}
143
144/// Bytes in `size[4] + type[1] + tag[2]`.
145pub const HEADER_SIZE: usize = P9_HEADER_SIZE;
146
147/// Bytes in a mutation operation identifier.
148pub const OP_ID_SIZE: usize = P9_OP_ID_LEN;
149
150/// The frame is an ambiguous resend of an operation identifier.
151pub const OP_FLAG_RETRY: u8 = P9_OP_FLAG_RETRY;
152
153/// All mutation-envelope flag bits currently defined by ZeroFS.
154pub const OP_KNOWN_FLAGS: u8 = P9_OP_KNOWN_FLAGS;
155
156/// Bytes in `op_id[16] + flags[1] + origin_writer_epoch[8]`.
157pub const OP_ENVELOPE_SIZE: usize = P9_OP_ENVELOPE_LEN;
158
159/// Fixed wire bytes in an enveloped `Twrite`, before its data payload.
160pub const TWRITE_OVERHEAD: usize = HEADER_SIZE + OP_ENVELOPE_SIZE + 4 + 8 + 4;
161
162/// Fixed wire bytes in `Rlopenatread`, before its data payload.
163pub const RLOPENATREAD_OVERHEAD: usize = P9_RLOPENATREAD_HDR as usize;
164
165/// Serialized size of a [`Qid`].
166pub const QID_WIRE_SIZE: usize = Qid::WIRE_SIZE;
167
168/// Serialized size of a [`Stat`].
169pub const STAT_WIRE_SIZE: usize = Stat::WIRE_SIZE;
170
171/// A bounded codec failure.
172#[derive(Clone, Copy, Debug, PartialEq, Eq)]
173pub enum CodecError {
174    /// The caller-provided output buffer cannot hold the request.
175    BufferTooSmall,
176    /// An encoded or declared frame exceeds the caller's message-size limit.
177    MessageTooLarge,
178    /// A 9P string exceeds the `u16` length field.
179    StringTooLong,
180    /// A walk contains more names than its `u16` count can represent.
181    TooManyNames,
182    /// An integer length computation overflowed.
183    LengthOverflow,
184    /// A frame or variable-length field ends before its declared length.
185    Truncated,
186    /// A declared frame size is smaller than the 9P header.
187    InvalidFrameSize,
188    /// The frame slice contains fewer or more bytes than its size field.
189    FrameSizeMismatch,
190    /// `Tversion` did not use `NOTAG`, or another request did use it.
191    InvalidTag,
192    /// The response tag does not match the outstanding request.
193    TagMismatch {
194        /// Tag allocated to the request.
195        expected: u16,
196        /// Tag received from the server.
197        actual: u16,
198    },
199    /// The frame type is outside the response subset understood here.
200    UnexpectedMessageType(u8),
201    /// A decoded fixed-layout response has extra bytes.
202    TrailingData,
203    /// A lock type is outside the three values defined by 9P.
204    InvalidLockType,
205}
206
207impl core::fmt::Display for CodecError {
208    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
209        write!(f, "9P codec error: {self:?}")
210    }
211}
212impl core::error::Error for CodecError {}
213impl From<core::num::TryFromIntError> for CodecError {
214    fn from(_: core::num::TryFromIntError) -> Self {
215        Self::LengthOverflow
216    }
217}
218
219/// Largest data payload an enveloped `Twrite` can carry within `msize`.
220pub fn max_write_payload(msize: u32) -> u32 {
221    msize.saturating_sub(TWRITE_OVERHEAD as u32)
222}
223
224/// Largest data payload an `Rlopenatread` can carry within `msize`.
225pub fn max_lopenatread_payload(msize: u32) -> u32 {
226    msize.saturating_sub(RLOPENATREAD_OVERHEAD as u32)
227}
228
229/// One request supported by the native client.
230#[derive(Clone, Copy)]
231pub enum Request<'a> {
232    /// Negotiate `9P2000.L.Z`. This request must use [`NOTAG`].
233    Tversion { msize: u32, version: &'a [u8] },
234    /// Query durability lineage and the active writer epoch.
235    Tgetlineage,
236    /// Bind a fresh fid to a known inode.
237    Trebind {
238        fid: u32,
239        inode_id: u64,
240        root_inode: u64,
241        flags: u8,
242        /// Legacy UTF-8 username, or the versioned binary credential payload.
243        uname: &'a [u8],
244        /// Numeric uid; this is fsuid when `uname` is a credential payload.
245        n_uname: u32,
246    },
247    /// Walk all names and return attributes for the destination.
248    Twalkgetattr {
249        fid: u32,
250        newfid: u32,
251        names: &'a [&'a [u8]],
252    },
253    /// Fetch attributes for a fid.
254    Tgetattr { fid: u32, request_mask: u64 },
255    /// Atomically update selected attributes and return the post-operation stat.
256    Tsetattrattr {
257        envelope: MutationEnvelope,
258        fid: u32,
259        valid: u32,
260        mode: u32,
261        uid: u32,
262        gid: u32,
263        size: u64,
264        atime_sec: u64,
265        atime_nsec: u64,
266        mtime_sec: u64,
267        mtime_nsec: u64,
268    },
269    /// Atomically allocate, punch, or zero a regular-file range.
270    Tfallocate {
271        envelope: MutationEnvelope,
272        fid: u32,
273        offset: u64,
274        length: u64,
275        mode: u32,
276    },
277    /// Open a copy of `fid` as `newfid`.
278    Tlopenat { fid: u32, newfid: u32, flags: u32 },
279    /// Open a copy of `fid` and prefetch bytes from offset zero.
280    Tlopenatread {
281        fid: u32,
282        newfid: u32,
283        flags: u32,
284        count: u32,
285    },
286    /// Create and open a regular file on `newfid`, preserving `dfid`.
287    Tlcreateattr {
288        envelope: MutationEnvelope,
289        dfid: u32,
290        newfid: u32,
291        name: &'a [u8],
292        flags: u32,
293        mode: u32,
294        gid: u32,
295    },
296    /// Create a directory and return its post-operation stat.
297    Tmkdirattr {
298        envelope: MutationEnvelope,
299        dfid: u32,
300        name: &'a [u8],
301        mode: u32,
302        gid: u32,
303    },
304    /// Create a symlink and return its post-operation stat.
305    Tsymlinkattr {
306        envelope: MutationEnvelope,
307        dfid: u32,
308        name: &'a [u8],
309        target: &'a [u8],
310        gid: u32,
311    },
312    /// Create a special node and return its post-operation stat.
313    Tmknodattr {
314        envelope: MutationEnvelope,
315        dfid: u32,
316        name: &'a [u8],
317        mode: u32,
318        major: u32,
319        minor: u32,
320        gid: u32,
321    },
322    /// Create a hard link and return the linked inode's post-operation stat.
323    Tlinkattr {
324        envelope: MutationEnvelope,
325        dfid: u32,
326        fid: u32,
327        name: &'a [u8],
328    },
329    /// Atomically rename one directory entry, replacing a compatible target.
330    Trenameat {
331        envelope: MutationEnvelope,
332        olddirfid: u32,
333        oldname: &'a [u8],
334        newdirfid: u32,
335        newname: &'a [u8],
336    },
337    /// Remove a directory entry; `AT_REMOVEDIR` selects rmdir semantics.
338    Tunlinkat {
339        envelope: MutationEnvelope,
340        dirfid: u32,
341        name: &'a [u8],
342        flags: u32,
343    },
344    /// Read a symlink's opaque target bytes.
345    Treadlink { fid: u32 },
346    /// Cancel or retire the outstanding request identified by `oldtag`.
347    Tflush { oldtag: u16 },
348    /// Read bytes from an open fid.
349    Tread { fid: u32, offset: u64, count: u32 },
350    /// Write bytes to an open fid using the ZeroFS mutation envelope.
351    Twrite {
352        envelope: MutationEnvelope,
353        fid: u32,
354        offset: u64,
355        data: &'a [u8],
356    },
357    /// Flush and verify the lineage of previously acknowledged writes.
358    Tfsyncdur { fid: u32, datasync: u32, token: u64 },
359    /// Read directory entries carrying full attributes.
360    Treaddirattr { fid: u32, offset: u64, count: u32 },
361    /// Release a fid.
362    Tclunk { fid: u32 },
363    /// Fetch filesystem capacity and limits.
364    Tstatfs { fid: u32 },
365    /// Acquire or release a byte range. `lock_type` is one of the
366    /// `LOCK_TYPE_*` values; a conflict is answered rather than waited on.
367    Tlock {
368        fid: u32,
369        lock_type: u8,
370        flags: u32,
371        start: u64,
372        length: u64,
373        proc_id: u32,
374        /// Opaque lock owner identity, echoed back by `Rgetlock`.
375        client_id: &'a [u8],
376    },
377    /// Report the lock that would conflict with this range, if any.
378    Tgetlock {
379        fid: u32,
380        lock_type: u8,
381        start: u64,
382        length: u64,
383        proc_id: u32,
384        client_id: &'a [u8],
385    },
386}
387
388impl Request<'_> {
389    fn as_message(&self) -> Result<(Message<'_>, MutationEnvelope), CodecError> {
390        Ok(match *self {
391            Self::Tversion { msize, version } => (
392                Message::Tversion { msize, version },
393                MutationEnvelope::default(),
394            ),
395            Self::Tgetlineage => (Message::Tgetlineage {}, MutationEnvelope::default()),
396            Self::Trebind {
397                fid,
398                inode_id,
399                root_inode,
400                flags,
401                uname,
402                n_uname,
403            } => (
404                Message::Trebind {
405                    fid,
406                    inode_id,
407                    root_inode,
408                    flags,
409                    uname,
410                    n_uname,
411                },
412                MutationEnvelope::default(),
413            ),
414            Self::Twalkgetattr { fid, newfid, names } => (
415                Message::Twalkgetattr {
416                    fid,
417                    newfid,
418                    nwname: names
419                        .len()
420                        .try_into()
421                        .map_err(|_| CodecError::TooManyNames)?,
422                    wnames: Names::Slices(names),
423                },
424                MutationEnvelope::default(),
425            ),
426            Self::Tgetattr { fid, request_mask } => (
427                Message::Tgetattr { fid, request_mask },
428                MutationEnvelope::default(),
429            ),
430            Self::Tsetattrattr {
431                envelope,
432                fid,
433                valid,
434                mode,
435                uid,
436                gid,
437                size,
438                atime_sec,
439                atime_nsec,
440                mtime_sec,
441                mtime_nsec,
442            } => (
443                Message::Tsetattrattr {
444                    fid,
445                    valid,
446                    mode,
447                    uid,
448                    gid,
449                    size,
450                    atime_sec,
451                    atime_nsec,
452                    mtime_sec,
453                    mtime_nsec,
454                },
455                envelope,
456            ),
457            Self::Tfallocate {
458                envelope,
459                fid,
460                offset,
461                length,
462                mode,
463            } => (
464                Message::Tfallocate {
465                    fid,
466                    offset,
467                    length,
468                    mode,
469                },
470                envelope,
471            ),
472            Self::Tlopenat { fid, newfid, flags } => (
473                Message::Tlopenat { fid, newfid, flags },
474                MutationEnvelope::default(),
475            ),
476            Self::Tlopenatread {
477                fid,
478                newfid,
479                flags,
480                count,
481            } => (
482                Message::Tlopenatread {
483                    fid,
484                    newfid,
485                    flags,
486                    count,
487                },
488                MutationEnvelope::default(),
489            ),
490            Self::Tlcreateattr {
491                envelope,
492                dfid,
493                newfid,
494                name,
495                flags,
496                mode,
497                gid,
498            } => (
499                Message::Tlcreateattr {
500                    dfid,
501                    newfid,
502                    name,
503                    flags,
504                    mode,
505                    gid,
506                },
507                envelope,
508            ),
509            Self::Tmkdirattr {
510                envelope,
511                dfid,
512                name,
513                mode,
514                gid,
515            } => (
516                Message::Tmkdirattr {
517                    dfid,
518                    name,
519                    mode,
520                    gid,
521                },
522                envelope,
523            ),
524            Self::Tsymlinkattr {
525                envelope,
526                dfid,
527                name,
528                target,
529                gid,
530            } => (
531                Message::Tsymlinkattr {
532                    dfid,
533                    name,
534                    symtgt: target,
535                    gid,
536                },
537                envelope,
538            ),
539            Self::Tmknodattr {
540                envelope,
541                dfid,
542                name,
543                mode,
544                major,
545                minor,
546                gid,
547            } => (
548                Message::Tmknodattr {
549                    dfid,
550                    name,
551                    mode,
552                    major,
553                    minor,
554                    gid,
555                },
556                envelope,
557            ),
558            Self::Tlinkattr {
559                envelope,
560                dfid,
561                fid,
562                name,
563            } => (Message::Tlinkattr { dfid, fid, name }, envelope),
564            Self::Trenameat {
565                envelope,
566                olddirfid,
567                oldname,
568                newdirfid,
569                newname,
570            } => (
571                Message::Trenameat {
572                    olddirfid,
573                    oldname,
574                    newdirfid,
575                    newname,
576                },
577                envelope,
578            ),
579            Self::Tunlinkat {
580                envelope,
581                dirfid,
582                name,
583                flags,
584            } => (
585                Message::Tunlinkat {
586                    dirfid,
587                    name,
588                    flags,
589                },
590                envelope,
591            ),
592            Self::Treadlink { fid } => (Message::Treadlink { fid }, MutationEnvelope::default()),
593            Self::Tflush { oldtag } => (Message::Tflush { oldtag }, MutationEnvelope::default()),
594            Self::Tread { fid, offset, count } => (
595                Message::Tread { fid, offset, count },
596                MutationEnvelope::default(),
597            ),
598            Self::Twrite {
599                envelope,
600                fid,
601                offset,
602                data,
603            } => (
604                Message::Twrite {
605                    fid,
606                    offset,
607                    count: data
608                        .len()
609                        .try_into()
610                        .map_err(|_| CodecError::MessageTooLarge)?,
611                    data,
612                },
613                envelope,
614            ),
615            Self::Tfsyncdur {
616                fid,
617                datasync,
618                token,
619            } => (
620                Message::Tfsyncdur {
621                    fid,
622                    datasync,
623                    token,
624                },
625                MutationEnvelope::default(),
626            ),
627            Self::Treaddirattr { fid, offset, count } => (
628                Message::Treaddirattr { fid, offset, count },
629                MutationEnvelope::default(),
630            ),
631            Self::Tclunk { fid } => (Message::Tclunk { fid }, MutationEnvelope::default()),
632            Self::Tstatfs { fid } => (Message::Tstatfs { fid }, MutationEnvelope::default()),
633            Self::Tlock {
634                fid,
635                lock_type,
636                flags,
637                start,
638                length,
639                proc_id,
640                client_id,
641            } => (
642                Message::Tlock {
643                    fid,
644                    lock_type: lock_type.try_into()?,
645                    flags,
646                    start,
647                    length,
648                    proc_id,
649                    client_id,
650                },
651                MutationEnvelope::default(),
652            ),
653            Self::Tgetlock {
654                fid,
655                lock_type,
656                start,
657                length,
658                proc_id,
659                client_id,
660            } => (
661                Message::Tgetlock {
662                    fid,
663                    lock_type: lock_type.try_into()?,
664                    start,
665                    length,
666                    proc_id,
667                    client_id,
668                },
669                MutationEnvelope::default(),
670            ),
671        })
672    }
673    fn tag_is_valid(&self, tag: u16) -> bool {
674        matches!(self, Self::Tversion { .. }) == (tag == NOTAG)
675    }
676}
677/// Encode a native-client request using the canonical frame codec.
678pub fn encode_request(
679    output: &mut [u8],
680    max_msize: u32,
681    tag: u16,
682    request: Request<'_>,
683) -> Result<usize, CodecError> {
684    if !request.tag_is_valid(tag) {
685        return Err(CodecError::InvalidTag);
686    }
687    let (body, envelope) = request.as_message()?;
688    encode_frame(output, max_msize, tag, envelope, &body, true)
689}
690/// Exact bytes needed for a native-client request, including its envelope.
691pub fn encoded_request_size(request: &Request<'_>) -> Result<usize, CodecError> {
692    let (body, _) = request.as_message()?;
693    encoded_frame_size(&body, true)
694}
695
696/// Encode the fixed portion of an enveloped `Twrite`.
697///
698/// The returned bytes declare the complete frame size and payload count, but
699/// deliberately omit the payload itself. A stream transport can submit this
700/// prefix and the caller-owned payload as two adjacent scatter-gather
701/// segments without first copying the payload into an encoded frame.
702pub fn encode_twrite_prefix(
703    output: &mut [u8],
704    max_msize: u32,
705    tag: u16,
706    envelope: MutationEnvelope,
707    fid: u32,
708    offset: u64,
709    data_length: usize,
710) -> Result<usize, CodecError> {
711    if tag == NOTAG {
712        return Err(CodecError::InvalidTag);
713    }
714    if data_length > u32::MAX as usize {
715        return Err(CodecError::MessageTooLarge);
716    }
717    let frame_size = TWRITE_OVERHEAD
718        .checked_add(data_length)
719        .ok_or(CodecError::LengthOverflow)?;
720    if frame_size > u32::MAX as usize || frame_size > max_msize as usize {
721        return Err(CodecError::MessageTooLarge);
722    }
723
724    let mut writer = Writer::new(output);
725    writer.put_u32(frame_size as u32)?;
726    writer.put_u8(message_type::TWRITE)?;
727    writer.put_u16(tag)?;
728    put_mutation_envelope(&mut writer, envelope)?;
729    writer.put_u32(fid)?;
730    writer.put_u64(offset)?;
731    writer.put_u32(data_length as u32)?;
732    Ok(writer.position)
733}
734
735/// Validate a four-byte frame prefix and return its declared size.
736///
737/// A socket transport can call this after reading the first four bytes, then
738/// read exactly the returned size minus four into its fixed receive buffer.
739pub fn decode_frame_size(prefix: &[u8], max_msize: u32) -> Result<usize, CodecError> {
740    let mut reader = Reader::new(prefix);
741    let size = reader.get_u32()?;
742    if size < HEADER_SIZE as u32 {
743        return Err(CodecError::InvalidFrameSize);
744    }
745    if size > max_msize {
746        return Err(CodecError::MessageTooLarge);
747    }
748    Ok(size as usize)
749}
750
751/// Decode the seven-byte header at the start of a response frame.
752///
753/// The body need not be present yet. A stream receiver uses this to validate
754/// the declared allocation and route the response by tag before reading the
755/// remainder of the frame.
756pub fn decode_header(prefix: &[u8], max_msize: u32) -> Result<Header, CodecError> {
757    let declared_size = decode_frame_size(prefix, max_msize)?;
758    let mut reader = Reader::new(prefix);
759    let _size = reader.get_u32()?;
760    let type_ = reader.get_u8()?;
761    let tag = reader.get_u16()?;
762    Ok(Header {
763        size: declared_size as u32,
764        type_,
765        tag,
766    })
767}
768
769/// Header common to every decoded response.
770#[derive(Clone, Copy, Debug, PartialEq, Eq)]
771pub struct Header {
772    pub size: u32,
773    pub type_: u8,
774    pub tag: u16,
775}
776
777/// A borrowed, validated response frame.
778#[derive(Clone, Copy, Debug)]
779pub struct DecodedResponse<'a> {
780    pub header: Header,
781    pub body: Response<'a>,
782}
783
784/// A decoded response in the native client subset.
785#[derive(Clone, Copy, Debug)]
786pub enum Response<'a> {
787    Rversion(Rversion<'a>),
788    Rgetlineage(Rgetlineage),
789    Rrebind(Rrebind),
790    Rwalkgetattr(Rwalkgetattr<'a>),
791    Rgetattr(Rgetattr),
792    Rsetattrattr(Stat),
793    Rfallocate,
794    /// Standard 9P `Rlopen` (type 13), accepted for compatibility.
795    Rlopen(Rlopen),
796    /// ZeroFS-private response to `Tlopenat` (type 237).
797    Rlopenat(Rlopen),
798    /// ZeroFS-private response to `Tlopenatread` (type 231).
799    Rlopenatread(Rlopenatread<'a>),
800    Rlcreateattr(Rlcreateattr),
801    Rmkdirattr(Stat),
802    Rsymlinkattr(Stat),
803    Rmknodattr(Stat),
804    Rlinkattr(Stat),
805    Rrenameat,
806    Runlinkat,
807    Rreadlink(Rreadlink<'a>),
808    Rflush,
809    Rread(Rread<'a>),
810    Rwrite(Rwrite),
811    Rfsync,
812    Rreaddirattr(Rreaddirattr<'a>),
813    Rclunk,
814    Rstatfs(Rstatfs),
815    Rlock(Rlock),
816    Rgetlock(Rgetlock<'a>),
817    Rlerror(Rlerror),
818}
819
820#[derive(Clone, Copy, Debug, PartialEq, Eq)]
821pub struct Rversion<'a> {
822    pub msize: u32,
823    pub version: WireString<&'a [u8]>,
824}
825
826#[derive(Clone, Copy, Debug)]
827pub struct Rwalkgetattr<'a> {
828    pub qids: Qids<'a>,
829    pub stat: Stat,
830}
831
832#[derive(Clone, Copy, Debug, PartialEq, Eq)]
833pub struct Rreadlink<'a> {
834    pub target: WireString<&'a [u8]>,
835}
836
837#[derive(Clone, Copy, Debug, PartialEq, Eq)]
838pub struct Rread<'a> {
839    pub data: WireBytes<&'a [u8]>,
840}
841
842/// Open result and best-effort data prefetched from offset zero.
843#[derive(Clone, Copy, Debug, PartialEq, Eq)]
844pub struct Rlopenatread<'a> {
845    pub qid: Qid,
846    pub iounit: u32,
847    /// One when `data` reaches EOF; zero when the prefetch is incomplete.
848    pub eof: u8,
849    pub data: WireBytes<&'a [u8]>,
850}
851
852/// Validated `Rreaddirattr` payload.
853#[derive(Clone, Copy, Debug)]
854pub struct Rreaddirattr<'a> {
855    data: WireBytes<&'a [u8]>,
856    entry_count: usize,
857}
858
859impl<'a> Rreaddirattr<'a> {
860    /// Serialized directory payload, excluding the outer `count[4]`.
861    pub fn data(&self) -> &'a [u8] {
862        self.data.0
863    }
864
865    /// Number of complete [`DirEntryPlus`] records in the payload.
866    pub fn len(&self) -> usize {
867        self.entry_count
868    }
869
870    pub fn is_empty(&self) -> bool {
871        self.entry_count == 0
872    }
873
874    /// Iterate over entries without allocating.
875    pub fn entries(&self) -> DirEntryPlusIter<'a> {
876        DirEntryPlusIter {
877            reader: Reader::new(self.data.0),
878            remaining: self.entry_count,
879        }
880    }
881}
882
883/// Validate a bare `Rreaddirattr.data` payload and return a borrowed view.
884///
885/// VFS callers use this on a request-owned reply frame, so directory actors
886/// never run while holding client state.
887pub fn decode_readdirattr_payload(data: &[u8]) -> Result<Rreaddirattr<'_>, CodecError> {
888    let entry_count = validate_dir_entries(data)?;
889    Ok(Rreaddirattr {
890        data: WireBytes::from(data),
891        entry_count,
892    })
893}
894
895/// The lock that would conflict with a `Tgetlock` probe.
896///
897/// No conflict is reported as `lock_type == LOCK_TYPE_UNLCK` with an empty
898/// `client_id`, so a zero-length string is the common case and not truncation.
899/// `client_id` borrows the reply frame; copy what you need before releasing it.
900#[derive(Clone, Copy, Debug, PartialEq, Eq)]
901pub struct Rgetlock<'a> {
902    pub lock_type: u8,
903    pub start: u64,
904    pub length: u64,
905    pub proc_id: u32,
906    pub client_id: WireString<&'a [u8]>,
907}
908
909/// Decode one complete response.
910///
911/// The decoder validates the size field, `max_msize`, tag, fixed-layout body
912/// length, counted payloads, every directory entry, and trailing data.
913pub fn decode_response<'a>(
914    frame: &'a [u8],
915    max_msize: u32,
916    expected_tag: u16,
917) -> Result<DecodedResponse<'a>, CodecError> {
918    let header = decode_header(frame, max_msize)?;
919    if header.size as usize != frame.len() {
920        return Err(CodecError::FrameSizeMismatch);
921    }
922    if header.tag != expected_tag {
923        return Err(CodecError::TagMismatch {
924            expected: expected_tag,
925            actual: header.tag,
926        });
927    }
928    let frame = decode_frame(frame, max_msize, false)?;
929    let body = match frame.body {
930        Message::Rgetlineage {
931            token,
932            writer_epoch,
933        } => Response::Rgetlineage(Rgetlineage {
934            token,
935            writer_epoch,
936        }),
937        Message::Rrebind { qid } => Response::Rrebind(Rrebind { qid }),
938        Message::Rgetattr { valid, stat } => Response::Rgetattr(Rgetattr { valid, stat }),
939        Message::Rlcreateattr { iounit, stat } => {
940            Response::Rlcreateattr(Rlcreateattr { iounit, stat })
941        }
942        Message::Rwrite { count } => Response::Rwrite(Rwrite { count }),
943        Message::Rstatfs {
944            r#type,
945            bsize,
946            blocks,
947            bfree,
948            bavail,
949            files,
950            ffree,
951            fsid,
952            namelen,
953        } => Response::Rstatfs(Rstatfs {
954            r#type,
955            bsize,
956            blocks,
957            bfree,
958            bavail,
959            files,
960            ffree,
961            fsid,
962            namelen,
963        }),
964        Message::Rlock { status } => Response::Rlock(Rlock { status }),
965        Message::Rlerror { ecode } => Response::Rlerror(Rlerror { ecode }),
966        Message::Rsetattrattr { stat } => Response::Rsetattrattr(stat),
967        Message::Rmkdirattr { stat } => Response::Rmkdirattr(stat),
968        Message::Rsymlinkattr { stat } => Response::Rsymlinkattr(stat),
969        Message::Rmknodattr { stat } => Response::Rmknodattr(stat),
970        Message::Rlinkattr { stat } => Response::Rlinkattr(stat),
971        Message::Rfallocate {} => Response::Rfallocate,
972        Message::Rrenameat {} => Response::Rrenameat,
973        Message::Runlinkat {} => Response::Runlinkat,
974        Message::Rflush {} => Response::Rflush,
975        Message::Rfsync {} => Response::Rfsync,
976        Message::Rclunk {} => Response::Rclunk,
977        Message::Rlopen { qid, iounit } => Response::Rlopen(Rlopen { qid, iounit }),
978        Message::Rlopenat { qid, iounit } => Response::Rlopenat(Rlopen { qid, iounit }),
979        Message::Rversion { msize, version } => Response::Rversion(Rversion {
980            msize,
981            version: WireString::from_storage(version),
982        }),
983        Message::Rwalkgetattr {
984            wqids: QidList::Encoded(bytes),
985            nwqid: count,
986            stat,
987        } => Response::Rwalkgetattr(Rwalkgetattr {
988            qids: Qids { bytes, count },
989            stat,
990        }),
991        Message::Rreadlink { target } => Response::Rreadlink(Rreadlink {
992            target: WireString::from_storage(target),
993        }),
994        Message::Rread { data, .. } => Response::Rread(Rread {
995            data: WireBytes::from(data),
996        }),
997        Message::Rlopenatread {
998            qid,
999            iounit,
1000            eof,
1001            data,
1002            ..
1003        } => Response::Rlopenatread(Rlopenatread {
1004            qid,
1005            iounit,
1006            eof,
1007            data: WireBytes::from(data),
1008        }),
1009        Message::Rreaddirattr { data, .. } => {
1010            Response::Rreaddirattr(decode_readdirattr_payload(data)?)
1011        }
1012        Message::Rgetlock {
1013            lock_type,
1014            start,
1015            length,
1016            proc_id,
1017            client_id,
1018        } => Response::Rgetlock(Rgetlock {
1019            lock_type: lock_type as u8,
1020            start,
1021            length,
1022            proc_id,
1023            client_id: WireString::from_storage(client_id),
1024        }),
1025        other => return Err(CodecError::UnexpectedMessageType(other.type_id())),
1026    };
1027    Ok(DecodedResponse {
1028        header: frame.header,
1029        body,
1030    })
1031}
1032
1033/// Borrowed list of QIDs in `Rwalkgetattr`.
1034#[derive(Clone, Copy, Debug)]
1035pub struct Qids<'a> {
1036    bytes: &'a [u8],
1037    count: u16,
1038}
1039
1040impl<'a> Qids<'a> {
1041    pub fn len(&self) -> usize {
1042        self.count as usize
1043    }
1044
1045    pub fn is_empty(&self) -> bool {
1046        self.count == 0
1047    }
1048
1049    /// Decode the QID at `index`.
1050    pub fn get(&self, index: usize) -> Option<Qid> {
1051        if index >= self.len() {
1052            return None;
1053        }
1054        let start = index.checked_mul(QID_WIRE_SIZE)?;
1055        let end = start.checked_add(QID_WIRE_SIZE)?;
1056        let bytes = self.bytes.get(start..end)?;
1057        let mut reader = Reader::new(bytes);
1058        decode_qid(&mut reader).ok()
1059    }
1060
1061    pub fn iter(&self) -> QidIter<'a> {
1062        QidIter {
1063            qids: *self,
1064            index: 0,
1065        }
1066    }
1067}
1068
1069/// Iterator over a borrowed [`Qids`] list.
1070pub struct QidIter<'a> {
1071    qids: Qids<'a>,
1072    index: usize,
1073}
1074
1075impl Iterator for QidIter<'_> {
1076    type Item = Qid;
1077
1078    fn next(&mut self) -> Option<Self::Item> {
1079        let qid = self.qids.get(self.index)?;
1080        self.index = self.index.saturating_add(1);
1081        Some(qid)
1082    }
1083
1084    fn size_hint(&self) -> (usize, Option<usize>) {
1085        let remaining = self.qids.len().saturating_sub(self.index);
1086        (remaining, Some(remaining))
1087    }
1088}
1089
1090impl ExactSizeIterator for QidIter<'_> {}
1091
1092/// One entry in an `Rreaddirattr` counted payload.
1093#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1094pub struct DirEntryPlus<'a> {
1095    pub qid: Qid,
1096    /// Cookie to send in the next `Treaddirattr`.
1097    pub offset: u64,
1098    pub type_: u8,
1099    pub name: &'a [u8],
1100    pub stat: Stat,
1101}
1102
1103/// Allocation-free iterator over validated `Rreaddirattr` entries.
1104pub struct DirEntryPlusIter<'a> {
1105    reader: Reader<'a>,
1106    remaining: usize,
1107}
1108
1109impl<'a> Iterator for DirEntryPlusIter<'a> {
1110    type Item = Result<DirEntryPlus<'a>, CodecError>;
1111
1112    fn next(&mut self) -> Option<Self::Item> {
1113        if self.remaining == 0 {
1114            return None;
1115        }
1116        self.remaining -= 1;
1117        Some(decode_dir_entry_plus(&mut self.reader))
1118    }
1119
1120    fn size_hint(&self) -> (usize, Option<usize>) {
1121        (self.remaining, Some(self.remaining))
1122    }
1123}
1124
1125impl ExactSizeIterator for DirEntryPlusIter<'_> {}
1126
1127fn validate_dir_entries(data: &[u8]) -> Result<usize, CodecError> {
1128    let mut reader = Reader::new(data);
1129    let mut count = 0usize;
1130    while reader.remaining() != 0 {
1131        let _entry = decode_dir_entry_plus(&mut reader)?;
1132        count = count.checked_add(1).ok_or(CodecError::LengthOverflow)?;
1133    }
1134    Ok(count)
1135}
1136
1137fn put_mutation_envelope(
1138    writer: &mut Writer<'_>,
1139    envelope: MutationEnvelope,
1140) -> Result<(), CodecError> {
1141    writer.put(&envelope.op_id)?;
1142    writer.put_u8(envelope.flags)?;
1143    writer.put_u64(envelope.origin_writer_epoch)
1144}
1145
1146fn string_size(value: &[u8]) -> Result<usize, CodecError> {
1147    if value.len() > u16::MAX as usize {
1148        return Err(CodecError::StringTooLong);
1149    }
1150    2usize
1151        .checked_add(value.len())
1152        .ok_or(CodecError::LengthOverflow)
1153}
1154
1155fn decode_dir_entry_plus<'a>(reader: &mut Reader<'a>) -> Result<DirEntryPlus<'a>, CodecError> {
1156    let (entry, length) = decode_entry(&reader.input[reader.position..], true)?;
1157    reader.take(length)?;
1158    Ok(DirEntryPlus {
1159        qid: entry.qid,
1160        offset: entry.offset,
1161        type_: entry.type_,
1162        name: entry.name,
1163        stat: entry.stat.ok_or(CodecError::Truncated)?,
1164    })
1165}
1166
1167fn decode_qid(reader: &mut Reader<'_>) -> Result<Qid, CodecError> {
1168    <Qid as messages::Fixed>::read(reader)
1169}
1170
1171struct Writer<'a> {
1172    output: &'a mut [u8],
1173    position: usize,
1174}
1175
1176impl<'a> Writer<'a> {
1177    fn new(output: &'a mut [u8]) -> Self {
1178        Self {
1179            output,
1180            position: 0,
1181        }
1182    }
1183
1184    fn put(&mut self, bytes: &[u8]) -> Result<(), CodecError> {
1185        let end = self
1186            .position
1187            .checked_add(bytes.len())
1188            .ok_or(CodecError::LengthOverflow)?;
1189        let destination = self
1190            .output
1191            .get_mut(self.position..end)
1192            .ok_or(CodecError::BufferTooSmall)?;
1193        destination.copy_from_slice(bytes);
1194        self.position = end;
1195        Ok(())
1196    }
1197
1198    fn put_u8(&mut self, value: u8) -> Result<(), CodecError> {
1199        self.put(&[value])
1200    }
1201
1202    fn put_u16(&mut self, value: u16) -> Result<(), CodecError> {
1203        self.put(&value.to_le_bytes())
1204    }
1205
1206    fn put_u32(&mut self, value: u32) -> Result<(), CodecError> {
1207        self.put(&value.to_le_bytes())
1208    }
1209
1210    fn put_u64(&mut self, value: u64) -> Result<(), CodecError> {
1211        self.put(&value.to_le_bytes())
1212    }
1213
1214    fn put_string(&mut self, value: &[u8]) -> Result<(), CodecError> {
1215        if value.len() > u16::MAX as usize {
1216            return Err(CodecError::StringTooLong);
1217        }
1218        self.put_u16(value.len() as u16)?;
1219        self.put(value)
1220    }
1221}
1222
1223#[derive(Clone, Copy, Debug)]
1224struct Reader<'a> {
1225    input: &'a [u8],
1226    position: usize,
1227}
1228
1229impl<'a> Reader<'a> {
1230    fn new(input: &'a [u8]) -> Self {
1231        Self { input, position: 0 }
1232    }
1233
1234    fn remaining(&self) -> usize {
1235        self.input.len().saturating_sub(self.position)
1236    }
1237
1238    fn take(&mut self, count: usize) -> Result<&'a [u8], CodecError> {
1239        let end = self
1240            .position
1241            .checked_add(count)
1242            .ok_or(CodecError::LengthOverflow)?;
1243        let bytes = self
1244            .input
1245            .get(self.position..end)
1246            .ok_or(CodecError::Truncated)?;
1247        self.position = end;
1248        Ok(bytes)
1249    }
1250
1251    fn get_u8(&mut self) -> Result<u8, CodecError> {
1252        match self.take(1)? {
1253            [value] => Ok(*value),
1254            _ => Err(CodecError::Truncated),
1255        }
1256    }
1257
1258    fn get_u16(&mut self) -> Result<u16, CodecError> {
1259        match self.take(2)? {
1260            [a, b] => Ok(u16::from_le_bytes([*a, *b])),
1261            _ => Err(CodecError::Truncated),
1262        }
1263    }
1264
1265    fn get_u32(&mut self) -> Result<u32, CodecError> {
1266        match self.take(4)? {
1267            [a, b, c, d] => Ok(u32::from_le_bytes([*a, *b, *c, *d])),
1268            _ => Err(CodecError::Truncated),
1269        }
1270    }
1271
1272    fn get_u64(&mut self) -> Result<u64, CodecError> {
1273        match self.take(8)? {
1274            [a, b, c, d, e, f, g, h] => Ok(u64::from_le_bytes([*a, *b, *c, *d, *e, *f, *g, *h])),
1275            _ => Err(CodecError::Truncated),
1276        }
1277    }
1278
1279    fn get_string(&mut self) -> Result<&'a [u8], CodecError> {
1280        let length = self.get_u16()? as usize;
1281        self.take(length)
1282    }
1283
1284    fn require_end(&self) -> Result<(), CodecError> {
1285        if self.remaining() == 0 {
1286            Ok(())
1287        } else {
1288            Err(CodecError::TrailingData)
1289        }
1290    }
1291}
1292
1293#[cfg(test)]
1294mod tests {
1295    use super::*;
1296    #[cfg(not(MODULE))]
1297    use std::{vec, vec::Vec};
1298
1299    const TEST_MSIZE: u32 = 4096;
1300
1301    fn put_header(frame: &mut [u8], type_: u8, tag: u16) {
1302        let size = frame.len() as u32;
1303        frame[0..4].copy_from_slice(&size.to_le_bytes());
1304        frame[4] = type_;
1305        frame[5..7].copy_from_slice(&tag.to_le_bytes());
1306    }
1307
1308    fn put_qid(writer: &mut Writer<'_>, qid: Qid) {
1309        writer.put_u8(qid.type_).unwrap();
1310        writer.put_u32(qid.version).unwrap();
1311        writer.put_u64(qid.path).unwrap();
1312    }
1313
1314    fn put_stat(writer: &mut Writer<'_>, stat: Stat) {
1315        put_qid(writer, stat.qid);
1316        writer.put_u32(stat.mode).unwrap();
1317        writer.put_u32(stat.uid).unwrap();
1318        writer.put_u32(stat.gid).unwrap();
1319        writer.put_u64(stat.nlink).unwrap();
1320        writer.put_u64(stat.rdev).unwrap();
1321        writer.put_u64(stat.size).unwrap();
1322        writer.put_u64(stat.blksize).unwrap();
1323        writer.put_u64(stat.blocks).unwrap();
1324        writer.put_u64(stat.atime_sec).unwrap();
1325        writer.put_u64(stat.atime_nsec).unwrap();
1326        writer.put_u64(stat.mtime_sec).unwrap();
1327        writer.put_u64(stat.mtime_nsec).unwrap();
1328        writer.put_u64(stat.ctime_sec).unwrap();
1329        writer.put_u64(stat.ctime_nsec).unwrap();
1330        writer.put_u64(stat.btime_sec).unwrap();
1331        writer.put_u64(stat.btime_nsec).unwrap();
1332        writer.put_u64(stat.r#gen).unwrap();
1333        writer.put_u64(stat.data_version).unwrap();
1334    }
1335
1336    fn mutation_envelope() -> MutationEnvelope {
1337        MutationEnvelope {
1338            op_id: [
1339                0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d,
1340                0x0e, 0x0f,
1341            ],
1342            flags: OP_FLAG_RETRY,
1343            origin_writer_epoch: 0x0807_0605_0403_0201,
1344        }
1345    }
1346
1347    fn encode_test_request(request: Request<'_>, tag: u16) -> Vec<u8> {
1348        let size = encoded_request_size(&request).unwrap();
1349        let mut frame = vec![0u8; size];
1350        assert_eq!(
1351            encode_request(&mut frame, TEST_MSIZE, tag, request),
1352            Ok(size)
1353        );
1354        frame
1355    }
1356
1357    fn assert_mutation_prefix(frame: &[u8], type_: u8, tag: u16) {
1358        assert_eq!(frame[4], type_);
1359        assert_eq!(&frame[5..7], &tag.to_le_bytes());
1360        assert_eq!(&frame[7..23], &mutation_envelope().op_id);
1361        assert_eq!(frame[23], OP_FLAG_RETRY);
1362        assert_eq!(
1363            &frame[24..32],
1364            &mutation_envelope().origin_writer_epoch.to_le_bytes()
1365        );
1366    }
1367
1368    #[test]
1369    fn malformed_borrowed_lists_cannot_be_encoded() {
1370        let walk = Message::Twalk {
1371            fid: 0,
1372            newfid: 1,
1373            nwname: 1,
1374            wnames: Names::Encoded {
1375                bytes: &[1, 0, b'a', b'b'],
1376                count: 1,
1377            },
1378        };
1379        assert_eq!(walk.body_size(), Err(CodecError::TrailingData));
1380        let walk = Message::Rwalk {
1381            nwqid: 1,
1382            wqids: QidList::Encoded(&[0; 14]),
1383        };
1384        assert_eq!(walk.body_size(), Err(CodecError::Truncated));
1385    }
1386
1387    #[test]
1388    fn tversion_matches_the_9p_layout() {
1389        let mut output = [0u8; 64];
1390        let request = Request::Tversion {
1391            msize: TEST_MSIZE,
1392            version: VERSION_9P2000L_ZEROFS,
1393        };
1394        assert_eq!(encoded_request_size(&request), Ok(23));
1395        let length = encode_request(&mut output, TEST_MSIZE, NOTAG, request).unwrap();
1396
1397        let expected = [
1398            23,
1399            0,
1400            0,
1401            0,
1402            message_type::TVERSION,
1403            0xff,
1404            0xff,
1405            0x00,
1406            0x10,
1407            0x00,
1408            0x00,
1409            10,
1410            0,
1411            b'9',
1412            b'P',
1413            b'2',
1414            b'0',
1415            b'0',
1416            b'0',
1417            b'.',
1418            b'L',
1419            b'.',
1420            b'Z',
1421        ];
1422        assert_eq!(&output[..length], &expected);
1423    }
1424
1425    #[test]
1426    fn tlopenatread_matches_the_compound_open_layout() {
1427        let request = Request::Tlopenatread {
1428            fid: 0x1122_3344,
1429            newfid: 0x5566_7788,
1430            flags: 0x99aa_bbcc,
1431            count: 0xddee_ff00,
1432        };
1433        assert_eq!(encoded_request_size(&request), Ok(HEADER_SIZE + 4 * 4));
1434
1435        let mut output = [0u8; HEADER_SIZE + 4 * 4];
1436        let length = encode_request(&mut output, TEST_MSIZE, 0x1234, request).unwrap();
1437        let expected = [
1438            23,
1439            0,
1440            0,
1441            0,
1442            message_type::TLOPENATREAD,
1443            0x34,
1444            0x12,
1445            0x44,
1446            0x33,
1447            0x22,
1448            0x11,
1449            0x88,
1450            0x77,
1451            0x66,
1452            0x55,
1453            0xcc,
1454            0xbb,
1455            0xaa,
1456            0x99,
1457            0x00,
1458            0xff,
1459            0xee,
1460            0xdd,
1461        ];
1462        assert_eq!(length, expected.len());
1463        assert_eq!(output, expected);
1464
1465        let request_size = output.len();
1466        assert_eq!(
1467            encode_request(&mut output, (request_size - 1) as u32, 0x1234, request),
1468            Err(CodecError::MessageTooLarge)
1469        );
1470        assert_eq!(
1471            encode_request(&mut output[..request_size - 1], TEST_MSIZE, 0x1234, request),
1472            Err(CodecError::BufferTooSmall)
1473        );
1474        assert_eq!(
1475            encode_request(&mut output, TEST_MSIZE, NOTAG, request),
1476            Err(CodecError::InvalidTag)
1477        );
1478    }
1479
1480    #[test]
1481    fn decodes_and_bounds_lopenatread_payloads() {
1482        assert_eq!(
1483            RLOPENATREAD_OVERHEAD,
1484            HEADER_SIZE + QID_WIRE_SIZE + 4 + 1 + 4
1485        );
1486        let tag = 0x1234;
1487        let qid = Qid {
1488            type_: QID_TYPE_FILE,
1489            version: 0x5566_7788,
1490            path: 0x0102_0304_0506_0708,
1491        };
1492        let mut frame = vec![0u8; RLOPENATREAD_OVERHEAD + 3];
1493        put_header(&mut frame, message_type::RLOPENATREAD, tag);
1494        let mut writer = Writer::new(&mut frame[HEADER_SIZE..]);
1495        put_qid(&mut writer, qid);
1496        writer.put_u32(8192).unwrap();
1497        writer.put_u8(1).unwrap();
1498        writer.put_u32(3).unwrap();
1499        writer.put(b"abc").unwrap();
1500
1501        match decode_response(&frame, frame.len() as u32, tag)
1502            .unwrap()
1503            .body
1504        {
1505            Response::Rlopenatread(reply) => {
1506                assert_eq!(reply.qid, qid);
1507                assert_eq!(reply.iounit, 8192);
1508                assert_eq!(reply.eof, 1);
1509                assert_eq!(reply.data.as_ref(), b"abc");
1510                assert_eq!(
1511                    reply.data.as_ref().as_ptr(),
1512                    frame[RLOPENATREAD_OVERHEAD..].as_ptr()
1513                );
1514            }
1515            _ => panic!("wrong response"),
1516        }
1517        assert!(matches!(
1518            decode_response(&frame, frame.len() as u32 - 1, tag),
1519            Err(CodecError::MessageTooLarge)
1520        ));
1521        assert_eq!(max_lopenatread_payload(frame.len() as u32), 3);
1522        assert_eq!(max_lopenatread_payload(RLOPENATREAD_OVERHEAD as u32 - 1), 0);
1523
1524        let mut fixed_prefix_truncated = vec![0u8; RLOPENATREAD_OVERHEAD - 1];
1525        put_header(&mut fixed_prefix_truncated, message_type::RLOPENATREAD, tag);
1526        assert!(matches!(
1527            decode_response(&fixed_prefix_truncated, TEST_MSIZE, tag),
1528            Err(CodecError::Truncated)
1529        ));
1530
1531        let count_offset = RLOPENATREAD_OVERHEAD - 4;
1532        let mut count_overrun = frame.clone();
1533        count_overrun[count_offset..RLOPENATREAD_OVERHEAD].copy_from_slice(&4u32.to_le_bytes());
1534        assert!(matches!(
1535            decode_response(&count_overrun, TEST_MSIZE, tag),
1536            Err(CodecError::Truncated)
1537        ));
1538
1539        let mut maximum_count = frame.clone();
1540        maximum_count[count_offset..RLOPENATREAD_OVERHEAD].copy_from_slice(&u32::MAX.to_le_bytes());
1541        assert!(matches!(
1542            decode_response(&maximum_count, TEST_MSIZE, tag),
1543            Err(CodecError::Truncated)
1544        ));
1545
1546        let mut trailing = frame;
1547        trailing[count_offset..RLOPENATREAD_OVERHEAD].copy_from_slice(&2u32.to_le_bytes());
1548        assert!(matches!(
1549            decode_response(&trailing, TEST_MSIZE, tag),
1550            Err(CodecError::TrailingData)
1551        ));
1552    }
1553
1554    #[test]
1555    fn twrite_matches_the_canonical_mutation_layout() {
1556        let mut output = [0u8; TWRITE_OVERHEAD + 3];
1557        let envelope = MutationEnvelope {
1558            op_id: [
1559                0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d,
1560                0x0e, 0x0f,
1561            ],
1562            flags: OP_FLAG_RETRY,
1563            origin_writer_epoch: 0x0807_0605_0403_0201,
1564        };
1565        let request = Request::Twrite {
1566            envelope,
1567            fid: 0x1122_3344,
1568            offset: 0x0102_0304_0506_0708,
1569            data: b"abc",
1570        };
1571        assert_eq!(encoded_request_size(&request), Ok(TWRITE_OVERHEAD + 3));
1572        let length = encode_request(&mut output, TEST_MSIZE, 0x1234, request).unwrap();
1573
1574        let expected = [
1575            51,
1576            0,
1577            0,
1578            0,
1579            message_type::TWRITE,
1580            0x34,
1581            0x12,
1582            0x00,
1583            0x01,
1584            0x02,
1585            0x03,
1586            0x04,
1587            0x05,
1588            0x06,
1589            0x07,
1590            0x08,
1591            0x09,
1592            0x0a,
1593            0x0b,
1594            0x0c,
1595            0x0d,
1596            0x0e,
1597            0x0f,
1598            OP_FLAG_RETRY,
1599            0x01,
1600            0x02,
1601            0x03,
1602            0x04,
1603            0x05,
1604            0x06,
1605            0x07,
1606            0x08,
1607            0x44,
1608            0x33,
1609            0x22,
1610            0x11,
1611            0x08,
1612            0x07,
1613            0x06,
1614            0x05,
1615            0x04,
1616            0x03,
1617            0x02,
1618            0x01,
1619            3,
1620            0,
1621            0,
1622            0,
1623            b'a',
1624            b'b',
1625            b'c',
1626        ];
1627        assert_eq!(length, expected.len());
1628        assert_eq!(output, expected);
1629
1630        let mut prefix = [0u8; TWRITE_OVERHEAD];
1631        assert_eq!(
1632            encode_twrite_prefix(
1633                &mut prefix,
1634                TEST_MSIZE,
1635                0x1234,
1636                envelope,
1637                0x1122_3344,
1638                0x0102_0304_0506_0708,
1639                3,
1640            ),
1641            Ok(TWRITE_OVERHEAD)
1642        );
1643        assert_eq!(prefix, expected[..TWRITE_OVERHEAD]);
1644    }
1645
1646    #[test]
1647    fn twrite_payload_is_bounded_by_the_enveloped_msize() {
1648        let maximum = max_write_payload(TEST_MSIZE) as usize;
1649        assert_eq!(maximum, TEST_MSIZE as usize - TWRITE_OVERHEAD);
1650
1651        let payload = vec![0xa5; maximum];
1652        let request = Request::Twrite {
1653            envelope: MutationEnvelope {
1654                op_id: [7; OP_ID_SIZE],
1655                flags: 0,
1656                origin_writer_epoch: 42,
1657            },
1658            fid: 9,
1659            offset: 11,
1660            data: &payload,
1661        };
1662        assert_eq!(encoded_request_size(&request), Ok(TEST_MSIZE as usize));
1663        let mut output = vec![0; TEST_MSIZE as usize];
1664        assert_eq!(
1665            encode_request(&mut output, TEST_MSIZE, 5, request),
1666            Ok(TEST_MSIZE as usize)
1667        );
1668        assert_eq!(
1669            &output[TWRITE_OVERHEAD - 4..TWRITE_OVERHEAD],
1670            &(maximum as u32).to_le_bytes()
1671        );
1672        assert_eq!(&output[TWRITE_OVERHEAD..], payload.as_slice());
1673
1674        let oversized = vec![0x5a; maximum + 1];
1675        let request = Request::Twrite {
1676            envelope: MutationEnvelope::default(),
1677            fid: 9,
1678            offset: 11,
1679            data: &oversized,
1680        };
1681        assert_eq!(encoded_request_size(&request), Ok(TEST_MSIZE as usize + 1));
1682        let mut output = vec![0; TEST_MSIZE as usize + 1];
1683        assert_eq!(
1684            encode_request(&mut output, TEST_MSIZE, 5, request),
1685            Err(CodecError::MessageTooLarge)
1686        );
1687    }
1688
1689    #[test]
1690    fn setattrattr_and_fallocate_match_canonical_mutation_layouts() {
1691        let setattr = encode_test_request(
1692            Request::Tsetattrattr {
1693                envelope: mutation_envelope(),
1694                fid: 0x1122_3344,
1695                valid: SETATTR_MODE | SETATTR_SIZE | SETATTR_MTIME | SETATTR_MTIME_SET,
1696                mode: 0o100640,
1697                uid: 1000,
1698                gid: 1001,
1699                size: 0x0102_0304_0506_0708,
1700                atime_sec: 11,
1701                atime_nsec: 12,
1702                mtime_sec: 13,
1703                mtime_nsec: 14,
1704            },
1705            0x1234,
1706        );
1707        assert_eq!(setattr.len(), 92);
1708        assert_mutation_prefix(&setattr, message_type::TSETATTRATTR, 0x1234);
1709        let mut body = Reader::new(&setattr[HEADER_SIZE + OP_ENVELOPE_SIZE..]);
1710        assert_eq!(body.get_u32(), Ok(0x1122_3344));
1711        assert_eq!(
1712            body.get_u32(),
1713            Ok(SETATTR_MODE | SETATTR_SIZE | SETATTR_MTIME | SETATTR_MTIME_SET)
1714        );
1715        assert_eq!(body.get_u32(), Ok(0o100640));
1716        assert_eq!(body.get_u32(), Ok(1000));
1717        assert_eq!(body.get_u32(), Ok(1001));
1718        assert_eq!(body.get_u64(), Ok(0x0102_0304_0506_0708));
1719        assert_eq!(body.get_u64(), Ok(11));
1720        assert_eq!(body.get_u64(), Ok(12));
1721        assert_eq!(body.get_u64(), Ok(13));
1722        assert_eq!(body.get_u64(), Ok(14));
1723        assert_eq!(body.require_end(), Ok(()));
1724
1725        let fallocate = encode_test_request(
1726            Request::Tfallocate {
1727                envelope: mutation_envelope(),
1728                fid: 9,
1729                offset: 10,
1730                length: 11,
1731                mode: FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE,
1732            },
1733            7,
1734        );
1735        assert_eq!(fallocate.len(), 56);
1736        assert_mutation_prefix(&fallocate, message_type::TFALLOCATE, 7);
1737        let mut body = Reader::new(&fallocate[HEADER_SIZE + OP_ENVELOPE_SIZE..]);
1738        assert_eq!(body.get_u32(), Ok(9));
1739        assert_eq!(body.get_u64(), Ok(10));
1740        assert_eq!(body.get_u64(), Ok(11));
1741        assert_eq!(
1742            body.get_u32(),
1743            Ok(FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE)
1744        );
1745        assert_eq!(body.require_end(), Ok(()));
1746    }
1747
1748    #[test]
1749    fn namespace_requests_match_canonical_compound_layouts() {
1750        let tag = 23;
1751
1752        let create = encode_test_request(
1753            Request::Tlcreateattr {
1754                envelope: mutation_envelope(),
1755                dfid: 1,
1756                newfid: 2,
1757                name: b"f",
1758                flags: 3,
1759                mode: 0o100640,
1760                gid: 4,
1761            },
1762            tag,
1763        );
1764        assert_eq!(create.len(), 55);
1765        assert_mutation_prefix(&create, message_type::TLCREATEATTR, tag);
1766        let mut body = Reader::new(&create[HEADER_SIZE + OP_ENVELOPE_SIZE..]);
1767        assert_eq!(body.get_u32(), Ok(1));
1768        assert_eq!(body.get_u32(), Ok(2));
1769        assert_eq!(body.get_string(), Ok(b"f".as_slice()));
1770        assert_eq!(body.get_u32(), Ok(3));
1771        assert_eq!(body.get_u32(), Ok(0o100640));
1772        assert_eq!(body.get_u32(), Ok(4));
1773        assert_eq!(body.require_end(), Ok(()));
1774
1775        let mkdir = encode_test_request(
1776            Request::Tmkdirattr {
1777                envelope: mutation_envelope(),
1778                dfid: 5,
1779                name: b"d",
1780                mode: 0o40750,
1781                gid: 6,
1782            },
1783            tag,
1784        );
1785        assert_eq!(mkdir.len(), 47);
1786        assert_mutation_prefix(&mkdir, message_type::TMKDIRATTR, tag);
1787        let mut body = Reader::new(&mkdir[HEADER_SIZE + OP_ENVELOPE_SIZE..]);
1788        assert_eq!(body.get_u32(), Ok(5));
1789        assert_eq!(body.get_string(), Ok(b"d".as_slice()));
1790        assert_eq!(body.get_u32(), Ok(0o40750));
1791        assert_eq!(body.get_u32(), Ok(6));
1792        assert_eq!(body.require_end(), Ok(()));
1793
1794        let symlink = encode_test_request(
1795            Request::Tsymlinkattr {
1796                envelope: mutation_envelope(),
1797                dfid: 7,
1798                name: b"s",
1799                target: b"to",
1800                gid: 8,
1801            },
1802            tag,
1803        );
1804        assert_eq!(symlink.len(), 47);
1805        assert_mutation_prefix(&symlink, message_type::TSYMLINKATTR, tag);
1806        let mut body = Reader::new(&symlink[HEADER_SIZE + OP_ENVELOPE_SIZE..]);
1807        assert_eq!(body.get_u32(), Ok(7));
1808        assert_eq!(body.get_string(), Ok(b"s".as_slice()));
1809        assert_eq!(body.get_string(), Ok(b"to".as_slice()));
1810        assert_eq!(body.get_u32(), Ok(8));
1811        assert_eq!(body.require_end(), Ok(()));
1812
1813        let mknod = encode_test_request(
1814            Request::Tmknodattr {
1815                envelope: mutation_envelope(),
1816                dfid: 9,
1817                name: b"p",
1818                mode: 0o10640,
1819                major: 10,
1820                minor: 11,
1821                gid: 12,
1822            },
1823            tag,
1824        );
1825        assert_eq!(mknod.len(), 55);
1826        assert_mutation_prefix(&mknod, message_type::TMKNODATTR, tag);
1827        let mut body = Reader::new(&mknod[HEADER_SIZE + OP_ENVELOPE_SIZE..]);
1828        assert_eq!(body.get_u32(), Ok(9));
1829        assert_eq!(body.get_string(), Ok(b"p".as_slice()));
1830        assert_eq!(body.get_u32(), Ok(0o10640));
1831        assert_eq!(body.get_u32(), Ok(10));
1832        assert_eq!(body.get_u32(), Ok(11));
1833        assert_eq!(body.get_u32(), Ok(12));
1834        assert_eq!(body.require_end(), Ok(()));
1835
1836        let link = encode_test_request(
1837            Request::Tlinkattr {
1838                envelope: mutation_envelope(),
1839                dfid: 13,
1840                fid: 14,
1841                name: b"h",
1842            },
1843            tag,
1844        );
1845        assert_eq!(link.len(), 43);
1846        assert_mutation_prefix(&link, message_type::TLINKATTR, tag);
1847        let mut body = Reader::new(&link[HEADER_SIZE + OP_ENVELOPE_SIZE..]);
1848        assert_eq!(body.get_u32(), Ok(13));
1849        assert_eq!(body.get_u32(), Ok(14));
1850        assert_eq!(body.get_string(), Ok(b"h".as_slice()));
1851        assert_eq!(body.require_end(), Ok(()));
1852
1853        let rename = encode_test_request(
1854            Request::Trenameat {
1855                envelope: mutation_envelope(),
1856                olddirfid: 15,
1857                oldname: b"a",
1858                newdirfid: 16,
1859                newname: b"b",
1860            },
1861            tag,
1862        );
1863        assert_eq!(rename.len(), 46);
1864        assert_mutation_prefix(&rename, message_type::TRENAMEAT, tag);
1865        let mut body = Reader::new(&rename[HEADER_SIZE + OP_ENVELOPE_SIZE..]);
1866        assert_eq!(body.get_u32(), Ok(15));
1867        assert_eq!(body.get_string(), Ok(b"a".as_slice()));
1868        assert_eq!(body.get_u32(), Ok(16));
1869        assert_eq!(body.get_string(), Ok(b"b".as_slice()));
1870        assert_eq!(body.require_end(), Ok(()));
1871
1872        let unlink = encode_test_request(
1873            Request::Tunlinkat {
1874                envelope: mutation_envelope(),
1875                dirfid: 17,
1876                name: b"x",
1877                flags: AT_REMOVEDIR,
1878            },
1879            tag,
1880        );
1881        assert_eq!(unlink.len(), 43);
1882        assert_mutation_prefix(&unlink, message_type::TUNLINKAT, tag);
1883        let mut body = Reader::new(&unlink[HEADER_SIZE + OP_ENVELOPE_SIZE..]);
1884        assert_eq!(body.get_u32(), Ok(17));
1885        assert_eq!(body.get_string(), Ok(b"x".as_slice()));
1886        assert_eq!(body.get_u32(), Ok(AT_REMOVEDIR));
1887        assert_eq!(body.require_end(), Ok(()));
1888
1889        let readlink = encode_test_request(Request::Treadlink { fid: 18 }, tag);
1890        assert_eq!(readlink.len(), HEADER_SIZE + 4);
1891        assert_eq!(readlink[4], message_type::TREADLINK);
1892        assert_eq!(&readlink[HEADER_SIZE..], &18u32.to_le_bytes());
1893    }
1894
1895    #[test]
1896    fn fixed_and_variable_requests_have_exact_sizes() {
1897        let mut output = [0u8; 128];
1898
1899        let walk = Request::Twalkgetattr {
1900            fid: 1,
1901            newfid: 2,
1902            names: &[b"dir", b"file"],
1903        };
1904        let walk_size = HEADER_SIZE + 4 + 4 + 2 + 2 + 3 + 2 + 4;
1905        assert_eq!(encoded_request_size(&walk), Ok(walk_size));
1906        let length = encode_request(&mut output, TEST_MSIZE, 5, walk).unwrap();
1907        assert_eq!(length, walk_size);
1908        assert_eq!(output[4], message_type::TWALKGETATTR);
1909        assert_eq!(&output[7..11], &1u32.to_le_bytes());
1910        assert_eq!(&output[11..15], &2u32.to_le_bytes());
1911        assert_eq!(&output[15..17], &2u16.to_le_bytes());
1912        assert_eq!(&output[17..22], &[3, 0, b'd', b'i', b'r']);
1913        assert_eq!(&output[22..28], &[4, 0, b'f', b'i', b'l', b'e']);
1914
1915        let rebind = Request::Trebind {
1916            fid: 3,
1917            inode_id: 4,
1918            root_inode: 5,
1919            flags: 1,
1920            uname: b"u",
1921            n_uname: 1000,
1922        };
1923        let rebind_size = HEADER_SIZE + 4 + 8 + 8 + 1 + 2 + 1 + 4;
1924        assert_eq!(encoded_request_size(&rebind), Ok(rebind_size));
1925        let length = encode_request(&mut output, TEST_MSIZE, 6, rebind).unwrap();
1926        assert_eq!(length, rebind_size);
1927        assert_eq!(output[4], message_type::TREBIND);
1928
1929        let cases = [
1930            (Request::Tgetlineage, message_type::TGETLINEAGE, HEADER_SIZE),
1931            (
1932                Request::Tgetattr {
1933                    fid: 1,
1934                    request_mask: 2,
1935                },
1936                message_type::TGETATTR,
1937                HEADER_SIZE + 12,
1938            ),
1939            (
1940                Request::Tlopenat {
1941                    fid: 1,
1942                    newfid: 2,
1943                    flags: 3,
1944                },
1945                message_type::TLOPENAT,
1946                HEADER_SIZE + 12,
1947            ),
1948            (
1949                Request::Tread {
1950                    fid: 1,
1951                    offset: 2,
1952                    count: 3,
1953                },
1954                message_type::TREAD,
1955                HEADER_SIZE + 16,
1956            ),
1957            (
1958                Request::Tfsyncdur {
1959                    fid: 1,
1960                    datasync: 1,
1961                    token: 2,
1962                },
1963                message_type::TFSYNCDUR,
1964                HEADER_SIZE + 16,
1965            ),
1966            (
1967                Request::Treaddirattr {
1968                    fid: 1,
1969                    offset: 2,
1970                    count: 3,
1971                },
1972                message_type::TREADDIRATTR,
1973                HEADER_SIZE + 16,
1974            ),
1975            (
1976                Request::Tclunk { fid: 1 },
1977                message_type::TCLUNK,
1978                HEADER_SIZE + 4,
1979            ),
1980            (
1981                Request::Tstatfs { fid: 1 },
1982                message_type::TSTATFS,
1983                HEADER_SIZE + 4,
1984            ),
1985        ];
1986        for (request, type_, expected_length) in cases {
1987            assert_eq!(encoded_request_size(&request), Ok(expected_length));
1988            let length = encode_request(&mut output, TEST_MSIZE, 7, request).unwrap();
1989            assert_eq!(length, expected_length);
1990            assert_eq!(output[4], type_);
1991        }
1992    }
1993
1994    #[test]
1995    fn flush_matches_the_standard_9p_layout() {
1996        let tag = 0x1234;
1997        let oldtag = 0xabcd;
1998        let request = Request::Tflush { oldtag };
1999        assert_eq!(encoded_request_size(&request), Ok(HEADER_SIZE + 2));
2000
2001        let frame = encode_test_request(request, tag);
2002        assert_eq!(frame.len(), HEADER_SIZE + 2);
2003        assert_eq!(frame[4], message_type::TFLUSH);
2004        assert_eq!(&frame[5..7], &tag.to_le_bytes());
2005        assert_eq!(&frame[HEADER_SIZE..], &oldtag.to_le_bytes());
2006
2007        let mut response = [0u8; HEADER_SIZE];
2008        put_header(&mut response, message_type::RFLUSH, tag);
2009        assert!(matches!(
2010            decode_response(&response, TEST_MSIZE, tag).unwrap().body,
2011            Response::Rflush
2012        ));
2013
2014        let mut trailing = [0u8; HEADER_SIZE + 1];
2015        put_header(&mut trailing, message_type::RFLUSH, tag);
2016        assert!(matches!(
2017            decode_response(&trailing, TEST_MSIZE, tag),
2018            Err(CodecError::TrailingData)
2019        ));
2020    }
2021
2022    #[test]
2023    fn lock_requests_match_the_9p_layout() {
2024        // These values also appear in the canonical message schema,
2025        // so pin them: a silent divergence would be a protocol split.
2026        assert_eq!(
2027            [LOCK_TYPE_RDLCK, LOCK_TYPE_WRLCK, LOCK_TYPE_UNLCK],
2028            [0, 1, 2]
2029        );
2030        assert_eq!(
2031            [LOCK_SUCCESS, LOCK_BLOCKED, LOCK_ERROR, LOCK_GRACE],
2032            [0, 1, 2, 3]
2033        );
2034        assert_eq!(LOCK_FLAGS_BLOCK, 1);
2035
2036        let lock = Request::Tlock {
2037            fid: 0x1122_3344,
2038            lock_type: LOCK_TYPE_WRLCK,
2039            flags: LOCK_FLAGS_BLOCK,
2040            start: 0x0102_0304_0506_0708,
2041            length: 4096,
2042            proc_id: 7,
2043            client_id: b"id",
2044        };
2045        assert_eq!(encoded_request_size(&lock), Ok(HEADER_SIZE + 31 + 2));
2046        let frame = encode_test_request(lock, 0x1234);
2047        let expected = [
2048            40,
2049            0,
2050            0,
2051            0,
2052            message_type::TLOCK,
2053            0x34,
2054            0x12,
2055            0x44,
2056            0x33,
2057            0x22,
2058            0x11,
2059            1,
2060            1,
2061            0,
2062            0,
2063            0,
2064            0x08,
2065            0x07,
2066            0x06,
2067            0x05,
2068            0x04,
2069            0x03,
2070            0x02,
2071            0x01,
2072            0x00,
2073            0x10,
2074            0,
2075            0,
2076            0,
2077            0,
2078            0,
2079            0,
2080            7,
2081            0,
2082            0,
2083            0,
2084            2,
2085            0,
2086            b'i',
2087            b'd',
2088        ];
2089        assert_eq!(frame.as_slice(), expected.as_slice());
2090
2091        let getlock = Request::Tgetlock {
2092            fid: 9,
2093            lock_type: LOCK_TYPE_RDLCK,
2094            start: 10,
2095            length: 11,
2096            proc_id: 12,
2097            client_id: b"peer",
2098        };
2099        assert_eq!(encoded_request_size(&getlock), Ok(HEADER_SIZE + 27 + 4));
2100        let frame = encode_test_request(getlock, 5);
2101        assert_eq!(frame.len(), HEADER_SIZE + 27 + 4);
2102        assert_eq!(frame[4], message_type::TGETLOCK);
2103        assert_eq!(&frame[5..7], &5u16.to_le_bytes());
2104        let mut body = Reader::new(&frame[HEADER_SIZE..]);
2105        assert_eq!(body.get_u32(), Ok(9));
2106        assert_eq!(body.get_u8(), Ok(LOCK_TYPE_RDLCK));
2107        assert_eq!(body.get_u64(), Ok(10));
2108        assert_eq!(body.get_u64(), Ok(11));
2109        assert_eq!(body.get_u32(), Ok(12));
2110        assert_eq!(body.get_string(), Ok(b"peer".as_slice()));
2111        assert_eq!(body.require_end(), Ok(()));
2112
2113        // An unnamed owner is legal, and the reserved size must still be exact.
2114        let anonymous = Request::Tgetlock {
2115            fid: 9,
2116            lock_type: LOCK_TYPE_UNLCK,
2117            start: 0,
2118            length: 0,
2119            proc_id: 0,
2120            client_id: b"",
2121        };
2122        assert_eq!(encoded_request_size(&anonymous), Ok(HEADER_SIZE + 27));
2123        assert_eq!(encode_test_request(anonymous, 5).len(), HEADER_SIZE + 27);
2124    }
2125
2126    /// The cases carried over verbatim from `lock_range.rs`, which is the copy
2127    /// userspace uses. Nothing else keeps the two in step.
2128    #[test]
2129    fn lock_range_subtraction_matches_the_owned_codec() {
2130        assert_eq!(lock_range_end(10, 0), u64::MAX);
2131        assert_eq!(lock_range_end(10, 5), 15);
2132        assert_eq!(lock_range_end(u64::MAX, 10), u64::MAX);
2133
2134        assert_eq!(
2135            subtract_lock_range(10, 90, 30, 20),
2136            [Some((10, 20)), Some((50, 50))]
2137        );
2138        // An open-ended survivor is re-encoded as EOF, not as a bounded tail.
2139        assert_eq!(
2140            subtract_lock_range(10, 0, 30, 20),
2141            [Some((10, 20)), Some((50, 0))]
2142        );
2143        assert_eq!(subtract_lock_range(10, 0, 30, 0), [Some((10, 20)), None]);
2144        // Disjoint ranges leave the held record exactly as it was.
2145        assert_eq!(subtract_lock_range(10, 20, 40, 10), [Some((10, 20)), None]);
2146        assert_eq!(subtract_lock_range(10, 20, 0, 40), [None, None]);
2147    }
2148
2149    #[test]
2150    fn rebind_binary_credentials_are_encoded_verbatim() {
2151        let credentials = [
2152            REBIND_CREDENTIAL_SENTINEL,
2153            REBIND_CREDENTIAL_VERSION,
2154            0xd2,
2155            0x04,
2156            0,
2157            0,
2158            2,
2159            0x2e,
2160            0x16,
2161            0,
2162            0,
2163            0x34,
2164            0x12,
2165            0,
2166            0,
2167        ];
2168        let request = Request::Trebind {
2169            fid: 3,
2170            inode_id: 4,
2171            root_inode: 0,
2172            flags: 0,
2173            uname: &credentials,
2174            n_uname: 1000,
2175        };
2176        let mut output = [0u8; 128];
2177        let length = encode_request(&mut output, TEST_MSIZE, 6, request).unwrap();
2178        assert_eq!(
2179            length,
2180            HEADER_SIZE + 4 + 8 + 8 + 1 + 2 + credentials.len() + 4
2181        );
2182
2183        let mut body = Reader::new(&output[HEADER_SIZE..length]);
2184        assert_eq!(body.get_u32(), Ok(3));
2185        assert_eq!(body.get_u64(), Ok(4));
2186        assert_eq!(body.get_u64(), Ok(0));
2187        assert_eq!(body.get_u8(), Ok(0));
2188        assert_eq!(body.get_string(), Ok(credentials.as_slice()));
2189        assert_eq!(body.get_u32(), Ok(1000));
2190        assert_eq!(body.require_end(), Ok(()));
2191    }
2192
2193    #[test]
2194    fn header_can_be_routed_before_the_body_arrives() {
2195        let header = [11, 0, 0, 0, message_type::RLERROR, 0x34, 0x12];
2196        assert_eq!(
2197            decode_header(&header, TEST_MSIZE),
2198            Ok(Header {
2199                size: 11,
2200                type_: message_type::RLERROR,
2201                tag: 0x1234,
2202            })
2203        );
2204        assert_eq!(
2205            decode_header(&header[..HEADER_SIZE - 1], TEST_MSIZE),
2206            Err(CodecError::Truncated)
2207        );
2208    }
2209
2210    #[test]
2211    fn errors_are_bounded_and_tags_are_checked() {
2212        let mut tiny = [0u8; HEADER_SIZE];
2213        assert_eq!(
2214            encode_request(
2215                &mut tiny,
2216                TEST_MSIZE,
2217                1,
2218                Request::Tread {
2219                    fid: 0,
2220                    offset: 0,
2221                    count: 0,
2222                },
2223            ),
2224            Err(CodecError::BufferTooSmall)
2225        );
2226        assert_eq!(
2227            encode_request(
2228                &mut [0u8; 64],
2229                TEST_MSIZE,
2230                1,
2231                Request::Tversion {
2232                    msize: TEST_MSIZE,
2233                    version: VERSION_9P2000L_ZEROFS,
2234                },
2235            ),
2236            Err(CodecError::InvalidTag)
2237        );
2238        assert_eq!(
2239            encode_request(
2240                &mut [0u8; 64],
2241                TEST_MSIZE,
2242                NOTAG,
2243                Request::Tclunk { fid: 1 },
2244            ),
2245            Err(CodecError::InvalidTag)
2246        );
2247    }
2248
2249    #[test]
2250    fn decodes_version_error_read_and_open_replies() {
2251        let mut version = [0u8; HEADER_SIZE + 4 + 2 + 10];
2252        put_header(&mut version, message_type::RVERSION, NOTAG);
2253        version[7..11].copy_from_slice(&TEST_MSIZE.to_le_bytes());
2254        version[11..13].copy_from_slice(&10u16.to_le_bytes());
2255        version[13..].copy_from_slice(VERSION_9P2000L_ZEROFS);
2256        let decoded = decode_response(&version, TEST_MSIZE, NOTAG).unwrap();
2257        match decoded.body {
2258            Response::Rversion(reply) => {
2259                assert_eq!(reply.msize, TEST_MSIZE);
2260                assert_eq!(reply.version.as_ref(), VERSION_9P2000L_ZEROFS);
2261            }
2262            _ => panic!("wrong response"),
2263        }
2264
2265        let mut error = [0u8; HEADER_SIZE + 4];
2266        put_header(&mut error, message_type::RLERROR, 9);
2267        error[7..].copy_from_slice(&5u32.to_le_bytes());
2268        match decode_response(&error, TEST_MSIZE, 9).unwrap().body {
2269            Response::Rlerror(reply) => assert_eq!(reply.ecode, 5),
2270            _ => panic!("wrong response"),
2271        }
2272
2273        let mut read = [0u8; HEADER_SIZE + 4 + 3];
2274        put_header(&mut read, message_type::RREAD, 10);
2275        read[7..11].copy_from_slice(&3u32.to_le_bytes());
2276        read[11..].copy_from_slice(b"abc");
2277        match decode_response(&read, TEST_MSIZE, 10).unwrap().body {
2278            Response::Rread(reply) => assert_eq!(reply.data.as_ref(), b"abc"),
2279            _ => panic!("wrong response"),
2280        }
2281
2282        let mut open = [0u8; HEADER_SIZE + QID_WIRE_SIZE + 4];
2283        put_header(&mut open, message_type::RLOPENAT, 11);
2284        let mut writer = Writer::new(&mut open[HEADER_SIZE..]);
2285        put_qid(
2286            &mut writer,
2287            Qid {
2288                type_: 0,
2289                version: 2,
2290                path: 3,
2291            },
2292        );
2293        writer.put_u32(8192).unwrap();
2294        match decode_response(&open, TEST_MSIZE, 11).unwrap().body {
2295            Response::Rlopenat(reply) => {
2296                assert_eq!(reply.qid.path, 3);
2297                assert_eq!(reply.iounit, 8192);
2298            }
2299            _ => panic!("wrong response"),
2300        }
2301    }
2302
2303    #[test]
2304    fn decodes_compound_attribute_namespace_and_readlink_replies() {
2305        let stat = Stat {
2306            qid: Qid {
2307                type_: QID_TYPE_FILE,
2308                version: 3,
2309                path: 0x1122_3344_5566_7788,
2310            },
2311            mode: 0o100640,
2312            uid: 1000,
2313            gid: 1001,
2314            nlink: 2,
2315            size: 123,
2316            mtime_sec: 456,
2317            data_version: 789,
2318            ..Stat::default()
2319        };
2320
2321        let mut create = [0u8; HEADER_SIZE + 4 + STAT_WIRE_SIZE];
2322        put_header(&mut create, message_type::RLCREATEATTR, 31);
2323        let mut writer = Writer::new(&mut create[HEADER_SIZE..]);
2324        writer.put_u32(8192).unwrap();
2325        put_stat(&mut writer, stat);
2326        match decode_response(&create, TEST_MSIZE, 31).unwrap().body {
2327            Response::Rlcreateattr(reply) => {
2328                assert_eq!(reply.iounit, 8192);
2329                assert_eq!(reply.stat, stat);
2330            }
2331            _ => panic!("wrong create response"),
2332        }
2333
2334        for (type_, expected) in [
2335            (message_type::RMKDIRATTR, 0u8),
2336            (message_type::RSYMLINKATTR, 1u8),
2337            (message_type::RMKNODATTR, 2u8),
2338            (message_type::RLINKATTR, 3u8),
2339            (message_type::RSETATTRATTR, 4u8),
2340        ] {
2341            let mut frame = [0u8; HEADER_SIZE + STAT_WIRE_SIZE];
2342            put_header(&mut frame, type_, 32);
2343            put_stat(&mut Writer::new(&mut frame[HEADER_SIZE..]), stat);
2344            let decoded = decode_response(&frame, TEST_MSIZE, 32).unwrap();
2345            let decoded_stat = match (expected, decoded.body) {
2346                (0, Response::Rmkdirattr(value))
2347                | (1, Response::Rsymlinkattr(value))
2348                | (2, Response::Rmknodattr(value))
2349                | (3, Response::Rlinkattr(value))
2350                | (4, Response::Rsetattrattr(value)) => value,
2351                _ => panic!("wrong stat response"),
2352            };
2353            assert_eq!(decoded_stat, stat);
2354        }
2355
2356        for (type_, expected) in [
2357            (message_type::RFALLOCATE, 0u8),
2358            (message_type::RRENAMEAT, 1u8),
2359            (message_type::RUNLINKAT, 2u8),
2360        ] {
2361            let mut frame = [0u8; HEADER_SIZE];
2362            put_header(&mut frame, type_, 33);
2363            let body = decode_response(&frame, TEST_MSIZE, 33).unwrap().body;
2364            assert!(matches!(
2365                (expected, body),
2366                (0, Response::Rfallocate) | (1, Response::Rrenameat) | (2, Response::Runlinkat)
2367            ));
2368        }
2369
2370        let mut readlink = [0u8; HEADER_SIZE + 2 + 6];
2371        put_header(&mut readlink, message_type::RREADLINK, 34);
2372        readlink[HEADER_SIZE..HEADER_SIZE + 2].copy_from_slice(&6u16.to_le_bytes());
2373        readlink[HEADER_SIZE + 2..].copy_from_slice(b"target");
2374        match decode_response(&readlink, TEST_MSIZE, 34).unwrap().body {
2375            Response::Rreadlink(reply) => assert_eq!(reply.target.as_ref(), b"target"),
2376            _ => panic!("wrong readlink response"),
2377        }
2378
2379        let truncated = &readlink[..readlink.len() - 1];
2380        assert!(matches!(
2381            decode_response(truncated, TEST_MSIZE, 34),
2382            Err(CodecError::FrameSizeMismatch)
2383        ));
2384    }
2385
2386    #[test]
2387    fn tfsyncdur_and_write_replies_match_the_canonical_layout() {
2388        let mut request = [0u8; HEADER_SIZE + 4 + 4 + 8];
2389        let length = encode_request(
2390            &mut request,
2391            TEST_MSIZE,
2392            0x1234,
2393            Request::Tfsyncdur {
2394                fid: 0x1122_3344,
2395                datasync: 1,
2396                token: 0x0807_0605_0403_0201,
2397            },
2398        )
2399        .unwrap();
2400        let expected = [
2401            23,
2402            0,
2403            0,
2404            0,
2405            message_type::TFSYNCDUR,
2406            0x34,
2407            0x12,
2408            0x44,
2409            0x33,
2410            0x22,
2411            0x11,
2412            1,
2413            0,
2414            0,
2415            0,
2416            1,
2417            2,
2418            3,
2419            4,
2420            5,
2421            6,
2422            7,
2423            8,
2424        ];
2425        assert_eq!(length, expected.len());
2426        assert_eq!(request, expected);
2427
2428        let mut write = [0u8; HEADER_SIZE + 4];
2429        put_header(&mut write, message_type::RWRITE, 7);
2430        write[HEADER_SIZE..].copy_from_slice(&123u32.to_le_bytes());
2431        match decode_response(&write, TEST_MSIZE, 7).unwrap().body {
2432            Response::Rwrite(response) => assert_eq!(response.count, 123),
2433            _ => panic!("wrong response"),
2434        }
2435
2436        let mut fsync = [0u8; HEADER_SIZE];
2437        put_header(&mut fsync, message_type::RFSYNC, 8);
2438        assert!(matches!(
2439            decode_response(&fsync, TEST_MSIZE, 8).unwrap().body,
2440            Response::Rfsync
2441        ));
2442
2443        let truncated = &write[..write.len() - 1];
2444        assert!(matches!(
2445            decode_response(truncated, TEST_MSIZE, 7),
2446            Err(CodecError::FrameSizeMismatch)
2447        ));
2448    }
2449
2450    #[test]
2451    fn decodes_lock_replies_and_rejects_truncation() {
2452        for status in [LOCK_SUCCESS, LOCK_BLOCKED] {
2453            let mut frame = [0u8; HEADER_SIZE + 1];
2454            put_header(&mut frame, message_type::RLOCK, 21);
2455            frame[HEADER_SIZE] = status;
2456            match decode_response(&frame, TEST_MSIZE, 21).unwrap().body {
2457                Response::Rlock(reply) => assert_eq!(reply.status, status),
2458                _ => panic!("wrong lock response"),
2459            }
2460        }
2461
2462        let mut getlock = [0u8; HEADER_SIZE + 1 + 8 + 8 + 4 + 2 + 4];
2463        put_header(&mut getlock, message_type::RGETLOCK, 22);
2464        let mut writer = Writer::new(&mut getlock[HEADER_SIZE..]);
2465        writer.put_u8(LOCK_TYPE_WRLCK).unwrap();
2466        writer.put_u64(64).unwrap();
2467        writer.put_u64(128).unwrap();
2468        writer.put_u32(4242).unwrap();
2469        writer.put_string(b"peer").unwrap();
2470        match decode_response(&getlock, TEST_MSIZE, 22).unwrap().body {
2471            Response::Rgetlock(reply) => {
2472                assert_eq!(reply.lock_type, LOCK_TYPE_WRLCK);
2473                assert_eq!(reply.start, 64);
2474                assert_eq!(reply.length, 128);
2475                assert_eq!(reply.proc_id, 4242);
2476                assert_eq!(reply.client_id.as_ref(), b"peer");
2477                // The owner identity borrows the frame instead of copying it.
2478                assert!(core::ptr::eq(
2479                    reply.client_id.as_ref().as_ptr(),
2480                    getlock[HEADER_SIZE + 23..].as_ptr(),
2481                ));
2482            }
2483            _ => panic!("wrong getlock response"),
2484        }
2485
2486        let mut headerless = [0u8; HEADER_SIZE];
2487        put_header(&mut headerless, message_type::RLOCK, 23);
2488        assert!(matches!(
2489            decode_response(&headerless, TEST_MSIZE, 23),
2490            Err(CodecError::Truncated)
2491        ));
2492
2493        // The declared frame size matches, so only the string length lies.
2494        let mut overrun = [0u8; HEADER_SIZE + 1 + 8 + 8 + 4 + 2];
2495        put_header(&mut overrun, message_type::RGETLOCK, 24);
2496        let mut writer = Writer::new(&mut overrun[HEADER_SIZE..]);
2497        writer.put_u8(LOCK_TYPE_RDLCK).unwrap();
2498        writer.put_u64(0).unwrap();
2499        writer.put_u64(0).unwrap();
2500        writer.put_u32(0).unwrap();
2501        writer.put_u16(3).unwrap();
2502        assert!(matches!(
2503            decode_response(&overrun, TEST_MSIZE, 24),
2504            Err(CodecError::Truncated)
2505        ));
2506
2507        let mut trailing = [0u8; HEADER_SIZE + 2];
2508        put_header(&mut trailing, message_type::RLOCK, 25);
2509        assert!(matches!(
2510            decode_response(&trailing, TEST_MSIZE, 25),
2511            Err(CodecError::TrailingData)
2512        ));
2513    }
2514
2515    #[test]
2516    fn walk_and_readdir_views_are_allocation_free() {
2517        let stat = Stat {
2518            qid: Qid {
2519                type_: 0x80,
2520                version: 7,
2521                path: 8,
2522            },
2523            mode: 0o40755,
2524            uid: 1000,
2525            gid: 1001,
2526            nlink: 2,
2527            size: 99,
2528            data_version: 42,
2529            ..Stat::default()
2530        };
2531        let qid = Qid {
2532            type_: 0,
2533            version: 3,
2534            path: 4,
2535        };
2536
2537        let mut walk = [0u8; HEADER_SIZE + 2 + QID_WIRE_SIZE + STAT_WIRE_SIZE];
2538        put_header(&mut walk, message_type::RWALKGETATTR, 12);
2539        let mut writer = Writer::new(&mut walk[HEADER_SIZE..]);
2540        writer.put_u16(1).unwrap();
2541        put_qid(&mut writer, qid);
2542        put_stat(&mut writer, stat);
2543        match decode_response(&walk, TEST_MSIZE, 12).unwrap().body {
2544            Response::Rwalkgetattr(reply) => {
2545                assert_eq!(reply.qids.len(), 1);
2546                assert_eq!(reply.qids.get(0), Some(qid));
2547                assert_eq!(reply.qids.get(1), None);
2548                assert_eq!(reply.stat, stat);
2549            }
2550            _ => panic!("wrong response"),
2551        }
2552
2553        let entry_size = QID_WIRE_SIZE + 8 + 1 + 2 + 4 + STAT_WIRE_SIZE;
2554        let mut readdir = [0u8; HEADER_SIZE + 4 + QID_WIRE_SIZE + 8 + 1 + 2 + 4 + STAT_WIRE_SIZE];
2555        put_header(&mut readdir, message_type::RREADDIRATTR, 13);
2556        readdir[7..11].copy_from_slice(&(entry_size as u32).to_le_bytes());
2557        let mut writer = Writer::new(&mut readdir[11..]);
2558        put_qid(&mut writer, qid);
2559        writer.put_u64(55).unwrap();
2560        writer.put_u8(0).unwrap();
2561        writer.put_string(b"name").unwrap();
2562        put_stat(&mut writer, stat);
2563        match decode_response(&readdir, TEST_MSIZE, 13).unwrap().body {
2564            Response::Rreaddirattr(reply) => {
2565                assert_eq!(reply.len(), 1);
2566                let entries = reply.entries().collect::<Result<Vec<_>, _>>().unwrap();
2567                assert_eq!(entries.len(), 1);
2568                assert_eq!(entries[0].qid, qid);
2569                assert_eq!(entries[0].offset, 55);
2570                assert_eq!(entries[0].name, b"name");
2571                assert_eq!(entries[0].stat, stat);
2572            }
2573            _ => panic!("wrong response"),
2574        }
2575    }
2576
2577    #[test]
2578    fn rejects_count_size_tag_and_trailing_data_violations() {
2579        let mut truncated = [0u8; HEADER_SIZE + 4 + 2];
2580        put_header(&mut truncated, message_type::RREAD, 1);
2581        truncated[7..11].copy_from_slice(&3u32.to_le_bytes());
2582        assert!(matches!(
2583            decode_response(&truncated, TEST_MSIZE, 1),
2584            Err(CodecError::Truncated)
2585        ));
2586
2587        let mut trailing = [0u8; HEADER_SIZE + 1];
2588        put_header(&mut trailing, message_type::RCLUNK, 2);
2589        assert!(matches!(
2590            decode_response(&trailing, TEST_MSIZE, 2),
2591            Err(CodecError::TrailingData)
2592        ));
2593        assert!(matches!(
2594            decode_response(&trailing, TEST_MSIZE, 3),
2595            Err(CodecError::TagMismatch {
2596                expected: 3,
2597                actual: 2,
2598            })
2599        ));
2600
2601        let mut mismatch = trailing;
2602        mismatch[0..4].copy_from_slice(&(HEADER_SIZE as u32).to_le_bytes());
2603        assert!(matches!(
2604            decode_response(&mismatch, TEST_MSIZE, 2),
2605            Err(CodecError::FrameSizeMismatch)
2606        ));
2607    }
2608}