diff --git a/Cargo.lock b/Cargo.lock index a704b086f..1301172ff 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2072,7 +2072,7 @@ checksum = "fe0f37c9e8f3c5a4a66ad655a93c74daac4ad00c441533bf5c6e7990bb42604e" [[package]] name = "smoltcp" version = "0.8.0" -source = "git+https://github.com/smoltcp-rs/smoltcp.git#35e833e33dfd3e4efc3eb7d5de06bec17c54b011" +source = "git+https://github.com/smoltcp-rs/smoltcp.git?rev=35e833e33dfd3e4efc3eb7d5de06bec17c54b011#35e833e33dfd3e4efc3eb7d5de06bec17c54b011" dependencies = [ "bitflags", "byteorder", diff --git a/services/com/src/lib.rs b/services/com/src/lib.rs index a7ca38bb4..dc669f05b 100644 --- a/services/com/src/lib.rs +++ b/services/com/src/lib.rs @@ -523,8 +523,13 @@ impl Com { let int_src = ComIntSources::from(mask_bit & ints as u16); if int_src != ComIntSources::Invalid { int_list.push(int_src); - if int_src == ComIntSources::WlanRxReady { - rxlen = Some(maybe_rxlen as u16) + if maybe_rxlen > NET_MTU { + log::error!("got an RX_LEN bigger than NET_MTU: {}, squashing packet; ints vector: 0x{:x?}", maybe_rxlen, ints); + rxlen = None; + } else { + if int_src == ComIntSources::WlanRxReady { + rxlen = Some(maybe_rxlen as u16) + } } } mask_bit <<= 1; diff --git a/services/dns/src/main.rs b/services/dns/src/main.rs index c7c7ea6a0..aa836f77a 100644 --- a/services/dns/src/main.rs +++ b/services/dns/src/main.rs @@ -103,7 +103,7 @@ impl Message { use DnsResponseCode::FormatError; let mut index = start; loop { - log::info!("cname index: {}", index); + log::trace!("cname index: {}", index); if *(self.datagram.get(index).ok_or(FormatError)?) == 0 { index += 1; break; @@ -117,7 +117,7 @@ impl Message { pub fn parse_response(&self) -> Result, DnsResponseCode> { use DnsResponseCode::FormatError; - log::info!("parsing packet: {:?}", self.datagram); + log::trace!("parsing packet: {:?}", self.datagram); let mut map = HashMap::::new(); // ASSUME: the query ID and response bit fields have already been checked @@ -128,9 +128,9 @@ impl Message { let mut index = 12; // fast forward past the qname for queries in 0..qdcount { - log::info!("parsing query{}, index {}", queries, index); + log::trace!("parsing query{}, index {}", queries, index); index = self.fast_foward_name(index)?; - log::info!("fast forward through qname to {}", index); + log::trace!("fast forward through qname to {}", index); // index is now at qtype let qtype = u16::from_be_bytes(self.datagram[index..index+2].try_into().unwrap()); if qtype != 1 && qtype != 28 { // A = 1, AAAA = 28 @@ -147,7 +147,7 @@ impl Message { } // index is now at the aname section for aname in 0..ancount { - log::info!("parsing aname{}, index {}", aname, index); + log::trace!("parsing aname{}, index {}", aname, index); // first check to see if we're dealing with a pointer or a name if self.datagram[index] >= 0xc0 { // pointer @@ -160,7 +160,7 @@ impl Message { } else { // name, fast forward past the name index = self.fast_foward_name(index)?; - log::info!("fast forward aname to {}", index); + log::trace!("fast forward aname to {}", index); } // index is now at type let atype = u16::from_be_bytes(self.datagram[index..index+2].try_into().unwrap()); @@ -177,6 +177,7 @@ impl Message { index += 2; // this is our TTL let ttl = u32::from_be_bytes(self.datagram[index..index+4].try_into().unwrap()); + log::trace!("got ttl: {}", ttl); index += 4; // this is the payload length let addr_len = u16::from_be_bytes(self.datagram[index..index+2].try_into().unwrap()); @@ -390,7 +391,7 @@ impl Resolver { #[xous::xous_main] fn xmain() -> ! { log_server::init_wait().unwrap(); - log::set_max_level(log::LevelFilter::Trace); + log::set_max_level(log::LevelFilter::Info); log::info!("my PID is {}", xous::process::id()); let xns = xous_names::XousNames::new().unwrap(); @@ -433,7 +434,7 @@ fn xmain() -> ! { let rand = resolver.trng_u32() as usize % cache_entry.len(); for (index, (ip_addr, _)) in cache_entry.iter().enumerate() { if rand == index { - log::info!("DNS cached: {}->{:?}", name, ip_addr); + log::debug!("DNS cached: {}->{:?}", name, ip_addr); let response = DnsResponse { addr: Some(NetIpAddr::from(*ip_addr)), code: DnsResponseCode::NoError, @@ -474,7 +475,7 @@ fn xmain() -> ! { } }, Err(e) => { - log::info!("DNS query failed: {}->{:?}", name, e); + log::debug!("DNS query failed: {}->{:?}", name, e); let response = DnsResponse { addr: None, code: e, @@ -497,7 +498,7 @@ fn xmain() -> ! { // decrement the TTL, and note which go to zero let mut expired_entries = Vec::::new(); for (entry, ttl) in cache_map.iter_mut() { - log::info!("entry: {:?}, ttl: {}, incr: {}", entry, ttl, increment); + log::debug!("entry: {:?}, ttl: {}, incr: {}", entry, ttl, increment); if *ttl < increment { *ttl = 0; expired_entries.push(*entry); @@ -507,7 +508,7 @@ fn xmain() -> ! { } // remove the entries that are 0 for entry in expired_entries { - log::info!("DNS cache expiring {:?}", entry); + log::debug!("DNS cache expiring {:?}", entry); cache_map.remove(&entry); } // if all the entries are removed, mark for removal from the cache entirely @@ -518,7 +519,7 @@ fn xmain() -> ! { } } for name in expired_names { - log::info!("DNS cache removing {}", &name); + log::debug!("DNS cache removing {}", &name); dns_cache.remove(&name); } } diff --git a/services/net/Cargo.toml b/services/net/Cargo.toml index 552805045..289a7f39e 100644 --- a/services/net/Cargo.toml +++ b/services/net/Cargo.toml @@ -27,7 +27,7 @@ trng = {path = "../trng"} # of the worked examples match the actual documentation now. # pin at a commit, at least, so we aren't building on shifting sand git = "https://github.com/smoltcp-rs/smoltcp.git" -commit = "35e833e33dfd3e4efc3eb7d5de06bec17c54b011" +rev = "35e833e33dfd3e4efc3eb7d5de06bec17c54b011" #path = "../../../smoltcp" #features = ["verbose"] #version = "0.7.5" diff --git a/services/net/src/api.rs b/services/net/src/api.rs index 061468718..80fcbf503 100644 --- a/services/net/src/api.rs +++ b/services/net/src/api.rs @@ -175,6 +175,7 @@ impl From for IpAddress { } } } +#[allow(dead_code)] pub fn ipaddress_to_ipaddr(other: IpAddress) -> IpAddr { match other { IpAddress::Ipv4(ipv4) => { @@ -291,8 +292,12 @@ impl XousScalarEndpoint { /// that assumes a 64-bit usize for the args on a 64-bit arch won't run on /// a 32-bit machine, so limit the max arg size to 32 bits. pub(crate) fn notify_custom_args(&mut self, custom: [Option; 4]) { + 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} } + ); match xous::send_message( cid, xous::Message::new_scalar( diff --git a/services/net/src/backend/ping.rs b/services/net/src/backend/ping.rs index 6be568e84..fe010b5fb 100644 --- a/services/net/src/backend/ping.rs +++ b/services/net/src/backend/ping.rs @@ -1,30 +1,23 @@ use std::convert::TryInto; -use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr, ToSocketAddrs}; +use std::net::IpAddr; use std::unimplemented; -use std::io; -use std::io::{Error, ErrorKind, Result}; use std::sync::{Arc, Mutex}; use std::thread; use std::thread::JoinHandle; use std::collections::HashMap; +use core::sync::atomic::{AtomicBool, Ordering}; use byteorder::{ByteOrder, NetworkEndian}; -use smoltcp::phy::{ChecksumCapabilities, DeviceCapabilities}; -use smoltcp::{ - time::{Duration, Instant}, -}; -use smoltcp::socket::{IcmpEndpoint, IcmpPacketMetadata, IcmpSocket, IcmpSocketBuffer, SocketSet}; +use smoltcp::phy::ChecksumCapabilities; use smoltcp::wire::{ - EthernetAddress, Icmpv4Packet, Icmpv4Repr, IpAddress, IpCidr, Ipv4Address, Ipv4Cidr, IpEndpoint, + Icmpv4Packet, Icmpv4Repr, IpAddress, Icmpv6Packet, Icmpv6Repr, Ipv6Address }; -use utralib::utra::trng_server; 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::*; ///////// Ping implementation @@ -41,9 +34,11 @@ use num_traits::*; /// /// The default timeout is 10 seconds. const PING_DEFAULT_TIMEOUT_MS: u64 = 10_000; +const PING_POLL_INTERVAL_MS: usize = 1_000; pub struct Ping { net: NetConn, cb_sid: SID, + self_cid: CID, handle: Option>, timer: ticktimer_server::Ticktimer, timeout: Arc>, @@ -54,6 +49,7 @@ pub struct Ping { checksum_caps: Arc>, src_addr: Arc>>, remote_addr: Arc>>, + one_shot_active: Arc, } impl Ping { @@ -70,7 +66,8 @@ impl Ping { let remote_addr = Arc::new(Mutex::new(None)); let checksum_caps = Arc::new(Mutex::new(ChecksumCapabilities::default())); // defaults to "Both" let timeout = Arc::new(Mutex::new(PING_DEFAULT_TIMEOUT_MS)); - + let one_shot_active = Arc::new(AtomicBool::new(false)); + let self_cid = xous::connect(cb_sid).unwrap(); let handle = thread::spawn({ let cb_sid_clone = cb_sid.clone(); let waiting_queue = Arc::clone(&waiting_queue); @@ -79,6 +76,8 @@ impl Ping { let checksum_caps = Arc::clone(&checksum_caps); let remote_addr = Arc::clone(&remote_addr); let timeout = Arc::clone(&timeout); + let one_shot_active = Arc::clone(&one_shot_active); + let self_cid = self_cid.clone(); move || { loop { let tt = ticktimer_server::Ticktimer::new().unwrap(); @@ -88,39 +87,48 @@ impl Ping { let buffer = unsafe {Buffer::from_memory_message(msg.body.memory_message().unwrap())}; let incoming = buffer.to_original::().unwrap(); let payload = &incoming.data[..incoming.len as usize]; - log::info!("pinger got {:?}", payload); - match *remote_addr.lock().unwrap() { - Some(IpAddress::Ipv4(_)) => { - log::info!("decode ipv4 ping"); + log::trace!("pinger got {:?}", payload); + let remote_addr_clone = match *remote_addr.lock().unwrap() { + Some(ra) => ra, + None => { + log::warn!("remote address was not set, yet somehow a remote has responded!"); + continue + }, + }; + match remote_addr_clone { + IpAddress::Ipv4(_) => { + log::trace!("decode ipv4 ping"); let icmp_packet = Icmpv4Packet::new_checked(&payload).unwrap(); - log::info!("icmp_packet: {:?}", icmp_packet); + log::trace!("icmp_packet: {:?}", icmp_packet); let icmp_repr = Icmpv4Repr::parse(&icmp_packet, &checksum_caps.lock().unwrap()).unwrap(); - log::info!("icmp_repr: {:?}", icmp_repr); + log::trace!("icmp_repr: {:?}", icmp_repr); if let Icmpv4Repr::EchoReply{ seq_no, data, .. } = icmp_repr { - log::info!("ping back of seq {}", seq_no); - if let Some(_) = waiting_queue.lock().unwrap().get(&seq_no) { + log::trace!("ping back of seq {}", seq_no); + let seq_valid = waiting_queue.lock().unwrap().contains_key(&seq_no); + // bind to seq_valid so lock is droppped, alowing lock to be got again inside the if below + if seq_valid { let packet_timestamp_ms = NetworkEndian::read_u64(data); waiting_queue.lock().unwrap().remove(&seq_no); - log::info!("sending notification of seq {}", seq_no); + log::trace!("sending notification of seq {}", seq_no); notify.lock().unwrap().notify_custom_args([ None, // replaced with discriminant setup in the callback Some((tt.elapsed_ms() - packet_timestamp_ms) as u32), - Some(u32::from_be_bytes(remote_addr.lock().unwrap().unwrap().as_bytes().try_into().unwrap())), + Some(u32::from_be_bytes(remote_addr_clone.as_bytes().try_into().unwrap())), None, ]); } else { - log::info!("pong seq {} not found!", seq_no); + log::warn!("pong seq {} not found!", seq_no); } } else { - log::info!("packet response did not match icmp template"); + log::warn!("packet response did not match icmp template"); } } - Some(IpAddress::Ipv6(_)) => { + IpAddress::Ipv6(_) => { if let Some(src_addr) = *src_addr.lock().unwrap() { let src_ipv6 = match src_addr { // not sure if this a valid way to convert v4->v6, but "meh" @@ -148,11 +156,12 @@ impl Ping { data, .. } = icmp_repr { - if let Some(_) = waiting_queue.lock().unwrap().get(&seq_no) { + let seq_valid = waiting_queue.lock().unwrap().contains_key(&seq_no); + // bind to seq_valid so lock is droppped, alowing lock to be got again inside the if below + if seq_valid { let packet_timestamp_ms = NetworkEndian::read_u64(data); waiting_queue.lock().unwrap().remove(&seq_no); - let addr = remote_addr.lock().unwrap().unwrap(); - let octet_slice = addr.as_bytes(); + let octet_slice = remote_addr_clone.as_bytes(); let mut octets: [u8; 16] = [0; 16]; for (&src, dst) in octet_slice.iter().zip(octets.iter_mut()) { *dst = src; @@ -169,20 +178,19 @@ impl Ping { log::error!("Got IPV6 response, but our source address wasn't set.") } } - Some(_) => { - log::error!("decode problem on remote address"); - unimplemented!() - }, - None => log::error!("Pong received, but somehow no remote address was specified. Ignoring.") + _ => { + log::warn!("Internal error on formatting of remote address. Memory corruption?"); + } } + log::info!("managing wait queue"); let timestamp = tt.elapsed_ms(); waiting_queue.lock().unwrap().retain(|seq, from| { if timestamp - *from < *timeout.lock().unwrap() { - log::info!("sequence {} still pending", seq); + log::trace!("sequence {} still pending", seq); true } else { - log::info!("expiring sequence {}", seq); - // TODO: fix IPV6 case + log::trace!("expiring sequence {}", seq); + // TODO: fix IPV6 case -- need to pack out partial args of the address or something... notify.lock().unwrap().notify_custom_args([ None, // replaced with discriminant setup in the callback None, // indicates failure -> resolves to 0 time @@ -195,11 +203,11 @@ impl Ping { }, Some(NetPingCallback::CheckTimeout) => { let timestamp = tt.elapsed_ms(); - waiting_queue.lock().unwrap().retain(|seq, from| { + waiting_queue.lock().unwrap().retain(|_seq, from| { if timestamp - *from < *timeout.lock().unwrap() { true } else { - // TODO: fix IPV6 case + // TODO: fix IPV6 case -- need to pack out partial args of the address or something... notify.lock().unwrap().notify_custom_args([ None, // replaced with discriminant setup in the callback None, // indicates failure -> resolves to 0 time @@ -209,6 +217,30 @@ impl Ping { false } }); + if waiting_queue.lock().unwrap().len() > 0 { + if !one_shot_active.swap(true, Ordering::SeqCst) { + log::trace!("spawing one-shot"); + thread::spawn({ + let self_cid = self_cid.clone(); + let one_shot_active = one_shot_active.clone(); + move || { + let tt = ticktimer_server::Ticktimer::new().unwrap(); + tt.sleep_ms(PING_POLL_INTERVAL_MS).unwrap(); + one_shot_active.store(false, Ordering::SeqCst); + match xous::send_message(self_cid, + Message::new_scalar(NetPingCallback::CheckTimeout.to_usize().unwrap(), 0, 0, 0, 0) + ) { + Ok(_) => {}, + Err(xous::Error::ServerNotFound) => { + log::warn!("Responder went out of scope for timeout poll. Maybe the lifetime of your Ping object was too short?"); + } + _ => panic!("unhandled error in sending ping poll") + } + } + }); + log::trace!("one-shot spawned"); + } + } } Some(NetPingCallback::SrcAddr) => { // source address is required for ipv6 icmp packet generation @@ -240,6 +272,7 @@ impl Ping { Ping { net, cb_sid, + self_cid, handle: Some(handle), timer: ticktimer_server::Ticktimer::new().unwrap(), timeout, @@ -250,8 +283,15 @@ impl Ping { checksum_caps, src_addr, remote_addr, + one_shot_active, } } + pub fn set_timeout(&mut self, timeout_ms: u64) { + *self.timeout.lock().unwrap() = timeout_ms; + } + pub fn get_timeout(&self) -> u64 { + *self.timeout.lock().unwrap() + } pub fn set_scalar_notification(&mut self, cid: CID, op: usize, discriminant: u32) { self.notify.lock().unwrap().set(cid, op, [Some(discriminant as usize), None, None, None]); } @@ -275,8 +315,20 @@ impl Ping { Message::new_scalar(Opcode::PingSetTtl.to_usize().unwrap(), ttl as usize, 0, 0, 0) ).expect("couldn't send set TTL message for ping"); } + /// blocks until all the pings have either pong'd or timed out -- not sure if this is actually a good idea to have instead of + /// relying on the async callback in all cases? + /* + pub fn wait_pong(&self) { + loop { + let no_pongs_pending = self.waiting_queue.lock().unwrap().is_empty(); + if no_pongs_pending { + break; + } else { + self.timer.sleep_ms(PING_POLL_INTERVAL_MS / 4).unwrap(); + } + } + }*/ pub fn ping(&mut self, remote: IpAddr) { - log::info!("ping"); let ident = 0x22b; let timestamp = self.timer.elapsed_ms(); let mut echo_payload = [0xffu8; 40]; @@ -284,7 +336,7 @@ impl Ping { let remote_addr = IpAddress::from(remote); match remote_addr { IpAddress::Ipv4(_) => { - log::info!("ping sending to {:?} seq_no {}", remote_addr, self.seq_no); + log::debug!("ping sending to {:?} seq_no {}", remote_addr, self.seq_no); let icmp_repr = Icmpv4Repr::EchoRequest { ident, seq_no: self.seq_no, @@ -306,6 +358,7 @@ impl Ping { buf.send(self.net.conn(), Opcode::PingTx.to_u32().unwrap()).expect("couldn't send Ping packet"); } IpAddress::Ipv6(_) => { + // this code probably does not work, as it has not been tested if let Some(src_addr) = *self.src_addr.lock().unwrap() { let src_ipv6 = match src_addr { // not sure if this a valid way to convert v4->v6, but "meh" @@ -354,6 +407,27 @@ impl Ping { // record the remote_addr so we know if we're parsing an ipv4 or ipv6 packet *self.remote_addr.lock().unwrap() = Some(remote_addr); + log::debug!("spawning first one-shot"); + self.one_shot_active.store(true, Ordering::SeqCst); + thread::spawn({ + let self_cid = self.self_cid.clone(); + let one_shot_active = self.one_shot_active.clone(); + move || { + let tt = ticktimer_server::Ticktimer::new().unwrap(); + tt.sleep_ms(PING_POLL_INTERVAL_MS).unwrap(); + one_shot_active.store(false, Ordering::SeqCst); + match xous::try_send_message(self_cid, + Message::new_scalar(NetPingCallback::CheckTimeout.to_usize().unwrap(), 0, 0, 0, 0) + ) { + Ok(_) => {}, + Err(xous::Error::ServerNotFound) => { + log::warn!("Responder went out of scope for timeout poll. Maybe the lifetime of your Ping object was too short?"); + } + _ => panic!("unhandled error in sending ping poll") + } + } + }); + log::debug!("spawning first one-shot spawned"); } } diff --git a/services/net/src/main.rs b/services/net/src/main.rs index 9e8bfc777..18bbffc0a 100644 --- a/services/net/src/main.rs +++ b/services/net/src/main.rs @@ -8,63 +8,23 @@ use com::api::{ComIntSources, Ipv4Conf, NET_MTU}; mod device; -use byteorder::{ByteOrder, NetworkEndian}; use xous::{send_message, Message, CID, SID, msg_scalar_unpack, msg_blocking_scalar_unpack}; use xous_ipc::Buffer; use std::collections::BTreeMap; use std::collections::HashMap; -use std::str::FromStr; use smoltcp::phy::{Medium, Device}; use smoltcp::iface::{InterfaceBuilder, NeighborCache, Routes, Interface}; use smoltcp::socket::{IcmpEndpoint, IcmpPacketMetadata, IcmpSocket, IcmpSocketBuffer, SocketSet}; use smoltcp::wire::{ - EthernetAddress, Icmpv4Packet, Icmpv4Repr, IpAddress, IpCidr, Ipv4Address, Ipv4Cidr, IpEndpoint + EthernetAddress, IpAddress, IpCidr, Ipv4Address, Ipv4Cidr, IpEndpoint }; use smoltcp::socket::{UdpPacketMetadata, UdpSocket, UdpSocketBuffer, SocketHandle}; -use smoltcp::{ - time::{Duration, Instant}, -}; +use smoltcp::time::Instant; use std::thread; use std::sync::Arc; use core::sync::atomic::{AtomicU32, Ordering}; -macro_rules! send_icmp_ping { - ( $repr_type:ident, $packet_type:ident, $ident:expr, $seq_no:expr, - $echo_payload:expr, $socket:expr, $remote_addr:expr ) => {{ - let icmp_repr = $repr_type::EchoRequest { - ident: $ident, - seq_no: $seq_no, - data: &$echo_payload, - }; - - let icmp_payload = $socket.send(icmp_repr.buffer_len(), $remote_addr).expect("couldn't send ping"); - - let icmp_packet = $packet_type::new_unchecked(icmp_payload); - (icmp_repr, icmp_packet) - }}; -} - -macro_rules! get_icmp_pong { - ( $repr_type:ident, $repr:expr, $payload:expr, $waiting_queue:expr, $remote_addr:expr, - $timestamp:expr, $received:expr ) => {{ - if let $repr_type::EchoReply { seq_no, data, .. } = $repr { - if let Some(_) = $waiting_queue.get(&seq_no) { - let packet_timestamp_ms = NetworkEndian::read_i64(data); - log::info!( - "{} bytes from {}: icmp_seq={}, time={}ms", - data.len(), - $remote_addr, - seq_no, - $timestamp.total_millis() - packet_timestamp_ms - ); - $waiting_queue.remove(&seq_no); - $received += 1; - } - } - }}; -} - fn set_ipv4_addr(iface: &mut Interface<'_, DeviceT>, cidr: Ipv4Cidr) where DeviceT: for<'d> Device<'d>, @@ -122,7 +82,7 @@ fn xmain() -> ! { let com = com::Com::new(&xns).unwrap(); let mut com_int_list: Vec:: = vec![]; com.ints_get_active(&mut com_int_list); - log::info!("COM initial pending interrupts: {:?}", com_int_list); + log::debug!("COM initial pending interrupts: {:?}", com_int_list); com_int_list.clear(); com_int_list.push(ComIntSources::WlanIpConfigUpdate); com_int_list.push(ComIntSources::WlanRxReady); @@ -130,7 +90,7 @@ fn xmain() -> ! { com.ints_enable(&com_int_list); com_int_list.clear(); com.ints_get_active(&mut com_int_list); - log::info!("COM pending interrupts after enabling: {:?}", com_int_list); + log::debug!("COM pending interrupts after enabling: {:?}", com_int_list); // build the waiting thread let wait_conn = Arc::new(AtomicU32::new(0)); @@ -155,7 +115,7 @@ fn xmain() -> ! { let deadline: u64 = (deadline_lsb as u64) | ((deadline_msb as u64) << 32); let now = tt.elapsed_ms(); if deadline > now { - log::info!("sleeping for {}", deadline - now); + log::debug!("sleeping for {}", deadline - now); tt.sleep_ms((deadline - now) as usize).unwrap(); send_message(parent_conn, Message::new_scalar(Opcode::NetPump.to_usize().unwrap(), 0, 0, 0, 0)).expect("couldn't pump the net loop"); } @@ -186,7 +146,7 @@ fn xmain() -> ! { icmp_socket.bind(IcmpEndpoint::Ident(ident)).expect("couldn't bind to icmp socket"); let icmp_handle = sockets.add(icmp_socket); - /// udp storage + // udp storage let mut udp_handles = HashMap::::new(); // 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 @@ -200,7 +160,6 @@ fn xmain() -> ! { let routes = Routes::new(BTreeMap::new()); let device = device::NetPhy::new(&xns); - let device_caps = device.capabilities(); let medium = device.capabilities().medium; let mut builder = InterfaceBuilder::new(device) .ip_addrs(ip_addrs) @@ -621,7 +580,7 @@ fn xmain() -> ! { let mut socket = sockets.get::(handle); match socket.recv() { Ok((data, endpoint)) => { - log::info!( + log::trace!( "udp:{} recv data: {:x?} from {}", port, data, @@ -673,7 +632,13 @@ fn xmain() -> ! { } for (_, responder_cid) in ping_responders.iter() { let buf = Buffer::into_buf(response).expect("couldn't alloc send buffer"); - buf.send(*responder_cid, NetPingCallback::RxData.to_u32().unwrap()).expect("couldn't send ping Rx data"); + match buf.send(*responder_cid, NetPingCallback::RxData.to_u32().unwrap()) { + Ok(_) => {}, + Err(xous::Error::ServerNotFound) => { + log::warn!("Ping responder went out of scope. Maybe the lifetime of the originator was not long enough?"); + } + _ => panic!("unhandled error in sending ping response") + } } } } diff --git a/services/shellchat/src/cmds/net_cmd.rs b/services/shellchat/src/cmds/net_cmd.rs index c7fb6342a..9a4feca29 100644 --- a/services/shellchat/src/cmds/net_cmd.rs +++ b/services/shellchat/src/cmds/net_cmd.rs @@ -4,6 +4,7 @@ use net::Duration; use xous::MessageEnvelope; use num_traits::*; use std::net::{SocketAddr, IpAddr}; +use std::thread; pub struct NetCmd { udp: Option, @@ -12,7 +13,6 @@ pub struct NetCmd { callback_conn: u32, udp_count: u32, dns: dns::Dns, - ping: Option, } impl NetCmd { pub fn new(xns: &xous_names::XousNames) -> Self { @@ -23,7 +23,6 @@ impl NetCmd { callback_conn: xns.request_connection_blocking(crate::SERVER_NAME_SHELLCHAT).unwrap(), udp_count: 0, dns: dns::Dns::new(&xns).unwrap(), - ping: None, } } } @@ -42,7 +41,7 @@ impl<'a> ShellCmdApi<'a> for NetCmd { fn process(&mut self, args: String::<1024>, env: &mut CommonEnv) -> Result>, xous::Error> { if self.callback_id.is_none() { let cb_id = env.register_handler(String::<256>::from_str(self.verb())); - log::info!("hooking net callback with ID {}", cb_id); + log::trace!("hooking net callback with ID {}", cb_id); self.callback_id = Some(cb_id); } @@ -116,26 +115,36 @@ impl<'a> ShellCmdApi<'a> for NetCmd { } } "ping" => { - if self.ping.is_none() { - let mut pinger = net::Ping::new(); - pinger.set_scalar_notification( - self.callback_conn, - self.callback_id.unwrap() as usize, - NetCmdDispatch::Ping.to_u32().unwrap() - ); - self.ping = Some(pinger); - log::info!("made pinger"); - } if let Some(name) = tokens.next() { match self.dns.lookup(name) { Ok(ipaddr) => { - log::info!("sending ping to {:?}", ipaddr); - if let Some(pinger) = &mut self.ping { - pinger.ping(IpAddr::from(ipaddr)); - write!(ret, "Ping to {} ({:?})", name, ipaddr).unwrap(); + log::debug!("sending ping to {:?}", ipaddr); + let count = if let Some(count_str) = tokens.next() { + count_str.parse::().unwrap() } else { - write!(ret, "Internal error in ping").unwrap(); - } + 1 + }; + thread::spawn({ + let count = count.clone(); + let cb_conn = self.callback_conn.clone(); + let cb_id = self.callback_id.unwrap() as usize; + move || { + let tt = ticktimer_server::Ticktimer::new().unwrap(); + let mut pinger = net::Ping::new(); + pinger.set_scalar_notification( + cb_conn, + cb_id, + NetCmdDispatch::Ping.to_u32().unwrap() + ); + for i in 0..count { + log::info!("ping {} of {}", i + 1, count); + pinger.ping(IpAddr::from(ipaddr)); + tt.sleep_ms(1000).unwrap(); + } + // pinger.wait_pong(); + } + }); + write!(ret, "Sending {} pings to {} ({:?})", count, name, ipaddr).unwrap(); } Err(e) => { write!(ret, "Can't ping, DNS lookup error: {:?}", e).unwrap(); @@ -160,7 +169,7 @@ impl<'a> ShellCmdApi<'a> for NetCmd { fn callback(&mut self, msg: &MessageEnvelope, _env: &mut CommonEnv) -> Result>, xous::Error> { use core::fmt::Write; - log::info!("net callback"); + log::debug!("net callback"); let mut ret = String::<1024>::new(); xous::msg_scalar_unpack!(msg, dispatch, response_time, remote, _, { match FromPrimitive::from_usize(dispatch) { diff --git a/services/shellchat/src/main.rs b/services/shellchat/src/main.rs index 633aad2dd..f467f043d 100644 --- a/services/shellchat/src/main.rs +++ b/services/shellchat/src/main.rs @@ -50,6 +50,7 @@ struct History { pub is_input: bool, } +#[allow(dead_code)] struct Repl { // optional structures that indicate new input to the Repl loop per iteration // an input string