diff --git a/services/net/src/api.rs b/services/net/src/api.rs index df2e674ae..47731a263 100644 --- a/services/net/src/api.rs +++ b/services/net/src/api.rs @@ -2,6 +2,8 @@ pub(crate) mod udp; pub(crate) use udp::*; pub(crate) mod ping; pub(crate) use ping::*; +pub(crate) mod tcp; +pub(crate) use tcp::*; pub use ping::NetPingCallback; use rkyv::{Archive, Deserialize, Serialize}; @@ -33,6 +35,10 @@ pub(crate) enum Opcode { UdpSetTtl, UdpGetTtl, + /// Calls for TCP implementation + TcpConnect, + TcpTx, + // The DNS server can hook the Net crate for notifications on config updates /// Adds an Ipv4 as a DNS server DnsHookAddIpv4, diff --git a/services/net/src/api/tcp.rs b/services/net/src/api/tcp.rs new file mode 100644 index 000000000..c057f6529 --- /dev/null +++ b/services/net/src/api/tcp.rs @@ -0,0 +1,47 @@ +use rkyv::{Archive, Deserialize, Serialize}; +use crate::api::*; +use com::api::NET_MTU; + +pub(crate) const TCP_BUFFER_SIZE: usize = NET_MTU; + +#[derive(Debug, Archive, Serialize, Deserialize, Copy, Clone)] +pub(crate) struct NetTcpConnect { + pub(crate) cb_sid: [u32; 4], + pub(crate) ip_addr: NetIpAddr, + pub(crate) remote_port: u16, + pub(crate) local_port: Option, + pub(crate) result: Option, +} + +#[derive(Debug, num_derive::FromPrimitive, num_derive::ToPrimitive)] +pub(crate) enum NetTcpCallback { + RxData, + Drop, +} + +/// 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 NetTcpResponse { + pub remote_ip_addr: NetIpAddr, + pub remote_port: u16, + pub len: u16, + pub data: [u8; TCP_BUFFER_SIZE], +} + +#[derive(Debug, Archive, Serialize, Deserialize, Copy, Clone)] +pub(crate) struct NetTcpTransmit { + pub remote_addr: NetIpAddr, + pub remote_port: u16, + pub local_port: u16, // this was given back in the connect, we need this to distinguish between multiple connections to the same server + pub len: u16, + pub data: [u8; TCP_BUFFER_SIZE], + pub result: Option, +} diff --git a/services/net/src/main.rs b/services/net/src/main.rs index 673e8c80a..cbc9178a5 100644 --- a/services/net/src/main.rs +++ b/services/net/src/main.rs @@ -26,7 +26,7 @@ use smoltcp::wire::{ }; use byteorder::{ByteOrder, NetworkEndian}; -use smoltcp::socket::{UdpPacketMetadata, UdpSocket, UdpSocketBuffer, SocketHandle}; +use smoltcp::socket::{UdpPacketMetadata, UdpSocket, UdpSocketBuffer, SocketHandle, TcpSocket, TcpSocketBuffer}; use smoltcp::time::Instant; use std::thread; use std::sync::Arc; @@ -79,6 +79,17 @@ pub struct PingConnection { retop: usize, } +#[derive(Hash, PartialEq, Eq)] +pub struct TcpConnection { + remote: IpAddress, + remote_port: u16, + local_port: u16, +} +pub struct TcpState { + handle: SocketHandle, + cid: CID, +} + fn set_com_ints(com_int_list: &mut Vec::) { com_int_list.clear(); com_int_list.push(ComIntSources::WlanIpConfigUpdate); @@ -107,6 +118,9 @@ fn xmain() -> ! { let com = com::Com::new(&xns).unwrap(); let timer = ticktimer_server::Ticktimer::new().unwrap(); + // we need a trng for port numbers + let trng = trng::Trng::new(&xns).unwrap(); + // 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(); @@ -161,6 +175,9 @@ fn xmain() -> ! { // 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 + // tcp storage + let mut tcp_handles = HashMap::::new(); + // other link storage let neighbor_cache = NeighborCache::new(BTreeMap::new()); let ip_addrs = [IpCidr::new(Ipv4Address::UNSPECIFIED.into(), 0)]; @@ -383,6 +400,75 @@ fn xmain() -> ! { dns_allclear_hook.clear(); xous::return_scalar(msg.sender, 1).expect("couldn't ack unhook"); }), + Some(Opcode::TcpConnect) => { + 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; + + // initiates a new connection to a remote server consisting of an (Address:Port) tuple. + // multiple connections can exist to a server, and they are furhte differentiated by the return port + let tcp_rx_buffer = TcpSocketBuffer::new(vec![0; TCP_BUFFER_SIZE]); + let tcp_tx_buffer = TcpSocketBuffer::new(vec![0; TCP_BUFFER_SIZE]); + let mut tcp_socket = TcpSocket::new(tcp_rx_buffer, tcp_tx_buffer); + let local_port = (49152 + trng.get_u32().unwrap() % 16384) as u16; + match tcp_socket.connect((address, remote_port), local_port) { + Ok(_) => { + let connection = TcpConnection { + remote: address, + remote_port, + local_port, + }; + let handle = sockets.add(tcp_socket); + let sid = tcpspec.cb_sid; + let cid = xous::connect(SID::from_array(sid)).unwrap(); + let tcp_cb_state = TcpState { + handle, + cid, + }; + tcp_handles.insert(connection, tcp_cb_state); + 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); + } + } + } + } + buf.replace(tcpspec).unwrap(); + }, + Some(Opcode::TcpTx) => { + 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), + remote_port: tcp_tx.remote_port, + local_port: tcp_tx.local_port, + }; + 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) { + Ok(_) => Some(NetMemResponse::Ok), + Err(_) => Some(NetMemResponse::LibraryError), + } + } else { + // inform the sender it should retry + tcp_tx.result = Some(NetMemResponse::SocketInUse); + } + } else { + tcp_tx.result = Some(NetMemResponse::Invalid); + } + buf.replace(tcp_tx).unwrap(); + }, Some(Opcode::UdpBind) => { let mut buf = unsafe{Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap())}; let udpspec = buf.to_original::().unwrap(); @@ -711,6 +797,44 @@ fn xmain() -> ! { } } + // this block handles TCP rx + { + for (connection, tcp_state) in tcp_handles.iter() { + let mut socket = sockets.get::(tcp_state.handle); + if socket.can_recv() { + match socket + .recv(|data| { + let mut response = NetTcpResponse { + remote_ip_addr: NetIpAddr::from(connection.remote), + remote_port: connection.remote_port, + 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 UDP { for (port, udpstate) in udp_handles.iter() { diff --git a/services/net/src/protocols.rs b/services/net/src/protocols.rs index 7a56d4067..2ad760b75 100644 --- a/services/net/src/protocols.rs +++ b/services/net/src/protocols.rs @@ -3,4 +3,6 @@ pub use udp::*; pub mod dns; pub use dns::*; pub mod ping; -pub use ping::*; \ No newline at end of file +pub use ping::*; +pub mod tcp_stream; +pub use tcp_stream::*; \ No newline at end of file diff --git a/services/net/src/protocols/tcp_listener.rs b/services/net/src/protocols/tcp_listener.rs new file mode 100644 index 000000000..bc38c5de5 --- /dev/null +++ b/services/net/src/protocols/tcp_listener.rs @@ -0,0 +1,52 @@ + +// this is if we need to be a server. implement this second. +pub struct TcpListener(!); + +impl TcpListener { + pub fn bind(_: io::Result<&SocketAddr>) -> io::Result { + unsupported() + } + + pub fn socket_addr(&self) -> io::Result { + self.0 + } + + pub fn accept(&self) -> io::Result<(TcpStream, SocketAddr)> { + self.0 + } + + pub fn duplicate(&self) -> io::Result { + self.0 + } + + pub fn set_ttl(&self, _: u32) -> io::Result<()> { + self.0 + } + + pub fn ttl(&self) -> io::Result { + self.0 + } + + pub fn set_only_v6(&self, _: bool) -> io::Result<()> { + self.0 + } + + pub fn only_v6(&self) -> io::Result { + self.0 + } + + pub fn take_error(&self) -> io::Result> { + self.0 + } + + pub fn set_nonblocking(&self, _: bool) -> io::Result<()> { + self.0 + } +} + +impl fmt::Debug for TcpListener { + fn fmt(&self, _f: &mut fmt::Formatter<'_>) -> fmt::Result { + self.0 + } +} + diff --git a/services/net/src/protocols/tcp_stream.rs b/services/net/src/protocols/tcp_stream.rs new file mode 100644 index 000000000..1cff58406 --- /dev/null +++ b/services/net/src/protocols/tcp_stream.rs @@ -0,0 +1,179 @@ +use std::convert::TryInto; +use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr, ToSocketAddrs}; +use std::unimplemented; +use std::io; +use std::io::{Error, ErrorKind, Result}; +use std::io::{Read, Write}; +use std::sync::{Arc, Mutex}; +use std::thread; +use std::thread::JoinHandle; + +use smoltcp::wire::{Ipv4Address, Ipv6Address, IpAddress}; +use smoltcp::{ + wire::IpEndpoint, + time::Duration, +}; + +use xous::{CID, Message, SID, msg_blocking_scalar_unpack, send_message}; +use xous_ipc::Buffer; +use crate::NetConn; +use crate::api::*; +//use crate::api::udp::*; +use num_traits::*; + +use std::io::{IoSliceMut, IoSlice}; +use std::net::Shutdown; +use std::fmt; + +// used by both clients and servers. implement this first. +pub struct TcpStream { + net: NetConn, + cb_sid: SID, + socket_addr: SocketAddr, + nonblocking: bool, +} + +impl TcpStream { + pub fn connect(maybe_socket: io::Result<&SocketAddr>) -> io::Result { + TcpStream::connect_inner(maybe_socket) + } + + pub fn connect_xous(addr: A) -> Result { + match addr.to_socket_addrs() { + Ok(socks) => { + match socks.into_iter().next() { + Some(socket_addr) => { + TcpStream::connect_inner( + Ok(&socket_addr), + ) + } + _ => Err(Error::new(ErrorKind::InvalidInput, "IP address invalid")) + } + } + _ => Err(Error::new(ErrorKind::InvalidInput, "IP address invalid")) + } + } + + pub fn connect_inner(maybe_socket: io::Result<&SocketAddr>) -> io::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(); + + unimplemented!() + } + + + + pub fn connect_timeout(_: &SocketAddr, _: Duration) -> io::Result { + unimplemented!() + } + + pub fn set_read_timeout(&self, _: Option) -> io::Result<()> { + unimplemented!() + } + + pub fn set_write_timeout(&self, _: Option) -> io::Result<()> { + unimplemented!() + } + + pub fn read_timeout(&self) -> io::Result> { + unimplemented!() + } + + pub fn write_timeout(&self) -> io::Result> { + unimplemented!() + } + + pub fn peek(&self, _: &mut [u8]) -> io::Result { + unimplemented!() + } + + pub fn read(&self, _: &mut [u8]) -> io::Result { + unimplemented!() + } + + pub fn read_vectored(&self, _: &mut [IoSliceMut<'_>]) -> io::Result { + unimplemented!() + } + + pub fn is_read_vectored(&self) -> bool { + unimplemented!() + } + + pub fn write(&self, _: &[u8]) -> io::Result { + unimplemented!() + } + + pub fn write_vectored(&self, _: &[IoSlice<'_>]) -> io::Result { + unimplemented!() + } + + pub fn is_write_vectored(&self) -> bool { + unimplemented!() + } + + pub fn peer_addr(&self) -> io::Result { + unimplemented!() + } + + pub fn socket_addr(&self) -> io::Result { + unimplemented!() + } + + pub fn shutdown(&self, _: Shutdown) -> io::Result<()> { + unimplemented!() + } + + pub fn duplicate(&self) -> io::Result { + unimplemented!() + } + + pub fn set_linger(&self, _: Option) -> io::Result<()> { + unimplemented!() + } + + pub fn linger(&self) -> io::Result> { + unimplemented!() + } + + pub fn set_nodelay(&self, _: bool) -> io::Result<()> { + unimplemented!() + } + + pub fn nodelay(&self) -> io::Result { + unimplemented!() + } + + pub fn set_ttl(&self, _: u32) -> io::Result<()> { + unimplemented!() + } + + pub fn ttl(&self) -> io::Result { + unimplemented!() + } + + pub fn take_error(&self) -> io::Result> { + unimplemented!() + } + + pub fn set_nonblocking(&self, _: bool) -> io::Result<()> { + unimplemented!() + } +} + +impl fmt::Debug for TcpStream { + fn fmt(&self, _f: &mut fmt::Formatter<'_>) -> fmt::Result { + unimplemented!() + } +} +/* +impl Read for TcpStream { + +} + +impl Write for TcpStream { + + +} +*/ \ No newline at end of file