From 70003b641ff22c78e6877211caf00dbadc111fe2 Mon Sep 17 00:00:00 2001 From: bunnie Date: Mon, 11 Jul 2022 04:05:53 +0800 Subject: [PATCH] migrate ecup to the status thread also rework the boot flow to have auto-update detect for EC updates --- services/status/Cargo.toml | 8 +- services/status/locales/i18n.json | 36 +++ services/status/src/ecup.rs | 495 ++++++++++++++++++++++++++++++ services/status/src/main.rs | 74 ++++- 4 files changed, 604 insertions(+), 9 deletions(-) create mode 100644 services/status/src/ecup.rs diff --git a/services/status/Cargo.toml b/services/status/Cargo.toml index b40766a72..fc262c498 100644 --- a/services/status/Cargo.toml +++ b/services/status/Cargo.toml @@ -36,6 +36,11 @@ chrono = {version = "0.4.19", default-features = false, features = ["std"]} sntpc = {version = "0.3.1"} #, features = ["log"] crossbeam = "0.8.1" +sha2 = {path="../engine-sha512"} +digest = "0.9.0" +xous-semver = "0.1.2" +com_rs-ref = {path = "../../imports/com_rs-ref"} + [target.'cfg(not(any(windows,unix)))'.dependencies] utralib = {path = "../../utralib"} @@ -48,5 +53,6 @@ debugprint = [] braille = [] # used for braille mode, so console isn't overwhelmed with status tts = [] # default = ["debugprint"] # "debugprint" -default = [] +dbg-ecupdate = [] ditherpunk = [] +default = [] diff --git a/services/status/locales/i18n.json b/services/status/locales/i18n.json index f63085cb3..18897ef0c 100644 --- a/services/status/locales/i18n.json +++ b/services/status/locales/i18n.json @@ -1,4 +1,40 @@ { + "ecup.invalid": { + "ja": "ECファームウェアパッケージが破損しているか無効です: ", + "en": "EC firmware package is corrupted or invalid: ", + "zh": "固件包已损坏或无效: ", + "en-tts": "EC firmware package is corrupted or invalid: " + }, + "ecup.abort": { + "ja": "エラーのため更新が中止されました! (EC)", + "en": "EC update aborted due to error!", + "zh": "更新因错误而中止!(EC)", + "en-tts": "EC update aborted due to error!" + }, + "ecup.erasing": { + "ja": "消去...", + "en": "Erasing...", + "zh": "擦除...", + "en-tts": "Erasing..." + }, + "ecup.writing": { + "ja": "書き込み...", + "en": "Writing...", + "zh": "写作...", + "en-tts": "Writing..." + }, + "ecup.please_reboot": { + "ja": "USBロードのアップデートが適用されました:できるだけ早く再起動してください...", + "en": "USB-loaded update was applied: please reboot at your earliest convenience...", + "zh": "已应用 USB 加载更新:请尽早重启...", + "en-tts": "USB-loaded update was applied: please reboot at your earliest convenience..." + }, + "ecup.resetting": { + "ja": "ECのリセット", + "en": "Resetting EC...", + "zh": "重置 EC", + "en-tts": "Resetting EC..." + }, "stats.measuring": { "ja": "測定...", "en": "Measuring...", diff --git a/services/status/src/ecup.rs b/services/status/src/ecup.rs new file mode 100644 index 000000000..a7f48c77c --- /dev/null +++ b/services/status/src/ecup.rs @@ -0,0 +1,495 @@ +use std::convert::TryInto; +use modals::Modals; +use num_traits::*; + +use sha2::*; +use digest::Digest; + +use locales::t; +use xous::msg_blocking_scalar_unpack; +use xous_semver::SemVer; + +// The opcodes here are hard-wired so that the shellchat debug commands +// can invoke one of these ops. Normally, we would never do this -- this is +// more of a debugging convenience and eventually I think this dependency +// will go away. +#[derive(num_derive::FromPrimitive, num_derive::ToPrimitive, Debug)] +pub(crate) enum UpdateOp { + #[cfg(feature="dbg-ecupdate")] + UpdateGateware = 0, + #[cfg(feature="dbg-ecupdate")] + UpdateFirmware = 1, + #[cfg(feature="dbg-ecupdate")] + UpdateWf200 = 2, + UpdateAuto = 3, + Quit = 4, + CheckCompat = 5, +} + +#[derive(num_derive::FromPrimitive, num_derive::ToPrimitive, Debug)] +pub(crate) enum UpdateResult { + PackageInvalid, + AutoDone, + NothingToDo, + Abort, +} +#[derive(PartialEq, Eq)] +enum PackageType { + Ec, + Wf200 +} + +const EC_GATEWARE_BASE: u32 = 0x0; +const EC_GATEWARE_LEN: u32 = 0x1_a000; +const EC_FIRMWARE_BASE: u32 = 0x1_a000; +const WF200_FIRMWARE_BASE: u32 = 0x9_C000; +const CTRL_PAGE_LEN: u32 = 0x1000; + +pub(crate) fn ecupdate_thread(sid: xous::SID) { + let xns = xous_names::XousNames::new().unwrap(); + let mut com = com::Com::new(&xns).unwrap(); + let ticktimer = ticktimer_server::Ticktimer::new().unwrap(); + let llio = llio::Llio::new(&xns); + let modals = modals::Modals::new(&xns).unwrap(); + let mut susres = susres::Susres::new_without_hook(&xns).unwrap(); + let netmgr = net::NetManager::new(); + + if com.flash_acquire().unwrap() == false { + log::error!("couldn't acquire exclusive access to the EC updater mechanism. All other operations will fail!"); + } + + #[cfg(any(target_os = "none", target_os = "xous"))] + let ec_package = xous::syscall::map_memory( + xous::MemoryAddress::new((xous::EC_FW_PKG_LOC + xous::FLASH_PHYS_BASE) as usize), + None, + xous::EC_FW_PKG_LEN as usize, + xous::MemoryFlags::R | xous::MemoryFlags::W, + ).expect("couldn't map EC firmware package memory range"); + #[cfg(any(target_os = "none", target_os = "xous"))] + let wf_package = xous::syscall::map_memory( + xous::MemoryAddress::new((xous::EC_WF200_PKG_LOC + xous::FLASH_PHYS_BASE) as usize), + None, + xous::EC_WF200_PKG_LEN as usize, + xous::MemoryFlags::R | xous::MemoryFlags::W, + ).expect("couldn't map EC wf200 package memory range"); + #[cfg(not(any(target_os = "none", target_os = "xous")))] + let ec_package = xous::syscall::map_memory( + None, + None, + xous::EC_FW_PKG_LEN as usize, + xous::MemoryFlags::R | xous::MemoryFlags::W, + ).expect("couldn't map EC firmware package memory range"); + #[cfg(not(any(target_os = "none", target_os = "xous")))] + let wf_package = xous::syscall::map_memory( + None, + None, + xous::EC_WF200_PKG_LEN as usize, + xous::MemoryFlags::R | xous::MemoryFlags::W, + ).expect("couldn't map EC wf200 package memory range"); + + loop { + let msg = xous::receive_message(sid).unwrap(); + log::debug!("EC updater got msg {:?}", msg); + match FromPrimitive::from_usize(msg.body.id()) { + #[cfg(feature="dbg-ecupdate")] + Some(UpdateOp::UpdateGateware) => { // blocking scalar + netmgr.connection_manager_stop().unwrap(); + com.wlan_leave().ok(); + ticktimer.sleep_ms(4000).unwrap(); // give a few seconds for any packets/updates to clear so we don't tigger panics as the EC is about to disappear... + + let package = unsafe{ core::slice::from_raw_parts(ec_package.as_ptr() as *const u8, xous::EC_FW_PKG_LEN as usize)}; + if !validate_package(package,PackageType::Ec) { + log::error!("firmware package did not pass validation"); + modals.show_notification( + &format!("{} gateware", t!("ecup.invalid", xous::LANG)), None).unwrap(); + } else { + susres.set_suspendable(false).unwrap(); // block suspend/resume operations + do_update(&mut com, &modals, package, CTRL_PAGE_LEN, EC_GATEWARE_BASE, EC_GATEWARE_LEN, "gateware"); + susres.set_suspendable(true).unwrap(); // resume suspend/resume operations + } + xous::return_scalar(msg.sender, 0).unwrap(); + }, + #[cfg(feature="dbg-ecupdate")] + Some(UpdateOp::UpdateFirmware) => { // blocking scalar + netmgr.connection_manager_stop().unwrap(); + com.wlan_leave().ok(); + ticktimer.sleep_ms(4000).unwrap(); // give a few seconds for any packets/updates to clear so we don't tigger panics as the EC is about to disappear... + + let package = unsafe{ core::slice::from_raw_parts(ec_package.as_ptr() as *const u8, xous::EC_FW_PKG_LEN as usize)}; + let mut temp: [u8; 4] = Default::default(); + temp.copy_from_slice(&package[0x28..0x2c]); + let length = u32::from_le_bytes(temp); // total length of package + + if !validate_package(package,PackageType::Ec) { + log::error!("firmware package did not pass validation"); + modals.show_notification( + &format!("{} firmware", t!("ecup.invalid", xous::LANG)), None).unwrap(); + } else { + susres.set_suspendable(false).unwrap(); // block suspend/resume operations + do_update(&mut com, &modals, package, EC_GATEWARE_LEN + CTRL_PAGE_LEN, + EC_FIRMWARE_BASE, length - (EC_GATEWARE_LEN), "firmware"); + susres.set_suspendable(true).unwrap(); // resume suspend/resume operations + } + xous::return_scalar(msg.sender, 0).unwrap(); + }, + #[cfg(feature="dbg-ecupdate")] + Some(UpdateOp::UpdateWf200) => { // blocking scalar + netmgr.connection_manager_stop().unwrap(); + com.wlan_leave().ok(); + ticktimer.sleep_ms(4000).unwrap(); // give a few seconds for any packets/updates to clear so we don't tigger panics as the EC is about to disappear... + + let package = unsafe{ core::slice::from_raw_parts(wf_package.as_ptr() as *const u8, xous::EC_WF200_PKG_LEN as usize)}; + let mut temp: [u8; 4] = Default::default(); + temp.copy_from_slice(&package[0x28..0x2c]); + let length = u32::from_le_bytes(temp); // total length of package + + if !validate_package(package,PackageType::Wf200) { + log::error!("WF200 firmware package did not pass validation"); + modals.show_notification( + &format!("{} wf200", t!("ecup.invalid", xous::LANG)), None).unwrap(); + } else { + susres.set_suspendable(false).unwrap(); // block suspend/resume operations + do_update(&mut com, &modals, package, CTRL_PAGE_LEN, + WF200_FIRMWARE_BASE, length, "wf200"); + susres.set_suspendable(true).unwrap(); // resume suspend/resume operations + } + + xous::return_scalar(msg.sender, 0).unwrap(); + }, + Some(UpdateOp::CheckCompat) => msg_blocking_scalar_unpack!(msg, _, _, _, _, { + let ec_rev = com.get_ec_sw_tag().unwrap(); // fetch the purported rev from the EC. We take it at face value. + if ec_rev < net::MIN_EC_REV { + log::warn!("EC firmware is too old to interoperate with the connection manager."); + let mut note = String::from(t!("net.ec_rev_old", xous::LANG)); + note.push_str(&format!("\n\n{}{}", t!("net.ec_current_rev", xous::LANG), ec_rev.to_string())); + modals.show_notification(¬e, None).unwrap(); + xous::return_scalar(msg.sender, 0).unwrap(); + } else { + xous::return_scalar(msg.sender, 1).unwrap(); + } + }), + Some(UpdateOp::UpdateAuto) => { // blocking scalar + const GW_HASH_OFFSET: usize = 0x58; + const FW_HASH_OFFSET: usize = 0x38; + const HASH_LEN: usize = 32; + const SEMVER_OFFSET: usize = 0x18; + const SEMVER_LEN: usize = 16; + const EC_FLASH_BASE: u32 = 0x2000_0000; + const MIN_EC_VER_WITH_HASHES: SemVer = SemVer { + maj: 0, min: 9, rev: 8, extra: 8, commit: None, + }; + const WF200_HASH_LEN: usize = 0x48; // this is actually hash + signature + keyset + + let ec_reported_rev = com.get_ec_sw_tag().unwrap(); // fetch the purported rev from the EC. We take it at face value. + log::info!("EC reported rev: {:?}", ec_reported_rev); + + let mut did_something = false; + let package = unsafe{ core::slice::from_raw_parts(ec_package.as_ptr() as *const u8, xous::EC_FW_PKG_LEN as usize)}; + + // the semver *could* be bogus at this point, but we'll validate the package (which contains the semver) before we use it. + // however, this check is much less computationally expensive than the package validation. + let length = u32::from_le_bytes(package[0x28..0x2c].try_into().unwrap()); + let semver_bytes = &package[0x1000 + length as usize - SEMVER_OFFSET..0x1000 + length as usize - SEMVER_OFFSET + SEMVER_LEN]; + let pkg_ver = SemVer::from(&semver_bytes[..16].try_into().unwrap()); + if pkg_ver > ec_reported_rev { + if validate_package(package,PackageType::Ec) { + // check to see if we need to do an update + // read the length of the package + let gw_hash = &package[0x1000 + length as usize - GW_HASH_OFFSET..0x1000 + length as usize - GW_HASH_OFFSET + HASH_LEN]; + let fw_hash = &package[0x1000 + length as usize - FW_HASH_OFFSET..0x1000 + length as usize - FW_HASH_OFFSET + HASH_LEN]; + did_something = true; + let mut do_gw = false; + let mut do_fw = false; + if ec_reported_rev >= MIN_EC_VER_WITH_HASHES { + // now determine if we have to flash gateware, firmware, or both. + let mut ver_ec_raw = [0u8; 256]; + match com.flash_verify( + EC_FLASH_BASE + + EC_GATEWARE_BASE + + (length - GW_HASH_OFFSET as u32), + &mut ver_ec_raw + ) { + Err(_) => { + xous::return_scalar(msg.sender, UpdateResult::Abort.to_usize().unwrap()).unwrap(); + continue; + } + _ => {} + } + if gw_hash != &ver_ec_raw[..HASH_LEN] { + do_gw = true; + do_fw = true; // if the gateware changed, we *always* update the firmware, because fw also contains the GW hash + } + if fw_hash != &ver_ec_raw[HASH_LEN..HASH_LEN*2] { + do_fw = true; + } + } else { + // this is an old, old version of the EC; always overwrite everything + do_gw = true; + do_fw = true; + } + log::info!("Auto-version check results: do_gw: {:?}, do_fw: {:?}", do_gw, do_fw); + if do_gw { + log::info!("updating GW"); + netmgr.connection_manager_stop().ok(); + llio.com_event_enable(false).ok(); + susres.set_suspendable(false).unwrap(); // block suspend/resume operations + if !do_update(&mut com, &modals, package, CTRL_PAGE_LEN, EC_GATEWARE_BASE, + EC_GATEWARE_LEN, "EC gateware") { + xous::return_scalar(msg.sender, UpdateResult::Abort.to_usize().unwrap()).unwrap(); + continue; + } + susres.set_suspendable(true).unwrap(); // resume suspend/resume operations + } + if do_fw { + log::info!("updating FW"); + netmgr.connection_manager_stop().unwrap(); + llio.com_event_enable(false).ok(); + susres.set_suspendable(false).unwrap(); // block suspend/resume operations + if !do_update(&mut com, &modals, package, EC_GATEWARE_LEN + CTRL_PAGE_LEN, + EC_FIRMWARE_BASE, length - (EC_GATEWARE_LEN), "EC firmware") { + xous::return_scalar(msg.sender, UpdateResult::Abort.to_usize().unwrap()).unwrap(); + continue; + } + susres.set_suspendable(true).unwrap(); // resume suspend/resume operations + } + } else { + log::error!("firmware package did not pass validation"); + modals.show_notification( + &format!("{} gateware", t!("ecup.invalid", xous::LANG)), None).unwrap(); + xous::return_scalar(msg.sender, UpdateResult::PackageInvalid.to_usize().unwrap()).unwrap(); + continue; + } + } else { + log::info!("EC Autoupdate check found that EC rev {:?} is newer or same as update rev {:?}; no update done", ec_reported_rev, pkg_ver); + } + + let package = unsafe{ core::slice::from_raw_parts(wf_package.as_ptr() as *const u8, xous::EC_WF200_PKG_LEN as usize)}; + let mut run_wf200_update = false; + // check to see if we need to do an update. For the WF200, we can only say if the hash is *different*, we don't know if it's newer + // we assume if it's different, we meant toupdate it. + if ec_reported_rev >= MIN_EC_VER_WITH_HASHES { + let mut ver_wf200_raw = [0u8; 256]; + match com.flash_verify( + EC_FLASH_BASE + + WF200_FIRMWARE_BASE, + &mut ver_wf200_raw + ) { + Err(_) => { + xous::return_scalar(msg.sender, UpdateResult::Abort.to_usize().unwrap()).unwrap(); + continue; + } + _ => {} + } + // NOTE: this means we *always* assume there is a staged WF200 update, even if it didn't + // change from the previous revision -- otherwise a "PackageInvalid" error will be thrown. + // so the USB updater script should always copy over the WF200 package whenever there's an EC update, + // because we must have it in order to make sure the version on the device is in sync with the intended version. + if package[CTRL_PAGE_LEN as usize..CTRL_PAGE_LEN as usize + WF200_HASH_LEN] != ver_wf200_raw[..WF200_HASH_LEN] { + run_wf200_update = true; + log::info!("wf200 rev is different"); + log::info!("package : {:x?}", &package[CTRL_PAGE_LEN as usize..CTRL_PAGE_LEN as usize + WF200_HASH_LEN]); + log::info!("readback: {:x?}", &ver_wf200_raw[..WF200_HASH_LEN]); + } + } else { + // ancient version of EC, must run all the updates if any update was run before on the GW + run_wf200_update = did_something; + } + if run_wf200_update { + if validate_package(package,PackageType::Wf200) { + log::info!("updating Wf200"); + did_something = true; + netmgr.connection_manager_stop().unwrap(); + llio.com_event_enable(false).ok(); + let length = u32::from_le_bytes(package[0x28..0x2c].try_into().unwrap()); + susres.set_suspendable(false).unwrap(); // block suspend/resume operations + if !do_update(&mut com, &modals, package, CTRL_PAGE_LEN, + WF200_FIRMWARE_BASE, length, "WF200") { + xous::return_scalar(msg.sender, UpdateResult::Abort.to_usize().unwrap()).unwrap(); + continue; + } + susres.set_suspendable(true).unwrap(); // resume suspend/resume operations + } else { + log::error!("wf200 package did not pass validation"); + modals.show_notification( + &format!("{} WF200", t!("ecup.invalid", xous::LANG)), None).unwrap(); + xous::return_scalar(msg.sender, UpdateResult::PackageInvalid.to_usize().unwrap()).unwrap(); + continue; + } + } + + if did_something { + modals.dynamic_notification(Some(t!("ecup.resetting", xous::LANG)), None).unwrap(); + log::info!("EC firmware had an update"); + ticktimer.sleep_ms(500).unwrap(); // paranoia wait + llio.ec_reset().unwrap(); // firmware should reload + ticktimer.sleep_ms(4000).unwrap(); + com.link_reset().unwrap(); + com.reseed_ec_trng().unwrap(); + modals.dynamic_notification_close().unwrap(); + } else { + log::info!("Nothing to update on the EC"); + } + + if did_something { + xous::return_scalar(msg.sender, UpdateResult::AutoDone.to_usize().unwrap()).unwrap(); + } else { + xous::return_scalar(msg.sender, UpdateResult::NothingToDo.to_usize().unwrap()).unwrap(); + } + }, + Some(UpdateOp::Quit) => { + log::info!("quitting updater thread"); + break; + }, + None => { + log::error!("received unknown opcode"); + } + } + } + xous::destroy_server(sid).unwrap(); +} + + +/// copies an image stored in a `package` slice, starting from `pkg_offset` in the `package` with length `len` +/// and writing to FLASH starting at a hardware offset of `flash_start` +fn do_update(com: &mut com::Com, modals: &Modals, package: &[u8], pkg_offset: u32, flash_start: u32, image_len: u32, name: &str) -> bool { + if (pkg_offset + image_len) > package.len() as u32 { + log::error!("Requested image is larger than the package length"); + return false; + } + // erase + modals.dynamic_notification(Some( + &format!("{}\n({})", t!("ecup.erasing", xous::LANG), name) + ), None).unwrap(); + log::info!("{}, erasing from 0x{:08x}, 0x{:x} bytes", name, flash_start, image_len); + if com.flash_erase(flash_start, image_len).unwrap() { + modals.dynamic_notification_close().unwrap(); + } else { + modals.dynamic_notification_close().unwrap(); + modals.show_notification( + &format!("{}\n({})", t!("ecup.abort", xous::LANG), name), None + ).unwrap(); + return false; + } + xous::yield_slice(); + + // program + log::info!("init progress: {:x}->{:x}", pkg_offset, pkg_offset + image_len); + modals.start_progress( + &format!("{}\n({})", t!("ecup.writing", xous::LANG), name), + flash_start, flash_start + image_len, flash_start).unwrap(); + // divide into 1k chunks and send over + let exact_chunks = package[pkg_offset as usize..(pkg_offset + image_len) as usize].chunks_exact(1024); + let lessthan_1k = exact_chunks.remainder(); + let mut prog_addr = flash_start; + let mut pages: [Option<[u8; 256]>; 4] = [None; 4]; + let mut progress_ctr = 0; + for chunks in exact_chunks { + for (full_page, dst_page) in chunks.chunks_exact(256).zip(pages.iter_mut()) { + *dst_page = Some( + { + let mut alloc_page:[u8; 256] = [0; 256]; + for (&src, dst) in full_page.iter().zip(alloc_page.iter_mut()) { + *dst = src; + } + alloc_page + } + ); + } + log::debug!("{} prog 0x{:08x} 4 pages", name, prog_addr); + if com.flash_program(prog_addr, pages).unwrap() == false { + modals.finish_progress().unwrap(); + modals.show_notification( + &format!("{}\n({})", t!("ecup.abort", xous::LANG), name), None + ).unwrap(); + return false; + } + prog_addr += 1024; + progress_ctr += 1; + if (progress_ctr % 6) == 0 { + log::info!("{} prog update 0x{:08x} 6*8 pages", name, prog_addr); + modals.update_progress(prog_addr).unwrap(); + } + } + // take the remainder that's less than 1k, and divide into 256-byte pages + if lessthan_1k.len() > 0 { + let fullpages = lessthan_1k.chunks_exact(256); + let leftovers = fullpages.remainder(); + let mut pages_written = 0; + pages = [None; 4]; // clear the pages buffer + for (full_page, dst_page) in fullpages.zip(pages.iter_mut()) { + *dst_page = Some( + { + let mut alloc_page:[u8; 256] = [0; 256]; + for (&src, dst) in full_page.iter().zip(alloc_page.iter_mut()) { + *dst = src; + } + alloc_page + } + ); + pages_written += 1; + } + // take the remainder that's less than 256-bytes, pad it to 256 bytes, and stick it in the very last page + if leftovers.len() > 0 { + pages[pages_written] = Some({ + let mut alloc_page: [u8; 256] = [0; 256]; + for(&src, dst) in leftovers.iter().zip(alloc_page.iter_mut()) { + *dst = src; + } + alloc_page + }); + } + let mut dbgcnt = 0; + for pg in pages.iter() { + if pg.is_some() { + dbgcnt += 1; + } + } + log::info!("{} prog 0x{:08x} {} pages (last op)", name, prog_addr, dbgcnt); + if com.flash_program(prog_addr, pages).unwrap() == false { + modals.finish_progress().unwrap(); + modals.show_notification( + &format!("{}\n({})", t!("ecup.abort", xous::LANG), name), None + ).unwrap(); + return false + } + } + modals.update_progress(pkg_offset + image_len).unwrap(); // my little pet peeve about progress bars always hitting 100% + xous::yield_slice(); + modals.finish_progress().unwrap(); + true +} + +fn validate_package(pkg: &[u8], pkg_type: PackageType) -> bool { + let mut hasher = sha2::Sha512Trunc256::new_with_strategy(FallbackStrategy::HardwareThenSoftware); + let mut temp: [u8; 4] = Default::default(); + temp.copy_from_slice(&pkg[0x20..0x24]); + if pkg_type == PackageType::Ec { + if temp != [0x70, 0x72, 0x65, 0x63] { // 'prec' + log::error!("EC firmware update package does not have the correct signature"); + return false; + } + } else { + if temp != [0x77, 0x66, 0x32, 0x30] { // 'wf20' + log::error!("WF200 update package does not have the correct signature"); + return false; + } + } + temp.copy_from_slice(&pkg[0x24..0x28]); + if u32::from_le_bytes(temp) != 1 { + log::error!("update package version mismatch"); + return false; + } + temp.copy_from_slice(&pkg[0x28..0x2c]); + let length = u32::from_le_bytes(temp); + hasher.update(&pkg[0x20..(length as usize + 4096)]); + let digest = hasher.finalize(); + log::debug!("digest: {:x?}", digest); + for(&stored, &computed) in pkg[..0x20].iter().zip(digest.iter()) { + if stored != computed { + log::error!("update package hash mismatch"); + return false; + } + } + true +} + diff --git a/services/status/src/main.rs b/services/status/src/main.rs index 619e419b9..c3112b419 100644 --- a/services/status/src/main.rs +++ b/services/status/src/main.rs @@ -9,6 +9,7 @@ mod kbdmenu; use kbdmenu::*; mod app_autogen; mod time; +mod ecup; use com::api::*; use core::fmt::Write; @@ -135,6 +136,7 @@ fn wrapped_main() -> ! { // we want this started really early, because it sanity checks the RTC and a bunch of other stuff. time::start_time_server(); + // ------------------ acquire the status canvas GID let xns = xous_names::XousNames::new().unwrap(); // 1 connection exactly -- from the GAM to set our canvas GID let status_gam_getter = xns @@ -158,12 +160,9 @@ fn wrapped_main() -> ! { } xous::destroy_server(status_gam_getter).unwrap(); + // ------------------ lay out our public API infrastructure // ok, now that we have a GID, we can continue on with our merry way let status_gid: Gid = Gid::new(canvas_gid); - log::trace!("|status: my canvas {:?}", status_gid); - - log::debug!("|status: registering GAM|status thread"); - // allow only one connection, from keyboard to us. let status_sid = xns.register_name(SERVER_NAME_STATUS, Some(1)).unwrap(); // create a connection for callback hooks @@ -177,7 +176,10 @@ fn wrapped_main() -> ! { pump_thread(pump_conn as _, pump_run); } }); + // used to show notifications, e.g. can't sleep while power is engaged. + let modals = modals::Modals::new(&xns).unwrap(); + // ------------------ render initial graphical display, so we don't seem broken on boot let gam = gam::Gam::new(&xns).expect("|status: can't connect to GAM"); let ticktimer = ticktimer_server::Ticktimer::new().expect("Couldn't connect to Ticktimer"); let susres = susres::Susres::new_without_hook(&xns).unwrap(); @@ -271,6 +273,7 @@ fn wrapped_main() -> ! { log::trace!("status redraw## initial"); gam.redraw().unwrap(); // initial boot redraw + // ------------------------ measure current security state and adjust messaging let sec_notes = Arc::new(Mutex::new(HashMap::new())); let mut last_sec_note_index = 0; let mut last_sec_note_size = 0; @@ -280,6 +283,47 @@ fn wrapped_main() -> ! { t!("secnote.usb_unlock", xous::LANG).to_string(), ); } + + // ------------------------ check firmware status and apply updates + // in debug mode, anyone could, in theory, connect to and trigger an EC update, given this permissive policy. + #[cfg(feature="dbg-ecupdate")] + let ecup_sid = xns.register_name("__ECUP server__", None).unwrap(); // do not change name, it is referred to in shellchat + #[cfg(not(feature="dbg-ecupdate"))] + let ecup_sid = xous::create_server().unwrap(); // totally private in this mode + let _ = thread::spawn({ + move || { + ecup::ecupdate_thread(ecup_sid); + } + }); + let ecup_conn = xous::connect(ecup_sid).unwrap(); + // check & automatically apply any EC updates + let mut needs_reboot = false; + match send_message(ecup_conn, + Message::new_blocking_scalar(ecup::UpdateOp::UpdateAuto.to_usize().unwrap(), 0, 0, 0, 0) + ).expect("couldn't send auto update command") { + xous::Result::Scalar1(r) => { + match FromPrimitive::from_usize(r) { + Some(ecup::UpdateResult::AutoDone) => { + // question: do we want to put something there that confirms that the reported EC firmware + // at this point matches the intended update? we /could/ do that, but if it fails then how? + needs_reboot = true; + // restore interrupts and connection manager + llio.com_event_enable(true).ok(); + netmgr.reset(); + netmgr.connection_manager_run().ok(); + } + Some(ecup::UpdateResult::NothingToDo) => log::info!("EC update check: nothing to do, firmware is up to date."), + Some(ecup::UpdateResult::Abort) => { + modals.show_notification(t!("ecup.abort", xous::LANG), None).unwrap(); + } + // note: invalid package triggers a pop-up in the update procedure, so we don't need to pop one up here. + Some(ecup::UpdateResult::PackageInvalid) => log::error!("EC firmware package did not validate"), + None => log::error!("invalid return code from EC update check"), + } + } + _ => log::error!("Invalid return type from UpdateAuto"), + } + let keys = Arc::new(Mutex::new( root_keys::RootKeys::new(&xns, None) .expect("couldn't connect to root_keys to query initialization state"), @@ -319,7 +363,11 @@ fn wrapped_main() -> ! { }); }; sec_notes.lock().unwrap().insert("current_app".to_string(), format!("Running: Shellchat").to_string()); // this is the default app on boot + if needs_reboot { + modals.show_notification(t!("ecup.please_reboot", xous::LANG), None).unwrap(); + } + // --------------------------- graphical loop timing let mut stats_phase: usize = 0; let charger_pump_interval = 180; @@ -336,6 +384,7 @@ fn wrapped_main() -> ! { let mut battstats_phase = true; let mut secnotes_force_redraw = false; + // --------------------------- sync to COM // the EC gets reset by the Net crate on boot to ensure that the state machines are synced up // this takes a few seconds, so we have a dead-wait here. This is a good spot for it because // the status bar reads "booting up..." during this period. @@ -348,18 +397,17 @@ fn wrapped_main() -> ! { com.req_batt_stats() .expect("Can't get battery stats from COM"); - // spawn a time UX manager thread + // --------------------------- spawn a time UX manager thread let time_sid = xous::create_server().unwrap(); let time_cid = xous::connect(time_sid).unwrap(); time::start_time_ux(time_sid); // this is used by the main loop to get the localtime to show on the status bar let mut localtime = llio::LocalTime::new(); + + // ---------------------------- build menus // used to hide time when the PDDB is not mounted let pddb_poller = pddb::PddbMountPoller::new(); - // used to show notifications, e.g. can't sleep while power is engaged. - let modals = modals::Modals::new(&xns).unwrap(); - log::debug!("starting main menu thread"); let main_menu_sid = xous::create_server().unwrap(); let status_cid = xous::connect(status_sid).unwrap(); @@ -386,9 +434,19 @@ fn wrapped_main() -> ! { }); log::info!("|status: starting main loop"); // don't change this -- factory test looks for this exact string + // ---------------------- final cleanup before entering main loop #[cfg(any(target_os = "none", target_os = "xous"))] llio.clear_wakeup_alarm().unwrap(); // this is here to clear any wake-up alarms that were set by a prior coldboot command + // spawn a thread to auto-mount the PDDB + let _ = thread::spawn({ + move || { + let tt = ticktimer_server::Ticktimer::new().unwrap(); + tt.sleep_ms(4000).unwrap(); // a brief pause, to allow the other startup bits to finish running + pddb::Pddb::new().try_mount(); + } + }); + // Automatic backlight-related variables. kbd.register_observer( SERVER_NAME_STATUS,