mirror of
https://github.com/saymrwulf/xous-core.git
synced 2026-11-17 08:40:52 +00:00
checkpoint to try something else
This commit is contained in:
parent
cf485fbbb2
commit
9b1c5e3f0c
4 changed files with 280 additions and 75 deletions
|
|
@ -39,6 +39,7 @@ pub(crate) enum Opcode {
|
|||
TcpConnect,
|
||||
TcpTx,
|
||||
TcpClose,
|
||||
TcpRxShutdown,
|
||||
|
||||
// The DNS server can hook the Net crate for notifications on config updates
|
||||
/// Adds an Ipv4 as a DNS server
|
||||
|
|
|
|||
|
|
@ -10,7 +10,10 @@ pub(crate) struct NetTcpManage {
|
|||
pub(crate) ip_addr: NetIpAddr,
|
||||
pub(crate) remote_port: u16,
|
||||
pub(crate) local_port: Option<u16>,
|
||||
pub(crate) timeout_ms: Option<u64>,
|
||||
pub(crate) keepalive_ms: Option<u64>,
|
||||
pub(crate) result: Option<NetMemResponse>,
|
||||
pub(crate) rx_shutdown: Option<bool>,
|
||||
}
|
||||
|
||||
#[derive(Debug, num_derive::FromPrimitive, num_derive::ToPrimitive)]
|
||||
|
|
@ -30,10 +33,8 @@ pub(crate) enum NetTcpCallback {
|
|||
/// 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],
|
||||
pub len: u16,
|
||||
}
|
||||
|
||||
#[derive(Debug, Archive, Serialize, Deserialize, Copy, Clone)]
|
||||
|
|
|
|||
|
|
@ -27,7 +27,7 @@ use smoltcp::wire::{
|
|||
use byteorder::{ByteOrder, NetworkEndian};
|
||||
|
||||
use smoltcp::socket::{UdpPacketMetadata, UdpSocket, UdpSocketBuffer, SocketHandle, TcpSocket, TcpSocketBuffer};
|
||||
use smoltcp::time::Instant;
|
||||
use smoltcp::time::{Instant, Duration};
|
||||
use std::thread;
|
||||
use std::sync::Arc;
|
||||
use core::sync::atomic::{AtomicU32, Ordering};
|
||||
|
|
@ -88,6 +88,7 @@ pub struct TcpConnection {
|
|||
pub struct TcpState {
|
||||
handle: SocketHandle,
|
||||
cid: CID,
|
||||
shutdown_rx: bool,
|
||||
}
|
||||
|
||||
fn set_com_ints(com_int_list: &mut Vec::<ComIntSources>) {
|
||||
|
|
@ -411,6 +412,12 @@ fn xmain() -> ! {
|
|||
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);
|
||||
if let Some(timeout) = tcpspec.timeout_ms {
|
||||
tcp_socket.set_timeout(Some(Duration::from_millis(timeout)));
|
||||
}
|
||||
if let Some(keepalive) = tcpspec.keepalive_ms {
|
||||
tcp_socket.set_keep_alive(Some(Duration::from_millis(keepalive)));
|
||||
}
|
||||
let local_port = (49152 + trng.get_u32().unwrap() % 16384) as u16;
|
||||
match tcp_socket.connect((address, remote_port), local_port) {
|
||||
Ok(_) => {
|
||||
|
|
@ -425,6 +432,7 @@ fn xmain() -> ! {
|
|||
let tcp_cb_state = TcpState {
|
||||
handle,
|
||||
cid,
|
||||
shutdown_rx: false,
|
||||
};
|
||||
tcp_handles.insert(connection, tcp_cb_state);
|
||||
tcpspec.result = Some(NetMemResponse::Ok);
|
||||
|
|
@ -445,6 +453,26 @@ fn xmain() -> ! {
|
|||
}
|
||||
buf.replace(tcpspec).unwrap();
|
||||
},
|
||||
Some(Opcode::TcpRxShutdown) => {
|
||||
let mut buf = unsafe{Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap())};
|
||||
let mut tcpspec = buf.to_original::<NetTcpManage, _>().unwrap();
|
||||
if let Some(local_port) = tcpspec.local_port {
|
||||
let connection = TcpConnection {
|
||||
remote: IpAddress::from(tcpspec.ip_addr),
|
||||
remote_port: tcpspec.remote_port,
|
||||
local_port,
|
||||
};
|
||||
if let Some(tcp_state) = tcp_handles.get_mut(&connection) {
|
||||
tcp_state.rx_shutdown = true;
|
||||
tcpspec.result = Some(NetMemResponse::Ok);
|
||||
} else {
|
||||
tcpspec.result = Some(NetMemResponse::Invalid);
|
||||
}
|
||||
} else {
|
||||
tcpspec.result = Some(NetMemResponse::Invalid);
|
||||
}
|
||||
buffer.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::<NetTcpTransmit, _>().unwrap();
|
||||
|
|
@ -459,7 +487,7 @@ fn xmain() -> ! {
|
|||
tcp_tx.result = match socket.send_slice(&tcp_tx.data) {
|
||||
Ok(octets) => {
|
||||
tcp_tx.len = octets as u16;
|
||||
Some(NetMemResponse::Ok)
|
||||
Some(NetMemResponse::Sent(octets as u16))
|
||||
},
|
||||
Err(_) => Some(NetMemResponse::LibraryError),
|
||||
}
|
||||
|
|
@ -825,37 +853,36 @@ fn xmain() -> ! {
|
|||
// this block handles TCP rx
|
||||
{
|
||||
for (connection, tcp_state) in tcp_handles.iter() {
|
||||
let mut socket = sockets.get::<TcpSocket>(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");
|
||||
if !tcp_state.shutdown_rx {
|
||||
let mut socket = sockets.get::<TcpSocket>(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(), ())
|
||||
}) {
|
||||
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");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -30,21 +30,39 @@ pub struct TcpStream {
|
|||
net: NetConn,
|
||||
cb_sid: SID,
|
||||
socket_addr: SocketAddr,
|
||||
local_port: u16,
|
||||
ticktimer: ticktimer_server::Ticktimer,
|
||||
|
||||
rx_buf: Arc::<Mutex::<Vec::<u8>>>,
|
||||
rx_handle: Option<JoinHandle::<()>>,
|
||||
/// xous-specific feature that allows for more efficent Rx than blocking. Caller must set_scalar_notification() to use it.
|
||||
rx_notify: Arc<Mutex<XousScalarEndpoint>>,
|
||||
|
||||
nonblocking: bool,
|
||||
read_timeout: Option<Duration>,
|
||||
write_timeout: Option<Duration>,
|
||||
rx_shutdown: bool,
|
||||
tx_shutdown: bool,
|
||||
}
|
||||
|
||||
impl TcpStream {
|
||||
pub fn connect(maybe_socket: io::Result<&SocketAddr>) -> io::Result<TcpStream> {
|
||||
TcpStream::connect_inner(maybe_socket)
|
||||
TcpStream::connect_inner(maybe_socket, None, None)
|
||||
}
|
||||
pub fn connect_timeout(maybe_socket: &SocketAddr, duration: Duration) -> io::Result<TcpStream> {
|
||||
TcpStream::connect_inner(maybe_socket, duration, None)
|
||||
}
|
||||
|
||||
pub fn connect_xous<A: ToSocketAddrs>(addr: A) -> Result<TcpStream> {
|
||||
/// 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<A: ToSocketAddrs>(addr: A, timeout: Option<Duration>, keepalive: Option<Duration>) -> Result<TcpStream> {
|
||||
match addr.to_socket_addrs() {
|
||||
Ok(socks) => {
|
||||
match socks.into_iter().next() {
|
||||
Some(socket_addr) => {
|
||||
TcpStream::connect_inner(
|
||||
Ok(&socket_addr),
|
||||
timeout,
|
||||
keepalive
|
||||
)
|
||||
}
|
||||
_ => Err(Error::new(ErrorKind::InvalidInput, "IP address invalid"))
|
||||
|
|
@ -53,66 +71,188 @@ impl TcpStream {
|
|||
_ => Err(Error::new(ErrorKind::InvalidInput, "IP address invalid"))
|
||||
}
|
||||
}
|
||||
|
||||
pub fn connect_inner(maybe_socket: io::Result<&SocketAddr>) -> io::Result<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(
|
||||
maybe_socket: io::Result<&SocketAddr>,
|
||||
timeout: Option<Duration>,
|
||||
keepalive: Option<Duration>) -> io::Result<TcpStream> {
|
||||
let socket = maybe_socket?;
|
||||
let xns = xous_names::XousNames::new().unwrap();
|
||||
let net = NetConn::new(&xns).unwrap();
|
||||
let cb_sid = xous::create_server().unwrap();
|
||||
let ticktimer = ticktimer_server::Ticktimer::new().unwrap();
|
||||
|
||||
unimplemented!()
|
||||
let rx_buf = Arc::new(Mutex::new(Vec::new()));
|
||||
let notify = Arc::new(Mutex::new(XousScalarEndpoint::new()));
|
||||
|
||||
let handle = thread::spawn({
|
||||
let cb_sid_clone = cb_sid.clone();
|
||||
let rx_buf = Arc::clone(&rx_buf);
|
||||
let notify = Arc::clone(¬ify);
|
||||
move || {
|
||||
loop {
|
||||
let msg = xous::receive_message(cb_sid_clone).unwrap();
|
||||
match FromPrimitive::from_usize(msg.body.id()) {
|
||||
Some(NetTcpCallback::RxData) => {
|
||||
let buffer = unsafe {Buffer::from_memory_message(msg.body.memory_message().unwrap())};
|
||||
let incoming = buffer.as_flat::<NetTcpResponse, _>().unwrap();
|
||||
{ // grab the lock once for better efficiency
|
||||
let mut rx_locked = rx_buf.lock().unwrap();
|
||||
for &d in incoming.data[..incoming.len as unsize].iter() {
|
||||
rx_locked.push(d);
|
||||
}
|
||||
}
|
||||
notify.lock().unwrap().notify(); // this will only notify if a destination has been set
|
||||
}
|
||||
Some(NetTcpCallback::Drop) => msg_blocking_scalar_unpack!(msg, _, _, _, _, {
|
||||
log::debug!("Drop received, exiting Tcp handler");
|
||||
xous::return_scalar(msg.sender, 1).unwrap();
|
||||
break;
|
||||
}),
|
||||
None => {
|
||||
log::error!("got unknown message type on Tcp callback: {:?}", msg);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
let request = NetTcpManage {
|
||||
cb_sid,
|
||||
ip_addr: NetPiAddr::from(socket),
|
||||
remote_port: socket.port(),
|
||||
local_port: None,
|
||||
timeout_ms: if let Some(d) = timeout { Some(d.total_millis()) } else { None },
|
||||
keepalive_ms: if let Some(d) = keepalive { Some(d.total_millis()) } else { None },
|
||||
result: None,
|
||||
rx_shutdown: None,
|
||||
};
|
||||
let mut buf = Buffer::into_buf(request)
|
||||
.or(Err(Error::new(ErrorKind::Other, "can't register with Net server")))?;
|
||||
buf.lend_mut(net.conn(), Opcode::TcpConnect.to_u32().unwrap())
|
||||
.or(Err(Error::new(ErrorKind::Other, "can't register with Net server")))?;
|
||||
let ret = buf.to_original::<NetTcpManage, _>().unwrap();
|
||||
match ret.result {
|
||||
Some(NetMemResponse::Ok) => {
|
||||
if let Some(local_port) = ret.local_port {
|
||||
Ok(TcpSocket {
|
||||
net,
|
||||
cb_sid,
|
||||
socket_addr: *socket,
|
||||
local_port,
|
||||
rx_buf,
|
||||
handle: Some(handle),
|
||||
rx_notify: notify,
|
||||
read_timeout: None,
|
||||
write_timeout: None,
|
||||
ticktimer,
|
||||
dest_socket: None,
|
||||
max_payload,
|
||||
nonblocking: false,
|
||||
rx_shutdown: false,
|
||||
tx_shutdown: false,
|
||||
})
|
||||
} else {
|
||||
Err(Error::new(ErrorKind::Other, "Net server failed to assign us a local port"))
|
||||
}
|
||||
},
|
||||
_ => {
|
||||
Err(Error::new(ErrorKind::Other, "can't register with Net server"))
|
||||
}
|
||||
}
|
||||
}
|
||||
pub fn set_scalar_notification(&mut self, cid: CID, op: usize, args: [Option<usize>; 4]) {
|
||||
self.rx_notify.lock().unwrap().set(cid, op, args);
|
||||
}
|
||||
pub fn clear_scalar_notification(&mut self) {
|
||||
self.rx_notify.lock().unwrap().clear();
|
||||
}
|
||||
|
||||
|
||||
|
||||
pub fn connect_timeout(_: &SocketAddr, _: Duration) -> io::Result<TcpStream> {
|
||||
unimplemented!()
|
||||
pub fn set_read_timeout(&mut self, timeout: Option<Duration>) -> io::Result<()> {
|
||||
if let Some(duration) = timeout {
|
||||
if duration.total_millis() == 0 {
|
||||
Err(Error::new(ErrorKind::InvalidInput, "zero duration is not valid"))
|
||||
} else {
|
||||
self.read_timeout = Some(duration);
|
||||
Ok(())
|
||||
}
|
||||
} else {
|
||||
self.read_timeout = None;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_read_timeout(&self, _: Option<Duration>) -> io::Result<()> {
|
||||
unimplemented!()
|
||||
pub fn set_write_timeout(&mut self, timeout: Option<Duration>) -> io::Result<()> {
|
||||
if let Some(duration) = timeout {
|
||||
if duration.total_millis() == 0 {
|
||||
Err(Error::new(ErrorKind::InvalidInput, "zero duration is not valid"))
|
||||
} else {
|
||||
self.write_timeout = Some(duration);
|
||||
Ok(())
|
||||
}
|
||||
} else {
|
||||
self.write_timeout = None;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_write_timeout(&self, _: Option<Duration>) -> io::Result<()> {
|
||||
unimplemented!()
|
||||
}
|
||||
|
||||
pub fn read_timeout(&self) -> io::Result<Option<Duration>> {
|
||||
unimplemented!()
|
||||
Ok(self.read_timeout)
|
||||
}
|
||||
|
||||
pub fn write_timeout(&self) -> io::Result<Option<Duration>> {
|
||||
unimplemented!()
|
||||
Ok(self.write_timeout)
|
||||
}
|
||||
|
||||
pub fn peek(&self, _: &mut [u8]) -> io::Result<usize> {
|
||||
unimplemented!()
|
||||
}
|
||||
|
||||
pub fn peer_addr(&self) -> io::Result<SocketAddr> {
|
||||
unimplemented!()
|
||||
Ok(self.socket_addr)
|
||||
}
|
||||
|
||||
pub fn socket_addr(&self) -> io::Result<SocketAddr> {
|
||||
unimplemented!()
|
||||
Ok(SocketAddr::new(
|
||||
IpAddr::V4(127, 0, 0, 1),
|
||||
self.local_port,
|
||||
))
|
||||
}
|
||||
|
||||
pub fn shutdown(&self, _: Shutdown) -> io::Result<()> {
|
||||
unimplemented!()
|
||||
pub fn shutdown(&self, request: Shutdown) -> io::Result<()> {
|
||||
match request {
|
||||
Shutdown::Read | Shutdown::Both => {
|
||||
let request = NetTcpManage {
|
||||
cb_sid,
|
||||
ip_addr: NetPiAddr::from(socket),
|
||||
remote_port: socket.port(),
|
||||
local_port: Some(self.local_port),
|
||||
timeout_ms: if let Some(d) = timeout { Some(d.total_millis()) } else { None },
|
||||
keepalive_ms: if let Some(d) = keepalive { Some(d.total_millis()) } else { None },
|
||||
result: None,
|
||||
rx_shutdown: Some(true),
|
||||
};
|
||||
let mut buf = Buffer::into_buf(request)
|
||||
.or(Err(Error::new(ErrorKind::Other, "can't register with Net server")))?;
|
||||
buf.lend_mut(net.conn(), Opcode::TcpRxShutdown.to_u32().unwrap())
|
||||
.or(Err(Error::new(ErrorKind::Other, "can't register with Net server")))?;
|
||||
let ret = buf.to_original::<NetTcpManage, _>().unwrap();
|
||||
|
||||
if request == Shutdown::Both {
|
||||
self.tx_shutdown = true;
|
||||
}
|
||||
match ret.result {
|
||||
Ok(_) => {
|
||||
self.rx_shutdown = true;
|
||||
Ok(())
|
||||
}
|
||||
Err(_) => {
|
||||
Err(Error::new(ErrorKind::Other, "Internal error"))
|
||||
}
|
||||
}
|
||||
}
|
||||
Shutdown::Write => {
|
||||
self.tx_shutdown = true;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn duplicate(&self) -> io::Result<TcpStream> {
|
||||
unimplemented!()
|
||||
}
|
||||
|
||||
pub fn set_linger(&self, _: Option<Duration>) -> io::Result<()> {
|
||||
unimplemented!()
|
||||
}
|
||||
|
||||
pub fn linger(&self) -> io::Result<Option<Duration>> {
|
||||
unimplemented!()
|
||||
}
|
||||
|
||||
pub fn set_nodelay(&self, _: bool) -> io::Result<()> {
|
||||
unimplemented!()
|
||||
}
|
||||
|
|
@ -136,6 +276,10 @@ impl TcpStream {
|
|||
pub fn set_nonblocking(&self, _: bool) -> io::Result<()> {
|
||||
unimplemented!()
|
||||
}
|
||||
|
||||
pub fn peek(&self, _: &mut [u8]) -> io::Result<usize> {
|
||||
unimplemented!()
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Debug for TcpStream {
|
||||
|
|
@ -144,10 +288,6 @@ impl fmt::Debug for TcpStream {
|
|||
}
|
||||
}
|
||||
|
||||
impl Drop for TcpStream {
|
||||
// do the close message here
|
||||
}
|
||||
|
||||
impl Read for TcpStream {
|
||||
fn read(&self, _: &mut [u8]) -> io::Result<usize> {
|
||||
unimplemented!()
|
||||
|
|
@ -159,3 +299,39 @@ impl Write for TcpStream {
|
|||
unimplemented!()
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for TcpStream {
|
||||
fn drop(&mut self) {
|
||||
let request = NetTcpManage {
|
||||
ip_addr: NetIpAddr::from(self.socket_addr),
|
||||
remote_port: self.socket_addr.port(),
|
||||
local_port: self.local_port,
|
||||
cb_sid: self.cb_sid.to_array(),
|
||||
timeout_ms: None,
|
||||
keepalive_ms: None,
|
||||
result: None,
|
||||
rx_shutdown: None, // this is ignored by the close because it is redundant
|
||||
};
|
||||
let mut buf = Buffer::into_buf(request).expect("can't unregister with Net server");
|
||||
buf.lend_mut(self.net.conn(), Opcode::TcpClose.to_u32().unwrap()).expect("can't unregister with Net server");
|
||||
match buf.to_original().unwrap() {
|
||||
NetMemResponse::Ok => {
|
||||
let drop_cid = xous::connect(self.cb_sid).unwrap();
|
||||
xous::send_message(
|
||||
drop_cid,
|
||||
Message::new_blocking_scalar(NetTcpCallback::Drop.to_usize().unwrap(), 0, 0, 0, 0)
|
||||
).expect("couldn't send Drop to our repsonding server");
|
||||
unsafe{xous::disconnect(drop_cid).ok()}; // should be safe because we're the only connection and the previous was a blocking scalar
|
||||
},
|
||||
_ => {
|
||||
panic!("Couldn't unregister with net server");
|
||||
}
|
||||
}
|
||||
// this will block until the responder thread exits, which it should because it received the Drop message
|
||||
if let Some(handle) = self.rx_handle.take() {
|
||||
handle.join().unwrap();
|
||||
}
|
||||
// now we can detroy the server id of the responder thread
|
||||
xous::destroy_server(self.cb_sid).ok();
|
||||
}
|
||||
}
|
||||
Loading…
Reference in a new issue