flesh out UDP API...as much as we can

Multicast/Broadcast is not supported by smoltcp it seems, so those
calls are just unimplemented. But we are able to clone UdpSocket,
for the sick puppies who like to do that sort of thing.
This commit is contained in:
bunnie 2021-10-19 04:42:06 +08:00
parent 0cbca7fbe1
commit 40771fbba7
4 changed files with 246 additions and 34 deletions

View file

@ -14,6 +14,8 @@ pub(crate) enum Opcode {
UdpBind,
UdpClose,
UdpTx,
UdpSetTtl,
UdpGetTtl,
/// initiates a ping packet
//PingSend,

View file

@ -10,10 +10,10 @@ use std::thread::JoinHandle;
use smoltcp::wire::{Ipv4Address, Ipv6Address, IpAddress};
use smoltcp::{
wire::IpEndpoint,
time::{Duration, Instant},
time::Duration,
};
use xous::{CID, SID, Message, msg_blocking_scalar_unpack};
use xous::{CID, Message, SID, msg_blocking_scalar_unpack, send_message};
use xous_ipc::Buffer;
use crate::NetConn;
use crate::api::*;
@ -39,6 +39,8 @@ pub struct UdpSocket{
write_timeout: Option<Duration>,
ticktimer: ticktimer_server::Ticktimer,
dest_socket: Option<SocketAddr>,
max_payload: Option<u16>,
nonblocking: bool,
}
// next steps: build this stub, and figure out how to clean up the error handling code.
@ -142,6 +144,8 @@ impl UdpSocket {
write_timeout: None,
ticktimer: ticktimer_server::Ticktimer::new().unwrap(),
dest_socket: None,
max_payload,
nonblocking: false,
})
},
_ => {
@ -149,6 +153,7 @@ impl UdpSocket {
}
}
}
pub fn get_nonblocking(&self) -> bool { self.nonblocking }
pub fn set_scalar_notification(&mut self, cid: CID, op: usize, args: [Option<usize>; 4]) {
self.notify.lock().unwrap().set(cid, op, args);
@ -212,6 +217,8 @@ impl UdpSocket {
self.rx_buf.lock().unwrap().insert(0, rx_pkt);
}
return Ok(len);
} else if self.nonblocking {
return Err(Error::new(ErrorKind::WouldBlock, "Nonblocking mode: Rx is empty"));
}
if timeout > self.ticktimer.elapsed_ms() {
return Err(Error::new(ErrorKind::WouldBlock, "UDP Rx timeout reached"));
@ -360,13 +367,63 @@ impl UdpSocket {
}
pub fn peer_addr(&self) -> io::Result<SocketAddr> {
unimplemented!("work in progress")
match self.dest_socket {
Some(dest) => {
Ok(dest)
}
None => {
Err(Error::new(ErrorKind::NotConnected, "No peer specified"))
}
}
}
pub fn duplicate(&self) -> io::Result<UdpSocket> {
unimplemented!("work in progress")
// do the basic clone connection
let mut cloned_socket = UdpSocket::bind_inner(Ok(&self.socket_addr), self.max_payload)?;
// now copy all the properties over as required by spec
cloned_socket.set_read_timeout(self.read_timeout)?;
cloned_socket.set_write_timeout(self.write_timeout)?;
if let Some(sa) = self.dest_socket {
cloned_socket.connect(Ok(&sa))?
}
cloned_socket.set_nonblocking(self.get_nonblocking())?;
// TTL doesn't need to be cloned because it is attached to the port itself in the Net server
Ok(cloned_socket)
}
pub fn set_ttl(&self, ttl: u32) -> io::Result<()> {
if ttl > 255 {
return Err(Error::new(ErrorKind::InvalidInput, "TTL must be less than 256"))
}
send_message(
self.net.conn(),
Message::new_scalar(Opcode::UdpSetTtl.to_usize().unwrap(), ttl as usize, self.socket_addr.port() as usize, 0, 0)
).map_or_else(|_| Ok(()), |_| Err(Error::new(ErrorKind::ConnectionRefused, "can't send TTL set message")))
}
pub fn ttl(&self) -> io::Result<u32> {
let result = send_message(
self.net.conn(),
Message::new_blocking_scalar(Opcode::UdpGetTtl.to_usize().unwrap(), self.socket_addr.port() as usize, 0, 0, 0)
).expect("couldn't retrieve TTL value");
if let xous::Result::Scalar1(ttl) = result {
Ok(ttl as u32)
} else {
Err(Error::new(ErrorKind::ConnectionRefused, "can't get TTL value from Net server"))
}
}
pub fn take_error(&self) -> io::Result<Option<io::Error>> {
// we don't have stateful errors, yet?...
Ok(None)
}
pub fn set_nonblocking(&mut self, nb: bool) -> io::Result<()> {
self.nonblocking = nb;
Ok(())
}
//////// the remaining functions are currently unimplemented: we don't have multicast or broadcast support //////////
pub fn set_broadcast(&self, _: bool) -> io::Result<()> {
unimplemented!("work in progress")
}
@ -399,22 +456,6 @@ impl UdpSocket {
unimplemented!("work in progress")
}
pub fn set_ttl(&self, _: u32) -> io::Result<()> {
unimplemented!("work in progress")
}
pub fn ttl(&self) -> io::Result<u32> {
unimplemented!("work in progress")
}
pub fn take_error(&self) -> io::Result<Option<io::Error>> {
unimplemented!("work in progress")
}
pub fn set_nonblocking(&self, _: bool) -> io::Result<()> {
unimplemented!("work in progress")
}
pub fn set_multicast_loop_v6(&self, _: bool) -> io::Result<()> {
unimplemented!("ipv6 not implemented")
}

View file

@ -9,8 +9,7 @@ use com::api::{ComIntSources, Ipv4Conf, NET_MTU};
mod device;
use byteorder::{ByteOrder, NetworkEndian};
use xous::msg_scalar_unpack;
use xous::{send_message, Message};
use xous::{send_message, Message, CID, SID, msg_scalar_unpack, msg_blocking_scalar_unpack};
use xous_ipc::Buffer;
use std::collections::BTreeMap;
use std::collections::HashMap;
@ -99,7 +98,8 @@ enum WaitOp {
pub struct UdpState {
handle: SocketHandle,
cid: xous::CID,
cid: CID,
sid: SID,
}
#[xous::xous_main]
@ -184,6 +184,10 @@ fn xmain() -> ! {
let mut sockets = SocketSet::new(vec![]);
let icmp_handle = sockets.add(icmp_socket);
let mut udp_handles = HashMap::<u16, UdpState>::new();
// UDP requires multiple copies. The way it works is that Tx can come from anyone;
// for Rx, copies of a CID,SID tuple are kept for every clone is kept in a HashMap. This
// allows for the Rx data to be cc:'d to each clone, and identified by SID upon drop
let mut udp_clones = HashMap::<u16, HashMap::<[u32; 4], CID>>::new(); // additional clones for UDP responders
let mut send_at = Instant::from_millis(0);
let mut seq_no = 0;
@ -220,8 +224,13 @@ fn xmain() -> ! {
let sr_cid = xous::connect(net_sid).expect("couldn't create suspend callback connection");
let mut susres = susres::Susres::new(&xns, api::Opcode::SuspendResume as u32, sr_cid).expect("couldn't create suspend/resume object");
let mut cid_to_disconnect: Option<CID> = None;
loop {
let mut msg = xous::receive_message(net_sid).unwrap();
if let Some(_dc_cid) = cid_to_disconnect.take() { // disconnect previous loop iter's connection after d/c OK response was sent
// CHECK WITH XOBS: maybe these connections are auto-closed when the server is destroyed?
// unsafe{xous::disconnect(dc_cid).expect("couldn't disconnect from dropped UDP object")};
}
match FromPrimitive::from_usize(msg.body.id()) {
Some(Opcode::UdpBind) => {
let mut buf = unsafe{Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap())};
@ -233,17 +242,39 @@ fn xmain() -> ! {
NET_MTU as usize
};
if udp_handles.contains_key(&udpspec.port) {
log::error!("Attempt to bind to udp:{}, already in use.", udpspec.port);
buf.replace(NetMemResponse::SocketInUse).unwrap();
// if we're already connected, just register the extra listener in the clones array
let sid = udpspec.cb_sid;
let cid = xous::connect(SID::from_array(sid)).unwrap();
if let Some(clone_map) = udp_clones.get_mut(&udpspec.port) {
// if a clone already exists, put the additional clone into the map
match clone_map.insert(sid, cid) {
Some(_) => {
log::error!("Something went wrong in a UDP clone operation -- same SID registered twice");
buf.replace(NetMemResponse::SocketInUse).unwrap()
}, // the same SID has double-registered, this is an error
None => buf.replace(NetMemResponse::Ok).unwrap()
}
} else {
// otherwise, create the clone mapping entry
let mut newmap = HashMap::new();
newmap.insert(sid, cid);
udp_clones.insert(
udpspec.port,
newmap
);
}
buf.replace(NetMemResponse::Ok).unwrap();
} else {
let udp_rx_buffer = UdpSocketBuffer::new(vec![UdpPacketMetadata::EMPTY], vec![0; buflen]);
let udp_tx_buffer = UdpSocketBuffer::new(vec![UdpPacketMetadata::EMPTY], vec![0; buflen]);
let mut udp_socket = UdpSocket::new(udp_rx_buffer, udp_tx_buffer);
match udp_socket.bind(udpspec.port) {
Ok(_) => {
let sid = SID::from_array(udpspec.cb_sid);
let udpstate = UdpState {
handle: sockets.add(udp_socket),
cid: xous::connect(xous::SID::from_array(udpspec.cb_sid)).unwrap(),
cid: xous::connect(sid).unwrap(),
sid
};
udp_handles.insert(udpspec.port, udpstate);
buf.replace(NetMemResponse::Ok).unwrap();
@ -258,10 +289,57 @@ fn xmain() -> ! {
Some(Opcode::UdpClose) => {
let mut buf = unsafe{Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap())};
let udpspec = buf.to_original::<NetUdpBind, _>().unwrap();
// need to find the SID that matches either in the clone array, or the primary binding.
// first check the clone array, then fall back to the primary binding
match udp_clones.get_mut(&udpspec.port) {
Some(clone_map) => {
match clone_map.remove(&udpspec.cb_sid) {
Some(cid) => {
cid_to_disconnect = Some(cid);
buf.replace(NetMemResponse::Ok).unwrap();
continue;
}
None => {}
}
}
None => {}
}
match udp_handles.remove(&udpspec.port) {
Some(udpstate) => {
sockets.get::<UdpSocket>(udpstate.handle).close();
buf.replace(NetMemResponse::Ok).unwrap()
if udpstate.sid == SID::from_array(udpspec.cb_sid) {
match udp_clones.get_mut(&udpspec.port) {
// if the clone map is nil, close the socket, we're done
None => {
sockets.get::<UdpSocket>(udpstate.handle).close();
buf.replace(NetMemResponse::Ok).unwrap();
}
// if the clone map has entries, promote an arbitrary map entry to the primary handle
Some(clone_map) => {
if clone_map.len() == 0 {
// removing SIDs doesn't remove the map, so it's possible to have an empty mapping. Get rid of it, and we're done.
udp_clones.remove(&udpspec.port);
sockets.get::<UdpSocket>(udpstate.handle).close();
buf.replace(NetMemResponse::Ok).unwrap();
} else {
// take an arbitrary key, re-insert it into the handles map.
let new_primary_sid = *clone_map.keys().next().unwrap(); // unwrap is appropriate because len already checked as not 0
let udpstate = UdpState {
handle: udpstate.handle,
cid: *clone_map.get(&new_primary_sid).unwrap(),
sid: SID::from_array(new_primary_sid),
};
udp_handles.insert(udpspec.port, udpstate);
// now remove it from the clone map
clone_map.remove(&new_primary_sid);
// clean up the clone map if it's empty
if clone_map.len() == 0 {
udp_clones.remove(&udpspec.port);
}
buf.replace(NetMemResponse::Ok).unwrap();
}
}
}
}
}
_ => {
buf.replace(NetMemResponse::Invalid).unwrap()
@ -291,6 +369,36 @@ fn xmain() -> ! {
_ => buf.replace(NetMemResponse::Invalid).unwrap()
}
},
Some(Opcode::UdpSetTtl) => msg_scalar_unpack!(msg, ttl, port, _, _, {
match udp_handles.get_mut(&(port as u16)) {
Some(udpstate) => {
let mut socket = sockets.get::<UdpSocket>(udpstate.handle);
let checked_ttl = if ttl > 255 || ttl == 0 {
64
} else {
ttl as u8
};
socket.set_hop_limit(Some(checked_ttl));
}
None => {
log::error!("Set TTL message received, but no port was bound! port {} ttl {}", port, ttl);
}
}
}),
Some(Opcode::UdpGetTtl) => msg_blocking_scalar_unpack!(msg, port, _, _, _, {
match udp_handles.get_mut(&(port as u16)) {
Some(udpstate) => {
let socket = sockets.get::<UdpSocket>(udpstate.handle);
let ttl = socket.hop_limit().unwrap_or(64); // 64 is the value used by smoltcp if hop limit isn't set
xous::return_scalar(msg.sender, ttl as usize).expect("couldn't return TTL");
}
None => {
log::error!("Set TTL message received, but no port was bound! port {}", port);
xous::return_scalar(msg.sender, usize::MAX).expect("couldn't return TTL");
}
}
}),
Some(Opcode::ComInterrupt) => {
com_int_list.clear();
let maybe_rxlen = com.ints_get_active(&mut com_int_list);
@ -413,6 +521,13 @@ fn xmain() -> ! {
}
let buf = Buffer::into_buf(response).expect("couldn't convert UDP response to memory message");
buf.send(udpstate.cid, NetUdpCallback::RxData.to_u32().unwrap()).expect("couldn't send UDP response");
// now send copies to the cloned receiver array, if they exist
if let Some(clone_map) = udp_clones.get(port) {
for &cids in clone_map.values() {
let buf = Buffer::into_buf(response).expect("couldn't convert UDP response to memory message");
buf.send(cids, NetUdpCallback::RxData.to_u32().unwrap()).expect("couldn't send UDP response");
}
}
}
Err(_) => {
// do nothing

View file

@ -8,6 +8,7 @@ use std::net::SocketAddr;
#[derive(Debug)]
pub struct NetCmd {
udp: Option<net::UdpSocket>,
udp_clone: Option<net::UdpSocket>,
callback_id: Option<u32>,
callback_conn: u32,
udp_count: u32,
@ -16,6 +17,7 @@ impl NetCmd {
pub fn new(xns: &xous_names::XousNames) -> Self {
NetCmd {
udp: None,
udp_clone: None,
callback_id: None,
callback_conn: xns.request_connection_blocking(crate::SERVER_NAME_SHELLCHAT).unwrap(),
udp_count: 0,
@ -26,6 +28,7 @@ impl NetCmd {
#[derive(Debug, num_derive::FromPrimitive, num_derive::ToPrimitive)]
pub(crate) enum NetCmdDispatch {
UdpTest1,
UdpTest2,
}
pub const UDP_TEST_SIZE: usize = 64;
@ -47,12 +50,11 @@ impl<'a> ShellCmdApi<'a> for NetCmd {
if let Some(sub_cmd) = tokens.next() {
match sub_cmd {
/// Testing of udp is done with netcat:
/// to send packets run `netcat -u <precursor ip address> 6502` on a remote host, and then type some data
/// to receive packets, use `netcat -u -l 6502`, on the same remote host, and it should show a packet of counts received
// Testing of udp is done with netcat:
// to send packets run `netcat -u <precursor ip address> 6502` on a remote host, and then type some data
// to receive packets, use `netcat -u -l 6502`, on the same remote host, and it should show a packet of counts received
"udp" => {
if let Some(udp_socket) = &
self.udp {
if let Some(udp_socket) = &self.udp {
write!(ret, "Socket listener already installed on {:?}.", udp_socket.socket_addr().unwrap()).unwrap();
} else {
let port = if let Some(tok_str) = tokens.next() {
@ -74,6 +76,27 @@ impl<'a> ShellCmdApi<'a> for NetCmd {
write!(ret, "Created UDP socket listener on port {}", port).unwrap();
}
}
"udpclose" => {
self.udp = None;
}
"udpclone" => {
if let Some(udp_socket) = &self.udp {
let mut udp_clone = udp_socket.duplicate().unwrap();
udp_clone.set_scalar_notification(
self.callback_conn,
self.callback_id.unwrap() as usize, // this is guaranteed in the prelude
[Some(NetCmdDispatch::UdpTest2.to_usize().unwrap()), None, None, None]
);
let sa = udp_clone.socket_addr().unwrap();
self.udp_clone = Some(udp_clone);
write!(ret, "Cloned UDP socket on {:?}", sa).unwrap();
} else {
write!(ret, "Run `net udp` before cloning.").unwrap();
}
}
"udpcloneclose" => {
self.udp_clone = None;
}
_ => {
write!(ret, "{}", helpstring).unwrap();
}
@ -123,7 +146,38 @@ impl<'a> ShellCmdApi<'a> for NetCmd {
log::error!("Got NetCmd callback from uninitialized socket");
write!(ret, "Got NetCmd callback from uninitialized socket").unwrap();
}
}
},
Some(NetCmdDispatch::UdpTest2) => {
if let Some(udp_socket) = &mut self.udp_clone {
let mut pkt: [u8; UDP_TEST_SIZE] = [0; UDP_TEST_SIZE];
match udp_socket.recv_from(&mut pkt) {
Ok((len, addr)) => {
write!(ret, "Clone UDP rx {} bytes: {:?}: {}\n", len, addr, std::str::from_utf8(&pkt[..len]).unwrap()).unwrap();
log::info!("Clone UDP rx {} bytes: {:?}: {:?}", len, addr, &pkt[..len]);
self.udp_count += 1;
let response_addr = SocketAddr::new(
addr.ip(),
udp_socket.socket_addr().unwrap().port()
);
match udp_socket.send_to(
format!("Clone received {} packets\n\r", self.udp_count).as_bytes(),
&response_addr
) {
Ok(len) => write!(ret, "UDP tx {} bytes", len).unwrap(),
Err(e) => write!(ret, "UDP tx err: {:?}", e).unwrap(),
}
},
Err(e) => {
log::error!("Net UDP error: {:?}", e);
write!(ret, "UDP receive error: {:?}", e).unwrap();
}
}
} else {
log::error!("Got NetCmd callback from uninitialized socket");
write!(ret, "Got NetCmd callback from uninitialized socket").unwrap();
}
},
None => {
log::error!("NetCmd callback with unrecognized dispatch ID");
write!(ret, "NetCmd callback with unrecognized dispatch ID").unwrap();