diff --git a/services/net/src/backend/udp.rs b/services/net/src/backend/udp.rs index 0be58809f..2260e7df1 100644 --- a/services/net/src/backend/udp.rs +++ b/services/net/src/backend/udp.rs @@ -1,5 +1,5 @@ use std::convert::TryInto; -use std::net::{SocketAddr, SocketAddrV4, Ipv4Addr, Ipv6Addr, IpAddr}; +use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr, ToSocketAddrs}; use std::unimplemented; use std::io; use std::io::{Error, ErrorKind, Result}; @@ -7,7 +7,6 @@ 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, @@ -38,8 +37,31 @@ pub struct UdpSocket{ // next steps: build this stub, and figure out how to clean up the error handling code. impl UdpSocket { - pub fn bind(socket: SocketAddr, max_payload: Option) -> Result { - //let socket = maybe_socket.unwrap(); + pub fn bind(maybe_socket: io::Result<&SocketAddr>) -> Result { + UdpSocket::bind_inner(maybe_socket, None) + } + pub fn bind_xous(socket: A, max_payload: Option) -> Result { + match socket.to_socket_addrs() { + Ok(socks) => { + match socks.into_iter().next() { + Some(socket_addr) => { + UdpSocket::bind_inner( + Ok(&socket_addr), + max_payload) + } + _ => { + Err(Error::new(ErrorKind::InvalidInput, "IP address invalid")) + } + } + } + _ => { + Err(Error::new(ErrorKind::InvalidInput, "IP address invalid")) + } + } + } + + fn bind_inner(maybe_socket: io::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(); @@ -96,7 +118,7 @@ impl UdpSocket { }); let request = NetUdpBind { - ip_addr: NetIpAddr::from(socket), + ip_addr: NetIpAddr::from(*socket), port: socket.port(), cb_sid: cb_sid.to_array(), max_payload, @@ -110,7 +132,7 @@ impl UdpSocket { Ok(UdpSocket { net, cb_sid, - socket_addr: socket, + socket_addr: *socket, rx_buf, handle: Some(handle), notify, @@ -125,7 +147,7 @@ impl UdpSocket { } } - pub fn set_scalar_notification(&mut self, cid: xous::CID, op: usize, args: [Option; 4]) { + pub fn set_scalar_notification(&mut self, cid: CID, op: usize, args: [Option; 4]) { self.notify.lock().unwrap().set(cid, op, args); } pub fn clear_scalar_notification(&mut self) { @@ -168,7 +190,7 @@ impl UdpSocket { Ok(self.write_timeout) } - pub fn recv(&self, pkt: &mut [u8]) -> io::Result { + fn recv_inner(&self, pkt: &mut[u8], do_peek: bool) -> io::Result { let timeout = if let Some(to) = self.read_timeout { to.total_millis() + self.ticktimer.elapsed_ms() } else { @@ -180,7 +202,13 @@ impl UdpSocket { for (&src, dst) in rx_pkt.data.iter().zip(pkt.iter_mut()) { *dst = src; } - return Ok(rx_pkt.data.len()); + let len = rx_pkt.data.len(); + if do_peek { + // re-insert the element after taking it out. We can't mux it above with the if/else because + // a peek is a borrow, but a remove is a move, and that's not easy to coerce in Rust + self.rx_buf.lock().unwrap().insert(0, rx_pkt); + } + return Ok(len); } if timeout > self.ticktimer.elapsed_ms() { return Err(Error::new(ErrorKind::WouldBlock, "UDP Rx timeout reached")); @@ -188,8 +216,14 @@ impl UdpSocket { xous::yield_slice(); } } + pub fn recv(&self, pkt: &mut [u8]) -> io::Result { + self.recv_inner(pkt, false) + } + pub fn peek(&self, pkt: &mut [u8]) -> io::Result { + self.recv_inner(pkt, true) + } - pub fn recv_from(&self, pkt: &mut [u8]) -> io::Result<(usize, SocketAddr)> { + fn recv_from_inner(&self, pkt: &mut [u8], do_peek: bool) -> io::Result<(usize, SocketAddr)> { let timeout = if let Some(to) = self.read_timeout { to.total_millis() + self.ticktimer.elapsed_ms() } else { @@ -221,12 +255,19 @@ impl UdpSocket { panic!("malformed endpoint record"); } }; + let len = rx_pkt.data.len(); + let socket_addr = SocketAddr::new( + addr, + rx_pkt.endpoint.port, + ); + if do_peek { + // re-insert the element after taking it out. We can't mux it above with the if/else because + // a peek is a borrow, but a remove is a move, and that's not easy to coerce in Rust + self.rx_buf.lock().unwrap().insert(0, rx_pkt); + } return Ok(( - rx_pkt.data.len(), - SocketAddr::new( - addr, - rx_pkt.endpoint.port, - ) + len, + socket_addr )); } if timeout > self.ticktimer.elapsed_ms() { @@ -236,9 +277,13 @@ impl UdpSocket { } } - pub fn peek(&self, _: &mut [u8]) -> io::Result { - unimplemented!("work in progress") + pub fn recv_from(&self, pkt: &mut [u8]) -> io::Result<(usize, SocketAddr)> { + self.recv_from_inner(pkt, false) } + pub fn peek_from(&self, pkt: &mut [u8]) -> io::Result<(usize, SocketAddr)> { + self.recv_from_inner(pkt, true) + } + pub fn send(&self, _: &[u8]) -> io::Result { unimplemented!("work in progress") @@ -252,10 +297,6 @@ impl UdpSocket { 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") } diff --git a/services/net/src/lib.rs b/services/net/src/lib.rs index 228a1113c..46cd53e99 100644 --- a/services/net/src/lib.rs +++ b/services/net/src/lib.rs @@ -1,10 +1,7 @@ #![cfg_attr(target_os = "none", no_std)] pub mod api; -use api::*; -use xous::{CID, send_message}; -use xous_ipc::Buffer; -use num_traits::*; +use xous::CID; pub mod backend; pub use backend::*; @@ -14,8 +11,6 @@ pub use smoltcp::time::Duration; /// 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 NetConn { pub(crate) fn new(xns: &xous_names::XousNames) -> Result { @@ -23,38 +18,11 @@ impl NetConn { let conn = xns.request_connection_blocking(api::SERVER_NAME_NET).expect("Can't connect to Net server"); 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}; @@ -71,25 +39,3 @@ impl Drop for NetConn { // de-allocate those items here. They don't need a reference count because they are object-specific } } -/* -/// 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/shellchat/src/cmds/net_cmd.rs b/services/shellchat/src/cmds/net_cmd.rs index 07855f6b2..54205df7e 100644 --- a/services/shellchat/src/cmds/net_cmd.rs +++ b/services/shellchat/src/cmds/net_cmd.rs @@ -3,7 +3,6 @@ use xous_ipc::String; use net::Duration; use xous::MessageEnvelope; use num_traits::*; -use std::net::ToSocketAddrs; #[derive(Debug)] pub struct NetCmd { @@ -47,8 +46,8 @@ impl<'a> ShellCmdApi<'a> for NetCmd { match sub_cmd { "udp" => { if self.udp.is_none() { - let mut udp = net::UdpSocket::bind( - "127.0.0.1:6969".to_socket_addrs().unwrap().into_iter().next().unwrap(), + let mut udp = net::UdpSocket::bind_xous( + "127.0.0.1:6969", Some(UDP_TEST_SIZE as u16) ).unwrap(); udp.set_read_timeout(Some(Duration::from_millis(1000))).unwrap();