diff --git a/services/dns/src/api.rs b/services/dns/src/api.rs index 67894e73c..664c097cb 100644 --- a/services/dns/src/api.rs +++ b/services/dns/src/api.rs @@ -1,7 +1,9 @@ +#[allow(dead_code)] pub(crate) const SERVER_NAME_DNS: &str = "_DNS Resolver Middleware_"; use net::NetIpAddr; use rkyv::{Archive, Deserialize, Serialize}; +#[allow(dead_code)] pub(crate) const DNS_NAME_LENGTH_LIMIT: usize = 256; #[allow(dead_code)] pub(crate) const DNS_PKT_MAX_LEN: usize = 512; diff --git a/services/dns/src/hosted.rs b/services/dns/src/hosted.rs new file mode 100644 index 000000000..c70abf68e --- /dev/null +++ b/services/dns/src/hosted.rs @@ -0,0 +1,41 @@ +use net::NetIpAddr; +use std::net::ToSocketAddrs; +use crate::DnsResponseCode; + +#[derive(Debug)] +pub struct Dns { +} +impl Dns { + pub fn new(_xns: &xous_names::XousNames) -> Result { + Ok(Dns { + }) + } + + /// Checks first to see if the name could be just an IPv4 or IPv6 in string form, + /// then tries to pass it to the DNS resolver. + pub fn lookup(&self, name: &str) -> Result { + log::debug!("looking up {}", name); + match (name, 80).to_socket_addrs() { // we throw away the port because we just want the IP address... + Ok(mut iter) => { + match iter.next() { + Some(addr) => { + log::debug!("{:?}", addr); + Ok(NetIpAddr::from(addr)) + }, + None => { + log::debug!("name error"); + Err(DnsResponseCode::NameError) + } + } + } + Err(e) => { + log::debug!("format error: {:?}", e); + Err(DnsResponseCode::FormatError) + } + } + } + pub fn flush_cache(&self) -> Result<(), xous::Error> { + log::warn!("DNS cache flush not implemented in hosted mode!"); + Ok(()) + } +} diff --git a/services/dns/src/hw.rs b/services/dns/src/hw.rs new file mode 100644 index 000000000..1294ad5ba --- /dev/null +++ b/services/dns/src/hw.rs @@ -0,0 +1,63 @@ +#![cfg_attr(target_os = "none", no_std)] +use xous::CID; +use xous_ipc::{Buffer, String}; +use num_traits::ToPrimitive; + +use net::NetIpAddr; +use std::net::IpAddr; + +use crate::api::*; + +#[derive(Debug)] +pub struct Dns { + conn: CID, +} +impl Dns { + pub fn new(xns: &xous_names::XousNames) -> Result { + REFCOUNT.fetch_add(1, Ordering::Relaxed); + let conn = xns.request_connection_blocking(crate::api::SERVER_NAME_DNS).expect("Can't connect to Dns server"); + Ok(Dns { + conn + }) + } + + /// Checks first to see if the name could be just an IPv4 or IPv6 in string form, + /// then tries to pass it to the DNS resolver. + pub fn lookup(&self, name: &str) -> Result { + if let Ok(simple_ip) = name.parse::() { + Ok(NetIpAddr::from(simple_ip)) + } else { + let alloc_name = String::::from_str(name); + let mut buf = Buffer::into_buf(alloc_name).or(Err(DnsResponseCode::UnknownError))?; + buf.lend_mut(self.conn, Opcode::Lookup.to_u32().unwrap()) + .or(Err(DnsResponseCode::UnknownError))?; + let response = buf.to_original::().or(Err(DnsResponseCode::UnknownError))?; + if let Some(addr) = response.addr { + Ok(addr) + } else { + Err(response.code) + } + } + } + pub fn flush_cache(&self) -> Result<(), xous::Error> { + xous::send_message( + self.conn, + xous::Message::new_scalar(Opcode::Flush.to_usize().unwrap(), 0, 0, 0, 0) + ).map(|_| ()) + } +} + +use core::sync::atomic::{AtomicU32, Ordering}; +static REFCOUNT: AtomicU32 = AtomicU32::new(0); +impl Drop for Dns { + fn drop(&mut self) { + // the connection to the server side must be reference counted, so that multiple instances of this object within + // a single process do not end up de-allocating the CID on other threads before they go out of scope. + // Note to future me: you want this. Don't get rid of it because you think, "nah, nobody will ever make more than one copy of this object". + if REFCOUNT.fetch_sub(1, Ordering::Relaxed) == 1 { + unsafe{xous::disconnect(self.conn).unwrap();} + } + // if there was object-specific state (such as a one-time use server for async callbacks, specific to the object instance), + // de-allocate those items here. They don't need a reference count because they are object-specific + } +} \ No newline at end of file diff --git a/services/dns/src/lib.rs b/services/dns/src/lib.rs index 2d24f6257..7a8f2644c 100644 --- a/services/dns/src/lib.rs +++ b/services/dns/src/lib.rs @@ -1,64 +1,12 @@ -#![cfg_attr(target_os = "none", no_std)] - pub mod api; use api::*; -use xous::CID; -use xous_ipc::{Buffer, String}; -use num_traits::ToPrimitive; -use net::NetIpAddr; -use std::net::IpAddr; +#[cfg(any(target_os = "none", target_os = "xous"))] +mod hw; +#[cfg(any(target_os = "none", target_os = "xous"))] +pub use hw::*; -#[derive(Debug)] -pub struct Dns { - conn: CID, -} -impl Dns { - pub fn new(xns: &xous_names::XousNames) -> Result { - REFCOUNT.fetch_add(1, Ordering::Relaxed); - let conn = xns.request_connection_blocking(api::SERVER_NAME_DNS).expect("Can't connect to Dns server"); - Ok(Dns { - conn - }) - } - - /// Checks first to see if the name could be just an IPv4 or IPv6 in string form, - /// then tries to pass it to the DNS resolver. - pub fn lookup(&self, name: &str) -> Result { - if let Ok(simple_ip) = name.parse::() { - Ok(NetIpAddr::from(simple_ip)) - } else { - let alloc_name = String::::from_str(name); - let mut buf = Buffer::into_buf(alloc_name).or(Err(DnsResponseCode::UnknownError))?; - buf.lend_mut(self.conn, Opcode::Lookup.to_u32().unwrap()) - .or(Err(DnsResponseCode::UnknownError))?; - let response = buf.to_original::().or(Err(DnsResponseCode::UnknownError))?; - if let Some(addr) = response.addr { - Ok(addr) - } else { - Err(response.code) - } - } - } - pub fn flush_cache(&self) -> Result<(), xous::Error> { - xous::send_message( - self.conn, - xous::Message::new_scalar(Opcode::Flush.to_usize().unwrap(), 0, 0, 0, 0) - ).map(|_| ()) - } -} - -use core::sync::atomic::{AtomicU32, Ordering}; -static REFCOUNT: AtomicU32 = AtomicU32::new(0); -impl Drop for Dns { - fn drop(&mut self) { - // the connection to the server side must be reference counted, so that multiple instances of this object within - // a single process do not end up de-allocating the CID on other threads before they go out of scope. - // Note to future me: you want this. Don't get rid of it because you think, "nah, nobody will ever make more than one copy of this object". - if REFCOUNT.fetch_sub(1, Ordering::Relaxed) == 1 { - unsafe{xous::disconnect(self.conn).unwrap();} - } - // if there was object-specific state (such as a one-time use server for async callbacks, specific to the object instance), - // de-allocate those items here. They don't need a reference count because they are object-specific - } -} \ No newline at end of file +#[cfg(not(any(target_os = "none", target_os = "xous")))] +mod hosted; +#[cfg(not(any(target_os = "none", target_os = "xous")))] +pub use hosted::*; diff --git a/services/net/src/api.rs b/services/net/src/api.rs index d647c6b7d..8230c7a6f 100644 --- a/services/net/src/api.rs +++ b/services/net/src/api.rs @@ -3,6 +3,7 @@ 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; diff --git a/services/net/src/protocols.rs b/services/net/src/protocols.rs index a641c4ac5..f132aa563 100644 --- a/services/net/src/protocols.rs +++ b/services/net/src/protocols.rs @@ -1,10 +1,28 @@ pub mod udp; pub use udp::*; + +#[cfg(any(target_os = "none", target_os = "xous"))] pub mod dns; +#[cfg(any(target_os = "none", target_os = "xous"))] pub use dns::*; +#[cfg(not(any(target_os = "none", target_os = "xous")))] +pub mod dns_hosted; +#[cfg(not(any(target_os = "none", target_os = "xous")))] +pub use dns_hosted::*; + pub mod ping; pub use ping::*; + +#[cfg(any(target_os = "none", target_os = "xous"))] pub mod tcp_stream; +#[cfg(any(target_os = "none", target_os = "xous"))] pub use tcp_stream::*; +#[cfg(any(target_os = "none", target_os = "xous"))] pub mod tcp_listener; +#[cfg(any(target_os = "none", target_os = "xous"))] pub use tcp_listener::*; + +#[cfg(not(any(target_os = "none", target_os = "xous")))] +pub mod tcp_hosted; +#[cfg(not(any(target_os = "none", target_os = "xous")))] +pub use tcp_hosted::*; diff --git a/services/net/src/protocols/dns_hosted.rs b/services/net/src/protocols/dns_hosted.rs new file mode 100644 index 000000000..d88d64572 --- /dev/null +++ b/services/net/src/protocols/dns_hosted.rs @@ -0,0 +1,31 @@ +use std::net::{IpAddr, Ipv4Addr}; +use std::io::Result; + +pub struct DnsServerManager { +} + +impl DnsServerManager { + pub fn register(_xns: &xous_names::XousNames) -> Result { + Ok(DnsServerManager { + }) + } + + /// Fake function that always returns true + pub fn add_server(&mut self, _addr: IpAddr) -> bool { + true + } + /// Fake function that always returns true + pub fn remove_server(&mut self, _addr: IpAddr) -> bool { + true + } + /// Fake function + pub fn clear(&mut self) { + } + /// Fake function + pub fn set_freeze(&mut self, _freeze: bool) { + } + /// Always returns 1.1.1.1 + pub fn get_random(&self) -> Option { + Some(IpAddr::V4(Ipv4Addr::new(1, 1, 1, 1))) + } +} diff --git a/services/net/src/protocols/tcp_hosted.rs b/services/net/src/protocols/tcp_hosted.rs new file mode 100644 index 000000000..1eaea86b0 --- /dev/null +++ b/services/net/src/protocols/tcp_hosted.rs @@ -0,0 +1,302 @@ +use std::net::{SocketAddr, ToSocketAddrs}; +use std::io; +use std::io::{Error, ErrorKind, Result}; +use std::io::{Read, Write}; +use std::net::TcpStream as TcpStreamHosted; +use smoltcp::time::Duration; +use std::net::Shutdown; +use std::unimplemented; +use std::net::TcpListener as TcpListenerHosted; + +pub struct TcpStream { + stream: TcpStreamHosted, +} + +impl TcpStream { + /// This is routine that allows a TcpListener to create a TcpStream object. The following must be observed: + /// 1. The `cb_sid`, `rx_buf` and `rx_notify` are the memory locations mapped into the already-allocated Rx thread + /// 2. These fields are not to be re-used in the Listener object that succeeds the current one + /* + pub(crate) fn build_from_listener( + net: NetConn, + cb_sid: SID, + remote: SocketAddr, + local_port: u16, + rx_buf: Arc::>>, + rx_notify: Arc>, + ) -> TcpStream { + TcpStream { + } + }*/ + pub fn connect(maybe_socket: io::Result<&SocketAddr>) -> io::Result { + if let Ok(socket) = maybe_socket { + match TcpStreamHosted::connect(socket) { + Ok(stream) => { + Ok(TcpStream{ + stream, + }) + }, + Err(e) => Err(e), + } + } else { + Err(Error::new(ErrorKind::InvalidInput, "IP address invalid")) + } + } + pub fn connect_timeout(maybe_socket: io::Result<&SocketAddr>, duration: Duration) -> io::Result { + if let Ok(socket) = maybe_socket { + let d = std::time::Duration::from_millis(duration.total_millis()); + match TcpStreamHosted::connect_timeout(socket, d) { + Ok(stream) => { + Ok(TcpStream{ + stream, + }) + }, + Err(e) => Err(e), + } + } else { + Err(Error::new(ErrorKind::InvalidInput, "IP address invalid")) + } + } + + /// This API call uses the stdlib-internal calling convention to assist with the process of migrating this into a true libstd + pub fn connect_xous(addr: A, timeout: Option, _keepalive: Option) -> Result { + if let Some (t) = timeout { + let d = std::time::Duration::from_millis(t.total_millis()); + match addr.to_socket_addrs() { + Ok(socks) => { + match socks.into_iter().next() { + Some(socket_addr) => { + match TcpStreamHosted::connect_timeout(&socket_addr, d) { + Ok(stream) => { + Ok(TcpStream{ + stream, + }) + }, + Err(e) => Err(e), + } + } + _ => Err(Error::new(ErrorKind::InvalidInput, "IP address invalid")) + } + } + _ => Err(Error::new(ErrorKind::InvalidInput, "IP address invalid")) + } + } else { + match TcpStreamHosted::connect(addr) { + Ok(stream) => { + Ok(TcpStream{ + stream, + }) + }, + Err(e) => Err(e), + } + } + } + /// dev note: if you need this function in hosted mode, contact bunnie. + pub fn set_scalar_notification(&mut self, _cid: xous::CID, _op: usize, _args: [Option; 4]) { + unimplemented!() + } + /// dev note: if you need this function in hosted mode, contact bunnie. + pub fn clear_scalar_notification(&mut self) { + unimplemented!() + } + + pub fn set_read_timeout(&mut self, timeout: Option) -> io::Result<()> { + let t = match timeout { + Some(d) => { + Some(std::time::Duration::from_millis(d.total_millis())) + } + None => None, + }; + self.stream.set_read_timeout(t) + } + pub fn set_write_timeout(&mut self, timeout: Option) -> io::Result<()> { + let t = match timeout { + Some(d) => { + Some(std::time::Duration::from_millis(d.total_millis())) + } + None => None, + }; + self.stream.set_write_timeout(t) + } + pub fn read_timeout(&self) -> io::Result> { + match self.stream.read_timeout() { + Ok(maybe_t) => { + match maybe_t { + Some(t) => { + Ok(Some(Duration::from_millis(t.as_millis() as u64))) + } + None => Ok(None) + } + }, + Err(e) => Err(e), + } + } + pub fn write_timeout(&self) -> io::Result> { + match self.stream.write_timeout() { + Ok(maybe_t) => { + match maybe_t { + Some(t) => { + Ok(Some(Duration::from_millis(t.as_millis() as u64))) + } + None => Ok(None) + } + }, + Err(e) => Err(e), + } + } + pub fn peer_addr(&self) -> io::Result { + self.stream.peer_addr() + } + pub fn socket_addr(&self) -> io::Result { + self.stream.local_addr() + } + + pub fn shutdown(&mut self, request: Shutdown) -> io::Result<()> { + self.stream.shutdown(request) + } + + pub fn set_nodelay(&self, setting: bool) -> io::Result<()> { + self.stream.set_nodelay(setting) + } + + pub fn nodelay(&self) -> io::Result { + self.stream.nodelay() + } + + pub fn set_ttl(&self, ttl: u32) -> io::Result<()> { + self.stream.set_ttl(ttl) + } + + pub fn ttl(&self) -> io::Result { + self.stream.ttl() + } + + /// I'm not quite sure this has any meaning on Xous. Right now this just checks if there is an + /// Rx state error in progress. + pub fn take_error(&self) -> io::Result> { + self.stream.take_error() + } + + pub fn set_nonblocking(&mut self, setting: bool) -> io::Result<()> { + self.stream.set_nonblocking(setting) + } + + pub fn duplicate(&self) -> io::Result { + match self.stream.try_clone() { + Ok(stream) => { + Ok(TcpStream { + stream + }) + }, + Err(e) => Err(e) + } + } + + pub fn peek(&self, buf: &mut [u8]) -> io::Result { + self.stream.peek(buf) + } +} + +impl Read for TcpStream { + fn read(&mut self, buf: &mut [u8]) -> io::Result { + self.stream.read(buf) + } +} + +impl Write for TcpStream { + fn write(&mut self, buf: &[u8]) -> io::Result { + self.stream.write(buf) + } + + /// In the case that Nagle's algo is enabled, packets can get stuck in the outgoing buffer. + /// This basically waits until Nagle's algo times out, and the data is sent. + fn flush(&mut self) -> io::Result<()> { + self.stream.flush() + } +} + + + +pub struct TcpListener { + listener: TcpListenerHosted, +} + +impl TcpListener { + pub fn bind(maybe_socket: io::Result<&SocketAddr>) -> io::Result { + match maybe_socket { + Ok(socket) => { + match TcpListenerHosted::bind(socket) { + Ok(listener) => { + Ok( + TcpListener { + listener, + } + ) + } + Err(e) => Err(e) + } + } + Err(e) => Err(e) + } + } + + pub fn bind_xous(addr: A) -> Result { + match TcpListenerHosted::bind(addr) { + Ok(listener) => { + Ok( + TcpListener { + listener, + } + ) + } + Err(e) => Err(e) + } + } + + pub fn set_scalar_notification(&mut self, _cid: xous::CID, _op: usize, _args: [Option; 4]) { + unimplemented!() + } + pub fn clear_scalar_notification(&mut self) { + unimplemented!() + } + + pub fn accept(&mut self) -> io::Result<(TcpStream, SocketAddr)> { + match self.listener.accept() { + Ok((stream, addr)) => { + Ok(( + TcpStream { + stream, + }, + addr + )) + } + Err(e) => Err(e) + } + } + + pub fn local_addr(&self) -> io::Result { + self.listener.local_addr() + } + + pub fn set_ttl(&self, ttl: u32) -> io::Result<()> { + self.listener.set_ttl(ttl) + } + + pub fn ttl(&self) -> io::Result { + self.listener.ttl() + } + + /// I'm not really sure what this does on Xous, as we don't have a SO_ERROR value in our OS. + /// Just returning Ok(None) for now. + pub fn take_error(&self) -> io::Result> { + self.listener.take_error() + } + + pub fn set_nonblocking(&mut self, setting: bool) -> io::Result<()> { + self.listener.set_nonblocking(setting) + } + + pub fn duplicate(&self) -> io::Result { + Err(Error::new(ErrorKind::Other, "Xous does not support cloned listeners")) + } +} diff --git a/services/net/src/protocols/tcp_listener.rs b/services/net/src/protocols/tcp_listener.rs index 571f873c3..fd7b6a8be 100644 --- a/services/net/src/protocols/tcp_listener.rs +++ b/services/net/src/protocols/tcp_listener.rs @@ -54,7 +54,7 @@ impl TcpListener { } } - pub fn bind_inner(maybe_socket: io::Result<&SocketAddr>) -> io::Result { + fn bind_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(); diff --git a/services/net/src/protocols/tcp_stream.rs b/services/net/src/protocols/tcp_stream.rs index 6638f1dbb..337e7f2c6 100644 --- a/services/net/src/protocols/tcp_stream.rs +++ b/services/net/src/protocols/tcp_stream.rs @@ -97,7 +97,7 @@ impl TcpStream { } } /// note that there is no provision in the rust stdlib to set a keepalive, so it's sort of wedged in here - pub fn connect_inner( + fn connect_inner( maybe_socket: io::Result<&SocketAddr>, timeout: Option, keepalive: Option) -> io::Result { diff --git a/services/shellchat/src/cmds/net_cmd.rs b/services/shellchat/src/cmds/net_cmd.rs index 0e67833ed..82daeea3d 100644 --- a/services/shellchat/src/cmds/net_cmd.rs +++ b/services/shellchat/src/cmds/net_cmd.rs @@ -1,11 +1,14 @@ use crate::{ShellCmdApi, CommonEnv}; use xous_ipc::String; -use net::{Duration, XousServerId, NetPingCallback}; +#[cfg(any(target_os = "none", target_os = "xous"))] +use net::XousServerId; +use net::{Duration, NetPingCallback}; use xous::MessageEnvelope; use num_traits::*; use std::net::{SocketAddr, IpAddr}; use std::io::Write; use std::io::Read; +use dns::Dns; // necessary to work around https://github.com/rust-lang/rust/issues/94182 pub struct NetCmd { udp: Option, @@ -13,7 +16,8 @@ pub struct NetCmd { callback_id: Option, callback_conn: u32, udp_count: u32, - dns: dns::Dns, + dns: Dns, + #[cfg(any(target_os = "none", target_os = "xous"))] ping: Option, } impl NetCmd { @@ -25,6 +29,7 @@ impl NetCmd { callback_conn: xns.request_connection_blocking(crate::SERVER_NAME_SHELLCHAT).unwrap(), udp_count: 0, dns: dns::Dns::new(&xns).unwrap(), + #[cfg(any(target_os = "none", target_os = "xous"))] ping: None, } } @@ -49,7 +54,11 @@ impl<'a> ShellCmdApi<'a> for NetCmd { use core::fmt::Write; let mut ret = String::<1024>::new(); + #[cfg(any(target_os = "none", target_os = "xous"))] let helpstring = "net [udp [port]] [udpclose] [udpclone] [udpcloneclose] [ping [host] [count]] [tcpget host/path]"; + // no ping in hosted mode -- why would you need it? we're using the host's network connection. + #[cfg(not(any(target_os = "none", target_os = "xous")))] + let helpstring = "net [udp [port]] [udpclose] [udpclone] [udpcloneclose] [count]] [tcpget host/path]"; let mut tokens = args.as_str().unwrap().split(' '); @@ -257,6 +266,7 @@ impl<'a> ShellCmdApi<'a> for NetCmd { } } } + #[cfg(any(target_os = "none", target_os = "xous"))] "ping" => { if let Some(name) = tokens.next() { match self.dns.lookup(name) {