diff --git a/services/net/src/api.rs b/services/net/src/api.rs index d5e4cdbbd..074cc97af 100644 --- a/services/net/src/api.rs +++ b/services/net/src/api.rs @@ -4,9 +4,11 @@ pub(crate) use udp::*; use rkyv::{Archive, Deserialize, Serialize}; use std::net::SocketAddr; use smoltcp::wire::IpAddress; +use std::convert::TryInto; pub(crate) const SERVER_NAME_NET: &str = "_Middleware Network Server_"; +/// Dispatch opcodes to the Net crate main loop. #[derive(num_derive::FromPrimitive, num_derive::ToPrimitive, Debug)] pub(crate) enum Opcode { UdpBind, @@ -35,6 +37,32 @@ pub(crate) enum NetCallback { Drop, } +#[derive(Debug, Archive, Serialize, Deserialize, Copy, Clone)] +pub(crate) enum NetMemResponse { + Ok, + Sent(u16), + OutOfMemory, + SocketInUse, + AccessDenied, + Invalid, + LibraryError, +} + +/////// a bunch of structures are re-derived here so we can infer `rkyv` traits on them +#[derive(Debug, Archive, Serialize, Deserialize, Copy, Clone)] +pub (crate) struct NetSocketAddr { + pub(crate) addr: NetIpAddr, + pub(crate) port: u16, +} +impl From for NetSocketAddr { + fn from(other: SocketAddr) -> NetSocketAddr { + NetSocketAddr { + addr: NetIpAddr::from(other), + port: other.port(), + } + } +} + #[derive(Debug, Archive, Serialize, Deserialize, Copy, Clone)] pub(crate) enum NetIpAddr { Ipv4([u8; 4]), @@ -67,6 +95,28 @@ impl From for NetIpAddr { } } } +impl From for IpAddress { + fn from(other: NetIpAddr) -> IpAddress { + match other { + NetIpAddr::Ipv4([a, b, c, d]) => { + IpAddress::Ipv4(smoltcp::wire::Ipv4Address::new(a, b, c, d)) + } + NetIpAddr::Ipv6(ipv6) => { + IpAddress::Ipv6(smoltcp::wire::Ipv6Address::new( + u16::from_be_bytes(ipv6[0..1].try_into().unwrap()), + u16::from_be_bytes(ipv6[2..3].try_into().unwrap()), + u16::from_be_bytes(ipv6[4..5].try_into().unwrap()), + u16::from_be_bytes(ipv6[6..7].try_into().unwrap()), + u16::from_be_bytes(ipv6[8..9].try_into().unwrap()), + u16::from_be_bytes(ipv6[10..11].try_into().unwrap()), + u16::from_be_bytes(ipv6[12..13].try_into().unwrap()), + u16::from_be_bytes(ipv6[14..15].try_into().unwrap()), + ) + ) + } + } + } +} /// This defines a Xous Scalar message endpoint. Used for defining /// notification messages for incoming packets, for main loops that want to be diff --git a/services/net/src/api/udp.rs b/services/net/src/api/udp.rs index d7036aacb..88ab30b10 100644 --- a/services/net/src/api/udp.rs +++ b/services/net/src/api/udp.rs @@ -21,13 +21,22 @@ pub(crate) struct NetUdpResponse { } #[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 +pub(crate) struct NetUdpTransmit { + pub dest_socket: Option, + /// local_port is the identifier for the socket handle, it must be specified + pub local_port: u16, + pub len: u16, + pub data: [u8; UDP_RESPONSE_MAX_LEN], } +/* not used as the connect state is kept on the caller's side +#[derive(Debug, Archive, Serialize, Deserialize, Copy, Clone)] +pub(crate) struct NetUdpConnect { + pub dest_socket: NetSocketAddr, + /// local_port is the identifier for the socket handle, it must be specified + pub local_port: u16, +}*/ + #[derive(Debug, Archive, Serialize, Deserialize, Copy, Clone)] pub(crate) struct NetUdpBind { pub(crate) cb_sid: [u32; 4], @@ -36,15 +45,6 @@ pub(crate) struct NetUdpBind { 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, -} - #[derive(Debug, num_derive::FromPrimitive, num_derive::ToPrimitive)] pub(crate) enum NetUdpCallback { RxData, diff --git a/services/net/src/backend/udp.rs b/services/net/src/backend/udp.rs index 2bdb7545a..0d7bb9b8c 100644 --- a/services/net/src/backend/udp.rs +++ b/services/net/src/backend/udp.rs @@ -38,7 +38,7 @@ pub struct UdpSocket{ read_timeout: Option, write_timeout: Option, ticktimer: ticktimer_server::Ticktimer, - dest_addr: Option, + dest_socket: Option, } // next steps: build this stub, and figure out how to clean up the error handling code. @@ -55,14 +55,10 @@ impl UdpSocket { Ok(&socket_addr), max_payload) } - _ => { - Err(Error::new(ErrorKind::InvalidInput, "IP address invalid")) - } + _ => Err(Error::new(ErrorKind::InvalidInput, "IP address invalid")) } } - _ => { - Err(Error::new(ErrorKind::InvalidInput, "IP address invalid")) - } + _ => Err(Error::new(ErrorKind::InvalidInput, "IP address invalid")) } } @@ -145,7 +141,7 @@ impl UdpSocket { read_timeout: None, write_timeout: None, ticktimer: ticktimer_server::Ticktimer::new().unwrap(), - dest_addr: None, + dest_socket: None, }) }, _ => { @@ -291,23 +287,79 @@ impl UdpSocket { self.recv_from_inner(pkt, true) } - pub fn connect(&self, _: io::Result<&SocketAddr>) -> io::Result<()> { - unimplemented!("work in progress") + pub fn connect(&mut self, maybe_socket_addr: io::Result<&SocketAddr>) -> io::Result<()> { + let socket = *maybe_socket_addr?; + self.dest_socket = Some(socket); + // the socket is just locally stored until the next send call, so there's nothing to send to the Net server + Ok(()) + } + pub fn connect_xous(&mut self, addr: A) -> io::Result<()> { + match addr.to_socket_addrs() { + Ok(socks) => { + match socks.into_iter().next() { + Some(socket_addr) => self.connect(Ok(&socket_addr)), + _ => Err(Error::new(ErrorKind::InvalidInput, "Destination socket invalid")) + } + } + _ => Err(Error::new(ErrorKind::InvalidInput, "Destination socket invalid")) + } } - pub fn send(&self, _: &[u8]) -> io::Result { - unimplemented!("work in progress") + pub fn send(&mut self, pkt: &[u8]) -> io::Result { + self.send_inner(pkt, None) } - pub fn send_to(&self, _: &[u8], _: &SocketAddr) -> io::Result { - unimplemented!("work in progress") + pub fn send_to(&mut self, pkt: &[u8], addr: &SocketAddr) -> io::Result { + self.send_inner(pkt, Some(addr)) + } + pub fn send_to_xous(&mut self, pkt: &[u8], addr: A) -> io::Result { + match addr.to_socket_addrs() { + Ok(socks) => { + match socks.into_iter().next() { + Some(socket_addr) => self.send_inner(pkt, Some(&socket_addr)), + _ => Err(Error::new(ErrorKind::InvalidInput, "Destination socket invalid")) + } + } + _ => Err(Error::new(ErrorKind::InvalidInput, "Destination socket invalid")) + } } - pub fn peer_addr(&self) -> io::Result { - unimplemented!("work in progress") + fn send_inner(&mut self, pkt: &[u8], maybe_dest: Option<&SocketAddr>) -> io::Result { + let dest = if let Some(&d) = maybe_dest { + Some(NetSocketAddr::from(d)) + } else { + // if not specified, grab from the local destination copy stored here + if let Some(dest) = self.dest_socket { + Some(NetSocketAddr::from(dest)) + } else { + return Err(Error::new(ErrorKind::AddrNotAvailable, "Destination address was not specified with connect")); + } + }; + let mut udp_tx = NetUdpTransmit { + dest_socket: dest, + local_port: self.socket_addr.port(), + len: pkt.len() as u16, + data: [0; UDP_RESPONSE_MAX_LEN], + }; + for (&src, dst) in pkt.iter().zip(udp_tx.data.iter_mut()) { + *dst = src; + } + + let mut buf = Buffer::into_buf(udp_tx) + .or(Err(Error::new(ErrorKind::Other, "can't send to Net server")))?; + buf.lend_mut(self.net.conn(), Opcode::UdpTx.to_u32().unwrap()) + .or(Err(Error::new(ErrorKind::Other, "can't send to Net server")))?; + match buf.to_original().unwrap() { + NetMemResponse::Sent(len) => Ok(len as usize), + _ => Err(Error::new(ErrorKind::Other, "send failed")), + } } pub fn socket_addr(&self) -> io::Result { + Ok(self.socket_addr) + } + + pub fn peer_addr(&self) -> io::Result { unimplemented!("work in progress") } diff --git a/services/net/src/main.rs b/services/net/src/main.rs index f0bceb88b..2fbcf995b 100644 --- a/services/net/src/main.rs +++ b/services/net/src/main.rs @@ -20,7 +20,7 @@ use smoltcp::phy::{Medium, Device}; use smoltcp::iface::{InterfaceBuilder, NeighborCache, Routes, Interface}; use smoltcp::socket::{IcmpEndpoint, IcmpPacketMetadata, IcmpSocket, IcmpSocketBuffer, SocketSet}; use smoltcp::wire::{ - EthernetAddress, Icmpv4Packet, Icmpv4Repr, IpAddress, IpCidr, Ipv4Address, Ipv4Cidr, + EthernetAddress, Icmpv4Packet, Icmpv4Repr, IpAddress, IpCidr, Ipv4Address, Ipv4Cidr, IpEndpoint }; use smoltcp::socket::{UdpPacketMetadata, UdpSocket, UdpSocketBuffer, SocketHandle}; use smoltcp::{ @@ -268,6 +268,29 @@ fn xmain() -> ! { } } }, + Some(Opcode::UdpTx) => { + use std::convert::TryInto; + let mut buf = unsafe{Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap())}; + let udp_tx = buf.to_original::().unwrap(); + match udp_handles.get_mut(&udp_tx.local_port) { + Some(udpstate) => { + if let Some(dest_socket) = udp_tx.dest_socket { + let endpoint = IpEndpoint::new( + dest_socket.addr.try_into().unwrap(), + dest_socket.port + ); + let mut socket = sockets.get::(udpstate.handle); + match socket.send_slice(&udp_tx.data[..udp_tx.len as usize], endpoint) { + Ok(_) => buf.replace(NetMemResponse::Sent(udp_tx.len)).unwrap(), + _ => buf.replace(NetMemResponse::LibraryError).unwrap(), + } + } else { + buf.replace(NetMemResponse::Invalid).unwrap() + } + } + _ => buf.replace(NetMemResponse::Invalid).unwrap() + } + }, Some(Opcode::ComInterrupt) => { com_int_list.clear(); let maybe_rxlen = com.ints_get_active(&mut com_int_list); diff --git a/services/shellchat/src/cmds/net_cmd.rs b/services/shellchat/src/cmds/net_cmd.rs index 54205df7e..daa2cf205 100644 --- a/services/shellchat/src/cmds/net_cmd.rs +++ b/services/shellchat/src/cmds/net_cmd.rs @@ -3,12 +3,14 @@ use xous_ipc::String; use net::Duration; use xous::MessageEnvelope; use num_traits::*; +use std::net::SocketAddr; #[derive(Debug)] pub struct NetCmd { udp: Option, callback_id: Option, callback_conn: u32, + udp_count: u32, } impl NetCmd { pub fn new(xns: &xous_names::XousNames) -> Self { @@ -16,6 +18,7 @@ impl NetCmd { udp: None, callback_id: None, callback_conn: xns.request_connection_blocking(crate::SERVER_NAME_SHELLCHAT).unwrap(), + udp_count: 0, } } } @@ -38,16 +41,27 @@ impl<'a> ShellCmdApi<'a> for NetCmd { use core::fmt::Write; let mut ret = String::<1024>::new(); - let helpstring = "net [udp]"; + let helpstring = "net [udp [port]]"; let mut tokens = args.as_str().unwrap().split(' '); if let Some(sub_cmd) = tokens.next() { match sub_cmd { + /// Testing of udp is done with netcat: + /// to send packets run `netcat -u 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 self.udp.is_none() { + 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() { + if let Ok(n) = tok_str.parse::() { n } else { 6502 } + } else { + 6502 + }; let mut udp = net::UdpSocket::bind_xous( - "127.0.0.1:6969", + format!("127.0.0.1:{}", port), Some(UDP_TEST_SIZE as u16) ).unwrap(); udp.set_read_timeout(Some(Duration::from_millis(1000))).unwrap(); @@ -57,9 +71,7 @@ impl<'a> ShellCmdApi<'a> for NetCmd { [Some(NetCmdDispatch::UdpTest1.to_usize().unwrap()), None, None, None] ); self.udp = Some(udp); - write!(ret, "Created UDP socket listener on port 6969").unwrap(); - } else { - write!(ret, "Socket listener already installed on 6969").unwrap(); + write!(ret, "Created UDP socket listener on port {}", port).unwrap(); } } _ => { @@ -82,12 +94,25 @@ impl<'a> ShellCmdApi<'a> for NetCmd { xous::msg_scalar_unpack!(msg, dispatch, _, _, _, { match FromPrimitive::from_usize(dispatch) { Some(NetCmdDispatch::UdpTest1) => { - if let Some(udp_socket) = &self.udp { + if let Some(udp_socket) = &mut self.udp { let mut pkt: [u8; UDP_TEST_SIZE] = [0; UDP_TEST_SIZE]; match udp_socket.recv_from(&mut pkt) { Ok((len, addr)) => { - write!(ret, "UDP received {} bytes: {:?}: {}", len, addr, std::str::from_utf8(&pkt[..len]).unwrap()).unwrap(); - log::info!("UDP received {} bytes: {:?}: {:?}", len, addr, &pkt[..len]); + write!(ret, "UDP rx {} bytes: {:?}: {}\n", len, addr, std::str::from_utf8(&pkt[..len]).unwrap()).unwrap(); + log::info!("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!("Received {} packets\n\r", self.udp_count).as_bytes(), + &response_addr + ) { + Ok(len) => write!(ret, "UDP tx {} bytes", len).unwrap(), + Err(_) => write!(ret, "UDP tx err").unwrap(), + } }, Err(e) => { log::error!("Net UDP error: {:?}", e);