diff --git a/crates/vfs/src/plan9fs.rs b/crates/vfs/src/plan9fs.rs index ae9e836..3f48a6d 100644 --- a/crates/vfs/src/plan9fs.rs +++ b/crates/vfs/src/plan9fs.rs @@ -85,6 +85,8 @@ const NOFID: u32 = 0xFFFF_FFFF; #[derive(Debug, Clone, Copy, PartialEq, Eq)] #[repr(u8)] pub enum P9MessageType { + /// Linux 9P error response carrying a numeric errno. + Rlerror = 7, /// Negotiate protocol version. Tversion = 100, /// Version negotiation reply. @@ -145,6 +147,7 @@ impl P9MessageType { /// Parse a message type from its on-disk byte value. pub fn from_u8(v: u8) -> Option { match v { + 7 => Some(Self::Rlerror), 100 => Some(Self::Tversion), 101 => Some(Self::Rversion), 102 => Some(Self::Tauth), @@ -268,26 +271,25 @@ impl P9Qid { /// /// Returns the parsed QID and the number of bytes consumed. pub fn from_bytes(buf: &[u8], offset: usize) -> Result<(Self, usize)> { - if buf.len() < offset + Self::WIRE_SIZE { - return Err(Error::InvalidArgument); - } - let qtype = P9QidType(buf[offset]); - let version = u32::from_le_bytes([ - buf[offset + 1], - buf[offset + 2], - buf[offset + 3], - buf[offset + 4], - ]); - let path = u64::from_le_bytes([ - buf[offset + 5], - buf[offset + 6], - buf[offset + 7], - buf[offset + 8], - buf[offset + 9], - buf[offset + 10], - buf[offset + 11], - buf[offset + 12], - ]); + let end = offset + .checked_add(Self::WIRE_SIZE) + .ok_or(Error::InvalidArgument)?; + let frame = buf.get(offset..end).ok_or(Error::InvalidArgument)?; + let qtype = P9QidType(*frame.first().ok_or(Error::InvalidArgument)?); + let version = u32::from_le_bytes( + frame + .get(1..5) + .ok_or(Error::InvalidArgument)? + .try_into() + .map_err(|_| Error::InvalidArgument)?, + ); + let path = u64::from_le_bytes( + frame + .get(5..13) + .ok_or(Error::InvalidArgument)? + .try_into() + .map_err(|_| Error::InvalidArgument)?, + ); Ok(( Self { qtype, @@ -302,12 +304,19 @@ impl P9Qid { /// /// Returns the number of bytes written. pub fn to_bytes(&self, buf: &mut [u8], offset: usize) -> Result { - if buf.len() < offset + Self::WIRE_SIZE { - return Err(Error::InvalidArgument); - } - buf[offset] = self.qtype.0; - buf[offset + 1..offset + 5].copy_from_slice(&self.version.to_le_bytes()); - buf[offset + 5..offset + 13].copy_from_slice(&self.path.to_le_bytes()); + let end = offset + .checked_add(Self::WIRE_SIZE) + .ok_or(Error::InvalidArgument)?; + let frame = buf.get_mut(offset..end).ok_or(Error::InvalidArgument)?; + *frame.first_mut().ok_or(Error::InvalidArgument)? = self.qtype.0; + frame + .get_mut(1..5) + .ok_or(Error::InvalidArgument)? + .copy_from_slice(&self.version.to_le_bytes()); + frame + .get_mut(5..13) + .ok_or(Error::InvalidArgument)? + .copy_from_slice(&self.path.to_le_bytes()); Ok(Self::WIRE_SIZE) } } @@ -437,6 +446,8 @@ pub struct P9Fid { pub mode: P9OpenMode, /// Current I/O offset for sequential reads/writes. pub offset: u64, + /// Effective server I/O unit, bounded by the negotiated message size. + pub iounit: u32, /// Path name associated with this FID (for debugging/display). pub path: [u8; MAX_NAME_LEN], /// Length of the path name. @@ -452,6 +463,7 @@ impl P9Fid { qid: P9Qid::new(P9QidType::FILE, 0, 0), mode: P9OpenMode::OREAD, offset: 0, + iounit: 0, path: [0; MAX_NAME_LEN], path_len: 0, } @@ -489,30 +501,47 @@ impl FidTable { /// /// Returns `OutOfMemory` if the table is full. pub fn alloc(&mut self) -> Result<(usize, u32)> { - let mut slot = None; - let mut i = 0; - while i < MAX_FIDS { - if matches!(self.fids[i].state, FidState::Free) { - slot = Some(i); - break; + let (slot, fid) = self.preview_alloc()?; + self.commit_alloc(slot, fid); + Ok((slot, fid)) + } + + fn preview_alloc(&self) -> Result<(usize, u32)> { + let mut slot = 0; + while slot < MAX_FIDS && !matches!(self.fids[slot].state, FidState::Free) { + slot += 1; + } + if slot == MAX_FIDS { + return Err(Error::OutOfMemory); + } + let mut fid = if self.next_fid == NOFID { + 1 + } else { + self.next_fid + }; + let mut attempts = 0; + while attempts <= self.active_count { + if self.lookup(fid) == Err(Error::NotFound) { + return Ok((slot, fid)); } - i += 1; + fid = match fid.checked_add(1) { + Some(next) if next != NOFID => next, + _ => 1, + }; + attempts += 1; } - let idx = slot.ok_or(Error::OutOfMemory)?; - let fid_num = self.next_fid; - // Advance next_fid with checked arithmetic; skip the reserved NOFID - // sentinel and wrap back to 1 on exhaustion so the counter never - // produces an invalid FID number. - self.next_fid = match self.next_fid.checked_add(1) { + Err(Error::OutOfMemory) + } + + fn commit_alloc(&mut self, slot: usize, fid: u32) { + self.next_fid = match fid.checked_add(1) { Some(n) if n != NOFID => n, _ => 1, }; - self.fids[idx].fid = fid_num; - self.fids[idx].state = FidState::Allocated; - self.fids[idx].offset = 0; - self.fids[idx].path_len = 0; + self.fids[slot] = P9Fid::free(); + self.fids[slot].fid = fid; + self.fids[slot].state = FidState::Allocated; self.active_count += 1; - Ok((idx, fid_num)) } /// Look up a FID by its numeric value. @@ -554,11 +583,7 @@ impl FidTable { /// Release (clunk) a FID, freeing its slot. pub fn release(&mut self, fid: u32) -> Result<()> { let idx = self.lookup(fid)?; - self.fids[idx].state = FidState::Free; - self.fids[idx].fid = 0; - self.fids[idx].qid = P9Qid::new(P9QidType::FILE, 0, 0); - self.fids[idx].offset = 0; - self.fids[idx].path_len = 0; + self.fids[idx] = P9Fid::free(); self.active_count = self.active_count.saturating_sub(1); Ok(()) } @@ -567,6 +592,12 @@ impl FidTable { pub fn active_count(&self) -> usize { self.active_count } + + fn clear(&mut self) { + self.fids = [const { P9Fid::free() }; MAX_FIDS]; + self.active_count = 0; + self.next_fid = 1; + } } // ── Plan9Message ──────────────────────────────────────────────── @@ -580,6 +611,8 @@ pub struct Plan9Message { buf: [u8; MAX_MESSAGE_SIZE as usize], /// Current write position in the buffer. pos: usize, + /// Active outbound frame limit. + limit: usize, } impl Plan9Message { @@ -588,7 +621,25 @@ impl Plan9Message { Self { buf: [0; MAX_MESSAGE_SIZE as usize], pos: HEADER_SIZE, + limit: MAX_MESSAGE_SIZE as usize, + } + } + + fn set_limit(&mut self, limit: u32) -> Result<()> { + let limit = limit as usize; + if !(HEADER_SIZE..=MAX_MESSAGE_SIZE as usize).contains(&limit) { + return Err(Error::InvalidArgument); + } + self.limit = limit; + Ok(()) + } + + fn reserve(&self, len: usize) -> Result> { + let end = self.pos.checked_add(len).ok_or(Error::InvalidArgument)?; + if end > self.limit { + return Err(Error::InvalidArgument); } + Ok(self.pos..end) } /// Reset the message for building a new request. @@ -604,41 +655,33 @@ impl Plan9Message { /// Append a u8 value to the message payload. pub fn put_u8(&mut self, v: u8) -> Result<()> { - if self.pos + 1 > self.buf.len() { - return Err(Error::InvalidArgument); - } - self.buf[self.pos] = v; - self.pos += 1; + let range = self.reserve(1)?; + self.buf[range.start] = v; + self.pos = range.end; Ok(()) } /// Append a u16 (little-endian) to the message payload. pub fn put_u16(&mut self, v: u16) -> Result<()> { - if self.pos + 2 > self.buf.len() { - return Err(Error::InvalidArgument); - } - self.buf[self.pos..self.pos + 2].copy_from_slice(&v.to_le_bytes()); - self.pos += 2; + let range = self.reserve(2)?; + self.buf[range.clone()].copy_from_slice(&v.to_le_bytes()); + self.pos = range.end; Ok(()) } /// Append a u32 (little-endian) to the message payload. pub fn put_u32(&mut self, v: u32) -> Result<()> { - if self.pos + 4 > self.buf.len() { - return Err(Error::InvalidArgument); - } - self.buf[self.pos..self.pos + 4].copy_from_slice(&v.to_le_bytes()); - self.pos += 4; + let range = self.reserve(4)?; + self.buf[range.clone()].copy_from_slice(&v.to_le_bytes()); + self.pos = range.end; Ok(()) } /// Append a u64 (little-endian) to the message payload. pub fn put_u64(&mut self, v: u64) -> Result<()> { - if self.pos + 8 > self.buf.len() { - return Err(Error::InvalidArgument); - } - self.buf[self.pos..self.pos + 8].copy_from_slice(&v.to_le_bytes()); - self.pos += 8; + let range = self.reserve(8)?; + self.buf[range.clone()].copy_from_slice(&v.to_le_bytes()); + self.pos = range.end; Ok(()) } @@ -648,22 +691,20 @@ impl Plan9Message { if len > u16::MAX as usize { return Err(Error::InvalidArgument); } - self.put_u16(len as u16)?; - if self.pos + len > self.buf.len() { - return Err(Error::InvalidArgument); - } - self.buf[self.pos..self.pos + len].copy_from_slice(s); - self.pos += len; + let total = len.checked_add(2).ok_or(Error::InvalidArgument)?; + let range = self.reserve(total)?; + let data_start = range.start + 2; + self.buf[range.start..data_start].copy_from_slice(&(len as u16).to_le_bytes()); + self.buf[data_start..range.end].copy_from_slice(s); + self.pos = range.end; Ok(()) } /// Append raw data bytes. pub fn put_data(&mut self, data: &[u8]) -> Result<()> { - if self.pos + data.len() > self.buf.len() { - return Err(Error::InvalidArgument); - } - self.buf[self.pos..self.pos + data.len()].copy_from_slice(data); - self.pos += data.len(); + let range = self.reserve(data.len())?; + self.buf[range.clone()].copy_from_slice(data); + self.pos = range.end; Ok(()) } @@ -702,49 +743,40 @@ impl Plan9Message { /// Read a u32 from a buffer at the given offset. pub fn read_u32(buf: &[u8], offset: usize) -> Result<(u32, usize)> { - if buf.len() < offset + 4 { - return Err(Error::InvalidArgument); - } - let v = u32::from_le_bytes([ - buf[offset], - buf[offset + 1], - buf[offset + 2], - buf[offset + 3], - ]); - Ok((v, offset + 4)) + let end = offset.checked_add(4).ok_or(Error::InvalidArgument)?; + let bytes = buf + .get(offset..end) + .ok_or(Error::InvalidArgument)? + .try_into() + .map_err(|_| Error::InvalidArgument)?; + Ok((u32::from_le_bytes(bytes), end)) } /// Read a u64 from a buffer at the given offset. pub fn read_u64(buf: &[u8], offset: usize) -> Result<(u64, usize)> { - if buf.len() < offset + 8 { - return Err(Error::InvalidArgument); - } - let v = u64::from_le_bytes([ - buf[offset], - buf[offset + 1], - buf[offset + 2], - buf[offset + 3], - buf[offset + 4], - buf[offset + 5], - buf[offset + 6], - buf[offset + 7], - ]); - Ok((v, offset + 8)) + let end = offset.checked_add(8).ok_or(Error::InvalidArgument)?; + let bytes = buf + .get(offset..end) + .ok_or(Error::InvalidArgument)? + .try_into() + .map_err(|_| Error::InvalidArgument)?; + Ok((u64::from_le_bytes(bytes), end)) } /// Read a length-prefixed string from a buffer at the given offset. /// /// Returns (byte slice, next offset). The slice borrows from `buf`. pub fn read_string(buf: &[u8], offset: usize) -> Result<(&[u8], usize)> { - if buf.len() < offset + 2 { - return Err(Error::InvalidArgument); - } - let len = u16::from_le_bytes([buf[offset], buf[offset + 1]]) as usize; - let start = offset + 2; - if buf.len() < start + len { - return Err(Error::InvalidArgument); - } - Ok((&buf[start..start + len], start + len)) + let start = offset.checked_add(2).ok_or(Error::InvalidArgument)?; + let length_bytes = buf + .get(offset..start) + .ok_or(Error::InvalidArgument)? + .try_into() + .map_err(|_| Error::InvalidArgument)?; + let len = u16::from_le_bytes(length_bytes) as usize; + let end = start.checked_add(len).ok_or(Error::InvalidArgument)?; + let value = buf.get(start..end).ok_or(Error::InvalidArgument)?; + Ok((value, end)) } } @@ -767,6 +799,146 @@ pub enum SessionState { Error, } +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum PendingKind { + Version, + Attach, + Walk, + Open, + Read, + Write, + Clunk, + Remove, + Stat, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum PendingOperation { + Version, + Attach { fid: u32 }, + Walk { src: u32, dst: u32, nwname: usize }, + Open { fid: u32, mode: P9OpenMode }, + Read { fid: u32, count: u32 }, + Write { fid: u32, count: u32 }, + Clunk { fid: u32 }, + Remove { fid: u32 }, + Stat { fid: u32 }, +} + +impl PendingOperation { + const fn kind(self) -> PendingKind { + match self { + Self::Version => PendingKind::Version, + Self::Attach { .. } => PendingKind::Attach, + Self::Walk { .. } => PendingKind::Walk, + Self::Open { .. } => PendingKind::Open, + Self::Read { .. } => PendingKind::Read, + Self::Write { .. } => PendingKind::Write, + Self::Clunk { .. } => PendingKind::Clunk, + Self::Remove { .. } => PendingKind::Remove, + Self::Stat { .. } => PendingKind::Stat, + } + } + + const fn expected_response(self) -> P9MessageType { + match self { + Self::Version => P9MessageType::Rversion, + Self::Attach { .. } => P9MessageType::Rattach, + Self::Walk { .. } => P9MessageType::Rwalk, + Self::Open { .. } => P9MessageType::Ropen, + Self::Read { .. } => P9MessageType::Rread, + Self::Write { .. } => P9MessageType::Rwrite, + Self::Clunk { .. } => P9MessageType::Rclunk, + Self::Remove { .. } => P9MessageType::Rremove, + Self::Stat { .. } => P9MessageType::Rstat, + } + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +struct PendingRequest { + tag: u16, + expected_response: P9MessageType, + operation: PendingOperation, +} + +impl PendingRequest { + const fn new(tag: u16, operation: PendingOperation) -> Self { + Self { + tag, + expected_response: operation.expected_response(), + operation, + } + } +} + +/// Result of completing a 9P walk request. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum P9WalkResult { + /// A zero-name walk cloned all source metadata into the destination FID. + Cloned { + /// Source FID. + source: u32, + /// Destination FID. + destination: u32, + }, + /// Every requested name was walked and the destination FID was committed. + Full { + /// Source FID. + source: u32, + /// Destination FID. + destination: u32, + /// Number of returned QIDs. + count: usize, + /// Returned QIDs in wire order. + qids: [P9Qid; MAX_WALK_ELEMS], + }, + /// Only a prefix was walked; the provisional destination was released. + Partial { + /// Source FID. + source: u32, + /// Number of successfully walked names. + count: usize, + /// Returned prefix QIDs in wire order. + qids: [P9Qid; MAX_WALK_ELEMS], + }, +} + +/// Request context for a response whose body is intentionally not parsed yet. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum P9RawRequest { + /// Read request envelope. + Read { + /// Target FID. + fid: u32, + /// Encoded maximum byte count. + count: u32, + }, + /// Write request envelope. + Write { + /// Target FID. + fid: u32, + /// Encoded byte count. + count: u32, + }, + /// Stat request envelope. + Stat { + /// Target FID. + fid: u32, + }, +} + +/// Correlated terminal response envelope without body interpretation. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct P9RawResponse<'a> { + /// Request context retired by this response. + pub request: P9RawRequest, + /// Exact response message type that matched the pending request. + pub response_type: P9MessageType, + /// Unparsed response bytes following the 9P envelope. + pub payload: &'a [u8], +} + // ── Plan9Session ──────────────────────────────────────────────── /// 9P2000.L client session. @@ -784,13 +956,8 @@ pub struct Plan9Session { root_fid: u32, /// Next tag number for request/response matching. next_tag: u16, - // SECURITY: every build_t* stores the tag it allocated here; every - // handle_r* reads the reply tag from parse_header and rejects it unless - // it matches this field. This prevents a malicious/compromised 9P server - // from replying with a forged tag that would be accepted as the response - // to a different in-flight request (FID/QID spoofing, F1 fix). - /// Tag of the most-recently-sent request; validated on every reply. - pending_tag: u16, + /// Single in-flight request correlation state. + pending: Option, /// Message serialization buffer. msg_buf: Plan9Message, /// User ID for authentication. @@ -810,7 +977,7 @@ impl Plan9Session { fid_table: FidTable::new(), root_fid: NOFID, next_tag: 1, - pending_tag: 0, + pending: None, msg_buf: Plan9Message::new(), uid: 0, mount_path: [0; MAX_MOUNT_PATH], @@ -828,14 +995,153 @@ impl Plan9Session { self.msize } - /// Allocate the next tag for a request. - fn alloc_tag(&mut self) -> u16 { - let tag = self.next_tag; - self.next_tag = self.next_tag.wrapping_add(1); + /// Abort the active connection and invalidate every tracked FID. + pub fn abort_connection(&mut self) { + self.pending = None; + self.fid_table.clear(); + self.root_fid = NOFID; + self.state = SessionState::Error; + } + + fn ensure_idle(&self) -> Result<()> { + if self.pending.is_some() { + return Err(Error::Busy); + } + Ok(()) + } + + fn commit_request(&mut self, tag: u16, operation: PendingOperation) { + self.pending = Some(PendingRequest::new(tag, operation)); + if tag == NOTAG { + return; + } + self.next_tag = tag.wrapping_add(1); if self.next_tag == NOTAG { self.next_tag = 1; } - tag + } + + fn pending_for(&self, kind: PendingKind) -> Result { + let pending = self.pending.ok_or(Error::InvalidArgument)?; + if pending.operation.kind() != kind { + return Err(Error::InvalidArgument); + } + Ok(pending) + } + + fn map_errno(errno: u32) -> Error { + use oncrix_lib::errno; + + match errno as i32 { + errno::EPERM | errno::EACCES => Error::PermissionDenied, + errno::ENOENT | errno::ESRCH | errno::EBADF => Error::NotFound, + errno::ENOMEM => Error::OutOfMemory, + errno::EBUSY => Error::Busy, + errno::EAGAIN => Error::WouldBlock, + errno::EINTR => Error::Interrupted, + errno::EEXIST => Error::AlreadyExists, + errno::EINVAL | errno::EFAULT => Error::InvalidArgument, + errno::ENOSYS => Error::NotImplemented, + _ => Error::IoError, + } + } + + fn release_fid(&mut self, fid: u32) -> Result<()> { + self.fid_table.release(fid)?; + if self.root_fid == fid { + self.root_fid = NOFID; + } + Ok(()) + } + + fn finish_error(&mut self, operation: PendingOperation) { + match operation { + PendingOperation::Attach { fid } => { + let _ = self.release_fid(fid); + } + PendingOperation::Walk { dst, .. } => { + let _ = self.fid_table.release(dst); + } + PendingOperation::Clunk { fid } | PendingOperation::Remove { fid } => { + let _ = self.release_fid(fid); + } + PendingOperation::Version => { + self.state = SessionState::Disconnected; + } + PendingOperation::Open { .. } + | PendingOperation::Read { .. } + | PendingOperation::Write { .. } + | PendingOperation::Stat { .. } => {} + } + self.pending = None; + } + + fn terminal_start( + &mut self, + reply: &[u8], + kind: PendingKind, + ) -> Result<(PendingRequest, usize)> { + let pending = self.pending_for(kind)?; + if reply.len() < HEADER_SIZE { + return Err(Error::InvalidArgument); + } + let tag = u16::from_le_bytes([reply[5], reply[6]]); + if tag != pending.tag { + return Err(Error::InvalidArgument); + } + if reply.len() > self.msize as usize { + self.abort_connection(); + return Err(Error::InvalidArgument); + } + let (msg_type, _, offset) = match Plan9Message::parse_header(reply) { + Ok(header) => header, + Err(error) => { + self.abort_connection(); + return Err(error); + } + }; + if msg_type == pending.expected_response { + return Ok((pending, offset)); + } + if msg_type == P9MessageType::Rlerror { + if reply.len() != HEADER_SIZE + 4 { + self.abort_connection(); + return Err(Error::InvalidArgument); + } + let (errno, end) = match Plan9Message::read_u32(reply, offset) { + Ok(value) => value, + Err(error) => { + self.abort_connection(); + return Err(error); + } + }; + if end != reply.len() { + self.abort_connection(); + return Err(Error::InvalidArgument); + } + self.finish_error(pending.operation); + return Err(Self::map_errno(errno)); + } + self.abort_connection(); + Err(Error::InvalidArgument) + } + + fn malformed_terminal(&mut self) -> Result { + self.abort_connection(); + Err(Error::InvalidArgument) + } + + fn prepare_message(&mut self, msg_type: P9MessageType, tag: u16) -> Result<()> { + self.msg_buf.set_limit(self.msize)?; + self.msg_buf.reset(msg_type, tag); + Ok(()) + } + + fn ensure_frame_size(&self, size: usize) -> Result<()> { + if size > self.msize as usize { + return Err(Error::InvalidArgument); + } + Ok(()) } /// Build a Tversion message to initiate protocol negotiation. @@ -843,13 +1149,15 @@ impl Plan9Session { /// The caller must send the returned bytes to the server and call /// [`handle_rversion`](Self::handle_rversion) with the reply. pub fn build_tversion(&mut self) -> Result<&[u8]> { - self.state = SessionState::Negotiating; - // SECURITY: Tversion always uses NOTAG (0xFFFF) per 9P spec; record it - // in pending_tag so handle_rversion can enforce the required value (F2). - self.pending_tag = NOTAG; - self.msg_buf.reset(P9MessageType::Tversion, NOTAG); + self.ensure_idle()?; + if self.state != SessionState::Disconnected { + return Err(Error::InvalidArgument); + } + self.prepare_message(P9MessageType::Tversion, NOTAG)?; self.msg_buf.put_u32(self.msize)?; self.msg_buf.put_string(&P9_VERSION)?; + self.commit_request(NOTAG, PendingOperation::Version); + self.state = SessionState::Negotiating; Ok(self.msg_buf.finalize()) } @@ -864,66 +1172,27 @@ impl Plan9Session { /// is bounded by `min(received_len, VERSION_STR_LEN)` so a crafted /// short string cannot cause an out-of-bounds index). pub fn handle_rversion(&mut self, reply: &[u8]) -> Result<()> { - let (msg_type, reply_tag, offset) = Plan9Message::parse_header(reply)?; - if msg_type != P9MessageType::Rversion { - self.state = SessionState::Error; - return Err(Error::IoError); - } - // SECURITY: 9P spec §4.1 requires the Rversion tag to equal NOTAG - // (0xFFFF). A server that sends any other tag value is either broken - // or adversarial; reject it before consuming any body fields (F1/F2). - if reply_tag != NOTAG { - self.state = SessionState::Error; - return Err(Error::InvalidArgument); - } - let (server_msize, offset) = Plan9Message::read_u32(reply, offset)?; - - // Reject degenerate msize values that would make the message buffer - // zero-sized or too small to hold a single 9P header. - if server_msize < MIN_MSIZE { - self.state = SessionState::Error; - return Err(Error::InvalidArgument); - } - - let (version_str, _offset) = Plan9Message::read_string(reply, offset)?; - - // Compare only up to min(received_len, VERSION_STR_LEN) bytes so a - // server that sends a shorter string can never make the index walk - // past the received slice. - let cmp_len = if version_str.len() < VERSION_STR_LEN { - version_str.len() - } else { - VERSION_STR_LEN - }; - // The lengths must also be equal for the strings to match. - let len_ok = version_str.len() == VERSION_STR_LEN; - let mut bytes_ok = true; - let mut i = 0; - while i < cmp_len { - if version_str[i] != P9_VERSION[i] { - bytes_ok = false; - break; - } - i += 1; - } - if !len_ok || !bytes_ok { - self.state = SessionState::Error; + if self.state != SessionState::Negotiating { return Err(Error::InvalidArgument); } - - // Accept the smaller of the two advertised sizes and clamp to the - // local maximum so we never allocate beyond our own buffer. - let negotiated = if server_msize < self.msize { - server_msize - } else { - self.msize + let (_, mut offset) = self.terminal_start(reply, PendingKind::Version)?; + let (server_msize, next) = match Plan9Message::read_u32(reply, offset) { + Ok(value) => value, + Err(_) => return self.malformed_terminal(), }; - self.msize = if negotiated > MAX_MESSAGE_SIZE { - MAX_MESSAGE_SIZE - } else { - negotiated + offset = next; + let (version, end) = match Plan9Message::read_string(reply, offset) { + Ok(value) => value, + Err(_) => return self.malformed_terminal(), }; - + if !(MIN_MSIZE..=self.msize).contains(&server_msize) + || version != P9_VERSION + || end != reply.len() + { + return self.malformed_terminal(); + } + self.pending = None; + self.msize = server_msize; self.state = SessionState::Versioned; Ok(()) } @@ -932,17 +1201,21 @@ impl Plan9Session { /// /// `aname` is the filesystem name on the server to attach to. pub fn build_tattach(&mut self, uid: u32, aname: &[u8]) -> Result<&[u8]> { + self.ensure_idle()?; if self.state != SessionState::Versioned { return Err(Error::InvalidArgument); } - self.uid = uid; - let (slot, fid_num) = self.fid_table.alloc()?; - let tag = self.alloc_tag(); - // SECURITY: record the client-chosen tag so handle_rattach can reject - // any reply whose tag does not match this outstanding request (F1). - self.pending_tag = tag; - self.msg_buf.reset(P9MessageType::Tattach, tag); - self.msg_buf.put_u32(fid_num)?; + if aname.len() > u16::MAX as usize { + return Err(Error::InvalidArgument); + } + let frame_size = 23usize + .checked_add(aname.len()) + .ok_or(Error::InvalidArgument)?; + self.ensure_frame_size(frame_size)?; + let (slot, fid) = self.fid_table.preview_alloc()?; + let tag = self.next_tag; + self.prepare_message(P9MessageType::Tattach, tag)?; + self.msg_buf.put_u32(fid)?; self.msg_buf.put_u32(NOFID)?; // afid (no auth) // uname self.msg_buf.put_string(b"")?; @@ -950,35 +1223,37 @@ impl Plan9Session { self.msg_buf.put_string(aname)?; // n_uname (9P2000.L extension: numeric uid) self.msg_buf.put_u32(uid)?; - self.root_fid = fid_num; - let fid_entry = self.fid_table.get_mut(slot)?; - fid_entry.state = FidState::Attached; + self.fid_table.commit_alloc(slot, fid); + self.root_fid = fid; + self.uid = uid; + self.commit_request(tag, PendingOperation::Attach { fid }); Ok(self.msg_buf.finalize()) } /// Handle an Rattach reply from the server. pub fn handle_rattach(&mut self, reply: &[u8]) -> Result { - let (msg_type, reply_tag, offset) = Plan9Message::parse_header(reply)?; - // SECURITY: reject any reply whose tag does not match the tag sent in - // the outstanding Tattach; prevents FID/QID spoofing via forged replies - // from an adversarial server (F1). - if reply_tag != self.pending_tag { - self.state = SessionState::Error; + if self.state != SessionState::Versioned { return Err(Error::InvalidArgument); } - if msg_type == P9MessageType::Rerror { - self.state = SessionState::Error; - return Err(Error::IoError); - } - if msg_type != P9MessageType::Rattach { - self.state = SessionState::Error; + let (pending, offset) = self.terminal_start(reply, PendingKind::Attach)?; + let PendingOperation::Attach { fid } = pending.operation else { return Err(Error::InvalidArgument); + }; + let (qid, consumed) = match P9Qid::from_bytes(reply, offset) { + Ok(value) => value, + Err(_) => return self.malformed_terminal(), + }; + let Some(end) = offset.checked_add(consumed) else { + return self.malformed_terminal(); + }; + if end != reply.len() { + return self.malformed_terminal(); } - let (qid, _) = P9Qid::from_bytes(reply, offset)?; - // Update root FID with the server's QID. - let slot = self.fid_table.lookup(self.root_fid)?; + let slot = self.fid_table.lookup(fid)?; let fid_entry = self.fid_table.get_mut(slot)?; fid_entry.qid = qid; + fid_entry.state = FidState::Attached; + self.pending = None; self.state = SessionState::Attached; Ok(qid) } @@ -990,20 +1265,32 @@ impl Plan9Session { /// /// Returns the wire message and the newly allocated destination FID number. pub fn build_twalk(&mut self, src_fid: u32, names: &[&[u8]]) -> Result<(&[u8], u32)> { + self.ensure_idle()?; if self.state != SessionState::Attached { return Err(Error::InvalidArgument); } if names.len() > MAX_WALK_ELEMS { return Err(Error::InvalidArgument); } - // Verify src_fid exists. - let _src_slot = self.fid_table.lookup(src_fid)?; - let (_dst_slot, dst_fid) = self.fid_table.alloc()?; - let tag = self.alloc_tag(); - // SECURITY: record the client-chosen tag so handle_rwalk can reject - // any reply whose tag does not match this outstanding request (F1). - self.pending_tag = tag; - self.msg_buf.reset(P9MessageType::Twalk, tag); + let src_slot = self.fid_table.lookup(src_fid)?; + let source = self.fid_table.get(src_slot)?; + if source.state != FidState::Attached || (!names.is_empty() && !source.qid.qtype.is_dir()) { + return Err(Error::InvalidArgument); + } + let mut frame_size = 17usize; + for name in names { + if name.len() > u16::MAX as usize { + return Err(Error::InvalidArgument); + } + frame_size = frame_size + .checked_add(2) + .and_then(|size| size.checked_add(name.len())) + .ok_or(Error::InvalidArgument)?; + } + self.ensure_frame_size(frame_size)?; + let (slot, dst_fid) = self.fid_table.preview_alloc()?; + let tag = self.next_tag; + self.prepare_message(P9MessageType::Twalk, tag)?; self.msg_buf.put_u32(src_fid)?; self.msg_buf.put_u32(dst_fid)?; self.msg_buf.put_u16(names.len() as u16)?; @@ -1012,97 +1299,107 @@ impl Plan9Session { self.msg_buf.put_string(names[i])?; i += 1; } + self.fid_table.commit_alloc(slot, dst_fid); + self.commit_request( + tag, + PendingOperation::Walk { + src: src_fid, + dst: dst_fid, + nwname: names.len(), + }, + ); Ok((self.msg_buf.finalize(), dst_fid)) } - /// Handle an Rwalk reply from the server. - /// - /// Returns the array of QIDs for each successfully walked element. - pub fn handle_rwalk( - &mut self, - reply: &[u8], - dst_fid: u32, - ) -> Result<(usize, [P9Qid; MAX_WALK_ELEMS])> { - let (msg_type, reply_tag, mut offset) = Plan9Message::parse_header(reply)?; - // SECURITY: reject any reply whose tag does not match the tag sent in - // the outstanding Twalk; prevents FID/QID spoofing via forged replies - // from an adversarial server (F1). - if reply_tag != self.pending_tag { - let _ = self.fid_table.release(dst_fid); - return Err(Error::InvalidArgument); - } - if msg_type == P9MessageType::Rerror { - // Walk failed — release the destination FID. - let _ = self.fid_table.release(dst_fid); - return Err(Error::NotFound); - } - if msg_type != P9MessageType::Rwalk { - let _ = self.fid_table.release(dst_fid); - return Err(Error::InvalidArgument); - } - if reply.len() < offset + 2 { - let _ = self.fid_table.release(dst_fid); + /// Handle an Rwalk reply and apply its full, partial, or clone result. + pub fn handle_rwalk(&mut self, reply: &[u8]) -> Result { + if self.state != SessionState::Attached { return Err(Error::InvalidArgument); } - let nwqid = u16::from_le_bytes([reply[offset], reply[offset + 1]]) as usize; - offset += 2; - // nwqid must not exceed the protocol maximum (16 elements). - if nwqid > MAX_WALK_ELEMS { - let _ = self.fid_table.release(dst_fid); + let (pending, mut offset) = self.terminal_start(reply, PendingKind::Walk)?; + let PendingOperation::Walk { src, dst, nwname } = pending.operation else { return Err(Error::InvalidArgument); - } - // Validate upfront that the buffer holds all nwqid QIDs before - // entering the loop. Use checked arithmetic to prevent overflow - // when computing the required byte span. - let qid_bytes = match nwqid.checked_mul(P9Qid::WIRE_SIZE) { - Some(n) => n, - None => { - let _ = self.fid_table.release(dst_fid); - return Err(Error::InvalidArgument); - } }; - let required_end = match offset.checked_add(qid_bytes) { - Some(n) => n, - None => { - let _ = self.fid_table.release(dst_fid); - return Err(Error::InvalidArgument); - } + let Some(count_end) = offset.checked_add(2) else { + return self.malformed_terminal(); }; - if required_end > reply.len() { - let _ = self.fid_table.release(dst_fid); - return Err(Error::InvalidArgument); + let Some(count_bytes) = reply.get(offset..count_end) else { + return self.malformed_terminal(); + }; + let count = u16::from_le_bytes([count_bytes[0], count_bytes[1]]) as usize; + if count > nwname || count > MAX_WALK_ELEMS { + return self.malformed_terminal(); } + offset = count_end; let mut qids = [P9Qid::new(P9QidType::FILE, 0, 0); MAX_WALK_ELEMS]; - let mut i = 0; - while i < nwqid { - let (qid, consumed) = P9Qid::from_bytes(reply, offset)?; - qids[i] = qid; - offset += consumed; - i += 1; - } - // Update the destination FID with the final QID. - if nwqid > 0 { - let slot = self.fid_table.lookup(dst_fid)?; - let fid_entry = self.fid_table.get_mut(slot)?; - fid_entry.state = FidState::Attached; - fid_entry.qid = qids[nwqid - 1]; - } - Ok((nwqid, qids)) + let mut index = 0; + while index < count { + let (qid, consumed) = match P9Qid::from_bytes(reply, offset) { + Ok(value) => value, + Err(_) => return self.malformed_terminal(), + }; + qids[index] = qid; + let Some(next) = offset.checked_add(consumed) else { + return self.malformed_terminal(); + }; + offset = next; + index += 1; + } + if offset != reply.len() { + return self.malformed_terminal(); + } + if nwname == 0 { + let src_slot = self.fid_table.lookup(src)?; + let mut cloned = self.fid_table.get(src_slot)?.clone(); + cloned.fid = dst; + let dst_slot = self.fid_table.lookup(dst)?; + *self.fid_table.get_mut(dst_slot)? = cloned; + self.pending = None; + return Ok(P9WalkResult::Cloned { + source: src, + destination: dst, + }); + } + if count == 0 { + return self.malformed_terminal(); + } + if count < nwname { + let _ = self.fid_table.release(dst); + self.pending = None; + return Ok(P9WalkResult::Partial { + source: src, + count, + qids, + }); + } + let slot = self.fid_table.lookup(dst)?; + let fid_entry = self.fid_table.get_mut(slot)?; + fid_entry.state = FidState::Attached; + fid_entry.qid = qids[count - 1]; + self.pending = None; + Ok(P9WalkResult::Full { + source: src, + destination: dst, + count, + qids, + }) } /// Build a Topen message to open a file identified by FID. pub fn build_topen(&mut self, fid: u32, mode: P9OpenMode) -> Result<&[u8]> { + self.ensure_idle()?; if self.state != SessionState::Attached { return Err(Error::InvalidArgument); } - let _slot = self.fid_table.lookup(fid)?; - let tag = self.alloc_tag(); - // SECURITY: record the client-chosen tag so handle_ropen can reject - // any reply whose tag does not match this outstanding request (F1). - self.pending_tag = tag; - self.msg_buf.reset(P9MessageType::Topen, tag); + let slot = self.fid_table.lookup(fid)?; + if self.fid_table.get(slot)?.state != FidState::Attached { + return Err(Error::InvalidArgument); + } + let tag = self.next_tag; + self.prepare_message(P9MessageType::Topen, tag)?; self.msg_buf.put_u32(fid)?; self.msg_buf.put_u8(mode.0)?; + self.commit_request(tag, PendingOperation::Open { fid, mode }); Ok(self.msg_buf.finalize()) } @@ -1116,66 +1413,45 @@ impl Plan9Session { /// (which would double-count the header offset and produce an OOB read /// on a crafted reply that is just long enough to pass the header check /// but shorter than `2 * HEADER_SIZE + QID_SIZE + 4`). - pub fn handle_ropen( - &mut self, - reply: &[u8], - fid: u32, - mode: P9OpenMode, - ) -> Result<(P9Qid, u32)> { - let (msg_type, reply_tag, offset) = Plan9Message::parse_header(reply)?; - // SECURITY: reject any reply whose tag does not match the tag sent in - // the outstanding Topen; prevents FID/QID spoofing via forged replies - // from an adversarial server (F1). - if reply_tag != self.pending_tag { - return Err(Error::InvalidArgument); - } - if msg_type == P9MessageType::Rerror { - return Err(Error::PermissionDenied); - } - if msg_type != P9MessageType::Ropen { + pub fn handle_ropen(&mut self, reply: &[u8]) -> Result<(P9Qid, u32)> { + let (pending, offset) = self.terminal_start(reply, PendingKind::Open)?; + let PendingOperation::Open { fid, mode } = pending.operation else { return Err(Error::InvalidArgument); - } - // Validate that the buffer holds the QID and iounit fields before - // reading them, using the absolute end position of each field. - let qid_end = match offset.checked_add(P9Qid::WIRE_SIZE) { - Some(n) => n, - None => return Err(Error::InvalidArgument), }; - let iounit_end = match qid_end.checked_add(4) { - Some(n) => n, - None => return Err(Error::InvalidArgument), + let (qid, consumed) = match P9Qid::from_bytes(reply, offset) { + Ok(value) => value, + Err(_) => return self.malformed_terminal(), }; - if iounit_end > reply.len() { - return Err(Error::InvalidArgument); + let Some(iounit_offset) = offset.checked_add(consumed) else { + return self.malformed_terminal(); + }; + let (raw_iounit, end) = match Plan9Message::read_u32(reply, iounit_offset) { + Ok(value) => value, + Err(_) => return self.malformed_terminal(), + }; + if end != reply.len() { + return self.malformed_terminal(); } - // `from_bytes` performs its own length check; the upfront guard above - // ensures it will succeed without an allocation-driven panic. - let (qid, _consumed) = P9Qid::from_bytes(reply, offset)?; - // Pass the absolute offset of the iounit field, not `offset + consumed` - // (which would be correct here only by coincidence and would fail if the - // header offset were ever non-zero relative to the QID start). - let (raw_iounit, _) = Plan9Message::read_u32(reply, qid_end)?; - // SECURITY: clamp the server-supplied iounit to MAX_IO_SIZE (F3). - // An adversarial server can send iounit=0 to cause a divide-by-zero in - // a read/write loop, or iounit > MAX_IO_SIZE to cause a buffer overflow. - // When iounit is 0, substitute MAX_IO_SIZE (the agreed-upon maximum) - // rather than propagating a value that callers cannot safely use. - let iounit = if raw_iounit == 0 { - MAX_IO_SIZE as u32 + let server_iounit = if raw_iounit == 0 { + self.msize } else { - raw_iounit.min(MAX_IO_SIZE as u32) + raw_iounit }; + let iounit = server_iounit.min(self.msize).min(MAX_IO_SIZE as u32); let slot = self.fid_table.lookup(fid)?; let fid_entry = self.fid_table.get_mut(slot)?; fid_entry.state = FidState::Open; fid_entry.qid = qid; fid_entry.mode = mode; fid_entry.offset = 0; + fid_entry.iounit = iounit; + self.pending = None; Ok((qid, iounit)) } /// Build a Tread message to read data from an open FID. pub fn build_tread(&mut self, fid: u32, offset: u64, count: u32) -> Result<&[u8]> { + self.ensure_idle()?; if self.state != SessionState::Attached { return Err(Error::InvalidArgument); } @@ -1184,23 +1460,31 @@ impl Plan9Session { if fid_entry.state != FidState::Open { return Err(Error::InvalidArgument); } - let clamped = if count as usize > MAX_IO_SIZE { - MAX_IO_SIZE as u32 + let budget = (self.msize - 11).min(MAX_IO_SIZE as u32); + let budget = if fid_entry.iounit == 0 { + budget } else { - count + budget.min(fid_entry.iounit) }; - let tag = self.alloc_tag(); - // SECURITY: record the client-chosen tag for reply validation (F1). - self.pending_tag = tag; - self.msg_buf.reset(P9MessageType::Tread, tag); + let clamped = count.min(budget); + let tag = self.next_tag; + self.prepare_message(P9MessageType::Tread, tag)?; self.msg_buf.put_u32(fid)?; self.msg_buf.put_u64(offset)?; self.msg_buf.put_u32(clamped)?; + self.commit_request( + tag, + PendingOperation::Read { + fid, + count: clamped, + }, + ); Ok(self.msg_buf.finalize()) } /// Build a Twrite message to write data to an open FID. pub fn build_twrite(&mut self, fid: u32, offset: u64, data: &[u8]) -> Result<&[u8]> { + self.ensure_idle()?; if self.state != SessionState::Attached { return Err(Error::InvalidArgument); } @@ -1212,74 +1496,124 @@ impl Plan9Session { if !fid_entry.mode.is_writable() { return Err(Error::PermissionDenied); } - let len = if data.len() > MAX_IO_SIZE { - MAX_IO_SIZE + let budget = (self.msize as usize - 23).min(MAX_IO_SIZE); + let budget = if fid_entry.iounit == 0 { + budget } else { - data.len() + budget.min(fid_entry.iounit as usize) }; - let tag = self.alloc_tag(); - // SECURITY: record the client-chosen tag for reply validation (F1). - self.pending_tag = tag; - self.msg_buf.reset(P9MessageType::Twrite, tag); + let len = data.len().min(budget); + let tag = self.next_tag; + self.prepare_message(P9MessageType::Twrite, tag)?; self.msg_buf.put_u32(fid)?; self.msg_buf.put_u64(offset)?; self.msg_buf.put_u32(len as u32)?; self.msg_buf.put_data(&data[..len])?; + self.commit_request( + tag, + PendingOperation::Write { + fid, + count: len as u32, + }, + ); Ok(self.msg_buf.finalize()) } /// Build a Tclunk message to release a FID. pub fn build_tclunk(&mut self, fid: u32) -> Result<&[u8]> { - let _slot = self.fid_table.lookup(fid)?; - let tag = self.alloc_tag(); - // SECURITY: record the client-chosen tag so handle_rclunk can reject - // any reply whose tag does not match this outstanding request (F1). - self.pending_tag = tag; - self.msg_buf.reset(P9MessageType::Tclunk, tag); + self.ensure_idle()?; + if self.state != SessionState::Attached { + return Err(Error::InvalidArgument); + } + self.fid_table.lookup(fid)?; + let tag = self.next_tag; + self.prepare_message(P9MessageType::Tclunk, tag)?; self.msg_buf.put_u32(fid)?; + self.commit_request(tag, PendingOperation::Clunk { fid }); Ok(self.msg_buf.finalize()) } - /// Handle an Rclunk reply and release the FID. - pub fn handle_rclunk(&mut self, reply: &[u8], fid: u32) -> Result<()> { - let (msg_type, reply_tag, _offset) = Plan9Message::parse_header(reply)?; - // SECURITY: reject any reply whose tag does not match the tag sent in - // the outstanding Tclunk; prevents FID spoofing via forged replies - // from an adversarial server (F1). - if reply_tag != self.pending_tag { - return Err(Error::InvalidArgument); - } - if msg_type == P9MessageType::Rerror { - return Err(Error::IoError); - } - if msg_type != P9MessageType::Rclunk { + /// Handle an Rclunk reply and release its correlated FID. + pub fn handle_rclunk(&mut self, reply: &[u8]) -> Result<()> { + let (pending, offset) = self.terminal_start(reply, PendingKind::Clunk)?; + let PendingOperation::Clunk { fid } = pending.operation else { return Err(Error::InvalidArgument); + }; + if offset != reply.len() { + return self.malformed_terminal(); } - self.fid_table.release(fid) + self.release_fid(fid)?; + self.pending = None; + Ok(()) } /// Build a Tremove message to delete a file and release the FID. pub fn build_tremove(&mut self, fid: u32) -> Result<&[u8]> { - let _slot = self.fid_table.lookup(fid)?; - let tag = self.alloc_tag(); - // SECURITY: record the client-chosen tag for reply validation (F1). - self.pending_tag = tag; - self.msg_buf.reset(P9MessageType::Tremove, tag); + self.ensure_idle()?; + if self.state != SessionState::Attached { + return Err(Error::InvalidArgument); + } + self.fid_table.lookup(fid)?; + let tag = self.next_tag; + self.prepare_message(P9MessageType::Tremove, tag)?; self.msg_buf.put_u32(fid)?; + self.commit_request(tag, PendingOperation::Remove { fid }); Ok(self.msg_buf.finalize()) } /// Build a Tstat message to retrieve file attributes. pub fn build_tstat(&mut self, fid: u32) -> Result<&[u8]> { - let _slot = self.fid_table.lookup(fid)?; - let tag = self.alloc_tag(); - // SECURITY: record the client-chosen tag for reply validation (F1). - self.pending_tag = tag; - self.msg_buf.reset(P9MessageType::Tstat, tag); + self.ensure_idle()?; + if self.state != SessionState::Attached { + return Err(Error::InvalidArgument); + } + self.fid_table.lookup(fid)?; + let tag = self.next_tag; + self.prepare_message(P9MessageType::Tstat, tag)?; self.msg_buf.put_u32(fid)?; + self.commit_request(tag, PendingOperation::Stat { fid }); Ok(self.msg_buf.finalize()) } + /// Retire a correlated read, write, or stat response without parsing its body. + pub fn finalize_unhandled_response<'a>( + &mut self, + reply: &'a [u8], + ) -> Result> { + let pending = self.pending.ok_or(Error::InvalidArgument)?; + let (kind, request) = match pending.operation { + PendingOperation::Read { fid, count } => { + (PendingKind::Read, P9RawRequest::Read { fid, count }) + } + PendingOperation::Write { fid, count } => { + (PendingKind::Write, P9RawRequest::Write { fid, count }) + } + PendingOperation::Stat { fid } => (PendingKind::Stat, P9RawRequest::Stat { fid }), + _ => return Err(Error::InvalidArgument), + }; + let (_, offset) = self.terminal_start(reply, kind)?; + self.pending = None; + Ok(P9RawResponse { + request, + response_type: pending.expected_response, + payload: &reply[offset..], + }) + } + + /// Handle an Rremove response and release its correlated FID. + pub fn handle_rremove(&mut self, reply: &[u8]) -> Result<()> { + let (pending, offset) = self.terminal_start(reply, PendingKind::Remove)?; + let PendingOperation::Remove { fid } = pending.operation else { + return Err(Error::InvalidArgument); + }; + if offset != reply.len() { + return self.malformed_terminal(); + } + self.release_fid(fid)?; + self.pending = None; + Ok(()) + } + /// Get the root FID for this session. pub fn root_fid(&self) -> u32 { self.root_fid @@ -1471,3 +1805,15 @@ impl Plan9Registry { self.count } } + +#[cfg(test)] +#[path = "plan9fs_frame_tests.rs"] +mod frame_tests; + +#[cfg(test)] +#[path = "plan9fs_session_tests.rs"] +mod session_tests; + +#[cfg(test)] +#[path = "plan9fs_protocol_tests.rs"] +mod protocol_tests; diff --git a/crates/vfs/src/plan9fs_frame_tests.rs b/crates/vfs/src/plan9fs_frame_tests.rs new file mode 100644 index 0000000..77807c2 --- /dev/null +++ b/crates/vfs/src/plan9fs_frame_tests.rs @@ -0,0 +1,356 @@ +// Copyright 2026 ONCRIX Contributors +// Copyright 2026 ONCRIX Contributors +// SPDX-License-Identifier: Apache-2.0 + +use super::session_tests::{assert_poisoned, attached, reply, tag, versioned}; +use super::{ + NOFID, NOTAG, P9MessageType, P9OpenMode, P9Qid, P9QidType, Plan9Message, Plan9Session, + SessionState, +}; +use oncrix_lib::Error; + +#[test] +fn characterization_header_rejects_lengths_below_wire_minimum() { + // Given + let frames: [&[u8]; 7] = [ + &[], + &[0], + &[0, 0], + &[0, 0, 0], + &[0, 0, 0, 0], + &[0, 0, 0, 0, 0], + &[0, 0, 0, 0, 0, 0], + ]; + + // When / Then + for frame in frames { + assert_eq!( + Plan9Message::parse_header(frame), + Err(Error::InvalidArgument) + ); + } +} + +#[test] +fn characterization_header_accepts_exact_seven_byte_frame() { + // Given + let frame = [7, 0, 0, 0, 100, 0x34, 0x12]; + + // When + let parsed = Plan9Message::parse_header(&frame); + + // Then + assert_eq!(parsed, Ok((P9MessageType::Tversion, 0x1234, 7))); +} + +#[test] +fn characterization_header_rejects_declared_size_mismatch() { + // Given + let frame = [8, 0, 0, 0, 100, 0, 0]; + + // When + let parsed = Plan9Message::parse_header(&frame); + + // Then + assert_eq!(parsed, Err(Error::InvalidArgument)); +} + +#[test] +fn characterization_header_rejects_declared_size_smaller_than_received() { + // Given / When / Then + let frame = [7, 0, 0, 0, 100, 0, 0, 0xAA]; + assert_eq!( + Plan9Message::parse_header(&frame), + Err(Error::InvalidArgument) + ); +} + +#[test] +fn frame_limit_persists_across_reset() { + // Given / When / Then + let mut message = Plan9Message::new(); + message.set_limit(8).unwrap(); + message.reset(P9MessageType::Tversion, 1); + assert_eq!(message.put_u16(1), Err(Error::InvalidArgument)); + message.reset(P9MessageType::Tattach, 2); + assert_eq!(message.put_u16(1), Err(Error::InvalidArgument)); +} + +#[test] +fn failed_puts_leave_message_position_unchanged() { + // Given / When / Then + let mut message = Plan9Message::new(); + message.set_limit(9).unwrap(); + message.reset(P9MessageType::Tversion, 1); + assert_eq!(message.put_string(b"x"), Err(Error::InvalidArgument)); + message.put_u16(0x1234).unwrap(); + assert_eq!(message.finalize(), &[9, 0, 0, 0, 100, 1, 0, 0x34, 0x12]); +} + +#[test] +fn terminal_fid_retirement_clears_only_matching_root() { + // Given / When / Then + let mut session = attached(); + let fid = session.root_fid(); + let slot = session.fid_table.lookup(fid).unwrap(); + let entry = session.fid_table.get_mut(slot).unwrap(); + entry.qid = P9Qid::new(P9QidType::DIR, 9, 9); + entry.mode = P9OpenMode::OWRITE; + entry.offset = 99; + entry.iounit = 77; + entry.path[0] = b'x'; + entry.path_len = 1; + let clunk_tag = tag(session.build_tclunk(fid).unwrap()); + let response = reply(P9MessageType::Rclunk, clunk_tag, &[]); + session.handle_rclunk(&response).unwrap(); + assert_eq!(session.root_fid(), NOFID); + let (reused, _) = session.fid_table.alloc().unwrap(); + let entry = session.fid_table.get(reused).unwrap(); + assert_eq!( + (entry.mode, entry.offset, entry.iounit), + (P9OpenMode::OREAD, 0, 0) + ); + assert_eq!(entry.qid, P9Qid::new(P9QidType::FILE, 0, 0)); + assert_eq!((entry.path[0], entry.path_len), (0, 0)); + + let mut non_root = attached(); + let root = non_root.root_fid(); + let (request, fid) = non_root.build_twalk(root, &[]).unwrap(); + let walk_tag = tag(request); + non_root + .handle_rwalk(&reply(P9MessageType::Rwalk, walk_tag, &[0, 0])) + .unwrap(); + let clunk_tag = tag(non_root.build_tclunk(fid).unwrap()); + non_root + .handle_rclunk(&reply(P9MessageType::Rclunk, clunk_tag, &[])) + .unwrap(); + assert_eq!(non_root.root_fid(), root); + + let mut removed = attached(); + let fid = removed.root_fid(); + let remove_tag = tag(removed.build_tremove(fid).unwrap()); + let response = reply(P9MessageType::Rremove, remove_tag, &[]); + removed.handle_rremove(&response).unwrap(); + assert_eq!(removed.root_fid(), NOFID); + let mut denied = attached(); + let fid = denied.root_fid(); + let remove_tag = tag(denied.build_tremove(fid).unwrap()); + let response = reply(P9MessageType::Rlerror, remove_tag, &13u32.to_le_bytes()); + let result = denied.handle_rremove(&response); + assert_eq!(result, Err(Error::PermissionDenied)); + assert_eq!(denied.root_fid(), NOFID); +} + +#[test] +fn lifecycle_second_builder_is_busy_without_mutation() { + // Given / When / Then + let mut negotiation = Plan9Session::new(); + negotiation.build_tversion().unwrap(); + assert_eq!(negotiation.build_tversion().map(|_| ()), Err(Error::Busy)); + let mut session = versioned(); + session.build_tattach(7, b"").unwrap(); + let root = session.root_fid(); + let count = session.fid_table().active_count(); + assert_eq!(session.build_tattach(7, b"").map(|_| ()), Err(Error::Busy)); + assert_eq!(session.build_twalk(root, &[]).map(|_| ()), Err(Error::Busy)); + assert_eq!( + (session.root_fid(), session.fid_table().active_count()), + (root, count) + ); +} + +#[test] +fn abort_connection_invalidates_pending_and_fids() { + // Given / When / Then + let mut session = attached(); + let fid = session.root_fid(); + session.build_tclunk(fid).unwrap(); + session.abort_connection(); + assert_poisoned(&session); + assert_eq!( + session.build_tclunk(fid).map(|_| ()), + Err(Error::InvalidArgument) + ); +} + +#[test] +fn lifecycle_malformed_matching_terminal_poisons_negotiation() { + // Given / When / Then + let mut session = Plan9Session::new(); + session.build_tversion().unwrap(); + assert!( + session + .handle_rversion(&reply(P9MessageType::Rversion, NOTAG, &[0])) + .is_err() + ); + assert_eq!(session.state(), SessionState::Error); + assert_eq!( + session.build_tversion().map(|_| ()), + Err(Error::InvalidArgument) + ); +} + +#[test] +fn lifecycle_stale_reply_cannot_complete_newer_request() { + // Given / When / Then + let mut session = attached(); + let fid = session.root_fid(); + let old_tag = tag(session.build_tstat(fid).unwrap()); + let old_reply = reply(P9MessageType::Rstat, old_tag, &[]); + session.finalize_unhandled_response(&old_reply).unwrap(); + let new_tag = tag(session.build_tstat(fid).unwrap()); + assert!(session.finalize_unhandled_response(&old_reply).is_err()); + let new_reply = reply(P9MessageType::Rstat, new_tag, &[]); + assert!(session.finalize_unhandled_response(&new_reply).is_ok()); +} + +#[test] +fn fid_allocator_skips_live_id_after_rollover() { + // Given / When / Then + let mut session = Plan9Session::new(); + let (_, first) = session.fid_table.alloc().unwrap(); + session.fid_table.next_fid = NOFID - 1; + let (_, last) = session.fid_table.alloc().unwrap(); + let (_, wrapped) = session.fid_table.alloc().unwrap(); + assert_eq!((first, last, wrapped), (1, NOFID - 1, 2)); + assert_eq!(session.fid_table.next_fid, 3); +} + +#[test] +fn characterization_header_rejects_unknown_message_type() { + // Given + let frame = [7, 0, 0, 0, 0, 0, 0]; + + // When + let parsed = Plan9Message::parse_header(&frame); + + // Then + assert_eq!(parsed, Err(Error::InvalidArgument)); +} + +#[test] +fn characterization_counted_string_returns_borrowed_payload() { + // Given + let frame = [3, 0, b'n', b'i', b'n', 0xAA]; + + // When + let parsed = Plan9Message::read_string(&frame, 0); + + // Then + let (value, next) = parsed.unwrap(); + assert_eq!(value, b"nin"); + assert_eq!(next, 5); + assert!(core::ptr::eq(value, &frame[2..5])); +} + +#[test] +fn characterization_counted_string_rejects_truncated_payload() { + // Given + let frame = [4, 0, b'n', b'i', b'n']; + + // When + let parsed = Plan9Message::read_string(&frame, 0); + + // Then + assert_eq!(parsed, Err(Error::InvalidArgument)); +} + +#[test] +fn characterization_qid_rejects_twelve_byte_frame() { + // Given + let frame = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; + + // When + let parsed = P9Qid::from_bytes(&frame, 0); + + // Then + assert_eq!(parsed, Err(Error::InvalidArgument)); +} + +#[test] +fn characterization_qid_roundtrips_at_zero_offset() { + // Given + let frame = [ + 0x80, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xAA, 0xBB, 0xCC, + ]; + let mut encoded = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; + + // When + let (qid, consumed) = P9Qid::from_bytes(&frame, 0).unwrap(); + let written = qid.to_bytes(&mut encoded, 0); + + // Then + assert_eq!(consumed, P9Qid::WIRE_SIZE); + assert_eq!(written, Ok(P9Qid::WIRE_SIZE)); + assert_eq!(encoded, frame); +} + +#[test] +fn characterization_qid_roundtrips_at_nonzero_offset() { + // Given + let frame = [ + 0xFE, 0x02, 0x04, 0x03, 0x02, 0x01, 0x08, 0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01, 0xEF, + ]; + let mut encoded = [0xFE, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xEF]; + + // When + let (qid, consumed) = P9Qid::from_bytes(&frame, 1).unwrap(); + let written = qid.to_bytes(&mut encoded, 1); + + // Then + assert_eq!(consumed, P9Qid::WIRE_SIZE); + assert_eq!(written, Ok(P9Qid::WIRE_SIZE)); + assert_eq!(encoded, frame); +} + +#[test] +fn offset_overflow_integer_reads_reject_maximum_and_near_maximum() { + // Given / When / Then + for offset in [usize::MAX, usize::MAX - 2] { + assert_eq!( + Plan9Message::read_u32(&[], offset), + Err(Error::InvalidArgument) + ); + } + for offset in [usize::MAX, usize::MAX - 4] { + assert_eq!( + Plan9Message::read_u64(&[], offset), + Err(Error::InvalidArgument) + ); + } +} + +#[test] +fn offset_overflow_read_string_rejects_maximum_offset() { + assert_eq!( + Plan9Message::read_string(&[], usize::MAX), + Err(Error::InvalidArgument) + ); +} + +#[test] +fn offset_overflow_read_string_rejects_near_maximum_offset() { + assert_eq!( + Plan9Message::read_string(&[], usize::MAX - 1), + Err(Error::InvalidArgument) + ); +} + +#[test] +fn offset_overflow_qid_decode_rejects_overflowing_offset() { + assert_eq!( + P9Qid::from_bytes(&[], usize::MAX - 6), + Err(Error::InvalidArgument) + ); +} + +#[test] +fn offset_overflow_qid_encode_rejects_overflowing_offset() { + let qid = P9Qid::new(P9QidType::FILE, 0, 0); + let mut frame = []; + + assert_eq!( + qid.to_bytes(&mut frame, usize::MAX - 6), + Err(Error::InvalidArgument) + ); +} diff --git a/crates/vfs/src/plan9fs_protocol_tests.rs b/crates/vfs/src/plan9fs_protocol_tests.rs new file mode 100644 index 0000000..85b59fa --- /dev/null +++ b/crates/vfs/src/plan9fs_protocol_tests.rs @@ -0,0 +1,280 @@ +// Copyright 2026 ONCRIX Contributors +// Copyright 2026 ONCRIX Contributors +// SPDX-License-Identifier: Apache-2.0 + +extern crate std; + +use super::session_tests::{ + QID, ROPEN, RWALK_ONE, VERSION_256, assert_poisoned, attached, opened, tag as request_tag, + versioned, walked, +}; +use super::{ + NOTAG, P9MessageType, P9OpenMode, P9RawRequest, P9WalkResult, Plan9Session, SessionState, +}; +use oncrix_lib::Error; +use std::vec::Vec; + +#[derive(Clone, Copy)] +enum Handler { + V, + A, + W, + O, + C, +} + +const HANDLERS: [Handler; 5] = [Handler::V, Handler::A, Handler::W, Handler::O, Handler::C]; + +type Pending = (Plan9Session, Handler, u32, u16, u8); + +fn wire(kind: u8, tag: u16, payload: &[u8]) -> Vec { + let mut frame = Vec::from([0, 0, 0, 0, kind]); + frame.extend_from_slice(&tag.to_le_bytes()); + frame.extend_from_slice(payload); + let size = (frame.len() as u32).to_le_bytes(); + frame[..4].copy_from_slice(&size); + frame +} + +fn pending(handler: Handler) -> Pending { + match handler { + Handler::V => { + let mut session = Plan9Session::new(); + session.build_tversion().unwrap(); + (session, handler, 0, NOTAG, P9MessageType::Rversion as u8) + } + Handler::A => { + let mut session = versioned(); + let tag = request_tag(session.build_tattach(7, b"").unwrap()); + let fid = session.root_fid(); + (session, handler, fid, tag, P9MessageType::Rattach as u8) + } + Handler::W => { + let mut session = attached(); + let root = session.root_fid(); + let (request, fid) = session.build_twalk(root, &[b"x"]).unwrap(); + let tag = request_tag(request); + (session, handler, fid, tag, P9MessageType::Rwalk as u8) + } + Handler::O => { + let (mut session, fid) = walked(); + let tag = request_tag(session.build_topen(fid, P9OpenMode::OREAD).unwrap()); + (session, handler, fid, tag, P9MessageType::Ropen as u8) + } + Handler::C => { + let mut session = attached(); + let fid = session.root_fid(); + let tag = request_tag(session.build_tclunk(fid).unwrap()); + (session, handler, fid, tag, P9MessageType::Rclunk as u8) + } + } +} + +fn finish(request: &mut Pending, tag_offset: u16, kind: Option) -> Result<(), Error> { + let payload = match request.1 { + Handler::V => &VERSION_256[..], + Handler::A => &QID[..], + Handler::W => &RWALK_ONE[..], + Handler::O => &ROPEN[..], + Handler::C => &[][..], + }; + let tag = request.3.wrapping_add(tag_offset); + let reply = wire(kind.unwrap_or(request.4), tag, payload); + match request.1 { + Handler::V => request.0.handle_rversion(&reply), + Handler::A => request.0.handle_rattach(&reply).map(|_| ()), + Handler::W => request.0.handle_rwalk(&reply).map(|_| ()), + Handler::O => request.0.handle_ropen(&reply).map(|_| ()), + Handler::C => request.0.handle_rclunk(&reply), + } +} + +#[test] +fn protocol_wrong_tags_preserve_pending_requests() { + // Given / When / Then + for handler in HANDLERS { + let mut request = pending(handler); + assert_eq!(finish(&mut request, 1, None), Err(Error::InvalidArgument)); + assert_eq!(finish(&mut request, 0, None), Ok(())); + assert_eq!(finish(&mut request, 0, None), Err(Error::InvalidArgument)); + } +} + +#[test] +fn protocol_wrong_handler_preserves_pending_request() { + // Given / When / Then + let mut request = pending(Handler::O); + let frame = wire(P9MessageType::Rclunk as u8, request.3, &[]); + assert_eq!(request.0.handle_rclunk(&frame), Err(Error::InvalidArgument)); + assert_eq!(finish(&mut request, 0, None), Ok(())); +} + +#[test] +fn protocol_matching_wrong_response_type_poisons_connection() { + // Given / When / Then + let mut request = pending(Handler::A); + let result = finish(&mut request, 0, Some(P9MessageType::Rwalk as u8)); + assert_eq!(result, Err(Error::InvalidArgument)); + assert_poisoned(&request.0); +} + +#[test] +fn protocol_literal_rlerror_errno_and_payload_rules() { + // Given / When / Then + for (errno, expected) in [(13, Error::PermissionDenied), (u32::MAX, Error::IoError)] { + let mut request = pending(Handler::A); + let result = request + .0 + .handle_rattach(&wire(7, request.3, &errno.to_le_bytes())); + assert_eq!(result, Err(expected)); + assert_eq!(request.0.state(), SessionState::Versioned); + } + let mut trailing = pending(Handler::A); + let result = trailing + .0 + .handle_rattach(&wire(7, trailing.3, &[13, 0, 0, 0, 0])); + assert_eq!(result, Err(Error::InvalidArgument)); + assert_poisoned(&trailing.0); + let mut version = pending(Handler::V); + let result = version + .0 + .handle_rversion(&wire(7, NOTAG, &13u32.to_le_bytes())); + assert_eq!(result, Err(Error::PermissionDenied)); + assert_eq!(version.0.state(), SessionState::Disconnected); + assert!(version.0.build_tversion().is_ok()); + let mut malformed_version = pending(Handler::V); + let result = malformed_version + .0 + .handle_rversion(&wire(7, NOTAG, &[13, 0, 0])); + assert_eq!(result, Err(Error::InvalidArgument)); + assert_poisoned(&malformed_version.0); + let mut legacy = pending(Handler::A); + let frame = wire(P9MessageType::Rerror as u8, legacy.3, &[]); + assert_eq!(legacy.0.handle_rattach(&frame), Err(Error::InvalidArgument)); + assert_poisoned(&legacy.0); + let mut clunk = pending(Handler::C); + let result = clunk + .0 + .handle_rclunk(&wire(7, clunk.3, &13u32.to_le_bytes())); + assert_eq!(result, Err(Error::PermissionDenied)); + assert_eq!(clunk.0.fid_table().lookup(clunk.2), Err(Error::NotFound)); + assert_eq!(clunk.0.root_fid(), super::NOFID); +} + +#[test] +fn protocol_raw_responses_borrow_payload_and_retire_context() { + // Given / When / Then + let (mut read, fid) = opened(P9OpenMode::OREAD); + let tag = request_tag(read.build_tread(fid, 0, 3).unwrap()); + let frame = wire(P9MessageType::Rread as u8, tag, b"read"); + let response = read.finalize_unhandled_response(&frame).unwrap(); + assert_eq!(response.request, P9RawRequest::Read { fid, count: 3 }); + assert_eq!(response.payload, b"read"); + assert_eq!( + read.finalize_unhandled_response(&frame), + Err(Error::InvalidArgument) + ); + let (mut write, fid) = opened(P9OpenMode::OWRITE); + let tag = request_tag(write.build_twrite(fid, 0, b"abc").unwrap()); + let frame = wire(P9MessageType::Rwrite as u8, tag, b"written"); + let response = write.finalize_unhandled_response(&frame).unwrap(); + assert_eq!(response.request, P9RawRequest::Write { fid, count: 3 }); + assert_eq!(response.response_type, P9MessageType::Rwrite); + assert_eq!(response.payload, b"written"); + let mut stat = attached(); + let fid = stat.root_fid(); + let tag = request_tag(stat.build_tstat(fid).unwrap()); + let frame = wire(P9MessageType::Rstat as u8, tag, b"stat"); + let response = stat.finalize_unhandled_response(&frame).unwrap(); + assert_eq!(response.request, P9RawRequest::Stat { fid }); + assert_eq!(response.response_type, P9MessageType::Rstat); + assert_eq!(response.payload, b"stat"); + let tag = request_tag(stat.build_tstat(fid).unwrap()); + let denied = wire(7, tag, &13u32.to_le_bytes()); + assert_eq!( + stat.finalize_unhandled_response(&denied), + Err(Error::PermissionDenied) + ); + assert_eq!(stat.state(), SessionState::Attached); +} + +#[test] +fn protocol_walk_reply_cardinality_and_commit_rules() { + // Given / When / Then + let mut more = attached(); + let root = more.root_fid(); + let tag = request_tag(more.build_twalk(root, &[b"x"]).unwrap().0); + let mut payload = Vec::from([2, 0]); + payload.extend_from_slice(&QID); + payload.extend_from_slice(&QID); + assert!( + more.handle_rwalk(&wire(P9MessageType::Rwalk as u8, tag, &payload)) + .is_err() + ); + assert_poisoned(&more); + let mut zero = attached(); + let root = zero.root_fid(); + let tag = request_tag(zero.build_twalk(root, &[b"x"]).unwrap().0); + assert!( + zero.handle_rwalk(&wire(P9MessageType::Rwalk as u8, tag, &[0, 0])) + .is_err() + ); + assert_poisoned(&zero); +} + +#[test] +fn protocol_zero_name_clone_copies_complete_metadata() { + // Given / When / Then + let mut clone = attached(); + let root = clone.root_fid(); + let root_slot = clone.fid_table().lookup(root).unwrap(); + let source = clone.fid_table.get_mut(root_slot).unwrap(); + source.mode = P9OpenMode::OWRITE; + source.qid.qtype = super::P9QidType::FILE; + source.offset = 17; + source.iounit = 19; + source.path[..3].copy_from_slice(b"src"); + source.path_len = 3; + let source_before = std::format!("{source:?}"); + let mut expected = source.clone(); + let (request, dst) = clone.build_twalk(root, &[]).unwrap(); + let tag = request_tag(request); + let result = clone + .handle_rwalk(&wire(P9MessageType::Rwalk as u8, tag, &[0, 0])) + .unwrap(); + assert_eq!( + result, + P9WalkResult::Cloned { + source: root, + destination: dst + } + ); + let dst_slot = clone.fid_table().lookup(dst).unwrap(); + let source = clone.fid_table().get(root_slot).unwrap(); + let destination = clone.fid_table().get(dst_slot).unwrap(); + expected.fid = dst; + assert_eq!(std::format!("{source:?}"), source_before); + assert_eq!( + std::format!("{destination:?}"), + std::format!("{expected:?}") + ); +} + +#[test] +fn protocol_partial_walk_releases_destination_and_preserves_source() { + // Given / When / Then + let mut session = attached(); + let root = session.root_fid(); + let (request, dst) = session.build_twalk(root, &[b"x", b"y"]).unwrap(); + let tag = request_tag(request); + let result = session + .handle_rwalk(&wire(P9MessageType::Rwalk as u8, tag, &RWALK_ONE)) + .unwrap(); + assert!(matches!( + result, + P9WalkResult::Partial { source, count: 1, qids } + if source == root && qids[0].qtype == super::P9QidType::FILE + )); + assert_eq!(session.fid_table().lookup(dst), Err(Error::NotFound)); + assert!(session.fid_table().lookup(root).is_ok()); +} diff --git a/crates/vfs/src/plan9fs_session_tests.rs b/crates/vfs/src/plan9fs_session_tests.rs new file mode 100644 index 0000000..318c948 --- /dev/null +++ b/crates/vfs/src/plan9fs_session_tests.rs @@ -0,0 +1,307 @@ +// Copyright 2026 ONCRIX Contributors +// Copyright 2026 ONCRIX Contributors +// SPDX-License-Identifier: Apache-2.0 + +extern crate std; + +use super::{ + FidState, NOFID, NOTAG, P9MessageType, P9OpenMode, P9QidType, P9WalkResult, Plan9Session, + SessionState, +}; +use oncrix_lib::Error; +use std::vec::Vec; + +pub(super) const VERSION_256: [u8; 14] = [ + 0, 1, 0, 0, 8, 0, b'9', b'P', b'2', b'0', b'0', b'0', b'.', b'L', +]; +pub(super) const QID: [u8; 13] = [0x80, 1, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0]; +pub(super) const RWALK_ONE: [u8; 15] = [1, 0, 0, 1, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0]; +pub(super) const ROPEN: [u8; 17] = [0, 1, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; + +pub(super) fn reply(kind: P9MessageType, tag: u16, payload: &[u8]) -> Vec { + let mut frame = Vec::from([0, 0, 0, 0, kind as u8]); + frame.extend_from_slice(&tag.to_le_bytes()); + frame.extend_from_slice(payload); + let size = (frame.len() as u32).to_le_bytes(); + frame[..4].copy_from_slice(&size); + frame +} + +pub(super) fn tag(request: &[u8]) -> u16 { + u16::from_le_bytes([request[5], request[6]]) +} + +pub(super) fn versioned() -> Plan9Session { + let mut session = Plan9Session::new(); + session.build_tversion().unwrap(); + session + .handle_rversion(&reply(P9MessageType::Rversion, NOTAG, &VERSION_256)) + .unwrap(); + session +} + +pub(super) fn attached() -> Plan9Session { + let mut session = versioned(); + let tag = tag(session.build_tattach(7, b"").unwrap()); + session + .handle_rattach(&reply(P9MessageType::Rattach, tag, &QID)) + .unwrap(); + session +} + +pub(super) fn walked() -> (Plan9Session, u32) { + let mut session = attached(); + let root = session.root_fid(); + let (request, fid) = session.build_twalk(root, &[b"x"]).unwrap(); + let tag = tag(request); + let result = session + .handle_rwalk(&reply(P9MessageType::Rwalk, tag, &RWALK_ONE)) + .unwrap(); + assert!(matches!( + result, + P9WalkResult::Full { source, destination, count: 1, qids } + if source == root && destination == fid && qids[0].qtype == P9QidType::FILE + )); + (session, fid) +} + +pub(super) fn opened(mode: P9OpenMode) -> (Plan9Session, u32) { + let (mut session, fid) = walked(); + let tag = tag(session.build_topen(fid, mode).unwrap()); + let (_, iounit) = session + .handle_ropen(&reply(P9MessageType::Ropen, tag, &ROPEN)) + .unwrap(); + assert_eq!(iounit, 256); + (session, fid) +} + +pub(super) fn fid_state(session: &Plan9Session, fid: u32) -> FidState { + let slot = session.fid_table().lookup(fid).unwrap(); + session.fid_table().get(slot).unwrap().state +} + +pub(super) fn assert_poisoned(session: &Plan9Session) { + assert_eq!(session.state(), SessionState::Error); + assert_eq!(session.root_fid(), NOFID); + assert_eq!(session.fid_table().active_count(), 0); +} + +#[test] +fn session_red_rversion_order_is_enforced() { + // Given / When / Then + let mut first_session = Plan9Session::new(); + let first = first_session.handle_rversion(&reply(P9MessageType::Rversion, NOTAG, &VERSION_256)); + let mut second_session = Plan9Session::new(); + second_session.build_tversion().unwrap(); + let second = second_session.build_tversion().map(|frame| frame.len()); + assert!( + matches!(first, Err(Error::InvalidArgument)) + && first_session.state() == SessionState::Disconnected + && second == Err(Error::Busy) + ); +} + +#[test] +fn session_red_msize_offer_is_enforced_without_mutation() { + // Given / When / Then + let mut session = Plan9Session::new(); + session.build_tversion().unwrap(); + let mut version = VERSION_256; + version[..4].copy_from_slice(&8193u32.to_le_bytes()); + let result = session.handle_rversion(&reply(P9MessageType::Rversion, NOTAG, &version)); + assert!(matches!(result, Err(Error::InvalidArgument)) && session.msize() == 8192); +} + +#[test] +fn session_red_inbound_negotiated_msize_is_checked_before_dispatch() { + // Given / When / Then + let mut session = versioned(); + let tag = tag(session.build_tattach(7, b"").unwrap()); + let result = session.handle_rattach(&reply(P9MessageType::Rerror, tag, &[0xA5; 250])); + assert_eq!(result, Err(Error::InvalidArgument)); + assert_poisoned(&session); +} + +#[test] +fn session_red_oversized_tattach_does_not_leak_root_fid() { + // Given / When / Then + let mut session = versioned(); + let result = session + .build_tattach(7, &[b'a'; 256]) + .map(|frame| frame.len()); + assert!( + result == Err(Error::InvalidArgument) + && session.root_fid() == NOFID + && session.fid_table().active_count() == 0 + ); +} + +#[test] +fn session_red_oversized_twalk_does_not_leak_destination_fid() { + // Given / When / Then + let mut session = attached(); + let root = session.root_fid(); + let result = session + .build_twalk(root, &[&[b'w'; 240]]) + .map(|(frame, _)| frame.len()); + assert!(result == Err(Error::InvalidArgument) && session.fid_table().active_count() == 1); +} + +#[test] +fn session_red_tread_count_fits_negotiated_msize() { + // Given / When / Then + let (mut session, fid) = opened(P9OpenMode::OREAD); + let slot = session.fid_table().lookup(fid).unwrap(); + assert_eq!(session.fid_table().get(slot).unwrap().iounit, 256); + let frame = session.build_tread(fid, 0, u32::MAX).unwrap(); + let count = u32::from_le_bytes([frame[19], frame[20], frame[21], frame[22]]); + assert_eq!(count, 245); +} + +#[test] +fn session_red_twrite_frame_and_count_fit_negotiated_msize() { + // Given / When / Then + let (mut session, fid) = opened(P9OpenMode::OWRITE); + let data = [0xA5; 300]; + let frame = session.build_twrite(fid, 0, &data).unwrap(); + let count = u32::from_le_bytes([frame[19], frame[20], frame[21], frame[22]]) as usize; + assert!(frame.len() == 256 && count == 233 && frame[23..] == data[..count]); +} + +#[test] +fn session_exact_and_overflow_variable_request_boundaries() { + // Given / When / Then + let mut attach = versioned(); + assert_eq!(attach.build_tattach(7, &[b'a'; 233]).unwrap().len(), 256); + let mut attach_over = versioned(); + let result = attach_over + .build_tattach(7, &[b'a'; 234]) + .map(|frame| frame.len()); + assert_eq!(result, Err(Error::InvalidArgument)); + let mut walk = attached(); + let root = walk.root_fid(); + assert_eq!( + walk.build_twalk(root, &[&[b'w'; 237]]).unwrap().0.len(), + 256 + ); + let mut walk_over = attached(); + let root = walk_over.root_fid(); + let result = walk_over + .build_twalk(root, &[&[b'w'; 238]]) + .map(|value| value.0.len()); + assert_eq!(result, Err(Error::InvalidArgument)); + let (mut open, fid) = opened(P9OpenMode::OREAD); + let result = open.build_twalk(fid, &[]).map(|_| ()); + assert_eq!(result, Err(Error::InvalidArgument)); +} + +#[test] +fn session_walk_and_open_require_legal_fid_states() { + // Given / When / Then + let mut walk = attached(); + let root = walk.root_fid(); + let slot = walk.fid_table.lookup(root).unwrap(); + walk.fid_table.get_mut(slot).unwrap().qid.qtype = P9QidType::FILE; + let result = walk.build_twalk(root, &[b"x"]).map(|_| ()); + assert!(result == Err(Error::InvalidArgument) && walk.fid_table().active_count() == 1); + let mut allocated = attached(); + let (_, fid) = allocated.fid_table.alloc().unwrap(); + let result = allocated.build_topen(fid, P9OpenMode::OREAD).map(|_| ()); + assert!( + result == Err(Error::InvalidArgument) && fid_state(&allocated, fid) == FidState::Allocated + ); + let (mut open, fid) = opened(P9OpenMode::OREAD); + let result = open.build_topen(fid, P9OpenMode::OREAD).map(|_| ()); + assert_eq!(result, Err(Error::InvalidArgument)); +} + +#[test] +fn session_iounit_caps_io_and_open_error_preserves_fid() { + // Given / When / Then + let (mut session, fid) = walked(); + let open_tag = tag(session.build_topen(fid, P9OpenMode::OREAD).unwrap()); + let mut payload = Vec::from(QID); + payload.extend_from_slice(&10u32.to_le_bytes()); + assert_eq!( + session + .handle_ropen(&reply(P9MessageType::Ropen, open_tag, &payload)) + .unwrap() + .1, + 10 + ); + let frame = session.build_tread(fid, 0, 100).unwrap(); + assert_eq!( + u32::from_le_bytes([frame[19], frame[20], frame[21], frame[22]]), + 10 + ); + let (mut denied, fid) = walked(); + let tag = tag(denied.build_topen(fid, P9OpenMode::OREAD).unwrap()); + assert_eq!( + denied.handle_ropen(&reply(P9MessageType::Rlerror, tag, &13u32.to_le_bytes())), + Err(Error::PermissionDenied), + ); + assert_eq!(fid_state(&denied, fid), FidState::Attached); +} + +#[test] +fn session_red_preversion_fid_builders_reject_without_mutation() { + // Given / When / Then + let mut session = Plan9Session::new(); + let (_, fid) = session.fid_table.alloc().unwrap(); + let clunk = session.build_tclunk(fid).map(|_| ()); + let remove = session.build_tremove(fid).map(|_| ()); + let stat = session.build_tstat(fid).map(|_| ()); + assert!( + clunk == Err(Error::InvalidArgument) + && remove == Err(Error::InvalidArgument) + && stat == Err(Error::InvalidArgument) + && session.fid_table().active_count() == 1 + ); +} + +#[test] +fn session_red_malformed_rattach_poisons_connection() { + // Given / When / Then + let mut session = versioned(); + let tag = tag(session.build_tattach(7, b"").unwrap()); + assert_eq!(fid_state(&session, session.root_fid()), FidState::Allocated); + let result = session.handle_rattach(&reply(P9MessageType::Rattach, tag, &[0])); + assert!(result.is_err()); + assert_poisoned(&session); +} + +#[test] +fn session_red_malformed_rwalk_poisons_connection() { + // Given / When / Then + let mut session = attached(); + let root = session.root_fid(); + let (request, _fid) = session.build_twalk(root, &[b"x"]).unwrap(); + let tag = tag(request); + let result = session.handle_rwalk(&reply(P9MessageType::Rwalk, tag, &[1, 0, 0])); + assert!(result.is_err()); + assert_poisoned(&session); +} + +#[test] +fn session_red_malformed_ropen_poisons_connection() { + // Given / When / Then + let (mut session, fid) = walked(); + let tag = tag(session.build_topen(fid, P9OpenMode::OREAD).unwrap()); + let result = session.handle_ropen(&reply(P9MessageType::Ropen, tag, &[0])); + assert!(result.is_err()); + assert_poisoned(&session); +} + +#[test] +fn session_red_malformed_rclunk_poisons_connection() { + // Given / When / Then + let mut session = attached(); + let fid = session.root_fid(); + let tag = tag(session.build_tclunk(fid).unwrap()); + let mut malformed = reply(P9MessageType::Rclunk, tag, &[]); + malformed[0] = 8; + let result = session.handle_rclunk(&malformed); + assert!(result.is_err()); + assert_poisoned(&session); + assert_eq!(session.fid_table().lookup(fid), Err(Error::NotFound)); +}