From 89442ff4ccaa9379058414150e80c858b930e71b Mon Sep 17 00:00:00 2001 From: Sean Cross Date: Thu, 17 Mar 2022 20:38:21 +0800 Subject: [PATCH] net: add StdTcp calls These calls have been tested to work to create tcp connections. Signed-off-by: Sean Cross --- services/net/src/api.rs | 302 +++++++--- services/net/src/main.rs | 1194 +++++++++++++++++++++++++++++--------- 2 files changed, 1119 insertions(+), 377 deletions(-) diff --git a/services/net/src/api.rs b/services/net/src/api.rs index 5c4f9488f..2afb13e37 100644 --- a/services/net/src/api.rs +++ b/services/net/src/api.rs @@ -1,26 +1,28 @@ pub(crate) mod udp; -#[allow(unused_imports)] // needed to keep hosted mode quiet, since the Udp implementation is a bodge +// needed to keep hosted mode quiet, since the Udp implementation is a bodge +#[allow(unused_imports)] pub(crate) use udp::*; pub(crate) mod ping; pub(crate) use ping::*; pub(crate) mod tcp; -#[allow(unused_imports)] // needed to keep hosted mode quiet, since the Tcp implementation is a bodge -pub(crate) use tcp::*; pub use ping::NetPingCallback; +// needed to keep hosted mode quiet, since the Tcp implementation is a bodge +#[allow(unused_imports)] +pub(crate) use tcp::*; +use com::SsidRecord; use rkyv::{Archive, Deserialize, Serialize}; -use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}; use smoltcp::wire::IpAddress; use std::convert::TryInto; use std::fmt; use std::fmt::Debug; use std::io::Write; -use com::SsidRecord; +use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}; // republish this so we can decode the icmpv4 error codes pub use smoltcp::wire::Icmpv4DstUnreachable; -pub(crate) const SERVER_NAME_NET: &str = "_Middleware Network Server_"; +pub(crate) const SERVER_NAME_NET: &str = "_Middleware Network Server_"; #[allow(dead_code)] pub const AP_DICT_NAME: &'static str = "wlan.networks"; @@ -30,54 +32,121 @@ pub const MIN_EC_REV: u32 = 0x00_09_06_00; /// Dispatch opcodes to the Net crate main loop. #[derive(num_derive::FromPrimitive, num_derive::ToPrimitive, Debug)] +#[repr(C)] pub(crate) enum Opcode { /// Calls for UDP implementation - UdpBind, - UdpClose, - UdpTx, - UdpSetTtl, - UdpGetTtl, + UdpBind = 0, + UdpClose = 1, + UdpTx = 2, + UdpSetTtl = 3, + UdpGetTtl = 4, /// Calls for TCP implementation - TcpConnect, - TcpTx, - TcpClose, - TcpManage, - TcpListen, - TcpManageListener, + TcpConnect = 5, + TcpTx = 6, + TcpClose = 7, + TcpManage = 8, + TcpListen = 9, + TcpManageListener = 10, // The DNS server can hook the Net crate for notifications on config updates /// Adds an Ipv4 as a DNS server - DnsHookAddIpv4, + DnsHookAddIpv4 = 11, /// Adds an Ipv6 as a DNS server. Separate messages because max scalar arg is 128 bits. - DnsHookAddIpv6, + DnsHookAddIpv6 = 12, /// Called on IP config update -- clears all DNS servers. - DnsHookAllClear, - DnsUnhookAll, + DnsHookAllClear = 13, + DnsUnhookAll = 14, /// Ping stack - Ping, - PingSetTtl, - PingGetTtl, - PingSetTimeout, - PingGetTimeout, + Ping = 15, + PingSetTtl = 16, + PingGetTtl = 17, + PingSetTimeout = 18, + PingGetTimeout = 19, /// Link Management, - GetIpv4Config, - Reset, - SubscribeWifiStats, - UnsubWifiStats, - FetchSsidList, - ConnMgrStartStop, + GetIpv4Config = 20, + Reset = 21, + SubscribeWifiStats = 22, + UnsubWifiStats = 23, + FetchSsidList = 24, + ConnMgrStartStop = 25, /// [Internal] com llio interrupt callback - ComInterrupt, + ComInterrupt = 26, /// [Internal] run the network stack code - NetPump, + NetPump = 27, /// Suspend/resume callback - SuspendResume, + SuspendResume = 28, /// Quit the server - Quit + Quit = 29, + + /// Create a connection to the target address + /// + /// # Arguments + /// + /// u8 array + /// -------|--------- + /// offset | Contents + /// =======|========= + /// 0 | port number, low byte + /// 1 | port number, high byte + /// 2 | address type -- 4 = ipv4, 6 = ipv6 + /// ... | remaining bytes are the address + /// + /// # Returns + /// + /// u16 array + /// -------|--------- + /// offset | Contents + /// =======|========= + /// 0 | 0 indicating success + /// 1 | Connection index + /// 2 | local port + /// 3 | remote port + /// + /// # Errors + /// + /// u8 array + /// -------|--------- + /// offset | Contents + /// =======|========= + /// 0 | 1 indicating error + /// 1 | 1 indicating error (duplicated) + /// 2 | 1 indicating error (duplicated) + /// 3 | 1 indicating error (duplicated) + /// 4 | Error code + StdTcpConnect = 30, + + /// Transmit data to the specified TCP Connection + /// + /// # Arguments + /// + /// The connection ID is OR-ed into the top 16 bits of the opcode. The payload + /// is pointed to by the data buffer, and the `Valid` and Offset` flags indicate + /// which regions inside the memory are valid. + /// + /// # Returns + /// + /// u32 array + /// -------|--------- + /// offset | Contents + /// =======|========= + /// 0 | 0 if no error, 1 if error + /// 1 | Number of bytes transferred, or code of the error + /// + StdTcpTx = 31, + + /// Receives data from the specified TCP Connection. The TCP connection number is + /// passed in the upper 16 bits of the opcode, and the number of received bytes + /// is returned as part of the `Valid` parameter. + StdTcpRx = 32, + + /// Close the TCP connection. The connection ID is specified in the upper 16 bits + /// of the opcode. This may be any kind of message (scalar, blockingscalar, memory, + /// etc.) + StdTcpClose = 33, } #[derive(Debug, Archive, Serialize, Deserialize, Copy, Clone, Default)] @@ -94,7 +163,7 @@ pub enum XousServerId { PrivateSid([u32; 4]), /// A name that needs to be looked up with XousNames. Easier to implement, but less secure as it requires /// an open connection slot that could be abused by other processes. - ServerName(xous_ipc::String::<64>), + ServerName(xous_ipc::String<64>), } /// These opcodes are reserved for private SIDs shared from a DNS server to @@ -127,6 +196,7 @@ pub(crate) enum NetCallback { } #[derive(Debug, Archive, Serialize, Deserialize, Copy, Clone, PartialEq, Eq)] +#[repr(C, u16)] pub(crate) enum NetMemResponse { Ok, Sent(u16), @@ -139,9 +209,21 @@ pub(crate) enum NetMemResponse { AlreadyUsed, } +#[repr(C)] +pub enum NetError { + Ok = 0, + OutOfMemory = 1, + SocketInUse = 2, + AccessDenied = 3, + Invalid = 4, + Finished = 5, + LibraryError = 6, + AlreadyUsed = 7, +} + /////// 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) struct NetSocketAddr { pub(crate) addr: NetIpAddr, pub(crate) port: u16, } @@ -162,24 +244,16 @@ pub enum NetIpAddr { 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()) - } + 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) - }, + IpAddress::Ipv4(ipv4) => NetIpAddr::Ipv4(ipv4.0), + IpAddress::Ipv6(ipv6) => NetIpAddr::Ipv6(ipv6.0), _ => { panic!("Invalid IpAddress") } @@ -189,24 +263,16 @@ impl From for NetIpAddr { impl From for NetIpAddr { fn from(other: IpAddr) -> NetIpAddr { match other { - IpAddr::V4(ipv4) => { - NetIpAddr::Ipv4(ipv4.octets()) - }, - IpAddr::V6(ipv6) => { - NetIpAddr::Ipv6(ipv6.octets()) - } + IpAddr::V4(ipv4) => NetIpAddr::Ipv4(ipv4.octets()), + IpAddr::V6(ipv6) => NetIpAddr::Ipv6(ipv6.octets()), } } } impl From for IpAddr { fn from(other: NetIpAddr) -> IpAddr { match other { - NetIpAddr::Ipv4(octets) => { - IpAddr::V4(Ipv4Addr::from(octets)) - } - NetIpAddr::Ipv6(octets) => { - IpAddr::V6(Ipv6Addr::from(octets)) - } + NetIpAddr::Ipv4(octets) => IpAddr::V4(Ipv4Addr::from(octets)), + NetIpAddr::Ipv6(octets) => IpAddr::V6(Ipv6Addr::from(octets)), } } } @@ -216,19 +282,16 @@ impl From for IpAddress { 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()), - ) - ) - } + 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()), + )), } } } @@ -243,7 +306,7 @@ pub fn ipaddress_to_ipaddr(other: IpAddress) -> IpAddr { let octets = ipv6.0; IpAddr::V6(Ipv6Addr::from(octets)) } - _ => unimplemented!() + _ => unimplemented!(), } } @@ -253,21 +316,30 @@ impl fmt::Display for NetIpAddr { NetIpAddr::Ipv4(octets) => { // Fast Path: if there's no alignment stuff, write directly to the buffer if fmt.precision().is_none() && fmt.width().is_none() { - write!(fmt, "{}.{}.{}.{}", octets[0], octets[1], octets[2], octets[3]) + write!( + fmt, + "{}.{}.{}.{}", + octets[0], octets[1], octets[2], octets[3] + ) } else { const IPV4_BUF_LEN: usize = 15; // Long enough for the longest possible IPv4 address let mut buf = [0u8; IPV4_BUF_LEN]; let mut buf_slice = &mut buf[..]; // Note: The call to write should never fail, hence the unwrap - write!(buf_slice, "{}.{}.{}.{}", octets[0], octets[1], octets[2], octets[3]).unwrap(); + write!( + buf_slice, + "{}.{}.{}.{}", + octets[0], octets[1], octets[2], octets[3] + ) + .unwrap(); let len = IPV4_BUF_LEN - buf_slice.len(); // This unsafe is OK because we know what is being written to the buffer let buf = unsafe { std::str::from_utf8_unchecked(&buf[..len]) }; fmt.pad(buf) } - }, + } NetIpAddr::Ipv6(ip) => ip.fmt(fmt), } } @@ -307,7 +379,7 @@ impl XousScalarEndpoint { XousScalarEndpoint { cid: None, op: None, - args: [None; 4] + args: [None; 4], } } pub(crate) fn get(&self) -> (Option, Option, [Option; 4]) { @@ -333,11 +405,11 @@ impl XousScalarEndpoint { 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}, - ) + self.args[0].unwrap_or_default(), + self.args[1].unwrap_or_default(), + self.args[2].unwrap_or_default(), + self.args[3].unwrap_or_default(), + ), ) { Ok(_) => (), Err(e) => { @@ -356,18 +428,63 @@ impl XousScalarEndpoint { log::trace!("custom args"); if let Some(cid) = self.cid { if let Some(op) = self.op { - log::trace!("ca: {} {} cust{:?} self{:?} 0:{}", cid, op, custom, self.args, - if let Some(b) = custom[0] {b as usize} else { if let Some(a) = self.args[0] {a} else {0} } + log::trace!( + "ca: {} {} cust{:?} self{:?} 0:{}", + cid, + op, + custom, + self.args, + if let Some(b) = custom[0] { + b as usize + } else { + if let Some(a) = self.args[0] { + a + } else { + 0 + } + } ); match xous::send_message( cid, xous::Message::new_scalar( op, - if let Some(b) = custom[0] {b as usize} else { if let Some(a) = self.args[0] {a} else {0} }, - if let Some(b) = custom[1] {b as usize} else { if let Some(a) = self.args[1] {a} else {0} }, - if let Some(b) = custom[2] {b as usize} else { if let Some(a) = self.args[2] {a} else {0} }, - if let Some(b) = custom[3] {b as usize} else { if let Some(a) = self.args[3] {a} else {0} }, - ) + if let Some(b) = custom[0] { + b as usize + } else { + if let Some(a) = self.args[0] { + a + } else { + 0 + } + }, + if let Some(b) = custom[1] { + b as usize + } else { + if let Some(a) = self.args[1] { + a + } else { + 0 + } + }, + if let Some(b) = custom[2] { + b as usize + } else { + if let Some(a) = self.args[2] { + a + } else { + 0 + } + }, + if let Some(b) = custom[3] { + b as usize + } else { + if let Some(a) = self.args[3] { + a + } else { + 0 + } + }, + ), ) { Ok(_) => (), Err(e) => { @@ -380,7 +497,6 @@ impl XousScalarEndpoint { } } - /// This is a "generic" object for registering a hook between a remote, potentially /// untrusted server and my process. The SID filled into the hook should be a /// "one time" (or perhaps better phrased as "single purpose") SID. In other words, it's diff --git a/services/net/src/main.rs b/services/net/src/main.rs index 47f4fc3b4..50764c8f4 100644 --- a/services/net/src/main.rs +++ b/services/net/src/main.rs @@ -3,34 +3,31 @@ mod api; use api::*; -use num_traits::*; use com::api::{ComIntSources, Ipv4Conf, NET_MTU}; +use num_traits::*; -mod device; mod connection_manager; +mod device; -use xous::{Message, CID, SID, msg_scalar_unpack, msg_blocking_scalar_unpack, send_message}; -use xous_ipc::Buffer; -use std::collections::BTreeMap; -use std::collections::HashMap; +use std::collections::{BTreeMap, HashMap}; use std::convert::TryInto; +use xous::{msg_blocking_scalar_unpack, msg_scalar_unpack, send_message, Message, CID, SID}; +use xous_ipc::Buffer; -use smoltcp::phy::{Medium, Device}; -use smoltcp::iface::{InterfaceBuilder, NeighborCache, Routes, Interface}; -use smoltcp::socket::{IcmpEndpoint, IcmpPacketMetadata, IcmpSocket, IcmpSocketBuffer, SocketSet}; -use smoltcp::wire::{ - EthernetAddress, IpAddress, IpCidr, Ipv4Address, Ipv4Cidr, IpEndpoint -}; -use smoltcp::wire::{ - Icmpv4Packet, Icmpv4Repr, Icmpv6Packet, Icmpv6Repr, -}; use byteorder::{ByteOrder, NetworkEndian}; +use smoltcp::iface::{Interface, InterfaceBuilder, NeighborCache, Routes}; +use smoltcp::phy::{Device, Medium}; +use smoltcp::socket::{IcmpEndpoint, IcmpPacketMetadata, IcmpSocket, IcmpSocketBuffer, SocketSet}; +use smoltcp::wire::{EthernetAddress, IpAddress, IpCidr, IpEndpoint, Ipv4Address, Ipv4Cidr}; +use smoltcp::wire::{Icmpv4Packet, Icmpv4Repr, Icmpv6Packet, Icmpv6Repr}; -use smoltcp::socket::{UdpPacketMetadata, UdpSocket, UdpSocketBuffer, SocketHandle, TcpSocket, TcpSocketBuffer}; -use smoltcp::time::{Instant, Duration}; -use std::thread; -use std::sync::Arc; use core::sync::atomic::{AtomicU32, Ordering}; +use smoltcp::socket::{ + SocketHandle, TcpSocket, TcpSocketBuffer, UdpPacketMetadata, UdpSocket, UdpSocketBuffer, +}; +use smoltcp::time::{Duration, Instant}; +use std::sync::Arc; +use std::thread; const PING_DEFAULT_TIMEOUT_MS: u32 = 10_000; @@ -39,7 +36,10 @@ where DeviceT: for<'d> Device<'d>, { iface.update_ip_addrs(|addrs| { - let dest = addrs.iter_mut().next().expect("trouble updating ipv4 addresses in routing table"); + let dest = addrs + .iter_mut() + .next() + .expect("trouble updating ipv4 addresses in routing table"); *dest = IpCidr::Ipv4(cidr); }); } @@ -92,7 +92,7 @@ pub struct TcpState { shutdown_rx: bool, } -fn set_com_ints(com_int_list: &mut Vec::) { +fn set_com_ints(com_int_list: &mut Vec) { com_int_list.clear(); com_int_list.push(ComIntSources::WlanIpConfigUpdate); com_int_list.push(ComIntSources::WlanRxReady); @@ -104,6 +104,260 @@ fn set_com_ints(com_int_list: &mut Vec::) { com_int_list.push(ComIntSources::WfxErr); } +fn parse_address(data: &[u8]) -> Option { + let mut i = data.iter(); + match i.next() { + Some(&4) => Some(smoltcp::wire::IpAddress::v4( + *i.next()?, + *i.next()?, + *i.next()?, + *i.next()?, + )), + Some(&6) => { + let mut new_addr = [0u8; 16]; + for octet in new_addr.iter_mut() { + *octet = *i.next()?; + } + let v6: std::net::Ipv6Addr = new_addr.into(); + Some(v6.into()) + } + _ => None, + } +} + +fn respond_with_error(mut env: xous::MessageEnvelope, code: NetError) -> Option<()> { + // If it's not a memory message, don't fill in the return information. + let body = match env.body.memory_message_mut() { + None => { + // But do respond to the scalar message, if it's a BlockingScalar + if env.body.scalar_message().is_some() && env.body.is_blocking() { + xous::return_scalar(env.sender, code as usize).ok(); + } + return None; + } + Some(b) => b, + }; + + let s: &mut [u8] = body.buf.as_slice_mut(); + let mut i = s.iter_mut(); + + // Duplicate error to ensure it's seen as an error regardless of byte order + *i.next()? = 1; + *i.next()? = 1; + *i.next()? = 1; + *i.next()? = 1; + *i.next()? = code as u8; + None +} + +fn std_tcp_connect( + mut msg: xous::MessageEnvelope, + local_port: u16, + sockets: &mut SocketSet, + our_sockets: &mut Vec>, +) { + // Ignore nonblocking and scalar messages + let body = match msg.body.memory_message_mut() { + Some(b) => b, + None => { + log::trace!("invalid message type"); + respond_with_error(msg, NetError::LibraryError); + return; + } + }; + + let bytes = body.buf.as_slice::(); + let remote_port = u16::from_le_bytes([bytes[0], bytes[1]]); + let address = match parse_address(&bytes[2..]) { + Some(addr) => addr, + None => { + log::trace!("couldn't parse address"); + respond_with_error(msg, NetError::LibraryError); + return; + } + }; + + // initiates a new connection to a remote server consisting of an (Address:Port) tuple. + // multiple connections can exist to a server, and they are further differentiated by the return port + let mut tcp_socket = TcpSocket::new( + TcpSocketBuffer::new(vec![0; TCP_BUFFER_SIZE]), + TcpSocketBuffer::new(vec![0; TCP_BUFFER_SIZE]), + ); + + // Attempt to connect, returning the error if there is one + if let Err(e) = tcp_socket + .connect((address, remote_port), local_port) + .map_err(|e| match e { + smoltcp::Error::Illegal => NetError::SocketInUse, + smoltcp::Error::Unaddressable => NetError::Invalid, + _ => NetError::LibraryError, + }) + { + log::trace!("couldn't connect"); + respond_with_error(msg, e); + return; + } + + let handle = sockets.add(tcp_socket); + + // Look for a free index, or add it onto the end. + let mut idx = None; + for (i, elem) in our_sockets.iter_mut().enumerate() { + if elem.is_none() { + idx = Some(i); + *elem = Some(handle); + break; + } + } + if idx.is_none() { + idx = Some(our_sockets.len()); + our_sockets.push(Some(handle)); + } + + // We're done with the `bytes` array now as we've extracted all the data from it. + drop(bytes); + let bfr = body.buf.as_slice_mut::(); + + log::trace!("successfully connected: {}", idx.unwrap_or_default()); + bfr[0] = 0; + bfr[1] = idx.unwrap_or_default() as u16; + bfr[2] = local_port as u16; + bfr[3] = remote_port as u16; +} + +fn std_tcp_tx( + mut msg: xous::MessageEnvelope, + sockets: &mut SocketSet, + tcp_tx_waiting: &mut Vec>, + our_sockets: &Vec>, +) { + let connection_handle_index = (msg.body.id() >> 16) & 0xffff; + let body = match msg.body.memory_message_mut() { + Some(body) => body, + None => { + respond_with_error(msg, NetError::LibraryError); + return; + } + }; + + let handle = match our_sockets.get(connection_handle_index) { + Some(Some(val)) => val, + _ => { + respond_with_error(msg, NetError::Invalid); + return; + } + }; + + let mut socket = sockets.get::(*handle); + if !socket.may_send() { + log::trace!("tx can't send, will retry"); + // Add the message to the TcpRxWaiting list, which will prevent it from getting + // responded to right away. + let mut idx = None; + for (i, elem) in tcp_tx_waiting.iter_mut().enumerate() { + if elem.is_none() { + idx = Some(i); + break; + } + } + if let Some(idx) = idx { + tcp_tx_waiting[idx] = Some((msg, *handle)); + } else { + tcp_tx_waiting.push(Some((msg, *handle))); + } + return; + } + + // Perform the transfer + let sent_octets = { + let data = body.buf.as_slice::(); + let length = body + .valid + .map(|v| { + if v.get() > data.len() { + data.len() + } else { + v.get() + } + }) + .unwrap_or_else(|| data.len()); + + match socket.send_slice(&data[..length]) { + Ok(octets) => octets, + Err(_) => { + respond_with_error(msg, NetError::LibraryError); + return; + } + } + }; + + log::trace!("sent {}", sent_octets); + let response_data = body.buf.as_slice_mut::(); + body.valid = xous::MemorySize::new(sent_octets); + response_data[0] = 0; + response_data[1] = sent_octets as u32; +} + +fn std_tcp_rx( + mut msg: xous::MessageEnvelope, + sockets: &mut SocketSet, + tcp_rx_waiting: &mut Vec>, + our_sockets: &Vec>, +) { + let connection_handle_index = (msg.body.id() >> 16) & 0xffff; + let body = match msg.body.memory_message_mut() { + Some(body) => body, + None => { + respond_with_error(msg, NetError::LibraryError); + return; + } + }; + + // Default to having no valid data upon return, indicating an error + body.valid = None; + + let handle = match our_sockets.get(connection_handle_index) { + Some(Some(val)) => val, + _ => { + respond_with_error(msg, NetError::Invalid); + return; + } + }; + + let mut socket = sockets.get::(*handle); + if socket.can_recv() { + log::trace!("receiving data right away"); + match socket.recv_slice(body.buf.as_slice_mut()) { + Ok(bytes) => { + body.valid = xous::MemorySize::new(bytes); + log::trace!("set body.valid = {:?}", body.valid); + } + Err(e) => { + log::error!("unable to receive: {:?}", e); + respond_with_error(msg, NetError::LibraryError); + } + } + return; + } + + log::trace!("socket was not able to receive, adding it to list of waiting messages"); + + // Add the message to the TcpRxWaiting list, which will prevent it from getting + // responded to right away. + let mut idx = None; + for (i, elem) in tcp_rx_waiting.iter_mut().enumerate() { + if elem.is_none() { + idx = Some(i); + break; + } + } + if let Some(idx) = idx { + tcp_rx_waiting[idx] = Some((msg, *handle)); + } else { + tcp_rx_waiting.push(Some((msg, *handle))); + } +} + #[xous::xous_main] fn xmain() -> ! { log_server::init_wait().unwrap(); @@ -111,7 +365,9 @@ fn xmain() -> ! { log::info!("my PID is {}", xous::process::id()); let xns = xous_names::XousNames::new().unwrap(); - let net_sid = xns.register_name(api::SERVER_NAME_NET, None).expect("can't register server"); + let net_sid = xns + .register_name(api::SERVER_NAME_NET, None) + .expect("can't register server"); let net_conn = xous::connect(net_sid).unwrap(); log::trace!("registered with NS -- {:?}", net_sid); @@ -125,10 +381,11 @@ fn xmain() -> ! { // hook the COM interrupt listener let net_cid = xous::connect(net_sid).unwrap(); - llio.hook_com_event_callback(Opcode::ComInterrupt.to_u32().unwrap(), net_cid).unwrap(); + llio.hook_com_event_callback(Opcode::ComInterrupt.to_u32().unwrap(), net_cid) + .unwrap(); llio.com_event_enable(true).unwrap(); // setup the interrupt masks - let mut com_int_list: Vec:: = vec![]; + let mut com_int_list: Vec = vec![]; com.ints_get_active(&mut com_int_list).ok(); log::debug!("COM initial pending interrupts: {:?}", com_int_list); set_com_ints(&mut com_int_list); @@ -143,31 +400,47 @@ fn xmain() -> ! { // storage for all our sockets let mut sockets = SocketSet::new(vec![]); + // Each process keeps track of its own sockets. These are kept in a Vec. When a handle + // is destroyed, it is turned into a `None`. + let mut process_sockets: HashMap, Vec>> = HashMap::new(); + + // When a client issues a Receive request, it will get placed here while the packet data + // is being accumulated. + let mut tcp_rx_waiting: Vec> = Vec::new(); + + // When a client issues a Send request, it will get placed here while the packet data + // is being accumulated. + let mut tcp_tx_waiting: Vec> = Vec::new(); + // ping storage // up to four concurrent pings in the queue let icmp_rx_buffer = IcmpSocketBuffer::new( vec![ - IcmpPacketMetadata::EMPTY, - IcmpPacketMetadata::EMPTY, - IcmpPacketMetadata::EMPTY, - IcmpPacketMetadata::EMPTY - ], - vec![0; 1024]); + IcmpPacketMetadata::EMPTY, + IcmpPacketMetadata::EMPTY, + IcmpPacketMetadata::EMPTY, + IcmpPacketMetadata::EMPTY, + ], + vec![0; 1024], + ); let icmp_tx_buffer = IcmpSocketBuffer::new( vec![ - IcmpPacketMetadata::EMPTY, - IcmpPacketMetadata::EMPTY, - IcmpPacketMetadata::EMPTY, - IcmpPacketMetadata::EMPTY - ], - vec![0; 1024]); + IcmpPacketMetadata::EMPTY, + IcmpPacketMetadata::EMPTY, + IcmpPacketMetadata::EMPTY, + IcmpPacketMetadata::EMPTY, + ], + vec![0; 1024], + ); let mut icmp_socket = IcmpSocket::new(icmp_rx_buffer, icmp_tx_buffer); let ident = 0x22b; - icmp_socket.bind(IcmpEndpoint::Ident(ident)).expect("couldn't bind to icmp socket"); + icmp_socket + .bind(IcmpEndpoint::Ident(ident)) + .expect("couldn't bind to icmp socket"); let icmp_handle = sockets.add(icmp_socket); let mut seq: u16 = 0; // this record stores the origin time + IP address of the outgoing ping sequence number - let mut ping_destinations = HashMap::>::new(); + let mut ping_destinations = HashMap::>::new(); let mut ping_timeout_ms = PING_DEFAULT_TIMEOUT_MS; // udp storage @@ -175,11 +448,11 @@ fn xmain() -> ! { // 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::>::new(); // additional clones for UDP responders + let mut udp_clones = HashMap::>::new(); // additional clones for UDP responders // tcp storage let mut tcp_handles = HashMap::::new(); - let mut tcp_listeners = HashMap::>::new(); + let mut tcp_listeners = HashMap::>::new(); // other link storage let neighbor_cache = NeighborCache::new(BTreeMap::new()); @@ -212,13 +485,19 @@ fn xmain() -> ! { log::trace!("ready to accept requests"); // register a suspend/resume listener let sr_cid = xous::connect(net_sid).expect("couldn't create suspend callback connection"); - let mut susres = susres::Susres::new(Some(susres::SuspendOrder::Early), &xns, api::Opcode::SuspendResume as u32, sr_cid).expect("couldn't create suspend/resume object"); + let mut susres = susres::Susres::new( + Some(susres::SuspendOrder::Early), + &xns, + api::Opcode::SuspendResume as u32, + sr_cid, + ) + .expect("couldn't create suspend/resume object"); // kick off the connection manager thread let cm_sid = xous::create_server().expect("couldn't create connection manager server"); let cm_cid = xous::connect(cm_sid).unwrap(); let activity_interval = Arc::new(AtomicU32::new(0)); - #[cfg(not(feature="renode-minimal"))] + #[cfg(not(feature = "renode-minimal"))] thread::spawn({ let activity_interval = activity_interval.clone(); move || { @@ -229,22 +508,28 @@ fn xmain() -> ! { let mut cid_to_disconnect: Option = 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 - unsafe{ + if let Some(dc_cid) = cid_to_disconnect.take() { + // disconnect previous loop iter's connection after d/c OK response was sent + unsafe { match xous::disconnect(dc_cid) { - Ok(_) => {}, - Err(xous::Error::ServerNotFound) => { - log::trace!("Disconnect returned the expected error code for a remote that has been destroyed.") - }, - Err(e) => { - log::error!("Attempt to de-allocate CID to destroyed server met with error: {:?}", e); - }, + Ok(_) => {} + Err(xous::Error::ServerNotFound) => { + log::trace!("Disconnect returned the expected error code for a remote that has been destroyed.") + } + Err(e) => { + log::error!( + "Attempt to de-allocate CID to destroyed server met with error: {:?}", + e + ); + } } } } - match FromPrimitive::from_usize(msg.body.id()) { + match FromPrimitive::from_usize(msg.body.id() & 0xffff) { Some(Opcode::Ping) => { - let mut buf = unsafe{Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap())}; + let mut buf = unsafe { + Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap()) + }; let mut pkt = buf.to_original::().unwrap(); let mut socket = sockets.get::(icmp_handle); if socket.can_send() { @@ -252,18 +537,22 @@ fn xmain() -> ! { let remote = IpAddress::from(pkt.endpoint); // we take advantage of the fact that the same CID is always returned for repeated connect requests to the same SID. let cid = match pkt.server { - XousServerId::PrivateSid(sid) => match xous::connect(SID::from_array(sid)) { - Ok(cid) => cid, - Err(e) => { - log::error!("Ping request with single-use callback SID is invalid. Aborting request. {:?}",e); - continue; + XousServerId::PrivateSid(sid) => { + match xous::connect(SID::from_array(sid)) { + Ok(cid) => cid, + Err(e) => { + log::error!("Ping request with single-use callback SID is invalid. Aborting request. {:?}",e); + continue; + } } } - XousServerId::ServerName(name) => match xns.request_connection(name.to_str()) { - Ok(cid) => cid, - Err(e) => { - log::error!("Ping request received, but callback name '{}' is invalid. Aborting request. {:?}", name, e); - continue; + XousServerId::ServerName(name) => { + match xns.request_connection(name.to_str()) { + Ok(cid) => cid, + Err(e) => { + log::error!("Ping request received, but callback name '{}' is invalid. Aborting request. {:?}", name, e); + continue; + } } } }; @@ -273,7 +562,12 @@ fn xmain() -> ! { cid, retop: pkt.return_opcode, }; - log::trace!("ping conn info: remote {:?} / cid: {} / retp: {}", remote, cid, pkt.return_opcode); + log::trace!( + "ping conn info: remote {:?} / cid: {} / retp: {}", + remote, + cid, + pkt.return_opcode + ); // this code will guarantee the sequence number goes up, but if multiple concurrent // pings are in progress, they may not be directly in sequence. This is OK. let now = timer.elapsed_ms(); @@ -320,23 +614,20 @@ fn xmain() -> ! { } seq += 1; // fire off a Pump to get the stack to actually transmit the ping; this call merely queues it for sending - xous::try_send_message(net_conn, - Message::new_scalar( - Opcode::NetPump.to_usize().unwrap(), - 0, 0, 0, 0) - ).ok(); + xous::try_send_message( + net_conn, + Message::new_scalar(Opcode::NetPump.to_usize().unwrap(), 0, 0, 0, 0), + ) + .ok(); pkt.sent_ok = Some(true); } else { pkt.sent_ok = Some(false); } - buf.replace(pkt).expect("Xous couldn't issue response to Ping request"); + buf.replace(pkt) + .expect("Xous couldn't issue response to Ping request"); } Some(Opcode::PingSetTtl) => msg_scalar_unpack!(msg, ttl, _, _, _, { - let checked_ttl = if ttl > 255 { - 255 as u8 - } else { - ttl as u8 - }; + let checked_ttl = if ttl > 255 { 255 as u8 } else { ttl as u8 }; let mut socket = sockets.get::(icmp_handle); socket.set_hop_limit(Some(checked_ttl)); }), @@ -356,7 +647,9 @@ fn xmain() -> ! { xous::return_scalar(msg.sender, ping_timeout_ms as usize).unwrap(); }), Some(Opcode::DnsHookAddIpv4) => { - let mut buf = unsafe{Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap())}; + let mut buf = unsafe { + Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap()) + }; let hook = buf.to_original::().unwrap(); if dns_ipv4_hook.is_set() { buf.replace(NetMemResponse::AlreadyUsed).unwrap(); @@ -370,7 +663,9 @@ fn xmain() -> ! { } } Some(Opcode::DnsHookAddIpv6) => { - let mut buf = unsafe{Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap())}; + let mut buf = unsafe { + Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap()) + }; let hook = buf.to_original::().unwrap(); if dns_ipv6_hook.is_set() { buf.replace(NetMemResponse::AlreadyUsed).unwrap(); @@ -384,7 +679,9 @@ fn xmain() -> ! { } } Some(Opcode::DnsHookAllClear) => { - let mut buf = unsafe{Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap())}; + let mut buf = unsafe { + Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap()) + }; let hook = buf.to_original::().unwrap(); if dns_allclear_hook.is_set() { buf.replace(NetMemResponse::AlreadyUsed).unwrap(); @@ -396,7 +693,6 @@ fn xmain() -> ! { ); buf.replace(NetMemResponse::Ok).unwrap(); } - } Some(Opcode::DnsUnhookAll) => msg_blocking_scalar_unpack!(msg, _, _, _, _, { dns_ipv4_hook.clear(); @@ -404,8 +700,71 @@ fn xmain() -> ! { dns_allclear_hook.clear(); xous::return_scalar(msg.sender, 1).expect("couldn't ack unhook"); }), + + Some(Opcode::StdTcpConnect) => { + // Pick a random locak port using the system's TRNG + let local_port = (trng.get_u32().unwrap() % 16384 + 49152) as u16; + let pid = msg.sender.pid(); + + std_tcp_connect( + msg, + local_port, + &mut sockets, + process_sockets.entry(pid).or_default(), + ); + } + + Some(Opcode::StdTcpTx) => { + let pid = msg.sender.pid(); + std_tcp_tx( + msg, + &mut sockets, + &mut tcp_tx_waiting, + process_sockets.entry(pid).or_default(), + ); + } + + Some(Opcode::StdTcpRx) => { + let pid = msg.sender.pid(); + std_tcp_rx( + msg, + &mut sockets, + &mut tcp_rx_waiting, + process_sockets.entry(pid).or_default(), + ); + } + + Some(Opcode::StdTcpClose) => { + let pid = msg.sender.pid(); + let connection_idx = msg.body.id() >> 16; + let handle = if let Some(connection) = process_sockets + .entry(pid) + .or_default() + .get_mut(connection_idx) + { + if let Some(connection) = connection.take() { + connection + } else { + respond_with_error(msg, NetError::Invalid); + continue; + } + } else { + respond_with_error(msg, NetError::Invalid); + continue; + }; + sockets.get::(handle).close(); + sockets.remove(handle); + if let Some(response) = msg.body.memory_message_mut() { + response.buf.as_slice_mut::()[0] = 0; + } else if !msg.body.is_blocking() && msg.body.is_blocking() { + xous::return_scalar(msg.sender, 0).ok(); + } + } + Some(Opcode::TcpConnect) => { - let mut buf = unsafe{Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap())}; + let mut buf = unsafe { + Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap()) + }; let mut tcpspec = buf.to_original::().unwrap(); // need to define this let address = IpAddress::from(tcpspec.ip_addr); let remote_port = tcpspec.remote_port; @@ -441,24 +800,24 @@ fn xmain() -> ! { tcpspec.local_port = Some(local_port); tcpspec.result = Some(NetMemResponse::Ok); } - Err(e) => { - match e { - smoltcp::Error::Illegal => { - tcpspec.result = Some(NetMemResponse::SocketInUse); - } - smoltcp::Error::Unaddressable => { - tcpspec.result = Some(NetMemResponse::Invalid); - } - _ => { - tcpspec.result = Some(NetMemResponse::LibraryError); - } + Err(e) => match e { + smoltcp::Error::Illegal => { + tcpspec.result = Some(NetMemResponse::SocketInUse); } - } + smoltcp::Error::Unaddressable => { + tcpspec.result = Some(NetMemResponse::Invalid); + } + _ => { + tcpspec.result = Some(NetMemResponse::LibraryError); + } + }, } buf.replace(tcpspec).unwrap(); - }, + } Some(Opcode::TcpManage) => { - let mut buf = unsafe{Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap())}; + let mut buf = unsafe { + Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap()) + }; let mut tcpspec = buf.to_original::().unwrap(); if let Some(local_port) = tcpspec.local_port { let connection = TcpConnection { @@ -486,7 +845,9 @@ fn xmain() -> ! { } TcpMgmtCode::SetTtl(mut ttl) => { let mut socket = sockets.get::(tcp_state.handle); - if ttl > 255 { ttl = 255; } + if ttl > 255 { + ttl = 255; + } if ttl > 0 { socket.set_hop_limit(Some(ttl as u8)); } else { @@ -511,7 +872,8 @@ fn xmain() -> ! { _ => Some(NetMemResponse::LibraryError), } ));*/ - tcpspec.mgmt_code = Some(TcpMgmtCode::ErrorCheck(NetMemResponse::Ok)); + tcpspec.mgmt_code = + Some(TcpMgmtCode::ErrorCheck(NetMemResponse::Ok)); tcpspec.result = Some(NetMemResponse::Ok); } TcpMgmtCode::Flush(_) => { @@ -538,8 +900,11 @@ fn xmain() -> ! { } buf.replace(tcpspec).unwrap(); } + Some(Opcode::TcpTx) => { - let mut buf = unsafe{Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap())}; + let mut buf = unsafe { + Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap()) + }; let mut tcp_tx = buf.to_original::().unwrap(); let connection = TcpConnection { remote: IpAddress::from(tcp_tx.remote_addr), @@ -549,12 +914,13 @@ fn xmain() -> ! { if let Some(tcp_state) = tcp_handles.get(&connection) { let mut socket = sockets.get::(tcp_state.handle); if socket.may_send() { - tcp_tx.result = match socket.send_slice(&tcp_tx.data[..tcp_tx.len as usize]) { + tcp_tx.result = match socket.send_slice(&tcp_tx.data[..tcp_tx.len as usize]) + { Ok(octets) => { log::trace!("sent {}", octets); tcp_tx.len = octets as u16; Some(NetMemResponse::Sent(octets as u16)) - }, + } Err(_) => Some(NetMemResponse::LibraryError), } } else { @@ -567,9 +933,11 @@ fn xmain() -> ! { tcp_tx.result = Some(NetMemResponse::Invalid); } buf.replace(tcp_tx).unwrap(); - }, + } Some(Opcode::TcpClose) => { - let mut buf = unsafe{Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap())}; + let mut buf = unsafe { + Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap()) + }; let mut tcpspec = buf.to_original::().unwrap(); // need to define this if let Some(local_port) = tcpspec.local_port { let connection = TcpConnection { @@ -590,7 +958,9 @@ fn xmain() -> ! { buf.replace(tcpspec).unwrap(); } Some(Opcode::TcpListen) => { - let mut buf = unsafe{Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap())}; + let mut buf = unsafe { + Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap()) + }; let mut tcpspec = buf.to_original::().unwrap(); let tcp_rx_buffer = TcpSocketBuffer::new(vec![0; TCP_BUFFER_SIZE]); @@ -600,7 +970,8 @@ fn xmain() -> ! { match tcp_socket.listen(tcpspec.local_port) { Ok(_) => { if let Some(list) = tcp_listeners.get(&tcpspec.local_port) { - if list.len() > 0 { // empty check necessary because an empty vector is left if a socket went from listening->active, or was dropped + if list.len() > 0 { + // empty check necessary because an empty vector is left if a socket went from listening->active, or was dropped // guarantee that all TTLs are same even if we're inserting a new socket let ttl = sockets.get::(list[0].handle).hop_limit(); tcp_socket.set_hop_limit(ttl); @@ -617,38 +988,46 @@ fn xmain() -> ! { }; if let Some(list) = tcp_listeners.get_mut(&tcpspec.local_port) { list.push(tcp_cb_state); - log::trace!("total listeners on port {}: {}", tcpspec.local_port, list.len()); + log::trace!( + "total listeners on port {}: {}", + tcpspec.local_port, + list.len() + ); } else { tcp_listeners.insert(tcpspec.local_port, vec![tcp_cb_state]); log::trace!("creating first listener on port {}", tcpspec.local_port); } tcpspec.result = Some(NetMemResponse::Ok); } - Err(e) => { - match e { - smoltcp::Error::Illegal => { - tcpspec.result = Some(NetMemResponse::SocketInUse); - } - smoltcp::Error::Unaddressable => { - tcpspec.result = Some(NetMemResponse::Invalid); - } - _ => { - tcpspec.result = Some(NetMemResponse::LibraryError); - } + Err(e) => match e { + smoltcp::Error::Illegal => { + tcpspec.result = Some(NetMemResponse::SocketInUse); } - } + smoltcp::Error::Unaddressable => { + tcpspec.result = Some(NetMemResponse::Invalid); + } + _ => { + tcpspec.result = Some(NetMemResponse::LibraryError); + } + }, } buf.replace(tcpspec).unwrap(); - }, + } Some(Opcode::TcpManageListener) => { - let mut buf = unsafe{Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap())}; + let mut buf = unsafe { + Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap()) + }; let mut tcpspec = buf.to_original::().unwrap(); match tcpspec.mgmt_code { Some(TcpMgmtCode::CloseListener) => { - if let Some(listener) = tcp_listeners.get_mut(&tcpspec.local_port.unwrap()) { + if let Some(listener) = tcp_listeners.get_mut(&tcpspec.local_port.unwrap()) + { if let Some(tcp_state) = listener.pop() { sockets.get::(tcp_state.handle).close(); - log::debug!("closing one listener on port {:?}", tcpspec.local_port); + log::debug!( + "closing one listener on port {:?}", + tcpspec.local_port + ); sockets.remove(tcp_state.handle); tcpspec.result = Some(NetMemResponse::Ok); // this may leave an empty vector in the tcp_listeners structure, but I think that's OK @@ -658,10 +1037,14 @@ fn xmain() -> ! { } } Some(TcpMgmtCode::SetTtl(mut ttl)) => { - if let Some(listener_vec) = tcp_listeners.get_mut(&tcpspec.local_port.unwrap()) { + if let Some(listener_vec) = + tcp_listeners.get_mut(&tcpspec.local_port.unwrap()) + { for listener in listener_vec.iter_mut() { let mut socket = sockets.get::(listener.handle); - if ttl > 255 { ttl = 255; } + if ttl > 255 { + ttl = 255; + } if ttl > 0 { socket.set_hop_limit(Some(ttl as u8)); } else { @@ -693,7 +1076,9 @@ fn xmain() -> ! { buf.replace(tcpspec).unwrap(); } Some(Opcode::UdpBind) => { - let mut buf = unsafe{Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap())}; + let mut buf = unsafe { + Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap()) + }; let udpspec = buf.to_original::().unwrap(); let buflen = if let Some(maxlen) = udpspec.max_payload { @@ -711,22 +1096,21 @@ fn xmain() -> ! { 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() + } // 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 - ); + 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 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(_) => { @@ -734,7 +1118,7 @@ fn xmain() -> ! { let udpstate = UdpState { handle: sockets.add(udp_socket), cid: xous::connect(sid).unwrap(), - sid + sid, }; udp_handles.insert(udpspec.port, udpstate); buf.replace(NetMemResponse::Ok).unwrap(); @@ -745,23 +1129,23 @@ fn xmain() -> ! { } } } - }, + } Some(Opcode::UdpClose) => { - let mut buf = unsafe{Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap())}; + let mut buf = unsafe { + Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap()) + }; let udpspec = buf.to_original::().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 => {} + 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) { @@ -803,21 +1187,21 @@ fn xmain() -> ! { } } } - _ => { - buf.replace(NetMemResponse::Invalid).unwrap() - } + _ => buf.replace(NetMemResponse::Invalid).unwrap(), } - }, + } Some(Opcode::UdpTx) => { use std::convert::TryInto; - let mut buf = unsafe{Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap())}; + 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 + dest_socket.port, ); let mut socket = sockets.get::(udpstate.handle); match socket.send_slice(&udp_tx.data[..udp_tx.len as usize], endpoint) { @@ -825,31 +1209,37 @@ fn xmain() -> ! { _ => buf.replace(NetMemResponse::LibraryError).unwrap(), } // fire off a Pump to get the stack to actually transmit the ping; the send call merely queues it for sending - xous::try_send_message(net_conn, + xous::try_send_message( + net_conn, Message::new_scalar( Opcode::NetPump.to_usize().unwrap(), - 0, 0, 0, 0) - ).ok(); + 0, + 0, + 0, + 0, + ), + ) + .ok(); } else { buf.replace(NetMemResponse::Invalid).unwrap() } } - _ => buf.replace(NetMemResponse::Invalid).unwrap() + _ => 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::(udpstate.handle); - let checked_ttl = if ttl > 255 || ttl == 0 { - 64 - } else { - ttl as u8 - }; + 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); + log::error!( + "Set TTL message received, but no port was bound! port {} ttl {}", + port, + ttl + ); } } }), @@ -861,7 +1251,10 @@ fn xmain() -> ! { 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); + 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"); } } @@ -873,16 +1266,22 @@ fn xmain() -> ! { Ok((maybe_rxlen, ints, raw_rxlen)) => { log::debug!("COM got interrupts: {:?}, {:?}", com_int_list, maybe_rxlen); // forward the interrupt to the connection manager as well - match xous::try_send_message(cm_cid, Message::new_scalar( - connection_manager::ConnectionManagerOpcode::ComInt.to_usize().unwrap(), - ints, - raw_rxlen, - 0, 0 - )) { - Ok(_) => {}, + match xous::try_send_message( + cm_cid, + Message::new_scalar( + connection_manager::ConnectionManagerOpcode::ComInt + .to_usize() + .unwrap(), + ints, + raw_rxlen, + 0, + 0, + ), + ) { + Ok(_) => {} Err(xous::Error::ServerQueueFull) => { log::warn!("Our net queue runneth over, interrupts were dropped."); - }, + } Err(e) => { log::error!("Unhandled error forwarding ComInt to the connection manager: {:?}", e); } @@ -897,11 +1296,13 @@ fn xmain() -> ! { match pending { ComIntSources::BatteryCritical => { log::warn!("Battery is critical! TODO: go into SHIP mode"); - }, + } ComIntSources::WlanIpConfigUpdate => { // right now the WLAN implementation only does IPV4. So IPV6 compatibility ends here. // if IPV6 gets added to the EC/COM bus, ideally this is one of a couple spots in Xous that needs a tweak. - let config = com.wlan_get_config().expect("couldn't retrieve updated ipv4 config"); + let config = com + .wlan_get_config() + .expect("couldn't retrieve updated ipv4 config"); log::info!("Network config acquired: {:?}", config); net_config = Some(config); let mac = EthernetAddress::from_bytes(&config.mac); @@ -912,7 +1313,8 @@ fn xmain() -> ! { // to neatly clear the ARP cache as the BTreeMap that underlies it is moved into the container and // no "clear" API is exposed, so let's just rebuild the whole interface if we get a DHCP renewal. let neighbor_cache = NeighborCache::new(BTreeMap::new()); - let ip_addrs = [IpCidr::new(Ipv4Address::UNSPECIFIED.into(), 0)]; + let ip_addrs = + [IpCidr::new(Ipv4Address::UNSPECIFIED.into(), 0)]; let routes = Routes::new(BTreeMap::new()); let device = device::NetPhy::new(&xns); let medium = device.capabilities().medium; @@ -926,13 +1328,15 @@ fn xmain() -> ! { } iface = builder.finalize(); - let ip_addr = - Ipv4Cidr::new(Ipv4Address::new( + let ip_addr = Ipv4Cidr::new( + Ipv4Address::new( config.addr[0], config.addr[1], config.addr[2], config.addr[3], - ), 24); + ), + 24, + ); set_ipv4_addr(&mut iface, ip_addr); let default_v4_gw = Ipv4Address::new( config.gtwy[0], @@ -944,23 +1348,30 @@ fn xmain() -> ! { // reset the default route, in case it has changed iface.routes_mut().remove_default_ipv4_route(); match iface.routes_mut().add_default_ipv4_route(default_v4_gw) { - Ok(route) => log::info!("routing table updated successfully [{:?}]", route), + Ok(route) => log::info!( + "routing table updated successfully [{:?}]", + route + ), Err(e) => log::error!("routing table update error: {}", e), } dns_allclear_hook.notify(); dns_ipv4_hook.notify_custom_args([ Some(u32::from_be_bytes(config.dns1)), - None, None, None, + None, + None, + None, ]); // the current implementation always returns 0.0.0.0 as the second dns, // ignore this if that's what we've got; otherwise, pass it on. if config.dns2 != [0, 0, 0, 0] { dns_ipv4_hook.notify_custom_args([ Some(u32::from_be_bytes(config.dns2)), - None, None, None, + None, + None, + None, ]); } - }, + } ComIntSources::WlanRxReady => { activity_interval.store(0, Ordering::Relaxed); // reset the activity interval to 0 if let Some(_config) = net_config { @@ -971,12 +1382,18 @@ fn xmain() -> ! { } match xous::try_send_message( net_conn, - Message::new_scalar(Opcode::NetPump.to_usize().unwrap(), 0, 0, 0, 0) + Message::new_scalar( + Opcode::NetPump.to_usize().unwrap(), + 0, + 0, + 0, + 0, + ), ) { - Ok(_) => {}, + Ok(_) => {} Err(xous::Error::ServerQueueFull) => { log::warn!("Our net queue runneth over, packets will be dropped."); - }, + } Err(e) => { log::error!("Unhandled error sending NetPump to self: {:?}", e); } @@ -985,14 +1402,14 @@ fn xmain() -> ! { log::error!("Got RxReady interrupt but no packet length specified!"); } } - }, + } _ => { log::debug!("Unhandled: {:?}", pending); } } } com.ints_ack(&com_int_list); - }, + } Err(xous::Error::Timeout) => { log::warn!("Interrupt fetch from COM timed out."); // bread crumb: this is a "normal" error to throw when the EC is being reset, @@ -1016,7 +1433,7 @@ fn xmain() -> ! { Some(Opcode::NetPump) => { let timestamp = Instant::from_millis(timer.elapsed_ms() as i64); match iface.poll(&mut sockets, timestamp) { - Ok(_) => { } + Ok(_) => {} Err(e) => { log::debug!("poll error: {}", e); } @@ -1028,37 +1445,112 @@ fn xmain() -> ! { if !tcp_state.shutdown_rx { let mut socket = sockets.get::(tcp_state.handle); if socket.can_recv() { - match socket - .recv(|data| { - let mut response = NetTcpResponse { - len: data.len() as u16, - data: [0; TCP_BUFFER_SIZE], - }; - for(&src, dst) in data.iter().zip(response.data.iter_mut()) { - *dst = src; - } - let buf = Buffer::into_buf(response).expect("couldn't convert TCP response to memory message"); - buf.send(tcp_state.cid, NetTcpCallback::RxData.to_u32().unwrap()).expect("couldn't send TCP response"); - (data.len(), ()) - }) { + match socket.recv(|data| { + let mut response = NetTcpResponse { + len: data.len() as u16, + data: [0; TCP_BUFFER_SIZE], + }; + for (&src, dst) in data.iter().zip(response.data.iter_mut()) { + *dst = src; + } + let buf = Buffer::into_buf(response) + .expect("couldn't convert TCP response to memory message"); + buf.send( + tcp_state.cid, + NetTcpCallback::RxData.to_u32().unwrap(), + ) + .expect("couldn't send TCP response"); + (data.len(), ()) + }) { Ok(_) => (), Err(e) => match e { smoltcp::Error::Illegal => { log::warn!("TCP fast open not supported"); - }, + } smoltcp::Error::Finished => { log::warn!("TCP packet received after close"); - }, + } _ => { log::warn!("Unknown TCP error"); } - } + }, } } } } } + // This block handles TCP Rx for libstd callers + for connection in tcp_rx_waiting.iter_mut() { + let (env, handle) = match connection { + &mut None => continue, + Some(s) => s, + }; + let mut socket = sockets.get::(*handle); + if !socket.can_recv() { + continue; + } + + let body = env.body.memory_message_mut().unwrap(); + match socket.recv_slice(body.buf.as_slice_mut()) { + Ok(count) => { + body.valid = xous::MemorySize::new(count); + } + Err(e) => { + log::trace!("unable to receive: {:?}", e); + body.valid = None; + } + } + + *connection = None; + } + + // This block handles TCP Tx for libstd callers + for connection in tcp_tx_waiting.iter_mut() { + match connection { + &mut None => continue, + Some(s) => { + let socket = sockets.get::(s.1); + if !socket.can_send() { + continue; + } + } + }; + let (mut env, handle) = connection.take().unwrap(); + let mut socket = sockets.get::(handle); + + let body = env.body.memory_message_mut().unwrap(); + // Perform the transfer + let sent_octets = { + let data = body.buf.as_slice::(); + let length = body + .valid + .map(|v| { + if v.get() > data.len() { + data.len() + } else { + v.get() + } + }) + .unwrap_or_else(|| data.len()); + + match socket.send_slice(&data[..length]) { + Ok(octets) => octets, + Err(_) => { + respond_with_error(env, NetError::LibraryError); + *connection = None; + continue; + } + } + }; + + log::trace!("sent {}", sent_octets); + let response_data = body.buf.as_slice_mut::(); + body.valid = xous::MemorySize::new(sent_octets); + response_data[0] = 0; + response_data[1] = sent_octets as u32; + } + // this block handles TCP listeners // There is no lock on sending Rx messages to the listener as it is being transformed // because all messages come from *this thread* and by definition it is not re-entrant. @@ -1066,14 +1558,19 @@ fn xmain() -> ! { // Then you must worry about the possibility of a race condition between the transition of a // TcpListener to a regular TcpStream client (that is, an Rx packet forwarded before the // TcpStream is fully built). - if tcp_listeners.len() > 0 { // skip the whole chunk if we don't have any tcp listeners - log::trace!("checking {} TCP listener sockets", tcp_listeners.len()); - for (&local_port, tcp_state_vec) in tcp_listeners.iter_mut() { + if tcp_listeners.len() > 0 { + // skip the whole chunk if we don't have any tcp listeners + log::trace!("checking {} TCP listener sockets", tcp_listeners.len()); + for (&local_port, tcp_state_vec) in tcp_listeners.iter_mut() { let mut remove_indices = Vec::::new(); for (index, tcp_state) in tcp_state_vec.iter().enumerate() { let socket = sockets.get::(tcp_state.handle); if socket.is_active() { - log::info!("Promoting a Listener on port {:?} from {:?} to a Stream", socket.local_endpoint(), socket.remote_endpoint()); + log::info!( + "Promoting a Listener on port {:?} from {:?} to a Stream", + socket.local_endpoint(), + socket.remote_endpoint() + ); // 1. promote this socket to a TCP rx socket (this creates a double-entry that is cleaned up in step 3) let connection = TcpConnection { remote: socket.remote_endpoint().addr, @@ -1088,9 +1585,18 @@ fn xmain() -> ! { remote_port: socket.remote_endpoint().port, local_port, }; - log::debug!("Listener active, notification sent to {}: {:x?}", tcp_state.cid, note); - let buf = Buffer::into_buf(note).expect("can't transform memory message"); - buf.send(tcp_state.cid, NetTcpCallback::ListenerActive.to_u32().unwrap()).expect("can't inform callback of active status"); + log::debug!( + "Listener active, notification sent to {}: {:x?}", + tcp_state.cid, + note + ); + let buf = + Buffer::into_buf(note).expect("can't transform memory message"); + buf.send( + tcp_state.cid, + NetTcpCallback::ListenerActive.to_u32().unwrap(), + ) + .expect("can't inform callback of active status"); log::trace!("listener index {} to remove", index); remove_indices.push(index); break; @@ -1136,19 +1642,24 @@ fn xmain() -> ! { for (&src, dst) in data.iter().zip(response.data.iter_mut()) { *dst = src; } - 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"); + 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"); + 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 - }, + } }; } } @@ -1161,7 +1672,9 @@ fn xmain() -> ! { } if socket.can_recv() { - let (payload, _) = socket.recv().expect("couldn't receive on socket despite asserting availability"); + let (payload, _) = socket + .recv() + .expect("couldn't receive on socket despite asserting availability"); log::trace!("icmp payload: {:x?}", payload); let now = timer.elapsed_ms(); @@ -1171,48 +1684,74 @@ fn xmain() -> ! { IpAddress::Ipv4(_) => { let icmp_packet = Icmpv4Packet::new_checked(&payload).unwrap(); let icmp_repr = - Icmpv4Repr::parse(&icmp_packet, &device_caps.checksum).unwrap(); + Icmpv4Repr::parse(&icmp_packet, &device_caps.checksum) + .unwrap(); if let Icmpv4Repr::EchoReply { seq_no, data, .. } = icmp_repr { - log::trace!("got icmp seq no {} / data: {:x?}", seq_no, data); + log::trace!( + "got icmp seq no {} / data: {:x?}", + seq_no, + data + ); if let Some(_) = waiting_queue.get(&seq_no) { let packet_timestamp_ms = NetworkEndian::read_i64(data); waiting_queue.remove(&seq_no); // use try_send_message because we don't want to block if the recipient's queue is full; // instead, the message is just dropped - match xous::try_send_message(connection.cid, + match xous::try_send_message( + connection.cid, Message::new_scalar( connection.retop, NetPingCallback::NoErr.to_usize().unwrap(), - u32::from_be_bytes(remote_addr.as_bytes().try_into().unwrap()) as usize, + u32::from_be_bytes( + remote_addr.as_bytes().try_into().unwrap(), + ) + as usize, seq_no as usize, (now as i64 - packet_timestamp_ms) as usize, - ) + ), ) { - Ok(_) => {}, + Ok(_) => {} Err(xous::Error::ServerQueueFull) => { log::warn!("Got seq {} response, but upstream server queue is full; dropping.", &seq_no); - }, + } Err(e) => { - log::error!("Unhandled error: {:?}; ignoring", e); + log::error!( + "Unhandled error: {:?}; ignoring", + e + ); } } } - } else if let Icmpv4Repr::DstUnreachable { reason, header, .. } = icmp_repr { - log::warn!("Got dst unreachable {:?}: {:?}", header.dst_addr, reason); + } else if let Icmpv4Repr::DstUnreachable { + reason, + header, + .. + } = icmp_repr + { + log::warn!( + "Got dst unreachable {:?}: {:?}", + header.dst_addr, + reason + ); let reason_code: u8 = From::from(reason); - match xous::try_send_message(connection.cid, + match xous::try_send_message( + connection.cid, Message::new_scalar( connection.retop, - NetPingCallback::Unreachable.to_usize().unwrap() | (reason_code as usize) << 24, - u32::from_be_bytes(remote_addr.as_bytes().try_into().unwrap()) as usize, + NetPingCallback::Unreachable.to_usize().unwrap() + | (reason_code as usize) << 24, + u32::from_be_bytes( + remote_addr.as_bytes().try_into().unwrap(), + ) + as usize, 0, 0, - ) + ), ) { - Ok(_) => {}, + Ok(_) => {} Err(xous::Error::ServerQueueFull) => { log::warn!("Got dst {:?} unreachable, but upstream server queue is full; dropping.", remote_addr); - }, + } Err(e) => { log::error!("Unhandled error: {:?}; ignoring", e); } @@ -1238,40 +1777,60 @@ fn xmain() -> ! { if let Some(_) = waiting_queue.get(&seq_no) { let packet_timestamp_ms = NetworkEndian::read_i64(data); waiting_queue.remove(&seq_no); - match xous::try_send_message(connection.cid, + match xous::try_send_message( + connection.cid, Message::new_scalar( connection.retop, NetPingCallback::NoErr.to_usize().unwrap(), - u32::from_be_bytes(ra[..4].try_into().unwrap()) as usize, - u32::from_be_bytes(ra[12..].try_into().unwrap()) as usize, + u32::from_be_bytes(ra[..4].try_into().unwrap()) + as usize, + u32::from_be_bytes(ra[12..].try_into().unwrap()) + as usize, (now as i64 - packet_timestamp_ms) as usize, - ) + ), ) { - Ok(_) => {}, + Ok(_) => {} Err(xous::Error::ServerQueueFull) => { log::warn!("Got seq {} response, but upstream server queue is full; dropping.", &seq_no); - }, + } Err(e) => { - log::error!("Unhandled error: {:?}; ignoring", e); + log::error!( + "Unhandled error: {:?}; ignoring", + e + ); } } } - } else if let Icmpv6Repr::DstUnreachable { reason, header, .. } = icmp_repr { + } else if let Icmpv6Repr::DstUnreachable { + reason, + header, + .. + } = icmp_repr + { let reason_code: u8 = From::from(reason); - log::warn!("Got dst unreachable {:?}: {:?}", header.dst_addr, reason); - match xous::try_send_message(connection.cid, + log::warn!( + "Got dst unreachable {:?}: {:?}", + header.dst_addr, + reason + ); + match xous::try_send_message( + connection.cid, Message::new_scalar( connection.retop, - NetPingCallback::Unreachable.to_usize().unwrap() | (reason_code as usize) << 24, - u32::from_be_bytes(ra[..4].try_into().unwrap()) as usize, - u32::from_be_bytes(ra[8..12].try_into().unwrap()) as usize, - u32::from_be_bytes(ra[12..].try_into().unwrap()) as usize, - ) - ){ - Ok(_) => {}, + NetPingCallback::Unreachable.to_usize().unwrap() + | (reason_code as usize) << 24, + u32::from_be_bytes(ra[..4].try_into().unwrap()) + as usize, + u32::from_be_bytes(ra[8..12].try_into().unwrap()) + as usize, + u32::from_be_bytes(ra[12..].try_into().unwrap()) + as usize, + ), + ) { + Ok(_) => {} Err(xous::Error::ServerQueueFull) => { log::warn!("Got dst {:?} unreachable, but upstream server queue is full; dropping.", remote_addr); - }, + } Err(e) => { log::error!("Unhandled error: {:?}; ignoring", e); } @@ -1366,28 +1925,41 @@ fn xmain() -> ! { if let Some(delay) = iface.poll_delay(&sockets, timestamp) { let delay_ms = delay.total_millis(); if delay_ms < 2 { - xous::try_send_message(net_conn, - Message::new_scalar( - Opcode::NetPump.to_usize().unwrap(), - 0, 0, 0, 0) - ).ok(); + xous::try_send_message( + net_conn, + Message::new_scalar(Opcode::NetPump.to_usize().unwrap(), 0, 0, 0, 0), + ) + .ok(); } else { if delay_threads.load(Ordering::SeqCst) < MAX_DELAY_THREADS { let prev_count = delay_threads.fetch_add(1, Ordering::SeqCst); - log::trace!("spawning checkup thread for {}ms. New total threads: {}", delay_ms, prev_count + 1); + log::trace!( + "spawning checkup thread for {}ms. New total threads: {}", + delay_ms, + prev_count + 1 + ); thread::spawn({ let parent_conn = net_conn.clone(); let delay_threads = delay_threads.clone(); move || { let tt = ticktimer_server::Ticktimer::new().unwrap(); tt.sleep_ms(delay_ms as usize).unwrap(); - xous::try_send_message(parent_conn, + xous::try_send_message( + parent_conn, Message::new_scalar( Opcode::NetPump.to_usize().unwrap(), - 0, 0, 0, 0) - ).ok(); + 0, + 0, + 0, + 0, + ), + ) + .ok(); let prev_count = delay_threads.fetch_sub(1, Ordering::SeqCst); - log::trace!("terminating checkup thread. New total threads: {}", prev_count - 1); + log::trace!( + "terminating checkup thread. New total threads: {}", + prev_count - 1 + ); } }); } else { @@ -1406,22 +1978,36 @@ fn xmain() -> ! { None }; buffer.replace(ser).expect("couldn't return config"); - }, + } Some(Opcode::SubscribeWifiStats) => { - let buffer = unsafe { - Buffer::from_memory_message(msg.body.memory_message().unwrap()) - }; + let buffer = + unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) }; // have to transform it through the local memory space because you can't re-lend pages let sub = buffer.to_original::().unwrap(); let buf = Buffer::into_buf(sub).expect("couldn't convert to memory message"); - buf.send(cm_cid, connection_manager::ConnectionManagerOpcode::SubscribeWifiStats.to_u32().unwrap()).expect("couldn't forward subscription request"); - }, + buf.send( + cm_cid, + connection_manager::ConnectionManagerOpcode::SubscribeWifiStats + .to_u32() + .unwrap(), + ) + .expect("couldn't forward subscription request"); + } Some(Opcode::UnsubWifiStats) => msg_blocking_scalar_unpack!(msg, s0, s1, s2, s3, { // now do something with the unsubscription - let response = xous::send_message(cm_cid, Message::new_blocking_scalar( - connection_manager::ConnectionManagerOpcode::UnsubWifiStats.to_usize().unwrap(), - s0, s1, s2, s3 - )).expect("couldn't send unsub message"); + let response = xous::send_message( + cm_cid, + Message::new_blocking_scalar( + connection_manager::ConnectionManagerOpcode::UnsubWifiStats + .to_usize() + .unwrap(), + s0, + s1, + s2, + s3, + ), + ) + .expect("couldn't send unsub message"); if let xous::Result::Scalar1(val) = response { xous::return_scalar(msg.sender, val).unwrap(); } else { @@ -1433,24 +2019,50 @@ fn xmain() -> ! { Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap()) }; let ret_storage = SsidList::default(); - let mut buf = Buffer::into_buf(ret_storage).expect("couldn't convert to memory message"); - buf.lend_mut(cm_cid, connection_manager::ConnectionManagerOpcode::FetchSsidList.to_u32().unwrap()).expect("couldn't forward ssid list request"); - let ret_list = buf.to_original::().expect("couldn't restore original"); + let mut buf = + Buffer::into_buf(ret_storage).expect("couldn't convert to memory message"); + buf.lend_mut( + cm_cid, + connection_manager::ConnectionManagerOpcode::FetchSsidList + .to_u32() + .unwrap(), + ) + .expect("couldn't forward ssid list request"); + let ret_list = buf + .to_original::() + .expect("couldn't restore original"); buffer.replace(ret_list).expect("couldn't return config"); - }, + } Some(Opcode::ConnMgrStartStop) => msg_scalar_unpack!(msg, code, _, _, _, { - if code == 0 { // 0 is stop, 1 is start - send_message(cm_cid, + if code == 0 { + // 0 is stop, 1 is start + send_message( + cm_cid, Message::new_scalar( - connection_manager::ConnectionManagerOpcode::Stop.to_usize().unwrap(), - 0, 0, 0, 0) - ).expect("couldn't send stop message"); + connection_manager::ConnectionManagerOpcode::Stop + .to_usize() + .unwrap(), + 0, + 0, + 0, + 0, + ), + ) + .expect("couldn't send stop message"); } else if code == 1 { - send_message(cm_cid, + send_message( + cm_cid, Message::new_scalar( - connection_manager::ConnectionManagerOpcode::Run.to_usize().unwrap(), - 0, 0, 0, 0) - ).expect("couldn't send stop message"); + connection_manager::ConnectionManagerOpcode::Run + .to_usize() + .unwrap(), + 0, + 0, + 0, + 0, + ), + ) + .expect("couldn't send stop message"); } else { log::error!("Got incorrect start/stop code: {}", code); } @@ -1480,7 +2092,9 @@ fn xmain() -> ! { com_int_list.clear(); com.ints_enable(&com_int_list); // disable all the interrupts - susres.suspend_until_resume(token).expect("couldn't execute suspend/resume"); + susres + .suspend_until_resume(token) + .expect("couldn't execute suspend/resume"); // re-enable the interrupts com_int_list.clear(); com_int_list.push(ComIntSources::WlanIpConfigUpdate); @@ -1504,8 +2118,20 @@ fn xmain() -> ! { } // clean up our program log::trace!("main loop exit, destroying servers"); - xous::send_message(cm_cid, Message::new_blocking_scalar(connection_manager::ConnectionManagerOpcode::Quit.to_usize().unwrap(), 0, 0, 0, 0)).expect("couldn't quit connection manager server"); - unsafe{xous::disconnect(cm_cid).ok()}; + xous::send_message( + cm_cid, + Message::new_blocking_scalar( + connection_manager::ConnectionManagerOpcode::Quit + .to_usize() + .unwrap(), + 0, + 0, + 0, + 0, + ), + ) + .expect("couldn't quit connection manager server"); + unsafe { xous::disconnect(cm_cid).ok() }; xns.unregister_server(net_sid).unwrap(); xous::destroy_server(net_sid).unwrap(); log::trace!("quitting");