From e6643e725dfeb13754a66c7fccbf8f12bc2dc520 Mon Sep 17 00:00:00 2001 From: bunnie Date: Mon, 18 Oct 2021 04:02:55 +0800 Subject: [PATCH] implement UDP rx --- Cargo.lock | 3 +- services/com/src/api.rs | 3 +- services/net/Cargo.toml | 4 +- services/net/src/api.rs | 154 ++++++++++++ services/net/src/backend.rs | 3 + services/net/src/backend/lookup.rs | 31 +++ services/net/src/backend/udp.rs | 373 +++++++++++++++++++++++++++++ services/net/src/lib.rs | 75 +++++- services/net/src/main.rs | 69 +++++- 9 files changed, 696 insertions(+), 19 deletions(-) create mode 100644 services/net/src/backend.rs create mode 100644 services/net/src/backend/lookup.rs create mode 100644 services/net/src/backend/udp.rs diff --git a/Cargo.lock b/Cargo.lock index fd07a8599..299efe93a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1246,12 +1246,13 @@ dependencies = [ "log-server", "num-derive", "num-traits", - "rkyv 0.7.18", + "rkyv 0.4.3", "smoltcp", "susres", "ticktimer-server", "utralib", "xous", + "xous-ipc", "xous-names", ] diff --git a/services/com/src/api.rs b/services/com/src/api.rs index e9e65f819..b868f445c 100644 --- a/services/com/src/api.rs +++ b/services/com/src/api.rs @@ -4,7 +4,8 @@ pub(crate) const SERVER_NAME_COM: &str = "_COM manager_"; pub use com_rs_ref::serdes::Ipv4Conf; -pub const NET_MTU: usize = 1500; +// extra 30 bytes for the header over 1500 +pub const NET_MTU: usize = 1530; #[derive(Debug, Default, Copy, Clone, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)] pub struct BattStats { /// instantaneous voltage in mV diff --git a/services/net/Cargo.toml b/services/net/Cargo.toml index b40ac83ce..c51ea1780 100644 --- a/services/net/Cargo.toml +++ b/services/net/Cargo.toml @@ -7,6 +7,7 @@ description = "Network middleware" [dependencies] xous = { path = "../../xous-rs" } +xous-ipc = {path="../../xous-ipc"} log-server = { path = "../log-server" } ticktimer-server = { path = "../ticktimer-server" } xous-names = { path = "../xous-names" } @@ -14,7 +15,8 @@ log = "0.4" num-derive = {version = "0.3", default-features = false} num-traits = {version = "0.2", default-features = false} susres = {path = "../susres"} -rkyv = "0.7.18" +#rkyv = "0.7.18" +rkyv = {version = "0.4.3", features = ["const_generics"], default-features = false} llio = {path = "../llio"} com = {path = "../com"} byteorder = { version = "1.0", default-features = false } diff --git a/services/net/src/api.rs b/services/net/src/api.rs index c29d93a90..43a1ce2dc 100644 --- a/services/net/src/api.rs +++ b/services/net/src/api.rs @@ -1,7 +1,20 @@ +use rkyv::{Archive, Deserialize, Serialize}; +use std::net::SocketAddr; +use smoltcp::wire::IpAddress; + pub(crate) const SERVER_NAME_NET: &str = "_Middleware Network Server_"; #[derive(num_derive::FromPrimitive, num_derive::ToPrimitive, Debug)] pub(crate) enum Opcode { + UdpBind, + UdpClose, + + /// initiates a ping packet + //PingSend, + + /// subscription for network responses + //NetCallbackSubscribe, + /// [Internal] com llio interrupt callback ComInterrupt, @@ -11,3 +24,144 @@ pub(crate) enum Opcode { /// Suspend/resume callback SuspendResume, } + +#[derive(Debug, num_derive::FromPrimitive, num_derive::ToPrimitive)] +pub(crate) enum NetCallback { + Ping, + Drop, +} + +#[derive(Debug, num_derive::FromPrimitive, num_derive::ToPrimitive)] +pub(crate) enum NetUdpCallback { + RxData, + Drop, +} + +#[derive(Debug, Archive, Serialize, Deserialize, Copy, Clone)] +pub(crate) enum NetIpAddr { + Ipv4([u8; 4]), + Ipv6([u8; 16]), +} +impl From for NetIpAddr { + fn from(other: SocketAddr) -> NetIpAddr { + match other { + SocketAddr::V4(sav4) => { + NetIpAddr::Ipv4(sav4.ip().octets()) + }, + SocketAddr::V6(sav6) => { + NetIpAddr::Ipv6(sav6.ip().octets()) + } + } + } +} +impl From for NetIpAddr { + fn from(other: IpAddress) -> NetIpAddr { + match other { + IpAddress::Ipv4(ipv4) => { + NetIpAddr::Ipv4(ipv4.0) + }, + IpAddress::Ipv6(ipv6) => { + NetIpAddr::Ipv6(ipv6.0) + }, + _ => { + panic!("Invalid IpAddress") + } + } + } +} + +/// The data field for a UDP response is limited to less than the theoretical +/// size of 64k. While UDP allows for a 64k packet, it seems no protoctols +/// in practice utilize such a length (about 512 bytes is the biggest), due +/// to MTU limitations downstream. Within Xous, memory is shared on a page-basis, +/// which is 4096 bytes, so the cost to share a page is almost the same regardless +/// of its size, as long as it is smaller than 4096 bytes. Hence, the number +/// 1800 bytes is picked to be a bit larger than our wifi MTU, but small +/// enough to fit in a page of RAM. Why not make it even bigger? Mainly to save +/// on the cost to repeatedly zeroize parts of RAM that are never used. +#[derive(Debug, Archive, Serialize, Deserialize, Copy, Clone)] +pub(crate) struct NetUdpResponse { + pub endpoint_ip_addr: NetIpAddr, + pub len: u16, + pub endpoint_port: u16, + pub data: [u8; 1800], +} + +#[derive(Debug, Archive, Serialize, Deserialize, Copy, Clone)] +pub(crate) struct ScalarHook { + pub sid: (u32, u32, u32, u32), + pub id: u32, // ID of the scalar message to send through (e.g. the discriminant of the Enum on the caller's side API) + pub cid: xous::CID, // caller-side connection ID for the scalar message to route to. Created by the caller before hooking. + pub token: Option<[u32; 4]>, // 128-bit random token used to identify a connection to the net crate +} + +#[derive(Debug, Archive, Serialize, Deserialize, Copy, Clone)] +pub(crate) struct NetUdpBind { + pub(crate) cb_sid: [u32; 4], + pub(crate) ip_addr: NetIpAddr, + pub(crate) port: u16, + pub(crate) max_payload: Option, // defaults to MTU if not specified +} + +#[derive(Debug, Archive, Serialize, Deserialize, Copy, Clone)] +pub(crate) enum NetMemResponse { + Ok, + OutOfMemory, + SocketInUse, + AccessDenied, + Invalid, +} + +/// This defines a Xous Scalar message endpoint. Used for defining +/// notification messages for incoming packets, for main loops that want to be +/// able to process both events from Xous and from the network. +pub struct XousScalarEndpoint { + cid: Option, + op: Option, + args: [Option; 4], +} +#[allow(dead_code)] +impl XousScalarEndpoint { + pub fn new() -> Self { + XousScalarEndpoint { + cid: None, + op: None, + args: [None; 4] + } + } + pub fn set(&mut self, cid: xous::CID, op: usize, args: [Option; 4]) { + self.cid = Some(cid); + self.op = Some(op); + self.args = args; + } + pub fn clear(&mut self) { + self.cid = None; + self.op = None; + self.args = [None; 4]; + } + pub fn is_set(&self) -> bool { + self.cid.is_some() && self.op.is_some() + } + pub fn notify(&mut self) { + if let Some(cid) = self.cid { + if let Some(op) = self.op { + match xous::send_message( + cid, + xous::Message::new_scalar( + op, + if let Some(a) = self.args[0] {a} else {0}, + if let Some(a) = self.args[1] {a} else {0}, + if let Some(a) = self.args[2] {a} else {0}, + if let Some(a) = self.args[3] {a} else {0}, + ) + ) { + Ok(_) => (), + Err(e) => { + log::error!("Couldn't send scalar notification, unmapping: {:?}", e); + self.clear(); + } + } + } + } + } +} \ No newline at end of file diff --git a/services/net/src/backend.rs b/services/net/src/backend.rs new file mode 100644 index 000000000..12c11729d --- /dev/null +++ b/services/net/src/backend.rs @@ -0,0 +1,3 @@ +//pub mod lookup; +pub mod udp; +pub use udp::*; \ No newline at end of file diff --git a/services/net/src/backend/lookup.rs b/services/net/src/backend/lookup.rs new file mode 100644 index 000000000..3fe850da0 --- /dev/null +++ b/services/net/src/backend/lookup.rs @@ -0,0 +1,31 @@ + +pub struct LookupHost(!); + +impl LookupHost { + pub fn port(&self) -> u16 { + self.0 + } +} + +impl Iterator for LookupHost { + type Item = SocketAddr; + fn next(&mut self) -> Option { + self.0 + } +} + +impl TryFrom<&str> for LookupHost { + type Error = io::Error; + + fn try_from(_v: &str) -> io::Result { + unsupported() + } +} + +impl<'a> TryFrom<(&'a str, u16)> for LookupHost { + type Error = io::Error; + + fn try_from(_v: (&'a str, u16)) -> io::Result { + unsupported() + } +} diff --git a/services/net/src/backend/udp.rs b/services/net/src/backend/udp.rs new file mode 100644 index 000000000..68aeaf1e1 --- /dev/null +++ b/services/net/src/backend/udp.rs @@ -0,0 +1,373 @@ +use std::convert::TryInto; +use std::net::{SocketAddr, SocketAddrV4, Ipv4Addr, Ipv6Addr, IpAddr}; +use std::unimplemented; +use std::io; +use std::io::{Error, ErrorKind, Result}; +use std::sync::{Arc, Mutex}; +use std::thread; +use std::thread::JoinHandle; + +use smoltcp::socket::UdpPacketMetadata; +use smoltcp::wire::{Ipv4Address, Ipv6Address, IpAddress}; +use smoltcp::{ + wire::IpEndpoint, + time::{Duration, Instant}, +}; + +use xous::{CID, SID, Message, msg_blocking_scalar_unpack}; +use xous_ipc::Buffer; +use crate::NetConn; +use crate::api::*; +use num_traits::*; + +pub struct UdpRx { + pub endpoint: IpEndpoint, + pub data: Vec, +} +pub struct UdpSocket{ + net: NetConn, + cb_sid: SID, + socket_addr: SocketAddr, + rx_buf: Arc>>, + handle: Option>, + notify: Arc>, + read_timeout: Option, + write_timeout: Option, + ticktimer: ticktimer_server::Ticktimer, +} + +// next steps: build this stub, and figure out how to clean up the error handling code. +impl UdpSocket { + pub fn bind(maybe_socket: Result<&SocketAddr>, max_payload: Option) -> Result { + let socket = maybe_socket?; + let xns = xous_names::XousNames::new().unwrap(); + let net = NetConn::new(&xns).unwrap(); + let cb_sid = xous::create_server().unwrap(); + + let rx_buf = Arc::new(Mutex::new(Vec::new())); + let notify = Arc::new(Mutex::new(XousScalarEndpoint::new())); + + let handle = thread::spawn({ + let cb_sid_clone = cb_sid.clone(); + let rx_buf = Arc::clone(&rx_buf); + let notify = Arc::clone(¬ify); + move || { + loop { + let msg = xous::receive_message(cb_sid_clone).unwrap(); + match FromPrimitive::from_usize(msg.body.id()) { + Some(NetUdpCallback::RxData) => { + let buffer = unsafe {Buffer::from_memory_message(msg.body.memory_message().unwrap())}; + let incoming = buffer.as_flat::().unwrap(); + let endpoint = match incoming.endpoint_ip_addr { + ArchivedNetIpAddr::Ipv4(v4_octets) => { + IpEndpoint::new( + IpAddress::Ipv4(Ipv4Address::from_bytes(&v4_octets)), + incoming.endpoint_port as u16, + ) + }, + ArchivedNetIpAddr::Ipv6(v6_octets) => { + IpEndpoint::new( + IpAddress::Ipv6(Ipv6Address::from_bytes(&v6_octets)), + incoming.endpoint_port as u16, + ) + }, + }; + let mut rx = UdpRx { + endpoint, + data: Vec::new(), + }; + for (&src, dst) in incoming.data.iter().zip(rx.data.iter_mut()) { + *dst = src; + } + rx_buf.lock().unwrap().push(rx); + notify.lock().unwrap().notify(); // this will only notify if a destination has been set + }, + Some(NetUdpCallback::Drop) => msg_blocking_scalar_unpack!(msg, _, _, _, _, { + log::debug!("Drop received, exiting Udp handler"); + xous::return_scalar(msg.sender, 1).unwrap(); // actual return value doesn't matter -- it's that there is a return value + break; + }), + None => { + log::error!("got unknown message type on Udp callback: {:?}", msg); + } + } + } + } + }); + + let request = NetUdpBind { + ip_addr: NetIpAddr::from(*socket), + port: socket.port(), + cb_sid: cb_sid.to_array(), + max_payload, + }; + let mut buf = Buffer::into_buf(request) + .or(Err(Error::new(ErrorKind::Other, "can't register with Net server")))?; + buf.lend_mut(net.conn(), Opcode::UdpBind.to_u32().unwrap()) + .or(Err(Error::new(ErrorKind::Other, "can't register with Net server")))?; + match buf.to_original().unwrap() { + NetMemResponse::Ok => { + Ok(UdpSocket { + net, + cb_sid, + socket_addr: *socket, + rx_buf, + handle: Some(handle), + notify, + read_timeout: None, + write_timeout: None, + ticktimer: ticktimer_server::Ticktimer::new().unwrap(), + }) + }, + _ => { + Err(Error::new(ErrorKind::Other, "can't register with Net server")) + } + } + } + + pub fn set_scalar_notification(&mut self, cid: xous::CID, op: usize, args: [Option; 4]) { + self.notify.lock().unwrap().set(cid, op, args); + } + pub fn clear_scalar_notification(&mut self) { + self.notify.lock().unwrap().clear(); + } + + pub fn set_read_timeout(&mut self, timeout: Option) -> io::Result<()> { + if let Some(duration) = timeout { + if duration.total_millis() == 0 { + Err(Error::new(ErrorKind::InvalidInput, "zero duration is not valid")) + } else { + self.read_timeout = Some(duration); + Ok(()) + } + } else { + self.read_timeout = None; + Ok(()) + } + } + + pub fn set_write_timeout(&mut self, timeout: Option) -> io::Result<()> { + if let Some(duration) = timeout { + if duration.total_millis() == 0 { + Err(Error::new(ErrorKind::InvalidInput, "zero duration is not valid")) + } else { + self.write_timeout = Some(duration); + Ok(()) + } + } else { + self.write_timeout = None; + Ok(()) + } + } + + pub fn read_timeout(&self) -> io::Result> { + Ok(self.read_timeout) + } + + pub fn write_timeout(&self) -> io::Result> { + Ok(self.write_timeout) + } + + pub fn recv(&self, pkt: &mut [u8]) -> io::Result { + let timeout = if let Some(to) = self.read_timeout { + to.total_millis() + self.ticktimer.elapsed_ms() + } else { + u64::MAX + }; + loop { + if self.rx_buf.lock().unwrap().len() > 0 { + let rx_pkt = self.rx_buf.lock().unwrap().remove(0); // safe b/c len > 1, checked above + for (&src, dst) in rx_pkt.data.iter().zip(pkt.iter_mut()) { + *dst = src; + } + return Ok(rx_pkt.data.len()); + } + if timeout > self.ticktimer.elapsed_ms() { + return Err(Error::new(ErrorKind::WouldBlock, "UDP Rx timeout reached")); + } + xous::yield_slice(); + } + } + + pub fn recv_from(&self, pkt: &mut [u8]) -> io::Result<(usize, SocketAddr)> { + let timeout = if let Some(to) = self.read_timeout { + to.total_millis() + self.ticktimer.elapsed_ms() + } else { + u64::MAX + }; + loop { + if self.rx_buf.lock().unwrap().len() > 0 { + let rx_pkt = self.rx_buf.lock().unwrap().remove(0); // safe b/c len > 1, checked above + for (&src, dst) in rx_pkt.data.iter().zip(pkt.iter_mut()) { + *dst = src; + } + let addr = match rx_pkt.endpoint.addr { + IpAddress::Ipv4(ipv4) => { + IpAddr::V4(Ipv4Addr::new(ipv4.0[0], ipv4.0[1], ipv4.0[2], ipv4.0[3])) + }, + IpAddress::Ipv6(ipv6) => { + IpAddr::V6(Ipv6Addr::new( + u16::from_be_bytes(ipv6.0[0..1].try_into().unwrap()), + u16::from_be_bytes(ipv6.0[2..3].try_into().unwrap()), + u16::from_be_bytes(ipv6.0[4..5].try_into().unwrap()), + u16::from_be_bytes(ipv6.0[6..7].try_into().unwrap()), + u16::from_be_bytes(ipv6.0[8..9].try_into().unwrap()), + u16::from_be_bytes(ipv6.0[10..11].try_into().unwrap()), + u16::from_be_bytes(ipv6.0[12..13].try_into().unwrap()), + u16::from_be_bytes(ipv6.0[14..15].try_into().unwrap()), + )) + }, + _ => { + panic!("malformed endpoint record"); + } + }; + return Ok(( + rx_pkt.data.len(), + SocketAddr::new( + addr, + rx_pkt.endpoint.port, + ) + )); + } + if timeout > self.ticktimer.elapsed_ms() { + return Err(Error::new(ErrorKind::WouldBlock, "UDP Rx timeout reached")); + } + xous::yield_slice(); + } + } + + pub fn peek(&self, _: &mut [u8]) -> io::Result { + unimplemented!("work in progress") + } + + pub fn send(&self, _: &[u8]) -> io::Result { + unimplemented!("work in progress") + } + + pub fn peer_addr(&self) -> io::Result { + unimplemented!("work in progress") + } + + pub fn socket_addr(&self) -> io::Result { + unimplemented!("work in progress") + } + + pub fn peek_from(&self, _: &mut [u8]) -> io::Result<(usize, SocketAddr)> { + unimplemented!("work in progress") + } + + pub fn send_to(&self, _: &[u8], _: &SocketAddr) -> io::Result { + unimplemented!("work in progress") + } + + pub fn duplicate(&self) -> io::Result { + unimplemented!("work in progress") + } + + pub fn set_broadcast(&self, _: bool) -> io::Result<()> { + unimplemented!("work in progress") + } + + pub fn broadcast(&self) -> io::Result { + unimplemented!("work in progress") + } + + pub fn set_multicast_loop_v4(&self, _: bool) -> io::Result<()> { + unimplemented!("work in progress") + } + + pub fn multicast_loop_v4(&self) -> io::Result { + unimplemented!("work in progress") + } + + pub fn set_multicast_ttl_v4(&self, _: u32) -> io::Result<()> { + unimplemented!("work in progress") + } + + pub fn multicast_ttl_v4(&self) -> io::Result { + unimplemented!("work in progress") + } + + pub fn join_multicast_v4(&self, _: &Ipv4Addr, _: &Ipv4Addr) -> io::Result<()> { + unimplemented!("work in progress") + } + + pub fn leave_multicast_v4(&self, _: &Ipv4Addr, _: &Ipv4Addr) -> io::Result<()> { + unimplemented!("work in progress") + } + + pub fn set_ttl(&self, _: u32) -> io::Result<()> { + unimplemented!("work in progress") + } + + pub fn ttl(&self) -> io::Result { + unimplemented!("work in progress") + } + + pub fn take_error(&self) -> io::Result> { + unimplemented!("work in progress") + } + + pub fn set_nonblocking(&self, _: bool) -> io::Result<()> { + unimplemented!("work in progress") + } + + pub fn connect(&self, _: io::Result<&SocketAddr>) -> io::Result<()> { + unimplemented!("work in progress") + } + + pub fn set_multicast_loop_v6(&self, _: bool) -> io::Result<()> { + unimplemented!("ipv6 not implemented") + } + + pub fn multicast_loop_v6(&self) -> io::Result { + unimplemented!("ipv6 not implemented") + } + + pub fn join_multicast_v6(&self, _: &Ipv6Addr, _: u32) -> io::Result<()> { + unimplemented!("ipv6 not implemented") + } + + pub fn leave_multicast_v6(&self, _: &Ipv6Addr, _: u32) -> io::Result<()> { + unimplemented!("ipv6 not implemented") + } + +} + +impl std::fmt::Debug for UdpSocket { + fn fmt(&self, _f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + unimplemented!("work in progress") + } +} + +impl Drop for UdpSocket { + fn drop(&mut self) { + let request = NetUdpBind { + ip_addr: NetIpAddr::from(self.socket_addr), + port: self.socket_addr.port(), + cb_sid: self.cb_sid.to_array(), + max_payload: None, + }; + let mut buf = Buffer::into_buf(request).expect("can't unregister with Net server"); + buf.lend_mut(self.net.conn(), Opcode::UdpClose.to_u32().unwrap()).expect("can't unregister with Net server"); + match buf.to_original().unwrap() { + NetMemResponse::Ok => { + let drop_cid = xous::connect(self.cb_sid).unwrap(); + xous::send_message( + drop_cid, + Message::new_blocking_scalar(NetUdpCallback::Drop.to_usize().unwrap(), 0, 0, 0, 0) + ).expect("couldn't send Drop to our repsonding server"); + unsafe{xous::disconnect(drop_cid).unwrap()}; // should be safe because we're the only connection and the previous was a blocking scalar + }, + _ => { + panic!("Couldn't unregister with net server"); + } + } + // this will block until the responder thread exits, which it should because it received the Drop message + if let Some(handle) = self.handle.take() { + handle.join().unwrap(); + } + // now we can detroy the server id of the responder thread + xous::destroy_server(self.cb_sid).unwrap(); + } +} \ No newline at end of file diff --git a/services/net/src/lib.rs b/services/net/src/lib.rs index e6b944da3..3bff4d26a 100644 --- a/services/net/src/lib.rs +++ b/services/net/src/lib.rs @@ -1,25 +1,64 @@ #![cfg_attr(target_os = "none", no_std)] pub mod api; +use api::*; use xous::{CID, send_message}; +use xous_ipc::Buffer; use num_traits::*; -pub struct Net { +pub mod backend; +pub use backend::*; + +/// NetConn is a crate-level structure that just counts the number of connections from this process to +/// the Net server. It's not mean to be created by user-facing code, so the visibility is (crate). +pub(crate) struct NetConn { conn: CID, + //cb_sid: Option, + //token: Option<[u32; 4]>, } -impl Net { - pub fn new(xns: &xous_names::XousNames) -> Result { +impl NetConn { + pub(crate) fn new(xns: &xous_names::XousNames) -> Result { REFCOUNT.store(REFCOUNT.load(Ordering::Relaxed) + 1, Ordering::Relaxed); let conn = xns.request_connection_blocking(api::SERVER_NAME_NET).expect("Can't connect to Net server"); - Ok(Net { - conn + Ok(NetConn { + conn, + //cb_sid: None, + //token: None, }) } + pub(crate) fn conn(&self) -> CID { + self.conn + } + // `cid` is the connection ID for the callback. The calling function would use `xous::connect(my_private_SID).unwrap()` to generate this number. + // The SID should never be disclosed to another crate, as it is private to each server, which is why the CID creation call must exist in the caller's code. +/* + pub fn hook_ping_callback(&mut self, id: u32, cid: CID) -> Result<(), xous::Error> { + if self.cb_sid.is_none() { + let sid = xous::create_server().unwrap(); + self.cb_sid = Some(sid); + let sid_tuple = sid.to_u32(); + xous::create_thread_4(net_cb_server, sid_tuple.0 as usize, sid_tuple.1 as usize, sid_tuple.2 as usize, sid_tuple.3 as usize).unwrap(); + let hookdata = ScalarHook { + sid: sid_tuple, + id, + cid, + token: None, + }; + let mut buf = Buffer::into_buf(hookdata).or(Err(xous::Error::InternalError))?; + buf.lend_mut(self.conn, Opcode::NetCallbackSubscribe.to_u32().unwrap()).map(|_|()) + let retdata = buf.to_original::().unwrap(); + self.token = retdata.token; + Ok(()) + } else { + Err(xous::Error::MemoryInUse) // can't hook it twice + } + } +*/ } use core::sync::atomic::{AtomicU32, Ordering}; static REFCOUNT: AtomicU32 = AtomicU32::new(0); -impl Drop for Net { +impl Drop for NetConn { fn drop(&mut self) { // the connection to the server side must be reference counted, so that multiple instances of this object within // a single process do not end up de-allocating the CID on other threads before they go out of scope. @@ -30,4 +69,26 @@ impl Drop for Net { // if there was object-specific state (such as a one-time use server for async callbacks, specific to the object instance), // de-allocate those items here. They don't need a reference count because they are object-specific } -} \ No newline at end of file +} +/* +/// handles callback messages that indicate an net packet has been returned, in the caller's process space +fn net_cb_server(sid0: usize, sid1: usize, sid2: usize, sid3: usize) { + let sid = xous::SID::from_u32(sid0 as u32, sid1 as u32, sid2 as u32, sid3 as u32); + loop { + let msg = xous::receive_message(sid).unwrap(); + match FromPrimitive::from_usize(msg.body.id()) { + Some(EventCallback::Event) => xous::msg_scalar_unpack!(msg, cid, id, free_play, avail_rec, { + // directly pass the scalar message onto the CID with the ID memorized in the original hook + send_message(cid as u32, + Message::new_scalar(id, free_play, avail_rec, 0, 0) + ).unwrap(); + }), + Some(EventCallback::Drop) => { + break; // this exits the loop and kills the thread + } + None => (), + } + } + xous::destroy_server(sid).unwrap(); +} +*/ \ No newline at end of file diff --git a/services/net/src/main.rs b/services/net/src/main.rs index 921749b0a..2a5c36656 100644 --- a/services/net/src/main.rs +++ b/services/net/src/main.rs @@ -22,7 +22,7 @@ use smoltcp::socket::{IcmpEndpoint, IcmpPacketMetadata, IcmpSocket, IcmpSocketBu use smoltcp::wire::{ EthernetAddress, Icmpv4Packet, Icmpv4Repr, IpAddress, IpCidr, Ipv4Address, Ipv4Cidr, }; -use smoltcp::socket::{UdpPacketMetadata, UdpSocket, UdpSocketBuffer}; +use smoltcp::socket::{UdpPacketMetadata, UdpSocket, UdpSocketBuffer, SocketHandle}; use smoltcp::{ time::{Duration, Instant}, }; @@ -178,7 +178,7 @@ fn xmain() -> ! { let mut sockets = SocketSet::new(vec![]); let icmp_handle = sockets.add(icmp_socket); - let mut handles = vec![]; + let mut udp_handles = HashMap::::new(); let mut send_at = Instant::from_millis(0); let mut seq_no = 0; @@ -220,19 +220,44 @@ fn xmain() -> ! { 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())}; - let udpspec = buf.to_original::().unwrap(); + let udpspec = buf.to_original::().unwrap(); let buflen = if let Some(maxlen) = udpspec.max_payload { maxlen as usize } else { NET_MTU as usize }; - 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 udp_socket = UdpSocket::new(udp_rx_buffer, udp_tx_buffer); - handles.push(sockets.add(udp_socket)); - - // TODO: add return code stuff, but let's see how much the borrow checker hates this code so far... + if udp_handles.contains_key(&udpspec.port) { + log::error!("Attempt to bind to udp:{}, already in use.", udpspec.port); + buf.replace(NetMemResponse::SocketInUse).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(_) => { + udp_handles.insert(udpspec.port, sockets.add(udp_socket)); + buf.replace(NetMemResponse::Ok).unwrap(); + } + Err(e) => { + log::error!("Udp couldn't bind to socket: {:?}", e); + buf.replace(NetMemResponse::Invalid).unwrap(); + } + } + } + }, + Some(Opcode::UdpClose) => { + let mut buf = unsafe{Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap())}; + let udpspec = buf.to_original::().unwrap(); + match udp_handles.remove(&udpspec.port) { + Some(handle) => { + sockets.get::(handle).close(); + buf.replace(NetMemResponse::Ok).unwrap() + } + _ => { + buf.replace(NetMemResponse::Invalid).unwrap() + } + } }, Some(Opcode::ComInterrupt) => { com_int_list.clear(); @@ -331,6 +356,32 @@ fn xmain() -> ! { log::debug!("poll error: {}", e); } } + + { + for (port, &handle) in udp_handles.iter() { + let mut socket = sockets.get::(handle); + match socket.recv() { + Ok((data, endpoint)) => { + log::info!( + "udp:{} recv data: {:?} from {}", + port, + std::str::from_utf8(data).unwrap(), + endpoint + ); + // return the data/endpoint tuple to the caller + // TODO + + } + Err(_) => { + // do nothing + }, + }; + } + } + + // this enclosure contains an ICMP implementation that needs to be deconstructed + // at the moment it bakes in a pinger and ping responder -- we need to remove the pinger + // and expose it to a generic interface. Once we figure out what that is. { let timestamp = timer.now(); let mut socket = sockets.get::(icmp_handle);