use crate::rpc::Program;
use crate::rpc::nfs2::{ErrorStatus, FHANDLE_LEN, FileHandle, NfsResult, Status};
use crate::rpc::xdr::{self, Utf16LeString};
use crate::{Error, Result, Slot};
pub const PROGRAM: Program = Program::MOUNT;
pub const VERSION: u32 = 1;
pub const PIONEER_PORT: u16 = 48276;
pub const EXPORT_SD: &str = "/B/";
pub const EXPORT_USB: &str = "/C/";
pub const EXPORT_REKORDBOX: &str = "/";
const MAX_ENTRIES: usize = 64;
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub struct Proc(pub u32);
impl Proc {
pub const NULL: Self = Self(0);
pub const MNT: Self = Self(1);
pub const DUMP: Self = Self(2);
pub const UMNT: Self = Self(3);
pub const UMNTALL: Self = Self(4);
pub const EXPORT: Self = Self(5);
pub fn name(self) -> Option<&'static str> {
Some(match self {
Self::NULL => "NULL",
Self::MNT => "MNT",
Self::DUMP => "DUMP",
Self::UMNT => "UMNT",
Self::UMNTALL => "UMNTALL",
Self::EXPORT => "EXPORT",
_ => return None,
})
}
}
impl core::fmt::Debug for Proc {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self.name() {
Some(name) => f.write_str(name),
None => write!(f, "mount::Proc({})", self.0),
}
}
}
pub fn export_path_for(slot: Slot) -> Option<&'static str> {
Some(match slot {
Slot::SD => EXPORT_SD,
Slot::USB => EXPORT_USB,
Slot::REKORDBOX => EXPORT_REKORDBOX,
_ => return None,
})
}
pub fn slot_for_export(path: &str) -> Option<Slot> {
if path.starts_with(EXPORT_SD) {
Some(Slot::SD)
} else if path.starts_with(EXPORT_USB) {
Some(Slot::USB)
} else if path == EXPORT_REKORDBOX {
Some(Slot::REKORDBOX)
} else {
None
}
}
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct Export {
pub path: Utf16LeString,
pub groups: Vec<String>,
}
impl Export {
pub fn new(path: &str, groups: &[&str]) -> Self {
Self {
path: Utf16LeString::new(path),
groups: groups.iter().map(|group| (*group).to_owned()).collect(),
}
}
pub const LINK_LOCAL_SUBNET: &'static str = "169.254.0.0/255.255.0.0";
}
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct MountEntry {
pub hostname: String,
pub directory: Utf16LeString,
}
#[derive(Clone, PartialEq, Eq, Debug)]
pub enum Request {
Null,
Mnt(Utf16LeString),
Dump,
Umnt(Utf16LeString),
UmntAll,
Export,
Unknown {
procedure: Proc,
arguments: Vec<u8>,
},
}
impl Request {
pub fn procedure(&self) -> Proc {
match self {
Self::Null => Proc::NULL,
Self::Mnt(_) => Proc::MNT,
Self::Dump => Proc::DUMP,
Self::Umnt(_) => Proc::UMNT,
Self::UmntAll => Proc::UMNTALL,
Self::Export => Proc::EXPORT,
Self::Unknown { procedure, .. } => *procedure,
}
}
pub fn path(&self) -> Option<&Utf16LeString> {
match self {
Self::Mnt(path) | Self::Umnt(path) => Some(path),
_ => None,
}
}
pub fn encode_arguments(&self) -> Vec<u8> {
let mut out = xdr::Writer::with_capacity(16);
match self {
Self::Null | Self::Dump | Self::UmntAll | Self::Export => {}
Self::Mnt(path) | Self::Umnt(path) => out.utf16le_string(path),
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::DUMP => Self::Dump,
Proc::UMNTALL => Self::UmntAll,
Proc::EXPORT => Self::Export,
Proc::MNT => Self::Mnt(input.utf16le_string(xdr::MAX_STRING)?),
Proc::UMNT => Self::Umnt(input.utf16le_string(xdr::MAX_STRING)?),
other => Self::Unknown {
procedure: other,
arguments: arguments.to_vec(),
},
})
}
}
#[derive(Clone, PartialEq, Eq, Debug)]
pub enum Response {
Null,
Mnt(NfsResult<FileHandle>),
Dump(Vec<MountEntry>),
Umnt,
UmntAll,
Export(Vec<Export>),
}
impl Response {
pub fn procedure(&self) -> Proc {
match self {
Self::Null => Proc::NULL,
Self::Mnt(_) => Proc::MNT,
Self::Dump(_) => Proc::DUMP,
Self::Umnt => Proc::UMNT,
Self::UmntAll => Proc::UMNTALL,
Self::Export(_) => Proc::EXPORT,
}
}
pub fn encode(&self) -> Vec<u8> {
let mut out = xdr::Writer::with_capacity(48);
match self {
Self::Null | Self::Umnt | Self::UmntAll => {}
Self::Mnt(Ok(handle)) => {
out.u32(Status::OK.0);
out.opaque_fixed(handle.as_bytes());
}
Self::Mnt(Err(status)) => out.u32(status.status().0),
Self::Dump(entries) => {
for entry in entries {
out.bool(true);
out.ascii_string(&entry.hostname);
out.utf16le_string(&entry.directory);
}
out.bool(false);
}
Self::Export(exports) => {
for export in exports {
out.bool(true);
out.utf16le_string(&export.path);
for group in &export.groups {
out.bool(true);
out.ascii_string(group);
}
out.bool(false);
}
out.bool(false);
}
}
out.into_bytes()
}
pub fn parse(procedure: Proc, results: &[u8]) -> Result<Self> {
let mut input = xdr::Reader::new(results);
Ok(match procedure {
Proc::NULL => Self::Null,
Proc::UMNT => Self::Umnt,
Proc::UMNTALL => Self::UmntAll,
Proc::MNT => match ErrorStatus::new(Status(input.u32()?)) {
None => Self::Mnt(Ok(FileHandle::parse(input.opaque_fixed(FHANDLE_LEN)?)?)),
Some(status) => Self::Mnt(Err(status)),
},
Proc::DUMP => Self::Dump(parse_dump(&mut input)?),
Proc::EXPORT => Self::Export(parse_exports(&mut input)?),
other => {
return Err(Error::malformed(
0,
format!("no reply decoder for MOUNT procedure {other:?}"),
));
}
})
}
}
fn parse_dump(input: &mut xdr::Reader<'_>) -> Result<Vec<MountEntry>> {
let mut entries = Vec::new();
while input.bool()? {
entries.push(MountEntry {
hostname: input.ascii_string(xdr::MAX_STRING)?,
directory: input.utf16le_string(xdr::MAX_STRING)?,
});
if entries.len() > MAX_ENTRIES {
return Err(too_many("a MOUNT DUMP listing", entries.len()));
}
}
Ok(entries)
}
fn parse_exports(input: &mut xdr::Reader<'_>) -> Result<Vec<Export>> {
let mut exports = Vec::new();
while input.bool()? {
let path = input.utf16le_string(xdr::MAX_STRING)?;
let mut groups = Vec::new();
while input.bool()? {
groups.push(input.ascii_string(xdr::MAX_STRING)?);
if groups.len() > MAX_ENTRIES {
return Err(too_many("an EXPORT group list", groups.len()));
}
}
exports.push(Export { path, groups });
if exports.len() > MAX_ENTRIES {
return Err(too_many("an EXPORT listing", exports.len()));
}
}
Ok(exports)
}
fn too_many(what: &'static str, seen: usize) -> Error {
Error::ImplausibleLength {
what,
length: u64::try_from(seen).unwrap_or(u64::MAX),
limit: u64::try_from(MAX_ENTRIES).unwrap_or(u64::MAX),
}
}
#[cfg(test)]
mod tests {
use super::*;
const ROOT_HANDLE: [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,
];
#[test]
fn a_mnt_call_carries_a_utf16le_path_counted_in_bytes() {
let request = Request::Mnt(Utf16LeString::new(EXPORT_USB));
assert_eq!(
request.encode_arguments(),
[
0x00, 0x00, 0x00, 0x06, 0x2f, 0x00, 0x43, 0x00, 0x2f, 0x00, 0x00, 0x00
]
);
assert_eq!(
Request::parse(Proc::MNT, &request.encode_arguments()).unwrap(),
request
);
}
#[test]
fn a_mnt_reply_is_a_status_then_a_bare_filehandle() {
let response = Response::Mnt(Ok(FileHandle(ROOT_HANDLE)));
let encoded = response.encode();
assert_eq!(encoded.len(), 4 + 32);
assert_eq!(encoded.get(..4), Some([0, 0, 0, 0].as_slice()));
assert_eq!(encoded.get(4..), Some(ROOT_HANDLE.as_slice()));
assert_eq!(Response::parse(Proc::MNT, &encoded).unwrap(), response);
}
#[test]
fn a_refused_mount_carries_only_a_status() {
let response = Response::Mnt(Err(ErrorStatus::ACCES));
assert_eq!(response.encode(), [0, 0, 0, 13]);
assert_eq!(
Response::parse(Proc::MNT, &[0, 0, 0, 13]).unwrap(),
response
);
}
#[test]
fn umnt_is_a_mnt_by_another_procedure_number() {
let sd = Request::Umnt(Utf16LeString::new(EXPORT_SD));
let usb = Request::Umnt(Utf16LeString::new(EXPORT_USB));
assert_eq!(sd.procedure(), Proc::UMNT);
assert_eq!(
sd.encode_arguments(),
Request::Mnt(Utf16LeString::new(EXPORT_SD)).encode_arguments(),
"same argument shape, different procedure"
);
assert_eq!(
Request::parse(Proc::UMNT, &usb.encode_arguments()).unwrap(),
usb
);
assert!(Response::Umnt.encode().is_empty());
}
#[test]
fn an_export_reply_has_a_utf16le_path_and_ascii_groups() {
let export = Export::new(EXPORT_USB, &[Export::LINK_LOCAL_SUBNET]);
let encoded = Response::Export(vec![export.clone()]).encode();
assert_eq!(
encoded.get(..4),
Some([0, 0, 0, 1].as_slice()),
"a value follows"
);
assert_eq!(
encoded.get(4..16),
Some(
[
0x00, 0x00, 0x00, 0x06, 0x2f, 0x00, 0x43, 0x00, 0x2f, 0x00, 0x00, 0x00
]
.as_slice()
),
"the path is UTF-16LE, six bytes for three characters"
);
assert_eq!(
encoded.get(20..24),
Some(23u32.to_be_bytes().as_slice()),
"the group is ASCII, so 23 characters announce 23 bytes, not 46"
);
assert_eq!(
encoded.get(24..47),
Some(b"169.254.0.0/255.255.0.0".as_slice()),
"one byte per character; decoding this as UTF-16LE gives mojibake"
);
let parsed = Response::parse(Proc::EXPORT, &encoded).unwrap();
assert_eq!(parsed, Response::Export(vec![export]));
let Response::Export(exports) = parsed else {
panic!("expected an export listing");
};
assert_eq!(
exports.first().map(|e| e.path.to_string_lossy()),
Some("/C/".to_owned())
);
assert_eq!(
exports
.first()
.and_then(|e| e.groups.first())
.map(String::as_str),
Some("169.254.0.0/255.255.0.0"),
"the whole link-local subnet: the mechanism behind passive access"
);
}
#[test]
fn an_export_with_two_per_host_groups_round_trips() {
let export = Export::new(
"/C/EXPORT",
&[
"169.254.244.181/255.255.255.255",
"169.254.192.112/255.255.255.255",
],
);
let encoded = Response::Export(vec![export.clone()]).encode();
assert_eq!(
Response::parse(Proc::EXPORT, &encoded).unwrap(),
Response::Export(vec![export])
);
}
#[test]
fn an_empty_export_list_is_a_bare_false() {
assert_eq!(Response::Export(Vec::new()).encode(), [0, 0, 0, 0]);
assert_eq!(
Response::parse(Proc::EXPORT, &[0, 0, 0, 0]).unwrap(),
Response::Export(Vec::new())
);
}
#[test]
fn an_export_path_is_matched_on_its_prefix() {
assert_eq!(slot_for_export("/C/"), Some(Slot::USB));
assert_eq!(slot_for_export("/C/EXPORT"), Some(Slot::USB));
assert_eq!(slot_for_export("/B/"), Some(Slot::SD));
assert_eq!(slot_for_export("/B/EXPORT"), Some(Slot::SD));
assert_eq!(slot_for_export("/"), Some(Slot::REKORDBOX));
assert_eq!(
slot_for_export("/A/"),
None,
"used by no observed client and presumed internal"
);
assert_eq!(slot_for_export(""), None);
}
#[test]
fn the_rekordbox_export_does_not_swallow_the_others() {
assert_eq!(slot_for_export("/C/"), Some(Slot::USB));
assert_ne!(slot_for_export("/C/"), Some(Slot::REKORDBOX));
}
#[test]
fn the_documented_export_table_round_trips_through_the_matcher() {
for slot in [Slot::SD, Slot::USB, Slot::REKORDBOX] {
let path = export_path_for(slot).unwrap();
assert_eq!(slot_for_export(path), Some(slot), "{slot:?} -> {path}");
}
assert_eq!(export_path_for(Slot::CD), None, "the CD slot has no export");
assert_eq!(export_path_for(Slot::NONE), None);
}
#[test]
fn a_dump_listing_round_trips() {
let entries = vec![MountEntry {
hostname: "169.254.99.100".to_owned(),
directory: Utf16LeString::new(EXPORT_USB),
}];
let encoded = Response::Dump(entries.clone()).encode();
assert_eq!(
Response::parse(Proc::DUMP, &encoded).unwrap(),
Response::Dump(entries)
);
}
#[test]
fn export_and_umntall_take_no_arguments() {
for request in [
Request::Export,
Request::UmntAll,
Request::Dump,
Request::Null,
] {
assert!(request.encode_arguments().is_empty());
assert_eq!(Request::parse(request.procedure(), &[]).unwrap(), request);
}
}
#[test]
fn a_truncated_mnt_path_is_truncation_not_garbage() {
let error = Request::parse(Proc::MNT, &[0, 0, 0, 6, 0x2f]).unwrap_err();
assert!(error.is_truncated(), "{error:?}");
}
#[test]
fn a_hostile_mnt_path_length_is_refused_before_allocating() {
let error = Request::parse(Proc::MNT, &[0xff, 0xff, 0xff, 0xff]).unwrap_err();
assert!(
matches!(error, Error::ImplausibleLength { .. }),
"{error:?}"
);
}
#[test]
fn the_observed_port_and_program_numbers() {
assert_eq!(PROGRAM.0, 100_005);
assert_eq!(VERSION, 1);
assert_eq!(PIONEER_PORT, 48276, "three devices, same number (F6)");
}
}