use crate::rpc::xdr;
use crate::rpc::{IpProtocol, Program};
use crate::{Error, Result};
pub const PROGRAM: Program = Program::PORTMAP;
pub const VERSION: u32 = 2;
pub const PORT: u16 = 111;
const MAX_MAPPINGS: usize = 512;
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub struct Proc(pub u32);
impl Proc {
pub const NULL: Self = Self(0);
pub const SET: Self = Self(1);
pub const UNSET: Self = Self(2);
pub const GETPORT: Self = Self(3);
pub const DUMP: Self = Self(4);
pub const CALLIT: Self = Self(5);
pub fn name(self) -> Option<&'static str> {
Some(match self {
Self::NULL => "NULL",
Self::SET => "SET",
Self::UNSET => "UNSET",
Self::GETPORT => "GETPORT",
Self::DUMP => "DUMP",
Self::CALLIT => "CALLIT",
_ => 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, "portmap::Proc({})", self.0),
}
}
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub struct Mapping {
pub program: Program,
pub version: u32,
pub protocol: IpProtocol,
pub port: u32,
}
impl Mapping {
pub fn query(program: Program, version: u32, protocol: IpProtocol) -> Self {
Self {
program,
version,
protocol,
port: 0,
}
}
pub fn registered(program: Program, version: u32, protocol: IpProtocol, port: u16) -> Self {
Self {
program,
version,
protocol,
port: u32::from(port),
}
}
fn write(&self, out: &mut xdr::Writer) {
out.u32(self.program.0);
out.u32(self.version);
out.u32(self.protocol.0);
out.u32(self.port);
}
fn read(input: &mut xdr::Reader<'_>) -> Result<Self> {
Ok(Self {
program: Program(input.u32()?),
version: input.u32()?,
protocol: IpProtocol(input.u32()?),
port: input.u32()?,
})
}
}
pub fn cdj_registrations(portmap_port: u16, mount_port: u16, nfs_port: u16) -> [Mapping; 3] {
[
Mapping::registered(
Program::NFS,
super::nfs2::VERSION,
IpProtocol::UDP,
nfs_port,
),
Mapping::registered(
Program::MOUNT,
super::mount::VERSION,
IpProtocol::UDP,
mount_port,
),
Mapping::registered(Program::PORTMAP, VERSION, IpProtocol::UDP, portmap_port),
]
}
#[derive(Clone, PartialEq, Eq, Debug)]
pub enum Request {
Null,
GetPort(Mapping),
Dump,
Unknown {
procedure: Proc,
arguments: Vec<u8>,
},
}
impl Request {
pub fn procedure(&self) -> Proc {
match self {
Self::Null => Proc::NULL,
Self::GetPort(_) => Proc::GETPORT,
Self::Dump => Proc::DUMP,
Self::Unknown { procedure, .. } => *procedure,
}
}
pub fn encode_arguments(&self) -> Vec<u8> {
let mut out = xdr::Writer::with_capacity(16);
match self {
Self::Null | Self::Dump => {}
Self::GetPort(mapping) => mapping.write(&mut out),
Self::Unknown { arguments, .. } => out.raw(arguments),
}
out.into_bytes()
}
pub fn parse(procedure: Proc, arguments: &[u8]) -> Result<Self> {
Ok(match procedure {
Proc::NULL => Self::Null,
Proc::DUMP => Self::Dump,
Proc::GETPORT => Self::GetPort(Mapping::read(&mut xdr::Reader::new(arguments))?),
other => Self::Unknown {
procedure: other,
arguments: arguments.to_vec(),
},
})
}
}
#[derive(Clone, PartialEq, Eq, Debug)]
pub enum Response {
Null,
GetPort(Option<u16>),
Dump(Vec<Mapping>),
}
impl Response {
pub fn procedure(&self) -> Proc {
match self {
Self::Null => Proc::NULL,
Self::GetPort(_) => Proc::GETPORT,
Self::Dump(_) => Proc::DUMP,
}
}
pub fn encode(&self) -> Vec<u8> {
let mut out = xdr::Writer::with_capacity(32);
match self {
Self::Null => {}
Self::GetPort(port) => out.u32(u32::from(port.unwrap_or(0))),
Self::Dump(mappings) => {
for mapping in mappings {
out.bool(true);
mapping.write(&mut out);
}
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::GETPORT => {
let raw = input.u32()?;
if raw == 0 {
Self::GetPort(None)
} else {
Self::GetPort(Some(u16::try_from(raw).map_err(|_| {
Error::malformed(0, format!("{raw} is not a port number"))
})?))
}
}
Proc::DUMP => {
let mut mappings = Vec::new();
while input.bool()? {
mappings.push(Mapping::read(&mut input)?);
if mappings.len() > MAX_MAPPINGS {
return Err(Error::ImplausibleLength {
what: "a portmap DUMP listing",
length: u64::try_from(mappings.len()).unwrap_or(u64::MAX),
limit: u64::try_from(MAX_MAPPINGS).unwrap_or(u64::MAX),
});
}
}
Self::Dump(mappings)
}
other => {
return Err(Error::malformed(
0,
format!("no reply decoder for portmap procedure {other:?}"),
));
}
})
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::rpc::mount;
#[test]
fn getport_arguments_are_four_words() {
let request = Request::GetPort(Mapping::query(Program::NFS, 2, IpProtocol::UDP));
let args = request.encode_arguments();
assert_eq!(
args,
[
0x00, 0x01, 0x86, 0xa3, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x11, 0x00, 0x00, 0x00, 0x00, ]
);
assert_eq!(Request::parse(Proc::GETPORT, &args).unwrap(), request);
}
#[test]
fn a_deck_asks_for_mountd_by_program_number_not_by_port() {
let request = Request::GetPort(Mapping::query(Program::MOUNT, 1, IpProtocol::UDP));
assert_eq!(
request.encode_arguments().get(..8),
Some([0x00, 0x01, 0x86, 0xa5, 0x00, 0x00, 0x00, 0x01].as_slice()),
"100005 v1"
);
}
#[test]
fn a_getport_reply_is_a_single_word() {
let encoded = Response::GetPort(Some(2049)).encode();
assert_eq!(encoded, 2049u32.to_be_bytes());
assert_eq!(
Response::parse(Proc::GETPORT, &encoded).unwrap(),
Response::GetPort(Some(2049))
);
}
#[test]
fn getport_zero_means_the_program_is_not_registered() {
assert_eq!(
Response::parse(Proc::GETPORT, &[0, 0, 0, 0]).unwrap(),
Response::GetPort(None)
);
assert_eq!(Response::GetPort(None).encode(), [0, 0, 0, 0]);
}
#[test]
fn a_port_outside_sixteen_bits_is_refused() {
let error = Response::parse(Proc::GETPORT, &[0x00, 0x01, 0x00, 0x00]).unwrap_err();
assert!(matches!(error, Error::Malformed { .. }), "{error:?}");
}
#[test]
fn a_dump_reply_reproduces_the_observed_cdj_registration_table() {
let mappings = cdj_registrations(PORT, mount::PIONEER_PORT, super::super::nfs2::PORT);
assert_eq!(
mappings,
[
Mapping::registered(Program::NFS, 2, IpProtocol::UDP, 2049),
Mapping::registered(Program::MOUNT, 1, IpProtocol::UDP, 48276),
Mapping::registered(Program::PORTMAP, 2, IpProtocol::UDP, 111),
]
);
let encoded = Response::Dump(mappings.to_vec()).encode();
assert_eq!(
encoded.len(),
3 * (4 + 16) + 4,
"three elements, each behind a value-follows word, then a false"
);
assert_eq!(
encoded.get(encoded.len() - 4..),
Some([0, 0, 0, 0].as_slice()),
"the list terminator"
);
assert_eq!(
Response::parse(Proc::DUMP, &encoded).unwrap(),
Response::Dump(mappings.to_vec())
);
}
#[test]
fn an_empty_dump_is_a_bare_false() {
assert_eq!(Response::Dump(Vec::new()).encode(), [0, 0, 0, 0]);
assert_eq!(
Response::parse(Proc::DUMP, &[0, 0, 0, 0]).unwrap(),
Response::Dump(Vec::new())
);
}
#[test]
fn null_takes_and_returns_nothing() {
assert!(Request::Null.encode_arguments().is_empty());
assert_eq!(Request::parse(Proc::NULL, &[]).unwrap(), Request::Null);
assert!(Response::Null.encode().is_empty());
}
#[test]
fn set_and_unset_decode_as_unknown_so_they_can_be_refused() {
for proc in [Proc::SET, Proc::UNSET, Proc::CALLIT] {
let request = Request::parse(proc, &[9; 16]).unwrap();
assert_eq!(request.procedure(), proc);
assert!(matches!(request, Request::Unknown { .. }));
}
}
#[test]
fn a_truncated_getport_is_truncation_not_garbage() {
let error = Request::parse(Proc::GETPORT, &[0, 0, 0, 1]).unwrap_err();
assert!(error.is_truncated(), "{error:?}");
}
#[test]
fn the_portmapper_is_on_the_well_known_port() {
assert_eq!(PROGRAM.0, 100_000);
assert_eq!(VERSION, 2);
assert_eq!(PORT, 111);
}
}