diff --git a/services/com/src/lib.rs b/services/com/src/lib.rs index 91106efca..f152b2d2d 100644 --- a/services/com/src/lib.rs +++ b/services/com/src/lib.rs @@ -579,12 +579,16 @@ impl Com { Message::new_blocking_scalar(Opcode::IntAck.to_usize().unwrap(), ack_val as usize, 0, 0, 0) ).expect("couldn't send IntSetMask message"); } - pub fn ints_get_active(&self, int_list: &mut Vec::) -> (Option, usize, usize) { + pub fn ints_get_active(&self, int_list: &mut Vec::) -> Result<(Option, usize, usize), xous::Error> { let response = send_message(self.conn, Message::new_blocking_scalar(Opcode::IntFetchVector.to_usize().unwrap(), 0, 0, 0, 0)) .expect("couldn't get IntFetchVector"); let mut rxlen: Option = None; if let xous::Result::Scalar2(ints, maybe_rxlen) = response { + if ints == 0xDDDD { + log::warn!("IntFetchVector: 0xDDDD sentinel returned"); + return Err(xous::Error::Timeout); + } let mut mask_bit: u16 = 1; for _ in 0..16 { let int_src = ComIntSources::from(mask_bit & ints as u16); @@ -603,7 +607,7 @@ impl Com { } mask_bit <<= 1; } - (rxlen, ints, maybe_rxlen) + Ok((rxlen, ints, maybe_rxlen)) } else { panic!("failed to send IntGetmask message"); } diff --git a/services/keyboard/src/main.rs b/services/keyboard/src/main.rs index 4dedcedd5..d591de70d 100644 --- a/services/keyboard/src/main.rs +++ b/services/keyboard/src/main.rs @@ -208,6 +208,7 @@ mod implementation { /// indicate if the chord has been captured. Once captured, further presses are ignored, until all keys are let up. chord_captured: bool, susres: RegManager::<{utra::keyboard::KEYBOARD_NUMREGS}>, + pub debug: usize, } fn handle_kbd(_irq_no: usize, arg: *mut usize) { @@ -233,11 +234,16 @@ mod implementation { xous::Message::new_scalar(Opcode::HandlerTrigger.to_usize().unwrap(), 0, 0, 0, 0)).ok(); } if kbd.csr.rf(utra::keyboard::EV_PENDING_INJECT) != 0 { - while kbd.csr.rf(utra::keyboard::UART_CHAR_STB) != 0 { - let c = kbd.csr.rf(utra::keyboard::UART_CHAR_CHAR); - xous::try_send_message(kbd.conn, - xous::Message::new_scalar(Opcode::InjectKey.to_usize().unwrap(), c as _, 0, 0, 0) - ).ok(); + loop { + let char_reg = kbd.csr.r(utra::keyboard::UART_CHAR); + if char_reg & kbd.csr.ms(utra::keyboard::UART_CHAR_STB, 1) != 0 { + xous::try_send_message(kbd.conn, + xous::Message::new_scalar(Opcode::InjectKey.to_usize().unwrap(), (char_reg & 0xff) as _, 0, 0, 0) + ).ok(); + kbd.debug += 1; + } else { + break; + } } } kbd.csr.wo(utra::keyboard::EV_PENDING, pending); @@ -300,6 +306,7 @@ mod implementation { chord_active: 0, chord_captured: false, susres: RegManager::new(csr.as_mut_ptr() as *mut u32), + debug: 0, }; xous::claim_interrupt( @@ -849,7 +856,8 @@ fn xmain() -> ! { log::warn!("kbd server is overriding WFI for debugging, remember to disable for production"); llio.wfi_override(true).unwrap(); }*/ - let mut inject_esc = false; + let mut esc_index: Option = None; + let mut esc_chars = [0u8; 16]; log::trace!("starting main loop"); loop { @@ -906,41 +914,61 @@ fn xmain() -> ! { }), Some(Opcode::InjectKey) => msg_scalar_unpack!(msg, k, _, _, _, { // key substitutions to help things work better - // 5b31 = home (5b7e now that we have things working better?? maybe this is a three-byte sequence and I'm missing a third?) - // 5b44 = left - // 5b43 = right - // 5b41 = up - // 5b42 = down - let k_prime = if !inject_esc { - match k { - 0x7f => 0x08, - 0x5b => { - inject_esc = true; - 0x00 + // 1b5b317e = home + // 1b5b44 = left + // 1b5b43 = right + // 1b5b41 = up + // 1b5b42 = down + log::trace!("{:x} {}", k, kbd.debug); + kbd.debug = 0; + + let key = match esc_index { + Some(i) => { + esc_chars[i] = (k & 0xff) as u8; + match esc_match(&esc_chars[..i + 1]) { + Ok(m) => { + if let Some(code) = m { + // Ok(Some(code)) is a character found + esc_chars = [0u8; 16]; + esc_index = None; + code + } else { + // Ok(None) means we're still accumulating characters + if i + 1 < esc_chars.len() { + esc_index = Some(i + 1); + } else { + esc_index = None; + esc_chars = [0u8; 16]; + } + '\u{0000}' + } + } + // invalid sequence encountered, abort + Err(_) => { + log::warn!("Unhandled escape sequence: {:x?}", &esc_chars[..i+1]); + esc_chars = [0u8; 16]; + esc_index = None; + '\u{0000}' + } } - _ => k as u32 } - } else { - inject_esc = false; - match k { - 0x7e => '∴' as u32, - 0x44 => '←' as u32, - 0x43 => '→' as u32, - 0x41 => '↑' as u32, - 0x42 => '↓' as u32, - _ => { - log::warn!("unknown escape sequence, ignoring: 0x5b{:x}", k); - 0 + _ => { + if k == 0x1b { + esc_index = Some(1); + esc_chars = [0u8; 16]; // clear the full search array with every escape sequence init + esc_chars[0] = 0x1b; + '\u{0000}' + } else { + let bs_del_fix = if k == 0x7f { + 0x08 + } else { + k + }; + core::char::from_u32(bs_del_fix as u32).unwrap_or('\u{0000}') } } }; - let key = if let Some(a) = core::char::from_u32(k_prime) { - a - } else { - log::warn!("Uninterpreable key sequence, ignoring: 0x{:x}", k); - '\u{0000}' - }; if let Some(conn) = listener_conn { if key != '\u{0000}' { log::info!("injecting key '{}'({:x})", key, key as u32); // always be noisy about this, it's an exploit path @@ -1029,3 +1057,33 @@ fn xmain() -> ! { log::trace!("quitting"); xous::terminate_process(0) } + +fn esc_match(esc_chars: &[u8]) -> Result, ()> { + let mut extended = Vec::::new(); + for (i, &c) in esc_chars.iter().enumerate() { + match i { + 0 => if c != 0x1b { return Err(()) }, + 1 => if c != 0x5b { return Err(()) }, + 2 => match c { + 0x41 => return Ok(Some('↑')), + 0x42 => return Ok(Some('↓')), + 0x43 => return Ok(Some('→')), + 0x44 => return Ok(Some('←')), + 0x7e => return Err(()), // premature end + _ => extended.push(c) + } + _ => if c == 0x7e { + if extended.len() == 1 { + if extended[0] == 0x31 { + return Ok(Some('∴')) + } + } else { + return Err(()) // code unrecognized + } + } else { + extended.push(c) + } + } + } + Ok(None) +} \ No newline at end of file diff --git a/services/net/src/connection_manager.rs b/services/net/src/connection_manager.rs index 66c9d01ed..605a14572 100644 --- a/services/net/src/connection_manager.rs +++ b/services/net/src/connection_manager.rs @@ -484,7 +484,11 @@ fn get_next_ssid(ssid_list: &mut HashSet, ssid_attempted: &mut HashSet) { + com_int_list.clear(); + com_int_list.push(ComIntSources::WlanIpConfigUpdate); + com_int_list.push(ComIntSources::WlanRxReady); + com_int_list.push(ComIntSources::BatteryCritical); + com_int_list.push(ComIntSources::Connect); + com_int_list.push(ComIntSources::Disconnect); + com_int_list.push(ComIntSources::WlanSsidScanUpdate); + com_int_list.push(ComIntSources::WlanSsidScanFinished); + com_int_list.push(ComIntSources::WfxErr); +} + #[xous::xous_main] fn xmain() -> ! { log_server::init_wait().unwrap(); @@ -101,20 +113,12 @@ fn xmain() -> ! { llio.com_event_enable(true).unwrap(); // setup the interrupt masks let mut com_int_list: Vec:: = vec![]; - com.ints_get_active(&mut com_int_list); + com.ints_get_active(&mut com_int_list).ok(); 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); - com_int_list.push(ComIntSources::BatteryCritical); - com_int_list.push(ComIntSources::Connect); - com_int_list.push(ComIntSources::Disconnect); - com_int_list.push(ComIntSources::WlanSsidScanUpdate); - com_int_list.push(ComIntSources::WlanSsidScanFinished); - com_int_list.push(ComIntSources::WfxErr); + set_com_ints(&mut com_int_list); com.ints_enable(&com_int_list); com_int_list.clear(); - com.ints_get_active(&mut com_int_list); + com.ints_get_active(&mut com_int_list).ok(); log::debug!("COM pending interrupts after enabling: {:?}", com_int_list); const MAX_DELAY_THREADS: u32 = 10; // limit the number of concurrent delay threads. Typically we have 1-2 running at any time, but DoS conditions could lead to many more. let delay_threads = Arc::new(AtomicU32::new(0)); @@ -554,128 +558,149 @@ fn xmain() -> ! { Some(Opcode::ComInterrupt) => { com_int_list.clear(); - let (maybe_rxlen, ints, raw_rxlen) = com.ints_get_active(&mut com_int_list); - 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(_) => {}, - 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); - } - }; - for &pending in com_int_list.iter() { - if pending == ComIntSources::Invalid { - log::error!("COM interrupt vector had an error, ignoring event."); - continue; - } - } - for &pending in com_int_list.iter() { - 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"); - log::info!("Network config acquired: {:?}", config); - net_config = Some(config); - let mac = EthernetAddress::from_bytes(&config.mac); - - // we need to clear the ARP cache in case we've migrated base stations (e.g. in a wireless network - // that is coverd by multiple AP), as the host AP's MAC address would have changed, and we wouldn't - // be able to route responses back. I can't seem to find a function in smoltcp 0.7.5 that allows us - // 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 routes = Routes::new(BTreeMap::new()); - let device = device::NetPhy::new(&xns); - let medium = device.capabilities().medium; - let mut builder = InterfaceBuilder::new(device) - .ip_addrs(ip_addrs) - .routes(routes); - if medium == Medium::Ethernet { - builder = builder - .ethernet_addr(mac) - .neighbor_cache(neighbor_cache); + match com.ints_get_active(&mut com_int_list) { + 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(_) => {}, + 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); } - iface = builder.finalize(); - - let ip_addr = - Ipv4Cidr::new(Ipv4Address::new( - config.addr[0], - config.addr[1], - config.addr[2], - config.addr[3], - ), 24); - set_ipv4_addr(&mut iface, ip_addr); - let default_v4_gw = Ipv4Address::new( - config.gtwy[0], - config.gtwy[1], - config.gtwy[2], - config.gtwy[3], - ); - - // 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), - Err(e) => log::error!("routing table update error: {}", e), + }; + for &pending in com_int_list.iter() { + if pending == ComIntSources::Invalid { + log::error!("COM interrupt vector had an error, ignoring event."); + continue; } - dns_allclear_hook.notify(); - dns_ipv4_hook.notify_custom_args([ - Some(u32::from_be_bytes(config.dns1)), - 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, - ]); - } - }, - ComIntSources::WlanRxReady => { - activity_interval.store(0, Ordering::Relaxed); // reset the activity interval to 0 - if let Some(_config) = net_config { - if let Some(rxlen) = maybe_rxlen { - match iface.device_mut().push_rx_avail(rxlen) { - None => {} //log::info!("pushed {} bytes avail to iface", rxlen), - Some(_) => log::warn!("Got more packets, but smoltcp didn't drain them in time"), + } + for &pending in com_int_list.iter() { + 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"); + log::info!("Network config acquired: {:?}", config); + net_config = Some(config); + let mac = EthernetAddress::from_bytes(&config.mac); + + // we need to clear the ARP cache in case we've migrated base stations (e.g. in a wireless network + // that is coverd by multiple AP), as the host AP's MAC address would have changed, and we wouldn't + // be able to route responses back. I can't seem to find a function in smoltcp 0.7.5 that allows us + // 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 routes = Routes::new(BTreeMap::new()); + let device = device::NetPhy::new(&xns); + let medium = device.capabilities().medium; + let mut builder = InterfaceBuilder::new(device) + .ip_addrs(ip_addrs) + .routes(routes); + if medium == Medium::Ethernet { + builder = builder + .ethernet_addr(mac) + .neighbor_cache(neighbor_cache); } - match xous::try_send_message( - net_conn, - Message::new_scalar(Opcode::NetPump.to_usize().unwrap(), 0, 0, 0, 0) - ) { - 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); + iface = builder.finalize(); + + let ip_addr = + Ipv4Cidr::new(Ipv4Address::new( + config.addr[0], + config.addr[1], + config.addr[2], + config.addr[3], + ), 24); + set_ipv4_addr(&mut iface, ip_addr); + let default_v4_gw = Ipv4Address::new( + config.gtwy[0], + config.gtwy[1], + config.gtwy[2], + config.gtwy[3], + ); + + // 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), + 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, + ]); + // 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, + ]); + } + }, + ComIntSources::WlanRxReady => { + activity_interval.store(0, Ordering::Relaxed); // reset the activity interval to 0 + if let Some(_config) = net_config { + if let Some(rxlen) = maybe_rxlen { + match iface.device_mut().push_rx_avail(rxlen) { + None => {} //log::info!("pushed {} bytes avail to iface", rxlen), + Some(_) => log::warn!("Got more packets, but smoltcp didn't drain them in time"), + } + match xous::try_send_message( + net_conn, + Message::new_scalar(Opcode::NetPump.to_usize().unwrap(), 0, 0, 0, 0) + ) { + 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); + } + } + } else { + log::error!("Got RxReady interrupt but no packet length specified!"); } } - } else { - log::error!("Got RxReady interrupt but no packet length specified!"); + }, + _ => { + log::debug!("Unhandled: {:?}", pending); } } - }, - _ => { - 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, + // or when it is handling the reset of the wifi subsystem, so it's not fatal. + // However, if we see this repeatedly, it might be a good idea to add some sort + // of event counter to log the number of times we've seen this consecutively and + // if it's too much, issue a reset to the EC. + + // refresh the interrupt list to the EC, just in case it lost the prior list + timer.sleep_ms(1000).unwrap(); // a brief delay because if the EC wasn't responding before, it probably needs /some/ time before being able to handle this next message + set_com_ints(&mut com_int_list); + com.ints_enable(&com_int_list); + com_int_list.clear(); + } + _ => { + // not fatal, just report it. + log::error!("Unhanlded error in COM interrupt fetch"); } } - com.ints_ack(&com_int_list); } Some(Opcode::NetPump) => { let timestamp = Instant::from_millis(timer.elapsed_ms() as i64); diff --git a/services/shellchat/src/cmds/ssid.rs b/services/shellchat/src/cmds/ssid.rs index 5c330b49f..d18dbd31f 100644 --- a/services/shellchat/src/cmds/ssid.rs +++ b/services/shellchat/src/cmds/ssid.rs @@ -31,8 +31,12 @@ impl<'a> ShellCmdApi<'a> for Ssid { if let Some(sub_cmd) = tokens.next() { match sub_cmd { + "force" => { + env.com.set_ssid_scanning(true).unwrap(); + write!(ret, "Forcing SSID scan. Warning: could put the connection manager in an inconsistent state.").unwrap(); + } "scan" => { - // SSID scanning is automatically initiated by the connection manager + // SSID scanning is automatically initiated by the connection manager, so we don't initiate it explicitly, just report results let ssid_list = env.com.ssid_fetch_as_list().unwrap(); write!(ret, "RSSI in dBm:\n").unwrap(); for (rssi, name) in ssid_list {