use std::fmt;
use crate::rpc::Program;
use crate::rpc::xdr::{self, Utf16LeString};
use crate::{Error, Result};
pub const PROGRAM: Program = Program::NFS;
pub const VERSION: u32 = 2;
pub const PORT: u16 = 2049;
pub const FHANDLE_LEN: usize = 32;
pub const MAX_DATA: usize = 8192;
pub const MAX_READ_PAYLOAD: u32 = 65_507;
pub const MAX_FILE_SIZE: u64 = 0xffff_ffff;
pub const MAX_NAME: u32 = xdr::MAX_STRING;
const MAX_DIR_ENTRIES: usize = 4096;
pub fn checked_offset(offset: u64) -> Result<u32> {
u32::try_from(offset).map_err(|_| Error::ImplausibleLength {
what: "an NFSv2 file offset or size (offsets are 32-bit)",
length: offset,
limit: MAX_FILE_SIZE,
})
}
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub struct Proc(pub u32);
impl Proc {
pub const NULL: Self = Self(0);
pub const GETATTR: Self = Self(1);
pub const SETATTR: Self = Self(2);
pub const ROOT: Self = Self(3);
pub const LOOKUP: Self = Self(4);
pub const READLINK: Self = Self(5);
pub const READ: Self = Self(6);
pub const WRITECACHE: Self = Self(7);
pub const WRITE: Self = Self(8);
pub const CREATE: Self = Self(9);
pub const REMOVE: Self = Self(10);
pub const RENAME: Self = Self(11);
pub const LINK: Self = Self(12);
pub const SYMLINK: Self = Self(13);
pub const MKDIR: Self = Self(14);
pub const RMDIR: Self = Self(15);
pub const READDIR: Self = Self(16);
pub const STATFS: Self = Self(17);
pub fn name(self) -> Option<&'static str> {
Some(match self {
Self::NULL => "NULL",
Self::GETATTR => "GETATTR",
Self::SETATTR => "SETATTR",
Self::ROOT => "ROOT",
Self::LOOKUP => "LOOKUP",
Self::READLINK => "READLINK",
Self::READ => "READ",
Self::WRITECACHE => "WRITECACHE",
Self::WRITE => "WRITE",
Self::CREATE => "CREATE",
Self::REMOVE => "REMOVE",
Self::RENAME => "RENAME",
Self::LINK => "LINK",
Self::SYMLINK => "SYMLINK",
Self::MKDIR => "MKDIR",
Self::RMDIR => "RMDIR",
Self::READDIR => "READDIR",
Self::STATFS => "STATFS",
_ => return None,
})
}
}
impl fmt::Debug for Proc {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self.name() {
Some(name) => f.write_str(name),
None => write!(f, "nfs2::Proc({})", self.0),
}
}
}
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub struct Status(pub u32);
impl Status {
pub const OK: Self = Self(0);
pub const PERM: Self = Self(1);
pub const NOENT: Self = Self(2);
pub const IO: Self = Self(5);
pub const NXIO: Self = Self(6);
pub const ACCES: Self = Self(13);
pub const EXIST: Self = Self(17);
pub const NODEV: Self = Self(19);
pub const NOTDIR: Self = Self(20);
pub const ISDIR: Self = Self(21);
pub const FBIG: Self = Self(27);
pub const NOSPC: Self = Self(28);
pub const ROFS: Self = Self(30);
pub const NAMETOOLONG: Self = Self(63);
pub const NOTEMPTY: Self = Self(66);
pub const DQUOT: Self = Self(69);
pub const STALE: Self = Self(70);
pub const WFLUSH: Self = Self(99);
pub fn name(self) -> Option<&'static str> {
Some(match self {
Self::OK => "NFS_OK",
Self::PERM => "NFSERR_PERM",
Self::NOENT => "NFSERR_NOENT",
Self::IO => "NFSERR_IO",
Self::NXIO => "NFSERR_NXIO",
Self::ACCES => "NFSERR_ACCES",
Self::EXIST => "NFSERR_EXIST",
Self::NODEV => "NFSERR_NODEV",
Self::NOTDIR => "NFSERR_NOTDIR",
Self::ISDIR => "NFSERR_ISDIR",
Self::FBIG => "NFSERR_FBIG",
Self::NOSPC => "NFSERR_NOSPC",
Self::ROFS => "NFSERR_ROFS",
Self::NAMETOOLONG => "NFSERR_NAMETOOLONG",
Self::NOTEMPTY => "NFSERR_NOTEMPTY",
Self::DQUOT => "NFSERR_DQUOT",
Self::STALE => "NFSERR_STALE",
Self::WFLUSH => "NFSERR_WFLUSH",
_ => return None,
})
}
}
impl fmt::Debug for Status {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self.name() {
Some(name) => f.write_str(name),
None => write!(f, "Status({})", self.0),
}
}
}
impl fmt::Display for Status {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(self, f)
}
}
pub type NfsResult<T> = core::result::Result<T, ErrorStatus>;
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub struct ErrorStatus(Status);
impl ErrorStatus {
pub const PERM: Self = Self(Status::PERM);
pub const NOENT: Self = Self(Status::NOENT);
pub const IO: Self = Self(Status::IO);
pub const NXIO: Self = Self(Status::NXIO);
pub const ACCES: Self = Self(Status::ACCES);
pub const EXIST: Self = Self(Status::EXIST);
pub const NODEV: Self = Self(Status::NODEV);
pub const NOTDIR: Self = Self(Status::NOTDIR);
pub const ISDIR: Self = Self(Status::ISDIR);
pub const FBIG: Self = Self(Status::FBIG);
pub const NOSPC: Self = Self(Status::NOSPC);
pub const ROFS: Self = Self(Status::ROFS);
pub const NAMETOOLONG: Self = Self(Status::NAMETOOLONG);
pub const NOTEMPTY: Self = Self(Status::NOTEMPTY);
pub const DQUOT: Self = Self(Status::DQUOT);
pub const STALE: Self = Self(Status::STALE);
pub const WFLUSH: Self = Self(Status::WFLUSH);
pub fn new(status: Status) -> Option<Self> {
if status == Status::OK {
None
} else {
Some(Self(status))
}
}
pub fn status(self) -> Status {
self.0
}
}
impl From<ErrorStatus> for Status {
fn from(status: ErrorStatus) -> Self {
status.status()
}
}
impl fmt::Debug for ErrorStatus {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(&self.0, f)
}
}
impl fmt::Display for ErrorStatus {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(&self.0, f)
}
}
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub struct FType(pub u32);
impl FType {
pub const NON: Self = Self(0);
pub const REG: Self = Self(1);
pub const DIR: Self = Self(2);
pub const BLK: Self = Self(3);
pub const CHR: Self = Self(4);
pub const LNK: Self = Self(5);
pub fn name(self) -> Option<&'static str> {
Some(match self {
Self::NON => "NFNON",
Self::REG => "NFREG",
Self::DIR => "NFDIR",
Self::BLK => "NFBLK",
Self::CHR => "NFCHR",
Self::LNK => "NFLNK",
_ => return None,
})
}
}
impl fmt::Debug for FType {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self.name() {
Some(name) => f.write_str(name),
None => write!(f, "FType({})", self.0),
}
}
}
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub struct FileHandle(pub [u8; FHANDLE_LEN]);
#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct FileHandleKey(pub [u8; FileHandle::KEY_LEN]);
impl FileHandle {
pub const LEN: usize = FHANDLE_LEN;
pub const KEY_LEN: usize = 12;
pub const ZERO: Self = Self([0; FHANDLE_LEN]);
pub fn fileid(&self) -> u32 {
let mut word = [0u8; 4];
for (slot, byte) in word.iter_mut().zip(self.0.iter()) {
*slot = *byte;
}
u32::from_be_bytes(word)
}
pub fn key(&self) -> FileHandleKey {
let mut key = [0u8; Self::KEY_LEN];
for (slot, byte) in key.iter_mut().zip(self.0.iter()) {
*slot = *byte;
}
FileHandleKey(key)
}
pub fn as_bytes(&self) -> &[u8; FHANDLE_LEN] {
&self.0
}
pub fn parse(bytes: &[u8]) -> Result<Self> {
let array: [u8; FHANDLE_LEN] = bytes.try_into().map_err(|_| {
Error::malformed(
0,
format!(
"a filehandle is {FHANDLE_LEN} bytes, got {len}",
len = bytes.len()
),
)
})?;
Ok(Self(array))
}
pub fn from_key(key: FileHandleKey) -> Self {
let mut bytes = [0u8; FHANDLE_LEN];
for (slot, byte) in bytes.iter_mut().zip(key.0.iter()) {
*slot = *byte;
}
Self(bytes)
}
}
impl From<FileHandleKey> for FileHandle {
fn from(key: FileHandleKey) -> Self {
Self::from_key(key)
}
}
impl From<FileHandle> for FileHandleKey {
fn from(handle: FileHandle) -> Self {
handle.key()
}
}
impl fmt::Debug for FileHandle {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let (kept, rewritten) = self.0.split_at(Self::KEY_LEN);
for byte in kept {
write!(f, "{byte:02x}")?;
}
f.write_str("|")?;
for byte in rewritten {
write!(f, "{byte:02x}")?;
}
Ok(())
}
}
impl fmt::Debug for FileHandleKey {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
for byte in &self.0 {
write!(f, "{byte:02x}")?;
}
Ok(())
}
}
#[derive(Clone, Copy, PartialEq, Eq, Hash, Default)]
pub struct Cookie(pub [u8; 4]);
impl Cookie {
pub const START: Self = Self([0; 4]);
}
impl fmt::Debug for Cookie {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "cookie:{:02x?}", self.0)
}
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub struct Fattr {
pub ftype: FType,
pub mode: u32,
pub nlink: u32,
pub uid: u32,
pub gid: u32,
pub size: u32,
pub blocksize: u32,
pub rdev: u32,
pub blocks: u32,
pub fsid: u32,
pub fileid: u32,
pub atime_sec: u32,
pub atime_usec: u32,
pub mtime_sec: u32,
pub mtime_usec: u32,
pub ctime_sec: u32,
pub ctime_usec: u32,
}
impl Fattr {
pub const WIRE_LEN: usize = 68;
pub const BLOCK_SIZE: u32 = 512;
pub const DIR_MODE: u32 = 0o040_666;
pub const FILE_MODE: u32 = 0o100_000;
pub const RDEV: u32 = 1;
pub const FSID: u32 = 2;
pub const EPOCH: u32 = 1_672_531_200;
pub fn directory(fileid: u32, mtime_sec: u32) -> Self {
Self {
ftype: FType::DIR,
mode: Self::DIR_MODE,
nlink: 1,
uid: 0,
gid: 0,
size: 0,
blocksize: Self::BLOCK_SIZE,
rdev: Self::RDEV,
blocks: 1,
fsid: Self::FSID,
fileid,
atime_sec: mtime_sec,
atime_usec: 0,
mtime_sec,
mtime_usec: 0,
ctime_sec: mtime_sec,
ctime_usec: 0,
}
}
pub fn regular_file(fileid: u32, size: u64, mtime_sec: u32) -> Result<Self> {
let size = checked_offset(size)?;
Ok(Self {
ftype: FType::REG,
mode: Self::FILE_MODE,
nlink: 1,
uid: 0,
gid: 0,
size,
blocksize: Self::BLOCK_SIZE,
rdev: Self::RDEV,
blocks: size.div_ceil(Self::BLOCK_SIZE),
fsid: Self::FSID,
fileid,
atime_sec: mtime_sec,
atime_usec: 0,
mtime_sec,
mtime_usec: 0,
ctime_sec: mtime_sec,
ctime_usec: 0,
})
}
pub fn is_directory(&self) -> bool {
self.ftype == FType::DIR
}
pub fn is_regular_file(&self) -> bool {
self.ftype == FType::REG
}
fn write(&self, out: &mut xdr::Writer) {
for word in [
self.ftype.0,
self.mode,
self.nlink,
self.uid,
self.gid,
self.size,
self.blocksize,
self.rdev,
self.blocks,
self.fsid,
self.fileid,
self.atime_sec,
self.atime_usec,
self.mtime_sec,
self.mtime_usec,
self.ctime_sec,
self.ctime_usec,
] {
out.u32(word);
}
}
fn read(input: &mut xdr::Reader<'_>) -> Result<Self> {
Ok(Self {
ftype: FType(input.u32()?),
mode: input.u32()?,
nlink: input.u32()?,
uid: input.u32()?,
gid: input.u32()?,
size: input.u32()?,
blocksize: input.u32()?,
rdev: input.u32()?,
blocks: input.u32()?,
fsid: input.u32()?,
fileid: input.u32()?,
atime_sec: input.u32()?,
atime_usec: input.u32()?,
mtime_sec: input.u32()?,
mtime_usec: input.u32()?,
ctime_sec: input.u32()?,
ctime_usec: input.u32()?,
})
}
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub struct FileRef {
pub handle: FileHandle,
pub attr: Fattr,
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub struct FileData<'a> {
pub attr: Fattr,
pub data: &'a [u8],
}
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct DirEntry {
pub fileid: u32,
pub name: Utf16LeString,
pub cookie: Cookie,
}
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct Listing {
pub entries: Vec<DirEntry>,
pub eof: bool,
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub struct FsStat {
pub tsize: u32,
pub bsize: u32,
pub blocks: u32,
pub bfree: u32,
pub bavail: u32,
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub struct ReadArgs {
pub handle: FileHandle,
pub offset: u32,
pub count: u32,
pub total_count: u32,
}
impl ReadArgs {
pub fn at(handle: FileHandle, offset: u64, count: u32) -> Result<Self> {
Ok(Self {
handle,
offset: checked_offset(offset)?,
count,
total_count: 0,
})
}
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub struct ReadDirArgs {
pub handle: FileHandle,
pub cookie: Cookie,
pub count: u32,
}
#[derive(Clone, PartialEq, Eq, Debug)]
pub enum Request {
Null,
GetAttr(FileHandle),
Lookup {
dir: FileHandle,
name: Utf16LeString,
},
Read(ReadArgs),
ReadDir(ReadDirArgs),
StatFs(FileHandle),
Unknown {
procedure: Proc,
arguments: Vec<u8>,
},
}
impl Request {
pub fn procedure(&self) -> Proc {
match self {
Self::Null => Proc::NULL,
Self::GetAttr(_) => Proc::GETATTR,
Self::Lookup { .. } => Proc::LOOKUP,
Self::Read(_) => Proc::READ,
Self::ReadDir(_) => Proc::READDIR,
Self::StatFs(_) => Proc::STATFS,
Self::Unknown { procedure, .. } => *procedure,
}
}
pub fn encode_arguments(&self) -> Vec<u8> {
let mut out = xdr::Writer::with_capacity(48);
match self {
Self::Null => {}
Self::GetAttr(handle) | Self::StatFs(handle) => out.opaque_fixed(handle.as_bytes()),
Self::Lookup { dir, name } => {
out.opaque_fixed(dir.as_bytes());
out.utf16le_string(name);
}
Self::Read(args) => {
out.opaque_fixed(args.handle.as_bytes());
out.u32(args.offset);
out.u32(args.count);
out.u32(args.total_count);
}
Self::ReadDir(args) => {
out.opaque_fixed(args.handle.as_bytes());
out.raw(&args.cookie.0);
out.u32(args.count);
}
Self::Unknown { arguments, .. } => out.raw(arguments),
}
out.into_bytes()
}
pub fn parse(procedure: Proc, arguments: &[u8]) -> Result<Self> {
let mut input = xdr::Reader::new(arguments);
Ok(match procedure {
Proc::NULL => Self::Null,
Proc::GETATTR => Self::GetAttr(read_handle(&mut input)?),
Proc::STATFS => Self::StatFs(read_handle(&mut input)?),
Proc::LOOKUP => Self::Lookup {
dir: read_handle(&mut input)?,
name: input.utf16le_string(MAX_NAME)?,
},
Proc::READ => Self::Read(ReadArgs {
handle: read_handle(&mut input)?,
offset: input.u32()?,
count: input.u32()?,
total_count: input.u32()?,
}),
Proc::READDIR => Self::ReadDir(ReadDirArgs {
handle: read_handle(&mut input)?,
cookie: read_cookie(&mut input)?,
count: input.u32()?,
}),
other => Self::Unknown {
procedure: other,
arguments: arguments.to_vec(),
},
})
}
}
fn read_handle(input: &mut xdr::Reader<'_>) -> Result<FileHandle> {
FileHandle::parse(input.opaque_fixed(FHANDLE_LEN)?)
}
fn read_cookie(input: &mut xdr::Reader<'_>) -> Result<Cookie> {
let bytes = input.opaque_fixed(4)?;
let array: [u8; 4] = bytes
.try_into()
.map_err(|_| Error::malformed(0, "a READDIR cookie is four bytes"))?;
Ok(Cookie(array))
}
#[derive(Clone, PartialEq, Eq, Debug)]
pub enum Response<'a> {
Null,
Attr(NfsResult<Fattr>),
Lookup(NfsResult<FileRef>),
Read(NfsResult<FileData<'a>>),
ReadDir(NfsResult<Listing>),
StatFs(NfsResult<FsStat>),
}
impl Response<'_> {
pub fn procedure(&self) -> Proc {
match self {
Self::Null => Proc::NULL,
Self::Attr(_) => Proc::GETATTR,
Self::Lookup(_) => Proc::LOOKUP,
Self::Read(_) => Proc::READ,
Self::ReadDir(_) => Proc::READDIR,
Self::StatFs(_) => Proc::STATFS,
}
}
pub fn status(&self) -> Status {
match self {
Self::Null => Status::OK,
Self::Attr(result) => status_of(result.as_ref()),
Self::Lookup(result) => status_of(result.as_ref()),
Self::Read(result) => status_of(result.as_ref()),
Self::ReadDir(result) => status_of(result.as_ref()),
Self::StatFs(result) => status_of(result.as_ref()),
}
}
pub fn encode(&self) -> Vec<u8> {
if matches!(self, Self::Null) {
return Vec::new();
}
let payload = match self {
Self::Read(Ok(read)) => read.data.len() + 4,
_ => 0,
};
let mut out = xdr::Writer::with_capacity(Fattr::WIRE_LEN + 8 + payload);
out.u32(self.status().0);
match self {
Self::Attr(Ok(attr)) => attr.write(&mut out),
Self::Lookup(Ok(found)) => {
out.opaque_fixed(found.handle.as_bytes());
found.attr.write(&mut out);
}
Self::Read(Ok(read)) => {
read.attr.write(&mut out);
out.opaque_var(read.data);
}
Self::ReadDir(Ok(listing)) => {
for entry in &listing.entries {
out.bool(true);
out.u32(entry.fileid);
out.utf16le_string(&entry.name);
out.raw(&entry.cookie.0);
}
out.bool(false);
out.bool(listing.eof);
}
Self::StatFs(Ok(stat)) => {
for word in [stat.tsize, stat.bsize, stat.blocks, stat.bfree, stat.bavail] {
out.u32(word);
}
}
Self::Null
| Self::Attr(Err(_))
| Self::Lookup(Err(_))
| Self::Read(Err(_))
| Self::ReadDir(Err(_))
| Self::StatFs(Err(_)) => {}
}
out.into_bytes()
}
pub fn parse(procedure: Proc, results: &[u8]) -> Result<Response<'_>> {
if procedure == Proc::NULL {
return Ok(Response::Null);
}
let mut input = xdr::Reader::new(results);
let status = Status(input.u32()?);
if let Some(status) = ErrorStatus::new(status) {
return Ok(match procedure {
Proc::GETATTR => Response::Attr(Err(status)),
Proc::LOOKUP => Response::Lookup(Err(status)),
Proc::READ => Response::Read(Err(status)),
Proc::READDIR => Response::ReadDir(Err(status)),
Proc::STATFS => Response::StatFs(Err(status)),
other => {
return Err(Error::malformed(
0,
format!("no reply decoder for NFS procedure {other:?}"),
));
}
});
}
parse_ok(procedure, &mut input)
}
}
fn parse_ok<'a>(procedure: Proc, input: &mut xdr::Reader<'a>) -> Result<Response<'a>> {
Ok(match procedure {
Proc::GETATTR => Response::Attr(Ok(Fattr::read(input)?)),
Proc::LOOKUP => Response::Lookup(Ok(FileRef {
handle: read_handle(input)?,
attr: Fattr::read(input)?,
})),
Proc::READ => Response::Read(Ok(FileData {
attr: Fattr::read(input)?,
data: input.opaque_var(MAX_READ_PAYLOAD, "a READ payload")?,
})),
Proc::READDIR => Response::ReadDir(Ok(parse_listing(input)?)),
Proc::STATFS => Response::StatFs(Ok(FsStat {
tsize: input.u32()?,
bsize: input.u32()?,
blocks: input.u32()?,
bfree: input.u32()?,
bavail: input.u32()?,
})),
other => {
return Err(Error::malformed(
0,
format!("no reply decoder for NFS procedure {other:?}"),
));
}
})
}
fn parse_listing(input: &mut xdr::Reader<'_>) -> Result<Listing> {
let mut entries = Vec::new();
while input.bool()? {
entries.push(DirEntry {
fileid: input.u32()?,
name: input.utf16le_string(MAX_NAME)?,
cookie: read_cookie(input)?,
});
if entries.len() > MAX_DIR_ENTRIES {
return Err(Error::ImplausibleLength {
what: "a READDIR listing",
length: u64::try_from(entries.len()).unwrap_or(u64::MAX),
limit: u64::try_from(MAX_DIR_ENTRIES).unwrap_or(u64::MAX),
});
}
}
let eof = if input.remaining() >= 4 {
input.bool()?
} else {
true
};
Ok(Listing { entries, eof })
}
fn status_of<T>(result: core::result::Result<&T, &ErrorStatus>) -> Status {
match result {
Ok(_) => Status::OK,
Err(status) => status.status(),
}
}
#[cfg(test)]
mod tests {
use super::*;
const SERVED: [u8; 32] = [
0x8a, 0x5e, 0xda, 0xb2, 0x82, 0x63, 0x24, 0x43, 0x21, 0x9e, 0x05, 0x1e, 0x4a, 0xde, 0x2d,
0x1d, 0x5b, 0xbc, 0x67, 0x1c, 0x78, 0x10, 0x51, 0xbf, 0x14, 0x37, 0x89, 0x7c, 0xbd, 0xfe,
0xa0, 0xf1,
];
const RETURNED: [u8; 32] = [
0x8a, 0x5e, 0xda, 0xb2, 0x82, 0x63, 0x24, 0x43, 0x21, 0x9e, 0x05, 0x1e, 0x03, 0x01, 0x2d,
0x00, 0x00, 0x00, 0x1b, 0x58, 0x00, 0x00, 0x00, 0x00, 0x03, 0x03, 0x01, 0x00, 0x00, 0x00,
0x01, 0x62,
];
#[test]
fn a_cdj_rewrites_all_but_the_leading_twelve_bytes_of_a_filehandle() {
let served = FileHandle(SERVED);
let returned = FileHandle(RETURNED);
assert_ne!(served, returned, "the whole handles differ");
assert_eq!(
served.key(),
returned.key(),
"but the twelve bytes a server may rely on are the same"
);
assert_eq!(
served.key().0,
[
0x8a, 0x5e, 0xda, 0xb2, 0x82, 0x63, 0x24, 0x43, 0x21, 0x9e, 0x05, 0x1e
]
);
}
#[test]
fn a_filehandle_debug_shows_where_the_truncation_falls() {
assert_eq!(
format!("{:?}", FileHandle(SERVED)),
"8a5edab282632443219e051e|4ade2d1d5bbc671c781051bf1437897cbdfea0f1"
);
}
#[test]
fn a_key_round_trips_through_a_zero_padded_handle() {
let key = FileHandle(SERVED).key();
let rebuilt = FileHandle::from_key(key);
assert_eq!(rebuilt.key(), key);
assert_eq!(
rebuilt.as_bytes().get(12..),
Some([0u8; 20].as_slice()),
"the twenty bytes a deck overwrites are ours to leave empty"
);
}
#[test]
fn a_filehandle_must_be_exactly_thirty_two_bytes() {
assert!(FileHandle::parse(&[0; 31]).is_err());
assert!(FileHandle::parse(&[0; 33]).is_err());
assert!(FileHandle::parse(&[0; 32]).is_ok());
}
#[test]
fn lookup_arguments_are_a_bare_handle_then_a_utf16le_name() {
let request = Request::Lookup {
dir: FileHandle(SERVED),
name: Utf16LeString::new("Contents"),
};
let args = request.encode_arguments();
assert_eq!(args.get(..32), Some(SERVED.as_slice()), "no length prefix");
assert_eq!(
args.get(32..36),
Some(16u32.to_be_bytes().as_slice()),
"eight characters announce sixteen bytes"
);
assert_eq!(
args.get(36..52),
Some(b"C\0o\0n\0t\0e\0n\0t\0s\0".as_slice())
);
assert_eq!(args.len(), 52, "16 is already aligned; no padding");
assert_eq!(Request::parse(Proc::LOOKUP, &args).unwrap(), request);
}
#[test]
fn read_arguments_carry_the_deprecated_total_count() {
let request = Request::Read(ReadArgs::at(FileHandle(SERVED), 8192, 8192).unwrap());
let args = request.encode_arguments();
assert_eq!(args.len(), 32 + 12);
assert_eq!(args.get(32..36), Some(8192u32.to_be_bytes().as_slice()));
assert_eq!(
args.get(36..40),
Some(8192u32.to_be_bytes().as_slice()),
"the size a real CDJ asks for (F19)"
);
assert_eq!(
args.get(40..44),
Some(0u32.to_be_bytes().as_slice()),
"totalcount was deprecated in RFC 1094 itself"
);
assert_eq!(Request::parse(Proc::READ, &args).unwrap(), request);
}
#[test]
fn an_offset_past_four_gigabytes_is_refused_rather_than_wrapped() {
let error = ReadArgs::at(FileHandle::ZERO, 0x1_0000_0000, 1280).unwrap_err();
assert!(
matches!(error, Error::ImplausibleLength { .. }),
"{error:?}"
);
assert!(ReadArgs::at(FileHandle::ZERO, MAX_FILE_SIZE, 1).is_ok());
}
#[test]
fn a_file_past_four_gigabytes_cannot_be_described() {
assert!(Fattr::regular_file(1, MAX_FILE_SIZE + 1, 0).is_err());
let attr = Fattr::regular_file(1, 7_633_531, 0).unwrap();
assert_eq!(attr.size, 7_633_531, "the size F18 measured");
assert_eq!(attr.blocks, 14_910, "7633531 / 512, rounded up");
assert!(attr.is_regular_file());
}
#[test]
fn a_fattr_is_seventeen_words() {
let attr = Fattr::directory(2, 0x5f5e_1000);
let response = Response::Attr(Ok(attr));
let encoded = response.encode();
assert_eq!(
encoded.len(),
4 + Fattr::WIRE_LEN,
"a status word plus 68 bytes"
);
assert_eq!(
Response::parse(Proc::GETATTR, &encoded).unwrap(),
Response::Attr(Ok(attr))
);
}
#[test]
fn an_error_reply_is_four_bytes_and_nothing_else() {
let encoded = Response::Lookup(Err(ErrorStatus::NOENT)).encode();
assert_eq!(encoded, [0, 0, 0, 2]);
assert_eq!(
Response::parse(Proc::LOOKUP, &encoded).unwrap(),
Response::Lookup(Err(ErrorStatus::NOENT))
);
}
#[test]
fn an_error_status_cannot_be_nfs_ok() {
assert_eq!(ErrorStatus::new(Status::OK), None);
assert_eq!(
ErrorStatus::new(Status::NOENT),
Some(ErrorStatus::NOENT),
"and every non-zero status is one"
);
assert_eq!(
ErrorStatus::new(Status(12_345)).map(ErrorStatus::status),
Some(Status(12_345)),
"including a status NFSv2 does not define"
);
for status in [ErrorStatus::NOENT, ErrorStatus::STALE, ErrorStatus::ACCES] {
let encoded = Response::Lookup(Err(status)).encode();
assert_eq!(encoded.len(), 4);
assert_eq!(
Response::parse(Proc::LOOKUP, &encoded).unwrap(),
Response::Lookup(Err(status))
);
}
}
#[test]
fn a_stale_handle_is_told_apart_from_a_missing_name() {
assert_eq!(Status::STALE.0, 70);
assert_eq!(Status::NOENT.0, 2);
assert_eq!(format!("{:?}", Status::STALE), "NFSERR_STALE");
}
#[test]
fn a_lookup_reply_is_a_handle_then_attributes() {
let found = FileRef {
handle: FileHandle(SERVED),
attr: Fattr::regular_file(9, 6_942_380, 0).unwrap(),
};
let encoded = Response::Lookup(Ok(found)).encode();
assert_eq!(encoded.len(), 4 + 32 + Fattr::WIRE_LEN);
assert_eq!(encoded.get(4..36), Some(SERVED.as_slice()));
let parsed = Response::parse(Proc::LOOKUP, &encoded).unwrap();
assert_eq!(parsed, Response::Lookup(Ok(found)));
let Response::Lookup(Ok(reference)) = parsed else {
panic!("expected a lookup result");
};
assert_eq!(reference.attr.size, 6_942_380);
}
#[test]
fn a_read_reply_borrows_its_payload() {
let attr = Fattr::regular_file(1, 8192, 0).unwrap();
let payload = vec![0xa5; 8192];
let encoded = Response::Read(Ok(FileData {
attr,
data: &payload,
}))
.encode();
assert_eq!(encoded.len(), 4 + Fattr::WIRE_LEN + 4 + 8192);
let parsed = Response::parse(Proc::READ, &encoded).unwrap();
let Response::Read(Ok(data)) = parsed else {
panic!("expected a read result");
};
assert_eq!(data.data.len(), 8192, "the NFSv2 maximum (F19)");
assert_eq!(data.attr, attr);
}
#[test]
fn a_short_read_is_representable_because_a_server_may_return_less() {
let attr = Fattr::regular_file(1, 100, 0).unwrap();
let encoded = Response::Read(Ok(FileData {
attr,
data: &[1, 2, 3],
}))
.encode();
let Response::Read(Ok(data)) = Response::parse(Proc::READ, &encoded).unwrap() else {
panic!("expected a read result");
};
assert_eq!(data.data, &[1, 2, 3]);
assert_eq!(data.attr.size, 100, "the file is longer than the reply");
}
#[test]
fn a_read_payload_over_the_nfsv2_maximum_is_refused() {
let mut out = xdr::Writer::new();
out.u32(Status::OK.0);
Fattr::directory(1, 0).write(&mut out);
out.u32(0xffff_ffff);
let error = Response::parse(Proc::READ, out.as_bytes()).unwrap_err();
assert!(
matches!(error, Error::ImplausibleLength { .. }),
"{error:?}"
);
}
#[test]
fn a_readdir_listing_round_trips_with_a_non_ascii_name() {
let listing = Listing {
entries: vec![
DirEntry {
fileid: 3,
name: Utf16LeString::new("PIONEER"),
cookie: Cookie([0, 0, 0, 1]),
},
DirEntry {
fileid: 4,
name: Utf16LeString::new("カガミ"),
cookie: Cookie([0, 0, 0, 2]),
},
],
eof: true,
};
let encoded = Response::ReadDir(Ok(listing.clone())).encode();
assert_eq!(
Response::parse(Proc::READDIR, &encoded).unwrap(),
Response::ReadDir(Ok(listing))
);
}
#[test]
fn an_empty_directory_is_not_an_error() {
let encoded = Response::ReadDir(Ok(Listing {
entries: Vec::new(),
eof: true,
}))
.encode();
assert_eq!(
encoded,
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
"status, no-more-entries, eof"
);
let Response::ReadDir(Ok(listing)) = Response::parse(Proc::READDIR, &encoded).unwrap()
else {
panic!("expected a listing");
};
assert!(listing.entries.is_empty() && listing.eof);
}
#[test]
fn readdir_arguments_carry_a_bare_four_byte_cookie() {
let request = Request::ReadDir(ReadDirArgs {
handle: FileHandle(SERVED),
cookie: Cookie::START,
count: 4096,
});
let args = request.encode_arguments();
assert_eq!(args.len(), 32 + 4 + 4);
assert_eq!(args.get(32..36), Some([0, 0, 0, 0].as_slice()));
assert_eq!(args.get(36..40), Some(4096u32.to_be_bytes().as_slice()));
assert_eq!(Request::parse(Proc::READDIR, &args).unwrap(), request);
}
#[test]
fn statfs_reports_five_words() {
let stat = FsStat {
tsize: 8192,
bsize: 512,
blocks: 1_000_000,
bfree: 500_000,
bavail: 500_000,
};
let encoded = Response::StatFs(Ok(stat)).encode();
assert_eq!(encoded.len(), 4 + 20);
assert_eq!(
Response::parse(Proc::STATFS, &encoded).unwrap(),
Response::StatFs(Ok(stat))
);
}
#[test]
fn getattr_and_statfs_take_a_bare_handle() {
for request in [
Request::GetAttr(FileHandle(SERVED)),
Request::StatFs(FileHandle(SERVED)),
] {
let args = request.encode_arguments();
assert_eq!(args, SERVED, "32 bytes, no prefix, no padding");
assert_eq!(Request::parse(request.procedure(), &args).unwrap(), request);
}
}
#[test]
fn a_write_procedure_decodes_as_unknown_so_it_can_be_refused_politely() {
let request = Request::parse(Proc::WRITE, &[1, 2, 3, 4]).unwrap();
assert_eq!(request.procedure(), Proc::WRITE);
assert!(matches!(request, Request::Unknown { .. }));
assert_eq!(request.encode_arguments(), [1, 2, 3, 4]);
}
#[test]
fn a_truncated_lookup_is_truncation_not_garbage() {
let error = Request::parse(Proc::LOOKUP, &[0; 20]).unwrap_err();
assert!(error.is_truncated(), "{error:?}");
}
#[test]
fn null_carries_nothing_in_either_direction() {
assert!(Request::Null.encode_arguments().is_empty());
assert!(Response::Null.encode().is_empty());
assert_eq!(Request::parse(Proc::NULL, &[]).unwrap(), Request::Null);
assert_eq!(Response::parse(Proc::NULL, &[]).unwrap(), Response::Null);
}
#[test]
fn the_observed_ports_and_program_numbers() {
assert_eq!(PROGRAM.0, 100_003);
assert_eq!(VERSION, 2);
assert_eq!(PORT, 2049);
assert_eq!(MAX_DATA, 8192);
}
}