pub mod mount;
pub mod nfs2;
pub mod portmap;
pub mod xdr;
use std::fmt;
use crate::{Error, Result};
pub use nfs2::{FileHandle, FileHandleKey};
pub const VERSION: u32 = 2;
const MSG_CALL: u32 = 0;
const MSG_REPLY: u32 = 1;
const MSG_ACCEPTED: u32 = 0;
const MSG_DENIED: u32 = 1;
#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct Xid(pub u32);
impl fmt::Debug for Xid {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "xid:{:#010x}", self.0)
}
}
#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct Program(pub u32);
impl Program {
pub const PORTMAP: Self = Self(100_000);
pub const NFS: Self = Self(100_003);
pub const MOUNT: Self = Self(100_005);
pub const STATUS: Self = Self(100_024);
pub fn name(self) -> Option<&'static str> {
Some(match self {
Self::PORTMAP => "portmapper",
Self::NFS => "nfs",
Self::MOUNT => "mountd",
Self::STATUS => "status",
_ => return None,
})
}
}
impl fmt::Debug for Program {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self.name() {
Some(name) => f.write_str(name),
None => write!(f, "Program({})", self.0),
}
}
}
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub struct IpProtocol(pub u32);
impl IpProtocol {
pub const TCP: Self = Self(6);
pub const UDP: Self = Self(17);
pub fn name(self) -> Option<&'static str> {
Some(match self {
Self::TCP => "tcp",
Self::UDP => "udp",
_ => return None,
})
}
}
impl fmt::Debug for IpProtocol {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self.name() {
Some(name) => f.write_str(name),
None => write!(f, "IpProtocol({})", self.0),
}
}
}
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub struct AuthFlavor(pub u32);
impl AuthFlavor {
pub const NULL: Self = Self(0);
pub const UNIX: Self = Self(1);
pub const SHORT: Self = Self(2);
pub const DES: Self = Self(3);
pub fn name(self) -> Option<&'static str> {
Some(match self {
Self::NULL => "AUTH_NULL",
Self::UNIX => "AUTH_UNIX",
Self::SHORT => "AUTH_SHORT",
Self::DES => "AUTH_DES",
_ => return None,
})
}
}
impl fmt::Debug for AuthFlavor {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self.name() {
Some(name) => f.write_str(name),
None => write!(f, "AuthFlavor({})", self.0),
}
}
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub struct Auth<'a> {
pub flavor: AuthFlavor,
pub body: &'a [u8],
}
impl Auth<'_> {
pub const NULL: Auth<'static> = Auth {
flavor: AuthFlavor::NULL,
body: &[],
};
}
impl<'a> Auth<'a> {
pub fn unix(body: &'a [u8]) -> Self {
Self {
flavor: AuthFlavor::UNIX,
body,
}
}
fn write(&self, out: &mut xdr::Writer) {
out.u32(self.flavor.0);
out.opaque_var(self.body);
}
fn read(input: &mut xdr::Reader<'a>) -> Result<Self> {
let flavor = AuthFlavor(input.u32()?);
let body = input.opaque_var(xdr::MAX_AUTH_BODY, "an opaque_auth body")?;
Ok(Self { flavor, body })
}
}
#[derive(Clone, PartialEq, Eq, Debug, Default)]
pub struct AuthUnix {
pub stamp: u32,
pub machine_name: String,
pub uid: u32,
pub gid: u32,
pub gids: Vec<u32>,
}
pub const STAMP_SEQUENCE: [u32; 40] = [
0x967b_8703,
0x9922_e112,
0xa492_1306,
0xdc1a_c513,
0x2a99_4a03,
0x0d98_8520,
0xf062_9c32,
0xbc69_0310,
0xf0af_010a,
0x177a_4420,
0xe0f3_9f14,
0xb0b6_3114,
0x6432_2e08,
0x561e_c900,
0xd040_9301,
0x0e05_c008,
0xceb5_1a0d,
0x9250_8c07,
0xb8be_fb0d,
0xa95e_e233,
0xfec9_9811,
0xb08c_e104,
0xe8ef_9718,
0x3c8e_f516,
0xf156_f120,
0xef2d_6300,
0x44a2_ed03,
0x9cc9_8c03,
0x44f3_b503,
0x8d96_1401,
0x1fde_921f,
0x2087_c50b,
0x1a37_e602,
0xf0bc_7107,
0x66ba_6b07,
0x1497_0216,
0x6d58_c300,
0xa29d_ce09,
0x70d2_b810,
0xad14_5926,
];
pub const STAMP_FIRST_CALL: u32 = 0x967b_8703;
pub fn stamp_for_xid(xid: Xid) -> Option<u32> {
let index = usize::try_from(xid.0.checked_sub(1)?).ok()?;
STAMP_SEQUENCE.get(index).copied()
}
impl AuthUnix {
pub fn cdj(stamp: u32) -> Self {
Self {
stamp,
machine_name: String::new(),
uid: 0,
gid: 0,
gids: Vec::new(),
}
}
pub fn encode(&self) -> Vec<u8> {
let mut out = xdr::Writer::with_capacity(24);
out.u32(self.stamp);
out.ascii_string(&self.machine_name);
out.u32(self.uid);
out.u32(self.gid);
out.u32_array(&self.gids);
out.into_bytes()
}
pub fn parse(body: &[u8]) -> Result<Self> {
let mut input = xdr::Reader::new(body);
Ok(Self {
stamp: input.u32()?,
machine_name: input.ascii_string(255)?,
uid: input.u32()?,
gid: input.u32()?,
gids: input.u32_array(16)?,
})
}
}
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct Call<'a> {
pub xid: Xid,
pub program: Program,
pub version: u32,
pub procedure: u32,
pub credential: Auth<'a>,
pub verifier: Auth<'a>,
pub arguments: &'a [u8],
}
impl<'a> Call<'a> {
pub fn new(
xid: Xid,
program: Program,
version: u32,
procedure: u32,
credential: Auth<'a>,
arguments: &'a [u8],
) -> Self {
Self {
xid,
program,
version,
procedure,
credential,
verifier: Auth::NULL,
arguments,
}
}
pub fn encode(&self) -> Vec<u8> {
let mut out = xdr::Writer::with_capacity(64 + self.arguments.len());
out.u32(self.xid.0);
out.u32(MSG_CALL);
out.u32(VERSION);
out.u32(self.program.0);
out.u32(self.version);
out.u32(self.procedure);
self.credential.write(&mut out);
self.verifier.write(&mut out);
out.raw(self.arguments);
out.into_bytes()
}
pub fn parse(data: &'a [u8]) -> Result<Self> {
let mut input = xdr::Reader::new(data);
let xid = Xid(input.u32()?);
let msg_type = input.u32()?;
if msg_type != MSG_CALL {
return Err(Error::malformed(
4,
format!("expected an RPC call (msg_type 0), got msg_type {msg_type}"),
));
}
let rpc_version = input.u32()?;
if rpc_version != VERSION {
return Err(Error::malformed(
8,
format!("unsupported RPC version {rpc_version}, expected {VERSION}"),
));
}
let program = Program(input.u32()?);
let version = input.u32()?;
let procedure = input.u32()?;
let credential = Auth::read(&mut input)?;
let verifier = Auth::read(&mut input)?;
Ok(Self {
xid,
program,
version,
procedure,
credential,
verifier,
arguments: input.rest(),
})
}
}
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub struct AcceptStat(pub u32);
impl AcceptStat {
pub const SUCCESS: Self = Self(0);
pub const PROG_UNAVAIL: Self = Self(1);
pub const PROG_MISMATCH: Self = Self(2);
pub const PROC_UNAVAIL: Self = Self(3);
pub const GARBAGE_ARGS: Self = Self(4);
pub const SYSTEM_ERR: Self = Self(5);
pub fn name(self) -> Option<&'static str> {
Some(match self {
Self::SUCCESS => "SUCCESS",
Self::PROG_UNAVAIL => "PROG_UNAVAIL",
Self::PROG_MISMATCH => "PROG_MISMATCH",
Self::PROC_UNAVAIL => "PROC_UNAVAIL",
Self::GARBAGE_ARGS => "GARBAGE_ARGS",
Self::SYSTEM_ERR => "SYSTEM_ERR",
_ => return None,
})
}
}
impl fmt::Debug for AcceptStat {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self.name() {
Some(name) => f.write_str(name),
None => write!(f, "AcceptStat({})", self.0),
}
}
}
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub struct RejectStat(pub u32);
impl RejectStat {
pub const RPC_MISMATCH: Self = Self(0);
pub const AUTH_ERROR: Self = Self(1);
}
impl fmt::Debug for RejectStat {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match *self {
Self::RPC_MISMATCH => f.write_str("RPC_MISMATCH"),
Self::AUTH_ERROR => f.write_str("AUTH_ERROR"),
Self(raw) => write!(f, "RejectStat({raw})"),
}
}
}
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub struct AuthStat(pub u32);
impl AuthStat {
pub const BADCRED: Self = Self(1);
pub const REJECTEDCRED: Self = Self(2);
pub const BADVERF: Self = Self(3);
pub const REJECTEDVERF: Self = Self(4);
pub const TOOWEAK: Self = Self(5);
}
impl fmt::Debug for AuthStat {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match *self {
Self::BADCRED => f.write_str("AUTH_BADCRED"),
Self::REJECTEDCRED => f.write_str("AUTH_REJECTEDCRED"),
Self::BADVERF => f.write_str("AUTH_BADVERF"),
Self::REJECTEDVERF => f.write_str("AUTH_REJECTEDVERF"),
Self::TOOWEAK => f.write_str("AUTH_TOOWEAK"),
Self(raw) => write!(f, "AuthStat({raw})"),
}
}
}
#[derive(Clone, PartialEq, Eq, Debug)]
pub enum Accepted<'a> {
Success(&'a [u8]),
ProgMismatch {
low: u32,
high: u32,
},
Failed(FailureStat),
}
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub struct FailureStat(AcceptStat);
impl FailureStat {
pub const PROG_UNAVAIL: Self = Self(AcceptStat::PROG_UNAVAIL);
pub const PROC_UNAVAIL: Self = Self(AcceptStat::PROC_UNAVAIL);
pub const GARBAGE_ARGS: Self = Self(AcceptStat::GARBAGE_ARGS);
pub const SYSTEM_ERR: Self = Self(AcceptStat::SYSTEM_ERR);
pub fn new(stat: AcceptStat) -> Option<Self> {
match stat {
AcceptStat::SUCCESS | AcceptStat::PROG_MISMATCH => None,
other => Some(Self(other)),
}
}
pub fn stat(self) -> AcceptStat {
self.0
}
}
impl fmt::Debug for FailureStat {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(&self.0, f)
}
}
impl Accepted<'_> {
pub fn stat(&self) -> AcceptStat {
match self {
Self::Success(_) => AcceptStat::SUCCESS,
Self::ProgMismatch { .. } => AcceptStat::PROG_MISMATCH,
Self::Failed(stat) => stat.stat(),
}
}
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Denied {
RpcMismatch {
low: u32,
high: u32,
},
AuthError(AuthStat),
Other(OtherReject),
}
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub struct OtherReject(RejectStat);
impl OtherReject {
pub fn new(stat: RejectStat) -> Option<Self> {
match stat {
RejectStat::RPC_MISMATCH | RejectStat::AUTH_ERROR => None,
other => Some(Self(other)),
}
}
pub fn stat(self) -> RejectStat {
self.0
}
}
impl fmt::Debug for OtherReject {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(&self.0, f)
}
}
#[derive(Clone, PartialEq, Eq, Debug)]
pub enum Reply<'a> {
Accepted {
xid: Xid,
verifier: Auth<'a>,
status: Accepted<'a>,
},
Denied {
xid: Xid,
reason: Denied,
},
}
impl<'a> Reply<'a> {
pub fn success(xid: Xid, results: &'a [u8]) -> Self {
Self::Accepted {
xid,
verifier: Auth::NULL,
status: Accepted::Success(results),
}
}
pub fn failed(xid: Xid, stat: FailureStat) -> Self {
Self::Accepted {
xid,
verifier: Auth::NULL,
status: Accepted::Failed(stat),
}
}
pub fn prog_mismatch(xid: Xid, low: u32, high: u32) -> Self {
Self::Accepted {
xid,
verifier: Auth::NULL,
status: Accepted::ProgMismatch { low, high },
}
}
pub fn xid(&self) -> Xid {
match *self {
Self::Accepted { xid, .. } | Self::Denied { xid, .. } => xid,
}
}
pub fn results(&self) -> Option<&'a [u8]> {
match self {
Self::Accepted {
status: Accepted::Success(results),
..
} => Some(results),
_ => None,
}
}
pub fn encode(&self) -> Vec<u8> {
let mut out = xdr::Writer::with_capacity(32 + self.results().map_or(0, <[u8]>::len));
match self {
Self::Accepted {
xid,
verifier,
status,
} => {
out.u32(xid.0);
out.u32(MSG_REPLY);
out.u32(MSG_ACCEPTED);
verifier.write(&mut out);
out.u32(status.stat().0);
match status {
Accepted::Success(results) => out.raw(results),
Accepted::ProgMismatch { low, high } => {
out.u32(*low);
out.u32(*high);
}
Accepted::Failed(_) => {}
}
}
Self::Denied { xid, reason } => {
out.u32(xid.0);
out.u32(MSG_REPLY);
out.u32(MSG_DENIED);
match reason {
Denied::RpcMismatch { low, high } => {
out.u32(RejectStat::RPC_MISMATCH.0);
out.u32(*low);
out.u32(*high);
}
Denied::AuthError(stat) => {
out.u32(RejectStat::AUTH_ERROR.0);
out.u32(stat.0);
}
Denied::Other(stat) => out.u32(stat.stat().0),
}
}
}
out.into_bytes()
}
pub fn parse(data: &'a [u8]) -> Result<Self> {
let mut input = xdr::Reader::new(data);
let xid = Xid(input.u32()?);
let msg_type = input.u32()?;
if msg_type != MSG_REPLY {
return Err(Error::malformed(
4,
format!("expected an RPC reply (msg_type 1), got msg_type {msg_type}"),
));
}
let reply_stat = input.u32()?;
match reply_stat {
MSG_DENIED => {
let reject = RejectStat(input.u32()?);
let reason = match reject {
RejectStat::RPC_MISMATCH => Denied::RpcMismatch {
low: input.u32()?,
high: input.u32()?,
},
RejectStat::AUTH_ERROR => Denied::AuthError(AuthStat(input.u32()?)),
other => Denied::Other(OtherReject(other)),
};
Ok(Self::Denied { xid, reason })
}
MSG_ACCEPTED => {
let verifier = Auth::read(&mut input)?;
let stat = AcceptStat(input.u32()?);
let status = match stat {
AcceptStat::SUCCESS => Accepted::Success(input.rest()),
AcceptStat::PROG_MISMATCH => Accepted::ProgMismatch {
low: input.u32()?,
high: input.u32()?,
},
other => Accepted::Failed(FailureStat(other)),
};
Ok(Self::Accepted {
xid,
verifier,
status,
})
}
other => Err(Error::malformed(
8,
format!("invalid reply_stat {other}, expected 0 or 1"),
)),
}
}
}
#[derive(Clone, PartialEq, Eq, Debug)]
pub enum Message<'a> {
Call(Call<'a>),
Reply(Reply<'a>),
}
impl<'a> Message<'a> {
pub fn parse(data: &'a [u8]) -> Result<Self> {
let mut header = xdr::Reader::new(data);
let _xid = header.u32()?;
let msg_type = header.u32()?;
match msg_type {
MSG_CALL => Call::parse(data).map(Message::Call),
MSG_REPLY => Reply::parse(data).map(Message::Reply),
other => Err(Error::malformed(
4,
format!("msg_type {other} is neither a call nor a reply"),
)),
}
}
pub fn xid(&self) -> Xid {
match self {
Self::Call(call) => call.xid,
Self::Reply(reply) => reply.xid(),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_call_header_is_laid_out_as_the_standard_says() {
let credential = AuthUnix::cdj(STAMP_FIRST_CALL).encode();
let args =
portmap::Request::GetPort(portmap::Mapping::query(Program::MOUNT, 1, IpProtocol::UDP))
.encode_arguments();
let call = Call::new(
Xid(0x1122_3344),
Program::PORTMAP,
portmap::VERSION,
portmap::Proc::GETPORT.0,
Auth::unix(&credential),
&args,
);
let raw = call.encode();
assert_eq!(raw.get(0..4), Some([0x11, 0x22, 0x33, 0x44].as_slice()));
assert_eq!(
raw.get(4..8),
Some([0, 0, 0, 0].as_slice()),
"msg_type CALL"
);
assert_eq!(raw.get(8..12), Some([0, 0, 0, 2].as_slice()), "rpcvers 2");
assert_eq!(raw.get(12..16), Some(100_000u32.to_be_bytes().as_slice()));
assert_eq!(raw.get(16..20), Some(2u32.to_be_bytes().as_slice()));
assert_eq!(raw.get(20..24), Some(3u32.to_be_bytes().as_slice()));
assert_eq!(raw.get(24..28), Some(1u32.to_be_bytes().as_slice()));
assert_eq!(raw.get(28..32), Some(20u32.to_be_bytes().as_slice()));
assert_eq!(raw.get(52..56), Some([0, 0, 0, 0].as_slice()), "verf NULL");
assert_eq!(raw.get(56..60), Some([0, 0, 0, 0].as_slice()), "empty body");
assert_eq!(raw.len(), 60 + 16, "header plus four GETPORT words");
}
#[test]
fn a_call_round_trips_with_auth_unix() {
let credential = AuthUnix::cdj(STAMP_FIRST_CALL).encode();
let call = Call::new(
Xid(1),
Program::NFS,
2,
nfs2::Proc::READ.0,
Auth::unix(&credential),
&[1, 2, 3, 4],
);
let raw = call.encode();
let parsed = Call::parse(&raw).unwrap();
assert_eq!(parsed, call);
assert_eq!(parsed.credential.flavor, AuthFlavor::UNIX);
assert_eq!(parsed.verifier.flavor, AuthFlavor::NULL);
assert!(parsed.verifier.body.is_empty());
assert_eq!(parsed.arguments, &[1, 2, 3, 4]);
}
#[test]
fn the_auth_unix_body_a_player_sends_is_twenty_bytes() {
let body = AuthUnix::cdj(STAMP_FIRST_CALL).encode();
assert_eq!(
body,
[
0x96, 0x7b, 0x87, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, ]
);
let parsed = AuthUnix::parse(&body).unwrap();
assert_eq!(parsed.stamp, STAMP_FIRST_CALL);
assert_eq!(parsed.machine_name, "");
assert_eq!((parsed.uid, parsed.gid), (0, 0));
assert!(parsed.gids.is_empty());
}
#[test]
fn only_the_stamp_varies_between_two_calls() {
let first = AuthUnix::cdj(STAMP_SEQUENCE[0]).encode();
let second = AuthUnix::cdj(STAMP_SEQUENCE[1]).encode();
assert_ne!(first.get(..4), second.get(..4));
assert_eq!(first.get(4..), second.get(4..));
}
#[test]
fn the_stamp_is_a_fixed_sequence_indexed_by_the_call_number_since_boot() {
assert_eq!(stamp_for_xid(Xid(1)), Some(STAMP_FIRST_CALL));
assert_eq!(stamp_for_xid(Xid(1)), Some(0x967b_8703));
assert_eq!(stamp_for_xid(Xid(2)), Some(0x9922_e112));
assert_eq!(stamp_for_xid(Xid(9)), Some(0xf0af_010a));
assert_eq!(stamp_for_xid(Xid(40)), Some(0xad14_5926));
}
#[test]
fn a_call_index_outside_the_observed_table_has_no_stamp_to_reproduce() {
assert_eq!(stamp_for_xid(Xid(41)), None);
assert_eq!(
stamp_for_xid(Xid(0)),
None,
"a deck's counter starts at one, so there is no zeroth call"
);
assert_eq!(stamp_for_xid(Xid(u32::MAX)), None);
}
#[test]
fn an_accepted_reply_round_trips() {
let raw = Reply::success(Xid(0xabcd), &[0xde, 0xad, 0xbe, 0xef]).encode();
let reply = Reply::parse(&raw).unwrap();
assert_eq!(reply.xid(), Xid(0xabcd));
assert_eq!(reply.results(), Some([0xde, 0xad, 0xbe, 0xef].as_slice()));
assert_eq!(
raw.get(0..12),
Some([0, 0, 0xab, 0xcd, 0, 0, 0, 1, 0, 0, 0, 0].as_slice()),
"xid, msg_type REPLY, reply_stat MSG_ACCEPTED"
);
assert_eq!(
raw.get(12..20),
Some([0, 0, 0, 0, 0, 0, 0, 0].as_slice()),
"AUTH_NULL verifier with an empty body"
);
}
#[test]
fn a_null_procedure_succeeds_with_no_results_which_is_not_a_failure() {
let raw = Reply::success(Xid(7), &[]).encode();
let reply = Reply::parse(&raw).unwrap();
assert_eq!(
reply.results(),
Some([].as_slice()),
"an empty result block and a failure are different things"
);
}
#[test]
fn proc_unavail_is_a_real_answer_and_carries_no_body() {
let raw = Reply::failed(Xid(1), FailureStat::PROC_UNAVAIL).encode();
assert_eq!(
raw.len(),
24,
"xid, msg_type, reply_stat, the two verifier words, the status — \
and nothing after it"
);
let reply = Reply::parse(&raw).unwrap();
assert!(matches!(
reply,
Reply::Accepted {
status: Accepted::Failed(FailureStat::PROC_UNAVAIL),
..
}
));
assert_eq!(reply.results(), None);
}
#[test]
fn a_status_that_carries_a_body_cannot_be_sent_as_a_bare_status() {
assert_eq!(FailureStat::new(AcceptStat::PROG_MISMATCH), None);
assert_eq!(
FailureStat::new(AcceptStat::SUCCESS),
None,
"SUCCESS is followed by the results, so it is not a failure either"
);
assert_eq!(
FailureStat::new(AcceptStat::PROC_UNAVAIL),
Some(FailureStat::PROC_UNAVAIL)
);
assert_eq!(
FailureStat::new(AcceptStat(99)).map(FailureStat::stat),
Some(AcceptStat(99)),
"an unfamiliar status has no body either, so it is representable"
);
assert_eq!(OtherReject::new(RejectStat::RPC_MISMATCH), None);
assert_eq!(OtherReject::new(RejectStat::AUTH_ERROR), None);
assert_eq!(
OtherReject::new(RejectStat(7)).map(OtherReject::stat),
Some(RejectStat(7))
);
}
#[test]
fn prog_mismatch_carries_the_supported_version_range() {
let raw = Reply::Accepted {
xid: Xid(1),
verifier: Auth::NULL,
status: Accepted::ProgMismatch { low: 2, high: 3 },
}
.encode();
let reply = Reply::parse(&raw).unwrap();
assert!(matches!(
reply,
Reply::Accepted {
status: Accepted::ProgMismatch { low: 2, high: 3 },
..
}
));
}
#[test]
fn a_denied_reply_has_no_verifier() {
let raw = Reply::Denied {
xid: Xid(1),
reason: Denied::AuthError(AuthStat::BADCRED),
}
.encode();
assert_eq!(
raw.len(),
20,
"xid, msg_type, reply_stat, reject_stat, auth_stat — and no \
verifier, which is why the two states are separate variants"
);
assert_eq!(
Reply::parse(&raw).unwrap(),
Reply::Denied {
xid: Xid(1),
reason: Denied::AuthError(AuthStat::BADCRED),
}
);
}
#[test]
fn an_rpc_mismatch_denial_round_trips() {
let reply = Reply::Denied {
xid: Xid(9),
reason: Denied::RpcMismatch { low: 2, high: 2 },
};
assert_eq!(Reply::parse(&reply.encode()).unwrap(), reply);
}
#[test]
fn a_call_is_not_mistaken_for_a_reply() {
let raw = Call::new(Xid(1), Program::PORTMAP, 2, 0, Auth::NULL, &[]).encode();
let error = Reply::parse(&raw).unwrap_err();
assert!(!error.is_truncated(), "{error:?}");
assert!(matches!(error, Error::Malformed { at: 4, .. }));
}
#[test]
fn a_reply_is_not_mistaken_for_a_call() {
let raw = Reply::success(Xid(1), &[]).encode();
assert!(matches!(
Call::parse(&raw),
Err(Error::Malformed { at: 4, .. })
));
}
#[test]
fn an_rpc_v1_or_v3_call_is_refused_rather_than_half_decoded() {
let mut raw = Call::new(Xid(1), Program::NFS, 2, 0, Auth::NULL, &[]).encode();
raw.splice(8..12, 3u32.to_be_bytes());
assert!(matches!(
Call::parse(&raw),
Err(Error::Malformed { at: 8, .. })
));
}
#[test]
fn an_unknown_program_still_decodes_so_a_server_can_answer_prog_unavail() {
let raw = Call::new(Xid(1), Program(999_999), 4, 12, Auth::NULL, &[]).encode();
let call = Call::parse(&raw).unwrap();
assert_eq!(call.program, Program(999_999));
assert_eq!(call.procedure, 12);
}
#[test]
fn a_message_dispatches_on_msg_type() {
let call = Call::new(Xid(1), Program::NFS, 2, 0, Auth::NULL, &[]).encode();
assert!(matches!(Message::parse(&call), Ok(Message::Call(_))));
let reply = Reply::success(Xid(1), &[]).encode();
assert!(matches!(Message::parse(&reply), Ok(Message::Reply(_))));
}
#[test]
fn a_runt_datagram_is_truncation_not_garbage() {
let error = Call::parse(&[0, 0, 0, 1]).unwrap_err();
assert!(error.is_truncated(), "{error:?}");
}
#[test]
fn an_oversized_auth_body_is_refused_before_allocating() {
let mut raw = Vec::new();
raw.extend_from_slice(&0u32.to_be_bytes()); raw.extend_from_slice(&MSG_CALL.to_be_bytes());
raw.extend_from_slice(&VERSION.to_be_bytes());
raw.extend_from_slice(&Program::NFS.0.to_be_bytes());
raw.extend_from_slice(&2u32.to_be_bytes());
raw.extend_from_slice(&1u32.to_be_bytes());
raw.extend_from_slice(&AuthFlavor::UNIX.0.to_be_bytes());
raw.extend_from_slice(&0xffff_ffffu32.to_be_bytes());
let error = Call::parse(&raw).unwrap_err();
assert!(
matches!(error, Error::ImplausibleLength { limit: 400, .. }),
"{error:?}"
);
}
#[test]
fn program_numbers_are_the_three_a_cdj_runs() {
assert_eq!(Program::PORTMAP.0, 100_000);
assert_eq!(Program::NFS.0, 100_003);
assert_eq!(Program::MOUNT.0, 100_005);
assert_eq!(format!("{:?}", Program::MOUNT), "mountd");
assert_eq!(format!("{:?}", Program(42)), "Program(42)");
}
}
#[cfg(test)]
mod captured {
use super::*;
use crate::rpc::xdr::Utf16LeString;
fn hex(text: &str) -> Vec<u8> {
let digits: Vec<char> = text.chars().filter(|c| !c.is_whitespace()).collect();
assert!(
digits.len().is_multiple_of(2),
"a hex literal needs an even number of digits, got {}",
digits.len()
);
digits
.chunks_exact(2)
.map(|pair| {
let byte: String = pair.iter().collect();
u8::from_str_radix(&byte, 16).expect("a hex literal must be hex")
})
.collect()
}
fn call(raw: &[u8]) -> Call<'_> {
let parsed = Call::parse(raw).expect("a captured call must decode");
assert_eq!(parsed.credential.flavor, AuthFlavor::UNIX);
assert_eq!(parsed.credential.body.len(), 20);
assert_eq!(parsed.verifier, Auth::NULL);
parsed
}
fn results(raw: &[u8]) -> &[u8] {
let parsed = Reply::parse(raw).expect("a captured reply must decode");
match parsed {
Reply::Accepted { verifier, .. } => assert_eq!(verifier, Auth::NULL),
Reply::Denied { .. } => panic!("no MSG_DENIED reply exists in the corpus"),
}
parsed.results().expect("every captured reply is a SUCCESS")
}
#[test]
fn a_real_getport_for_mountd_is_answered_with_48276() {
let raw = hex(
"000000010000000000000002000186a00000000200000003000000010000001496\
7b8703000000000000000000000000000000000000000000000000000186a50000\
00010000001100000000",
);
let parsed = call(&raw);
assert_eq!(
raw.len(),
76,
"every GETPORT call in the corpus is 76 bytes"
);
assert_eq!(parsed.xid, Xid(1), "a deck's first call after power-on");
assert_eq!(parsed.program, Program::PORTMAP);
assert_eq!((parsed.version, parsed.procedure), (2, 3));
let credential = AuthUnix::parse(parsed.credential.body).unwrap();
assert_eq!(Some(credential.stamp), stamp_for_xid(parsed.xid));
assert_eq!(credential.stamp, 0x967b_8703);
assert_eq!(credential.machine_name, "");
assert_eq!((credential.uid, credential.gid), (0, 0));
assert!(credential.gids.is_empty());
let request =
portmap::Request::parse(portmap::Proc(parsed.procedure), parsed.arguments).unwrap();
assert_eq!(
request,
portmap::Request::GetPort(portmap::Mapping::query(Program::MOUNT, 1, IpProtocol::UDP))
);
assert_eq!(parsed.encode(), raw, "and it re-encodes byte for byte");
let reply = hex("0000000100000001000000000000000000000000000000000000bc94");
assert_eq!(reply.len(), 28, "every GETPORT reply is 28 bytes");
assert_eq!(
portmap::Response::parse(portmap::Proc::GETPORT, results(&reply)).unwrap(),
portmap::Response::GetPort(Some(mount::PIONEER_PORT))
);
assert_eq!(Reply::parse(&reply).unwrap().encode(), reply);
}
#[test]
fn a_real_getport_for_nfsd_is_answered_with_2049() {
let raw = hex(
"000000020000000000000002000186a00000000200000003000000010000001499\
22e112000000000000000000000000000000000000000000000000000186a30000\
00020000001100000000",
);
let parsed = call(&raw);
assert_eq!(parsed.xid, Xid(2));
assert_eq!(
AuthUnix::parse(parsed.credential.body).unwrap().stamp,
0x9922_e112,
"entry two of the sequence, on a deck's second call"
);
assert_eq!(
portmap::Request::parse(portmap::Proc(parsed.procedure), parsed.arguments).unwrap(),
portmap::Request::GetPort(portmap::Mapping::query(Program::NFS, 2, IpProtocol::UDP))
);
let reply = hex("00000002000000010000000000000000000000000000000000000801");
assert_eq!(
portmap::Response::parse(portmap::Proc::GETPORT, results(&reply)).unwrap(),
portmap::Response::GetPort(Some(nfs2::PORT))
);
}
#[test]
fn a_real_portmap_dump_lists_exactly_nfs_mountd_and_portmapper() {
let reply = hex(
"10000001000000010000000000000000000000000000000000000001000186a300\
000002000000110000080100000001000186a5000000010000001100 00bc940000\
0001000186a00000000200000011000000 6f00000000",
);
let decoded = portmap::Response::parse(portmap::Proc::DUMP, results(&reply)).unwrap();
assert_eq!(
decoded,
portmap::Response::Dump(
portmap::cdj_registrations(portmap::PORT, mount::PIONEER_PORT, nfs2::PORT).to_vec()
),
"the table `cdj_registrations` publishes is the one a deck publishes, \
in the same order"
);
assert_eq!(
decoded.encode(),
results(&reply),
"and our encoder reproduces it byte for byte"
);
}
#[test]
fn a_real_null_reply_is_twenty_four_bytes_of_header() {
let reply = hex("100000000000000100000000000000000000000000000000");
assert_eq!(reply.len(), 24);
assert_eq!(
results(&reply),
&[] as &[u8],
"void results, which is not the same as a failure"
);
assert_eq!(Reply::parse(&reply).unwrap().encode(), reply);
}
#[test]
fn a_real_mnt_of_the_usb_export_carries_a_utf16le_path() {
let raw = hex(
"000000030000000000000002000186a5000000010000000100000001000000 14a4\
921306000000000000000000000000000000000000000000000000 000000062f00\
43002f000011",
);
let parsed = call(&raw);
assert_eq!(raw.len(), 72);
assert_eq!(parsed.program, Program::MOUNT);
assert_eq!((parsed.version, parsed.procedure), (1, 1));
let request =
mount::Request::parse(mount::Proc(parsed.procedure), parsed.arguments).unwrap();
assert_eq!(request, mount::Request::Mnt(Utf16LeString::new("/C/")));
assert_eq!(
request.path().map(Utf16LeString::len_bytes),
Some(6),
"three characters, six bytes — the prefix counts bytes"
);
assert_eq!(mount::slot_for_export("/C/"), Some(crate::Slot::USB));
assert_eq!(parsed.encode(), raw);
assert_eq!(
parsed.arguments.get(10..),
Some([0x00, 0x11].as_slice()),
"including the padding, whatever it holds"
);
let ours = request.encode_arguments();
assert_eq!(ours.len(), parsed.arguments.len());
assert_eq!(ours.get(..10), parsed.arguments.get(..10));
assert_eq!(ours.get(10..), Some([0x00, 0x00].as_slice()));
let reply = hex(
"000000030000000100000000000000000000000000000000000000000125 38a801\
2538a8012538a80000000000000000000000000000000000000000",
);
assert_eq!(reply.len(), 60);
let handle = match mount::Response::parse(mount::Proc::MNT, results(&reply)).unwrap() {
mount::Response::Mnt(Ok(handle)) => handle,
other => panic!("expected a root filehandle, got {other:?}"),
};
assert_eq!(
handle.as_bytes().get(12..),
Some([0u8; 20].as_slice()),
"a deck fills only the twelve bytes it considers a handle"
);
assert_eq!(handle.fileid(), 0x0125_38a8);
assert_eq!(
mount::Response::Mnt(Ok(handle)).encode(),
results(&reply),
"and our encoder reproduces the reply body byte for byte"
);
}
#[test]
fn a_real_mnt_of_the_sd_export_differs_by_one_character() {
let raw = hex(
"000017fc0000000000000002000186a5000000010000000100000001000000149c\
0fcd05000000000000000000000000000000000000000000000000000000062f00\
42002f000011",
);
let parsed = call(&raw);
let request =
mount::Request::parse(mount::Proc(parsed.procedure), parsed.arguments).unwrap();
assert_eq!(request, mount::Request::Mnt(Utf16LeString::new("/B/")));
assert_eq!(mount::slot_for_export("/B/"), Some(crate::Slot::SD));
let reply = hex(
"000017fc00000001000000000000000000000000000000000000000002253 8a802\
2538a8022538a80000000000000000000000000000000000000000",
);
let handle = match mount::Response::parse(mount::Proc::MNT, results(&reply)).unwrap() {
mount::Response::Mnt(Ok(handle)) => handle,
other => panic!("expected a root filehandle, got {other:?}"),
};
assert_eq!(
handle.fileid(),
0x0225_38a8,
"02… for the SD mount root against 01… for the USB one, same deck"
);
}
#[test]
fn a_real_mnt_of_c_slash_export_proves_the_spelling_varies() {
let raw = hex(
"000000050000000000000002000186a5000000010000000100000001000000142a\
994a03000000000000000000000000000000000000000000000000000000122f00\
43002f004500580050004f00520054000004",
);
let parsed = call(&raw);
let request =
mount::Request::parse(mount::Proc(parsed.procedure), parsed.arguments).unwrap();
let path = request.path().unwrap();
assert_eq!(path.to_string_lossy(), "/C/EXPORT");
assert_eq!(path.len_bytes(), 18, "nine characters, eighteen bytes");
assert_eq!(
mount::slot_for_export("/C/EXPORT"),
Some(crate::Slot::USB),
"a matcher keyed on the whole string would miss this"
);
}
#[test]
fn a_real_umnt_follows_the_eject_and_is_answered_with_nothing() {
let raw = hex(
"000017f90000000000000002000186a5000000010000000300000001000000147a\
c50e0c000000000000000000000000000000000000000000000000000000062f00\
43002f003cd2",
);
let parsed = call(&raw);
assert_eq!(parsed.procedure, 3);
assert_eq!(
mount::Request::parse(mount::Proc(parsed.procedure), parsed.arguments).unwrap(),
mount::Request::Umnt(Utf16LeString::new("/C/"))
);
assert_eq!(
raw.get(70..),
Some([0x3c, 0xd2].as_slice()),
"more uninitialised padding, and a different value from the MNT"
);
let reply = hex("000017f90000000100000000000000000000000000000000");
assert_eq!(reply.len(), 24);
assert_eq!(results(&reply), &[] as &[u8]);
assert_eq!(
mount::Response::parse(mount::Proc::UMNT, results(&reply)).unwrap(),
mount::Response::Umnt
);
}
#[test]
fn a_real_export_reply_mixes_utf16le_and_ascii_in_one_structure() {
let reply = hex(
"10000001000000010000000000000000000000000000000000000001000000062f\
0043002f00000000000001000000173136392e3235342e302e302f3235352e3235\
352e302e30000000000000000000",
);
let decoded = mount::Response::parse(mount::Proc::EXPORT, results(&reply)).unwrap();
assert_eq!(
decoded,
mount::Response::Export(vec![mount::Export::new(
"/C/",
&[mount::Export::LINK_LOCAL_SUBNET]
)])
);
let mount::Response::Export(exports) = &decoded else {
panic!("expected an export listing");
};
let export = exports.first().unwrap();
assert_eq!(export.path.as_bytes(), hex("2f0043002f00"), "F12's raw=…");
assert_eq!(export.path.len_bytes(), 6, "six bytes for three characters");
assert_eq!(
export.groups.first().map(String::len),
Some(23),
"and 23 bytes for 23 characters, because the group is not UTF-16"
);
assert_eq!(
decoded.encode(),
results(&reply),
"byte for byte, both encodings in one reply"
);
}
#[test]
fn a_real_export_reply_may_name_individual_hosts_instead_of_a_subnet() {
let reply = hex(
"00000002000000010000000000000000000000000000000000000001000000122f\
0043002f004500580050004f00520054000000000000010000001f3136392e3235\
342e3234342e3138312f3235352e3235352e3235352e32353500000000000000000\
1000000122f0043002f004500580050004f00520054000000000000010000001f31\
36392e3235342e3139322e3131322f3235352e3235352e3235352e3235350000000\
00000000000",
);
let mount::Response::Export(exports) =
mount::Response::parse(mount::Proc::EXPORT, results(&reply)).unwrap()
else {
panic!("expected an export listing");
};
assert_eq!(exports.len(), 2, "one entry per peer that has mounted");
for export in &exports {
assert_eq!(export.path.to_string_lossy(), "/C/EXPORT");
}
assert_eq!(
exports
.iter()
.filter_map(|e| e.groups.first())
.map(String::as_str)
.collect::<Vec<_>>(),
[
"169.254.244.181/255.255.255.255",
"169.254.192.112/255.255.255.255"
],
"decoding these as UTF-16LE is what produced CJK mojibake"
);
}
#[test]
fn a_real_lookup_walks_one_component_and_returns_a_handle_and_attributes() {
let raw = hex(
"000000040000000000000002000186a300000002000000040000000100000014dc\
1ac513000000000000000000000000000000000000000000000000012538a80125\
38a8012538a80301000000001b5800000000010301000000026600000010430 06f\
006e00740065006e0074007300",
);
let parsed = call(&raw);
assert_eq!(parsed.program, Program::NFS);
assert_eq!((parsed.version, parsed.procedure), (2, 4));
let request = nfs2::Request::parse(nfs2::Proc(parsed.procedure), parsed.arguments).unwrap();
let nfs2::Request::Lookup { dir, name } = &request else {
panic!("expected a LOOKUP, got {request:?}");
};
assert_eq!(name.to_string_lossy(), "Contents");
assert_eq!(name.len_bytes(), 16, "eight characters, sixteen bytes");
assert_eq!(
dir.as_bytes().get(..12),
Some(hex("012538a8012538a8012538a8").as_slice())
);
assert_ne!(
dir.as_bytes().get(12..),
Some([0u8; 20].as_slice()),
"the twenty bytes the deck overwrote are its own bookkeeping"
);
assert_eq!(
parsed.encode(),
raw,
"sixteen is a multiple of four, so there is no padding to differ over"
);
let reply = hex(
"00000004000000010000000000000000000000000000000000000000012f1d5401\
2538a8012538a8000000000000000000000000000000000000000000000002 0000\
41b60000000100000000000000000000000000000200000000010000000100000002\
012f1d5463b0cd000000000063b0cd000000000063b0cd0000000000",
);
let nfs2::Response::Lookup(Ok(found)) =
nfs2::Response::parse(nfs2::Proc::LOOKUP, results(&reply)).unwrap()
else {
panic!("expected a successful lookup");
};
assert!(found.attr.is_directory());
assert_eq!(
found.attr.mode,
nfs2::Fattr::DIR_MODE,
"0o40666, not 0o40755"
);
assert_eq!(found.attr.rdev, nfs2::Fattr::RDEV, "1, not 0");
assert_eq!(found.attr.fsid, nfs2::Fattr::FSID);
assert_eq!(found.attr.blocksize, nfs2::Fattr::BLOCK_SIZE);
assert_eq!(found.attr.mtime_sec, nfs2::Fattr::EPOCH);
assert_eq!(
found.attr.size, 0,
"a deck reports every directory as empty"
);
assert_eq!(found.attr.blocks, 1);
assert_eq!(
found.attr.fileid,
found.handle.fileid(),
"a LOOKUP's fileid is the first word of the handle it returns"
);
assert_eq!(
nfs2::Response::Lookup(Ok(found)).encode(),
results(&reply),
"byte for byte"
);
assert_eq!(
nfs2::Fattr::directory(found.handle.fileid(), nfs2::Fattr::EPOCH),
found.attr,
"and our synthesised directory attributes are the deck's, field for field"
);
}
#[test]
fn a_real_lookup_of_a_japanese_filename_decodes_as_utf16le() {
let raw = hex(
"000000860000000000000002000186a30000000200000004000000010000001449\
97101400000000000000000000000000000000000000000000000 08d518a807bb1\
94a16b4070bd0301d20000001b580000000003030100000002cc00000026300032\
002e00200041006b0069006200610020002d002000ab30ac30df302e006d007000\
33008930",
);
let parsed = call(&raw);
let nfs2::Request::Lookup { name, .. } =
nfs2::Request::parse(nfs2::Proc(parsed.procedure), parsed.arguments).unwrap()
else {
panic!("expected a LOOKUP");
};
assert_eq!(name.to_string_lossy(), "02. Akiba - カガミ.mp3");
assert_eq!(name.len_bytes(), 38, "19 characters, 38 bytes");
assert_eq!(
name.as_bytes().get(24..30),
Some(hex("ab30ac30df30").as_slice()),
"カガミ as three little-endian code units"
);
assert_eq!(
Utf16LeString::new("02. Akiba - カガミ.mp3").as_bytes(),
name.as_bytes(),
"and our encoder produces exactly what the deck sent"
);
}
#[test]
fn a_real_failed_lookup_is_a_status_and_nothing_else() {
let reply = hex("00000026000000010000000000000000000000000000000000000002");
assert_eq!(reply.len(), 28);
assert_eq!(
nfs2::Response::parse(nfs2::Proc::LOOKUP, results(&reply)).unwrap(),
nfs2::Response::Lookup(Err(nfs2::ErrorStatus::NOENT))
);
}
#[test]
fn a_real_getattr_reply_is_a_status_and_seventeen_words() {
let raw = hex(
"000000080000000000000002000186a30000000200000001000000010000001 4bc\
690310000000000000000000000000000000000000000000000000013218440131\
1954012538a80000000000000000000000000000000000000000",
);
let parsed = call(&raw);
assert_eq!(
raw.len(),
92,
"every GETATTR call in the corpus is 92 bytes"
);
let nfs2::Request::GetAttr(handle) =
nfs2::Request::parse(nfs2::Proc(parsed.procedure), parsed.arguments).unwrap()
else {
panic!("expected a GETATTR");
};
assert_eq!(parsed.encode(), raw, "a bare handle needs no padding");
let reply = hex(
"000000080000000100000000000000000000000000000000000000000000000100\
008000000000010000000000000000006974940000020000000001000034bb0000\
00020132184463b0cd000000000063b0cd000000000063b0cd0000000000",
);
assert_eq!(reply.len(), 96, "24 header + 4 status + 68 fattr");
let nfs2::Response::Attr(Ok(attr)) =
nfs2::Response::parse(nfs2::Proc::GETATTR, results(&reply)).unwrap()
else {
panic!("expected attributes");
};
assert!(attr.is_regular_file());
assert_eq!(
attr.mode,
nfs2::Fattr::FILE_MODE,
"0o100000 — S_IFREG with no permission bits at all"
);
assert_eq!((attr.nlink, attr.uid, attr.gid), (1, 0, 0));
assert_eq!(attr.size, 6_911_124);
assert_eq!(attr.blocks, 13_499, "6911124 / 512, rounded up");
assert_eq!(attr.blocksize, nfs2::Fattr::BLOCK_SIZE);
assert_eq!(attr.rdev, nfs2::Fattr::RDEV);
assert_eq!(attr.fsid, nfs2::Fattr::FSID);
assert_eq!(attr.fileid, handle.fileid(), "the first word of the handle");
for time in [attr.atime_sec, attr.mtime_sec, attr.ctime_sec] {
assert_eq!(time, nfs2::Fattr::EPOCH, "2023-01-01T00:00:00Z, hard-coded");
}
assert_eq!(nfs2::Response::Attr(Ok(attr)).encode(), results(&reply));
let ours =
nfs2::Fattr::regular_file(handle.fileid(), 6_911_124, nfs2::Fattr::EPOCH).unwrap();
assert_eq!(
ours, attr,
"our synthesised fattr is the deck's, field for field"
);
}
#[test]
fn a_real_read_call_is_always_a_hundred_and_four_bytes() {
let raw = hex(
"0000000c0000000000000002000186a30000000200000006000000010000001 4b0\
b631140000000000000000000000000000000000000000000000000134155401341\
300012b2810000000000000000000000000000000000000000000000c8d00002000\
00000000",
);
let parsed = call(&raw);
assert_eq!(raw.len(), 104);
let nfs2::Request::Read(args) =
nfs2::Request::parse(nfs2::Proc(parsed.procedure), parsed.arguments).unwrap()
else {
panic!("expected a READ");
};
assert_eq!(args.offset, 3213);
assert_eq!(args.count, 8192, "the NFSv2 maximum (F19)");
assert_eq!(
args.total_count, 0,
"deprecated in RFC 1094 itself; zero in all 53,322 READ calls"
);
assert_eq!(parsed.encode(), raw);
}
#[test]
fn a_real_read_may_ask_for_far_more_than_the_nfsv2_maximum() {
let raw = hex(
"0000025c0000000000000002000186a30000000200000006000000010000001 4ff\
fbb503000000000000000000000000000000000000000000000000012542e401311\
954012538a800000000000000000000000000000000000000000000002c00006f8c\
00000000",
);
let parsed = call(&raw);
let nfs2::Request::Read(args) =
nfs2::Request::parse(nfs2::Proc(parsed.procedure), parsed.arguments).unwrap()
else {
panic!("expected a READ");
};
assert_eq!(
args.offset, 44,
"past a container header, not block-aligned"
);
assert_eq!(args.count, 28_556);
assert!(
args.count > u32::try_from(nfs2::MAX_DATA).unwrap(),
"and the serving deck answered it in full"
);
assert!(args.count <= nfs2::MAX_READ_PAYLOAD);
}
#[test]
fn a_real_read_reply_carries_an_empty_fattr_and_only_a_fileid() {
let head = hex(
"0000000c00000001000000000000000000000000000000000000000000000000\
0000000000000000000000000000000000000000000000000000000000000000\
0000000001341554000000000000000000000000000000000000000000000000\
00002000",
);
assert_eq!(
head.len(),
100,
"24 header + 4 status + 68 fattr + 4 length"
);
let mut body = head.clone();
body.extend(std::iter::repeat_n(0u8, 8192));
let nfs2::Response::Read(Ok(data)) =
nfs2::Response::parse(nfs2::Proc::READ, results(&body)).unwrap()
else {
panic!("expected a read result");
};
assert_eq!(data.data.len(), 8192);
assert_eq!(data.attr.ftype, nfs2::FType::NON);
assert_eq!(data.attr.mode, 0);
assert_eq!(
data.attr.size, 0,
"and size zero here does NOT mean the file is empty"
);
assert_eq!(data.attr.blocksize, 0);
assert_eq!(data.attr.mtime_sec, 0);
assert_eq!(
data.attr.fileid, 0x0134_1554,
"the only populated field, and it is the call handle's first word"
);
}
#[test]
fn a_real_deck_returns_a_handle_we_never_served() {
let served = FileHandle::parse(&hex(
"8a5edab282632443219e051e4ade2d1d5bbc671c781051bf1437897cbdfea0f1",
))
.unwrap();
let returned = FileHandle::parse(&hex(
"8a5edab282632443219e051e03012d0000001b58000000000303010000000162",
))
.unwrap();
assert_ne!(served, returned, "a spec-conformant server sees a stranger");
assert_eq!(
served.key(),
returned.key(),
"and the twelve bytes it may rely on are untouched"
);
assert_eq!(served.fileid(), returned.fileid());
}
}
#[cfg(test)]
mod fuzz {
use super::*;
struct Lcg(u64);
impl Lcg {
fn next_u32(&mut self) -> u32 {
self.0 = self
.0
.wrapping_mul(6_364_136_223_846_793_005)
.wrapping_add(1_442_695_040_888_963_407);
u32::try_from(self.0 >> 32).unwrap_or(0)
}
fn next_byte(&mut self) -> u8 {
u8::try_from(self.next_u32() & 0xff).unwrap_or(0)
}
fn below(&mut self, limit: usize) -> usize {
if limit == 0 {
0
} else {
usize::try_from(self.next_u32()).unwrap_or(0) % limit
}
}
}
fn parse_every_way(data: &[u8]) {
let _ = Message::parse(data);
let _ = Reply::parse(data);
let _ = AuthUnix::parse(data);
if let Ok(call) = Call::parse(data) {
for procedure in 0..20u32 {
let _ = portmap::Request::parse(portmap::Proc(procedure), call.arguments);
let _ = mount::Request::parse(mount::Proc(procedure), call.arguments);
let _ = nfs2::Request::parse(nfs2::Proc(procedure), call.arguments);
}
}
for procedure in 0..20u32 {
let _ = portmap::Response::parse(portmap::Proc(procedure), data);
let _ = mount::Response::parse(mount::Proc(procedure), data);
let _ = nfs2::Response::parse(nfs2::Proc(procedure), data);
}
let mut reader = xdr::Reader::new(data);
let _ = reader.u32();
let _ = reader.u64();
let _ = reader.opaque_var(xdr::MAX_STRING, "fuzz");
let _ = reader.utf16le_string(xdr::MAX_STRING);
let _ = reader.ascii_string(xdr::MAX_STRING);
let _ = reader.u32_array(16);
let _ = reader.opaque_fixed(nfs2::FHANDLE_LEN);
let _ = xdr::Utf16LeString::from_bytes(data).to_string_lossy();
}
#[test]
fn no_random_datagram_can_panic_a_parser() {
let mut rng = Lcg(0x5eed_1e55);
for _ in 0..20_000 {
let len = rng.below(160);
let bytes: Vec<u8> = (0..len).map(|_| rng.next_byte()).collect();
parse_every_way(&bytes);
}
}
fn valid_datagrams() -> Vec<Vec<u8>> {
let credential = AuthUnix::cdj(STAMP_FIRST_CALL).encode();
vec![
Call::new(
Xid(1),
Program::PORTMAP,
2,
portmap::Proc::GETPORT.0,
Auth::unix(&credential),
&portmap::Request::GetPort(portmap::Mapping::query(
Program::MOUNT,
1,
IpProtocol::UDP,
))
.encode_arguments(),
)
.encode(),
Call::new(
Xid(2),
Program::MOUNT,
1,
mount::Proc::MNT.0,
Auth::unix(&credential),
&mount::Request::Mnt(xdr::Utf16LeString::new("/C/")).encode_arguments(),
)
.encode(),
Call::new(
Xid(3),
Program::NFS,
2,
nfs2::Proc::LOOKUP.0,
Auth::unix(&credential),
&nfs2::Request::Lookup {
dir: FileHandle::ZERO,
name: xdr::Utf16LeString::new("Contents"),
}
.encode_arguments(),
)
.encode(),
Reply::success(
Xid(3),
&nfs2::Response::Lookup(Ok(nfs2::FileRef {
handle: FileHandle::ZERO,
attr: nfs2::Fattr::directory(1, nfs2::Fattr::EPOCH),
}))
.encode(),
)
.encode(),
Reply::success(
Xid(4),
&mount::Response::Export(vec![mount::Export::new(
"/C/",
&[mount::Export::LINK_LOCAL_SUBNET],
)])
.encode(),
)
.encode(),
Reply::success(
Xid(5),
&portmap::Response::Dump(
portmap::cdj_registrations(111, mount::PIONEER_PORT, nfs2::PORT).to_vec(),
)
.encode(),
)
.encode(),
Reply::success(
Xid(6),
&nfs2::Response::ReadDir(Ok(nfs2::Listing {
entries: vec![nfs2::DirEntry {
fileid: 1,
name: xdr::Utf16LeString::new("PIONEER"),
cookie: nfs2::Cookie([0, 0, 0, 1]),
}],
eof: true,
}))
.encode(),
)
.encode(),
]
}
#[test]
fn no_mutation_of_a_valid_datagram_can_panic_a_parser() {
let mut rng = Lcg(0xc0ff_ee42);
for seed in &valid_datagrams() {
for cut in 0..=seed.len() {
parse_every_way(seed.get(..cut).unwrap_or(seed));
}
for position in 0..seed.len() {
for value in [0x00, 0x01, 0x7f, 0x80, 0xfe, 0xff] {
let mut mutated = seed.clone();
if let Some(slot) = mutated.get_mut(position) {
*slot = value;
}
parse_every_way(&mutated);
}
}
for _ in 0..2_000 {
let mut mutated = seed.clone();
for _ in 0..=rng.below(6) {
let position = rng.below(mutated.len().max(1));
if let Some(slot) = mutated.get_mut(position) {
*slot = rng.next_byte();
}
}
parse_every_way(&mutated);
}
}
}
#[test]
fn a_hostile_length_prefix_is_refused_rather_than_allocated() {
let credential = AuthUnix::cdj(STAMP_FIRST_CALL).encode();
let arguments = nfs2::Request::Lookup {
dir: FileHandle::ZERO,
name: xdr::Utf16LeString::new("Contents"),
}
.encode_arguments();
let mut call = Call::new(
Xid(1),
Program::NFS,
2,
nfs2::Proc::LOOKUP.0,
Auth::unix(&credential),
&arguments,
)
.encode();
assert_eq!(call.get(92..96), Some(16u32.to_be_bytes().as_slice()));
if let Some(slot) = call.get_mut(92..96) {
slot.copy_from_slice(&0xffff_ffffu32.to_be_bytes());
}
let parsed = Call::parse(&call).expect("the header is still intact");
let error = nfs2::Request::parse(nfs2::Proc::LOOKUP, parsed.arguments)
.expect_err("a four-gigabyte name must be refused");
assert!(
matches!(error, Error::ImplausibleLength { limit, .. } if limit == u64::from(nfs2::MAX_NAME)),
"expected a capped refusal, got {error:?}"
);
assert!(
!error.is_truncated(),
"and it is not truncation: more bytes would not help"
);
let mut call = Call::new(
Xid(1),
Program::NFS,
2,
nfs2::Proc::LOOKUP.0,
Auth::unix(&credential),
&arguments,
)
.encode();
if let Some(slot) = call.get_mut(28..32) {
slot.copy_from_slice(&0xffff_ffffu32.to_be_bytes());
}
assert!(
matches!(
Call::parse(&call),
Err(Error::ImplausibleLength { limit: 400, .. })
),
"an oversized opaque_auth body must be refused before allocating"
);
}
#[test]
fn no_length_prefix_at_any_offset_can_panic_a_parser() {
let credential = AuthUnix::cdj(STAMP_FIRST_CALL).encode();
let seed = Call::new(
Xid(1),
Program::NFS,
2,
nfs2::Proc::LOOKUP.0,
Auth::unix(&credential),
&nfs2::Request::Lookup {
dir: FileHandle::ZERO,
name: xdr::Utf16LeString::new("Contents"),
}
.encode_arguments(),
)
.encode();
for position in 0..seed.len().saturating_sub(4) {
for claim in [0xffff_ffffu32, 0x8000_0000, 0x0010_0000, 0x0000_ffff] {
let mut mutated = seed.clone();
if let Some(slot) = mutated.get_mut(position..position + 4) {
slot.copy_from_slice(&claim.to_be_bytes());
}
parse_every_way(&mutated);
}
}
}
}
#[cfg(test)]
mod loopback {
use super::*;
use crate::rpc::xdr::Utf16LeString;
const HANDLE: FileHandle = FileHandle([7; nfs2::FHANDLE_LEN]);
fn exchange_call<'a>(
program: Program,
version: u32,
procedure: u32,
arguments: &'a [u8],
datagram: &'a mut Vec<u8>,
) -> Call<'a> {
let credential = AuthUnix::cdj(STAMP_FIRST_CALL).encode();
*datagram = Call::new(
Xid(0x0350_0001),
program,
version,
procedure,
Auth::unix(&credential),
arguments,
)
.encode();
let parsed = Call::parse(datagram).expect("a call we built must parse");
assert_eq!(parsed.program, program);
assert_eq!(parsed.version, version);
assert_eq!(parsed.procedure, procedure);
assert_eq!(parsed.xid, Xid(0x0350_0001));
parsed
}
fn exchange_reply<'a>(results: &'a [u8], datagram: &'a mut Vec<u8>) -> &'a [u8] {
*datagram = Reply::success(Xid(0x0350_0001), results).encode();
let parsed = Reply::parse(datagram).expect("a reply we built must parse");
assert_eq!(parsed.xid(), Xid(0x0350_0001));
parsed.results().expect("a success carries results")
}
#[test]
fn every_portmap_procedure_survives_a_full_exchange() {
let cases = [
(portmap::Request::Null, portmap::Response::Null),
(
portmap::Request::GetPort(portmap::Mapping::query(
Program::MOUNT,
1,
IpProtocol::UDP,
)),
portmap::Response::GetPort(Some(mount::PIONEER_PORT)),
),
(
portmap::Request::GetPort(portmap::Mapping::query(
Program::NFS,
2,
IpProtocol::UDP,
)),
portmap::Response::GetPort(None),
),
(
portmap::Request::Dump,
portmap::Response::Dump(
portmap::cdj_registrations(portmap::PORT, mount::PIONEER_PORT, nfs2::PORT)
.to_vec(),
),
),
];
for (request, response) in cases {
let arguments = request.encode_arguments();
let mut wire = Vec::new();
let call = exchange_call(
Program::PORTMAP,
portmap::VERSION,
request.procedure().0,
&arguments,
&mut wire,
);
let seen = portmap::Request::parse(portmap::Proc(call.procedure), call.arguments)
.expect("the server must decode what the client encoded");
assert_eq!(seen, request, "the call did not survive the wire");
let results = response.encode();
let mut wire = Vec::new();
let got = portmap::Response::parse(
portmap::Proc(call.procedure),
exchange_reply(&results, &mut wire),
)
.expect("the client must decode what the server encoded");
assert_eq!(got, response, "the reply did not survive the wire");
}
}
#[test]
fn every_mount_procedure_survives_a_full_exchange() {
let cases = [
(mount::Request::Null, mount::Response::Null),
(
mount::Request::Mnt(Utf16LeString::new(mount::EXPORT_USB)),
mount::Response::Mnt(Ok(HANDLE)),
),
(
mount::Request::Mnt(Utf16LeString::new("/C/EXPORT")),
mount::Response::Mnt(Err(nfs2::ErrorStatus::ACCES)),
),
(
mount::Request::Umnt(Utf16LeString::new(mount::EXPORT_SD)),
mount::Response::Umnt,
),
(mount::Request::UmntAll, mount::Response::UmntAll),
(
mount::Request::Dump,
mount::Response::Dump(vec![mount::MountEntry {
hostname: "169.254.99.100".to_owned(),
directory: Utf16LeString::new(mount::EXPORT_USB),
}]),
),
(
mount::Request::Export,
mount::Response::Export(vec![
mount::Export::new(mount::EXPORT_SD, &[mount::Export::LINK_LOCAL_SUBNET]),
mount::Export::new(mount::EXPORT_USB, &[mount::Export::LINK_LOCAL_SUBNET]),
]),
),
];
for (request, response) in cases {
let arguments = request.encode_arguments();
let mut wire = Vec::new();
let call = exchange_call(
Program::MOUNT,
mount::VERSION,
request.procedure().0,
&arguments,
&mut wire,
);
let seen = mount::Request::parse(mount::Proc(call.procedure), call.arguments)
.expect("the server must decode what the client encoded");
assert_eq!(seen, request, "the call did not survive the wire");
let results = response.encode();
let mut wire = Vec::new();
let got = mount::Response::parse(
mount::Proc(call.procedure),
exchange_reply(&results, &mut wire),
)
.expect("the client must decode what the server encoded");
assert_eq!(got, response, "the reply did not survive the wire");
}
}
fn nfs_exchanges(payload: &[u8]) -> Vec<(nfs2::Request, nfs2::Response<'_>)> {
let attr = nfs2::Fattr::regular_file(1, 7_633_531, nfs2::Fattr::EPOCH)
.expect("a 7 MB file is well inside the 32-bit ceiling");
vec![
(nfs2::Request::Null, nfs2::Response::Null),
(
nfs2::Request::GetAttr(HANDLE),
nfs2::Response::Attr(Ok(attr)),
),
(
nfs2::Request::GetAttr(HANDLE),
nfs2::Response::Attr(Err(nfs2::ErrorStatus::STALE)),
),
(
nfs2::Request::Lookup {
dir: HANDLE,
name: Utf16LeString::new("02. Akiba - カガミ.mp3"),
},
nfs2::Response::Lookup(Ok(nfs2::FileRef {
handle: HANDLE,
attr,
})),
),
(
nfs2::Request::Lookup {
dir: HANDLE,
name: Utf16LeString::new("Contents"),
},
nfs2::Response::Lookup(Err(nfs2::ErrorStatus::NOENT)),
),
(
nfs2::Request::Read(nfs2::ReadArgs::at(HANDLE, 8192, 8192).unwrap()),
nfs2::Response::Read(Ok(nfs2::FileData {
attr,
data: payload,
})),
),
(
nfs2::Request::ReadDir(nfs2::ReadDirArgs {
handle: HANDLE,
cookie: nfs2::Cookie::START,
count: 4096,
}),
nfs2::Response::ReadDir(Ok(nfs2::Listing {
entries: vec![
nfs2::DirEntry {
fileid: 2,
name: Utf16LeString::new("PIONEER"),
cookie: nfs2::Cookie([0, 0, 0, 1]),
},
nfs2::DirEntry {
fileid: 3,
name: Utf16LeString::new("カガミ"),
cookie: nfs2::Cookie([0, 0, 0, 2]),
},
],
eof: false,
})),
),
(
nfs2::Request::StatFs(HANDLE),
nfs2::Response::StatFs(Ok(nfs2::FsStat {
tsize: 8192,
bsize: 512,
blocks: 1_000_000,
bfree: 0,
bavail: 0,
})),
),
(
nfs2::Request::Unknown {
procedure: nfs2::Proc::WRITE,
arguments: vec![1, 2, 3, 4, 5, 6, 7, 8],
},
nfs2::Response::Null,
),
]
}
#[test]
fn every_nfs_procedure_survives_a_full_exchange() {
let payload = vec![0x5a; 1280];
for (request, response) in nfs_exchanges(&payload) {
let arguments = request.encode_arguments();
let mut wire = Vec::new();
let call = exchange_call(
Program::NFS,
nfs2::VERSION,
request.procedure().0,
&arguments,
&mut wire,
);
let seen = nfs2::Request::parse(nfs2::Proc(call.procedure), call.arguments)
.expect("the server must decode what the client encoded");
assert_eq!(seen, request, "the call did not survive the wire");
if matches!(request, nfs2::Request::Unknown { .. }) {
continue; }
let results = response.encode();
let mut wire = Vec::new();
let got = nfs2::Response::parse(
nfs2::Proc(call.procedure),
exchange_reply(&results, &mut wire),
)
.expect("the client must decode what the server encoded");
assert_eq!(got, response, "the reply did not survive the wire");
}
}
#[test]
fn every_refusal_a_server_can_send_survives_the_wire() {
let refusals = [
Reply::failed(Xid(1), FailureStat::PROG_UNAVAIL),
Reply::failed(Xid(1), FailureStat::PROC_UNAVAIL),
Reply::failed(Xid(1), FailureStat::GARBAGE_ARGS),
Reply::failed(Xid(1), FailureStat::SYSTEM_ERR),
Reply::Accepted {
xid: Xid(1),
verifier: Auth::NULL,
status: Accepted::ProgMismatch { low: 2, high: 2 },
},
Reply::Denied {
xid: Xid(1),
reason: Denied::AuthError(AuthStat::TOOWEAK),
},
Reply::Denied {
xid: Xid(1),
reason: Denied::RpcMismatch { low: 2, high: 2 },
},
Reply::prog_mismatch(Xid(1), 2, 2),
Reply::Denied {
xid: Xid(1),
reason: Denied::Other(
OtherReject::new(RejectStat(9)).expect("9 is not a defined reject_stat"),
),
},
];
for refusal in refusals {
let wire = refusal.encode();
let parsed = Reply::parse(&wire).expect("a refusal we built must parse");
assert_eq!(parsed, refusal);
assert_eq!(
parsed.results(),
None,
"a refusal carries no results, and a caller must not find any"
);
assert_eq!(parsed.encode(), wire, "and it re-encodes byte for byte");
}
}
#[test]
fn a_listing_of_exactly_the_cap_survives_and_one_more_does_not() {
let mapping = portmap::Mapping::registered(Program::NFS, 2, IpProtocol::UDP, nfs2::PORT);
for (count, should_parse) in [(512usize, true), (513, false)] {
let listing = portmap::Response::Dump(vec![mapping; count]);
let parsed = portmap::Response::parse(portmap::Proc::DUMP, &listing.encode());
assert_eq!(
parsed.is_ok(),
should_parse,
"a portmap DUMP of {count} mappings"
);
}
for (count, should_parse) in [(64usize, true), (65, false)] {
let listing = mount::Response::Export(vec![
mount::Export::new(
"/C/",
&["169.254.0.0/255.255.0.0"]
);
count
]);
let parsed = mount::Response::parse(mount::Proc::EXPORT, &listing.encode());
assert_eq!(parsed.is_ok(), should_parse, "an EXPORT of {count} entries");
let groups = vec!["169.254.0.0/255.255.0.0"; count];
let listing = mount::Response::Export(vec![mount::Export::new("/C/", &groups)]);
let parsed = mount::Response::parse(mount::Proc::EXPORT, &listing.encode());
assert_eq!(
parsed.is_ok(),
should_parse,
"an export with {count} groups"
);
}
let entry = mount::MountEntry {
hostname: "169.254.99.100".to_owned(),
directory: Utf16LeString::new("/C/"),
};
for (count, should_parse) in [(64usize, true), (65, false)] {
let listing = mount::Response::Dump(vec![entry.clone(); count]);
let parsed = mount::Response::parse(mount::Proc::DUMP, &listing.encode());
assert_eq!(parsed.is_ok(), should_parse, "a MOUNT DUMP of {count}");
}
}
}