1use crate::error::PortmapError;
2use crate::types::{PMAP_PROG, PROGRAM, VERSION, mapping, pmaplist};
3use onc_rpc_client::RpcClient;
4use onc_rpc_client::RpcError;
5use onc_rpc_client::transport::io::{AsyncRead, AsyncWrite};
6use onc_xdr::{Pack, Unpack, Void};
7
8#[derive(Debug)]
10pub struct PortmapperClient<IO> {
11 rpc: RpcClient<IO>,
12}
13
14impl<IO> PortmapperClient<IO>
15where
16 IO: AsyncRead + AsyncWrite + Send,
17{
18 pub fn new(io: IO) -> Self {
23 Self { rpc: RpcClient::new(io) }
24 }
25
26 pub async fn null(&mut self) -> Result<(), RpcError> {
28 let _ = self.call::<Void, Void>(PMAP_PROG::PMAPPROC_NULL, Void).await?;
29 Ok(())
30 }
31
32 #[expect(clippy::similar_names, reason = "prog and prot are standard names used in portmapper")]
34 pub async fn set(&mut self, prog: u32, vers: u32, prot: u32, port: u32) -> Result<bool, RpcError> {
35 let args = mapping { prog, vers, prot, port };
36 self.call::<mapping, bool>(PMAP_PROG::PMAPPROC_SET, args).await
37 }
38
39 #[expect(clippy::similar_names, reason = "prog and prot are standard names used in portmapper")]
41 pub async fn unset(&mut self, prog: u32, vers: u32, prot: u32, port: u32) -> Result<bool, RpcError> {
42 let args = mapping { prog, vers, prot, port };
43 self.call::<mapping, bool>(PMAP_PROG::PMAPPROC_UNSET, args).await
44 }
45
46 #[expect(clippy::similar_names, reason = "prog and prot are standard names used in portmapper")]
49 pub async fn getport(&mut self, prog: u32, vers: u32, prot: u32) -> Result<u16, PortmapError> {
50 let args = mapping { prog, vers, prot, port: 0 };
51
52 let port = self.call::<mapping, u32>(PMAP_PROG::PMAPPROC_GETPORT, args).await?;
53
54 let port_u16: Result<u16, _> = port.try_into();
55 match port_u16 {
56 Ok(0) => Err(PortmapError::ProgramUnavailable),
57 Ok(port) => Ok(port),
58 Err(_) => Err(PortmapError::InvalidPortValue(port)),
59 }
60 }
61
62 pub async fn dump(&mut self) -> Result<Vec<mapping>, RpcError> {
64 let mappings = self.call::<Void, pmaplist>(PMAP_PROG::PMAPPROC_DUMP, Void).await?;
65 Ok(mappings.into_inner())
66 }
67
68 #[expect(clippy::similar_names, reason = "prog and proc are the RFC field names")]
76 pub async fn callit(&mut self, prog: u32, vers: u32, proc: u32, args: &[u8]) -> Result<crate::types::call_result<'static>, RpcError> {
77 let call = crate::types::call_args { prog, vers, proc, args: onc_xdr::Opaque::borrowed(args) };
78 self.call::<crate::types::call_args<'_>, crate::types::call_result<'static>>(PMAP_PROG::PMAPPROC_CALLIT, call).await
79 }
80
81 async fn call<C, R>(&mut self, proc: PMAP_PROG, args: C) -> Result<R, RpcError>
83 where
84 R: Unpack,
85 C: Pack + Send + Sync,
86 {
87 self.rpc.call::<C, R>(PROGRAM, VERSION, proc as u32, &args).await
88 }
89}