From b7453b627e0c65f4dd84fa4ee5b6ccee0a76df74 Mon Sep 17 00:00:00 2001 From: bunnie Date: Sun, 19 Jun 2022 01:01:25 +0800 Subject: [PATCH] add API tokens to prediction API The prediction API now takes an API token. This is a 128-bit number that gets passed to the prediction engine, and it's meant to be unique for every context that requires a predictor. It's up to the prediction engine to do anything with the token. For the "null" engines (such as the icontray for `vault` and `tts`) the token is just ignored. But for example, in `shellchat`, the API token is used to store a history record in a HashMap on a per-token basis. This means that every app that uses the `shellchat` history function gets their own history that can only be read out by that app. The actual token itself is mostly passed through the API. The token storage is in the Context layer (each Context has a record for a token, that starts as `None`), and is passed down to the predictor every time the context swaps, and the predictor receives the token and passes it back if the token was `Some`, or allocates a new random token if it was `None`. Note that everything is a Context, including, for example, menus and modal dialog boxes, but not all contexts have predictors. Only Contexts that ask for a predictor have them. This mechanism works smoothly in this model (as opposed to other hacks and work-arounds previously tried getting to this solution). --- apps/vault/src/ux/icontray.rs | 46 ++++++-- services/gam/src/contexts.rs | 25 +++- services/ime-frontend/src/main.rs | 32 ++++-- services/ime-plugin-api/src/lib.rs | 72 ++++++++++-- services/ime-plugin-shell/src/main.rs | 158 ++++++++++++++++++-------- services/ime-plugin-tts/src/main.rs | 40 ++++++- 6 files changed, 295 insertions(+), 78 deletions(-) diff --git a/apps/vault/src/ux/icontray.rs b/apps/vault/src/ux/icontray.rs index db53d15d7..5c89067f5 100644 --- a/apps/vault/src/ux/icontray.rs +++ b/apps/vault/src/ux/icontray.rs @@ -2,6 +2,7 @@ use ime_plugin_api::*; use xous_ipc::{String, Buffer}; use num_traits::FromPrimitive; +use xous::msg_scalar_unpack; pub(crate) const SERVER_NAME_ICONTRAY: &'static str = "_vault icon tray plugin_"; @@ -18,8 +19,7 @@ pub(crate) fn icontray_server() { // however, because the predictor is connected only on demand -- we leave this as open-ended, which // means anyone could send something to this server if they knew the name of it. - // TODO:: FIX THIS - let ime_sh_sid = xns.register_name(SERVER_NAME_ICONTRAY, None /*Some(1)*/).expect("can't register server"); + let ime_sh_sid = xns.register_name(SERVER_NAME_ICONTRAY, None).expect("can't register server"); let mytriggers = PredictionTriggers { newline: false, @@ -27,10 +27,42 @@ pub(crate) fn icontray_server() { whitespace: false, }; + let mut api_token: Option<[u32; 4]> = None; loop { let mut msg = xous::receive_message(ime_sh_sid).unwrap(); log::trace!("received message {:?}", msg); match FromPrimitive::from_usize(msg.body.id()) { + Some(Opcode::Acquire) => { + let mut buffer = unsafe { + Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap()) + }; + let mut ret = buffer.to_original::().unwrap(); + if api_token.is_none() { + if let Some(token) = ret.token { + api_token = Some(token); + } else { + let new_token = xous::create_server_id().unwrap().to_array(); + ret.token = Some(new_token); + api_token = Some(new_token); + } + } else { + ret.token = None; + log::warn!("attempt to acquire lock on a predictor that was already locked"); + } + buffer.replace(ret).unwrap(); + } + Some(Opcode::Release) => msg_scalar_unpack!(msg, t0, t1, t2, t3, { + let token = [t0 as u32, t1 as u32, t2 as u32, t3 as u32]; + if let Some(t) = api_token { + if t == token { + api_token.take(); + } else { + log::warn!("Release called with an invalid token"); + } + } else { + log::warn!("Release called on a predictor that was in a released state"); + } + }), Some(Opcode::Input) => { let buffer = unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) }; let s = buffer.as_flat::, _>().unwrap(); @@ -38,12 +70,10 @@ pub(crate) fn icontray_server() { log::info!("Input: {}", s.as_str()); } Some(Opcode::Picked) => { - let buffer = unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) }; - let s = buffer.as_flat::, _>().unwrap(); - // input is dynamically updated here - log::info!("Picked: {}", s.as_str()); + // this is ignored } Some(Opcode::Prediction) => { + // we don't check the API token here, because our "predictions" are just the four menu slots let mut buffer = unsafe { Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap()) }; let mut prediction: Prediction = buffer.to_original::().unwrap(); // every key press, the four slots get queried @@ -64,7 +94,9 @@ pub(crate) fn icontray_server() { xous::return_scalar(msg.sender, mytriggers.into()).expect("couldn't return GetPredictionTriggers"); } Some(Opcode::Quit) => { - log::error!("received quit, goodbye!"); break; + if api_token.is_some() { + log::error!("received quit, goodbye!"); break; + } } None => {log::error!("unknown Opcode");} } diff --git a/services/gam/src/contexts.rs b/services/gam/src/contexts.rs index b1d88a852..5fbb3a7c8 100644 --- a/services/gam/src/contexts.rs +++ b/services/gam/src/contexts.rs @@ -60,6 +60,8 @@ pub(crate) struct UxContext { pub gam_token: [u32; 4], /// set to true if keyboard vibrate is turned on pub vibe: bool, + /// API token for the predictor. Allows our prediction history to be shown only when our context is active. + pub pred_token: Option<[u32; 4]>, /// CID to send ContextEvents pub listener: xous::CID, @@ -157,6 +159,8 @@ impl ContextManager { rawkeys_id: None, vibe: false, imef_menu_mode: false, + // this gets initialized on the first attempt to change predictors, not here + pred_token: None, }; self.contexts.insert(token, ux_context); }, @@ -179,6 +183,7 @@ impl ContextManager { rawkeys_id: registration.rawkeys_id, vibe: false, imef_menu_mode: false, + pred_token: None, }; if registration.app_name.as_str().unwrap() == MAIN_MENU_NAME { @@ -207,6 +212,7 @@ impl ContextManager { rawkeys_id: registration.rawkeys_id, vibe: false, imef_menu_mode: false, + pred_token: None, }; self.contexts.insert(token, ux_context); // this check gives permissions to password boxes to render inverted text @@ -235,6 +241,7 @@ impl ContextManager { rawkeys_id: registration.rawkeys_id, vibe: false, imef_menu_mode: false, + pred_token: None, }; self.contexts.insert(token, ux_context); } @@ -381,8 +388,8 @@ impl ContextManager { { // now re-check-out the new context and finalize things let maybe_new_focus = self.get_context_by_token(token); - if let Some(context) = maybe_new_focus { - if context.predictor.is_some() { + let pred_api_token = if let Some(context) = maybe_new_focus { + let pred_token = if context.predictor.is_some() { // only hook up the IMEF if a predictor is selected for this context let descriptor = ImefDescriptor { input_canvas: @@ -403,15 +410,25 @@ impl ContextManager { }, predictor: context.predictor, token: context.gam_token, + predictor_token: context.pred_token, }; - self.imef.connect_backend(descriptor).expect("couldn't connect IMEF to the current app"); + log::info!("sending api token: {:x?}", descriptor.predictor_token); + let pred_api_token = self.imef.connect_backend(descriptor).expect("couldn't connect IMEF to the current app"); + log::info!("got api token: {:x?}", pred_api_token); self.imef_active = true; + Some(pred_api_token) } else { self.imef_active = false; - } + None + }; // now recompute the drawability of canvases, based on on-screen visibility and trust state recompute_canvases(canvases); + pred_token + } else { None }; + if let Some(c) = self.get_context_by_token_mut(token) { + log::info!("setting pred api token: {:x?} on context {:x?}", pred_api_token, token); + c.pred_token = pred_api_token; } } log::trace!("foregrounding new context"); diff --git a/services/ime-frontend/src/main.rs b/services/ime-frontend/src/main.rs index a95742526..c207d6bae 100644 --- a/services/ime-frontend/src/main.rs +++ b/services/ime-frontend/src/main.rs @@ -243,7 +243,7 @@ impl InputTracker { } } - pub fn update(&mut self, newkeys: [char; 4], force_redraw: bool) -> Result>, xous::Error> { + pub fn update(&mut self, newkeys: [char; 4], force_redraw: bool, api_token: [u32; 4]) -> Result>, xous::Error> { let debug1= false; let mut update_predictor = force_redraw; let mut retstring: Option> = None; @@ -586,7 +586,8 @@ impl InputTracker { // Query the prediction engine for the latest predictions if let Some(pred) = self.predictor { for i in 0..self.pred_options.len() { - let p = if let Some(prediction) = pred.get_prediction(i as u32).expect("couldn't query prediction engine") { + let p = if let Some(prediction) = + pred.get_prediction(i as u32, api_token).expect("couldn't query prediction engine") { Some(String::from(prediction.as_str().unwrap_or("UTF-8 Error"))) } else { None @@ -682,13 +683,15 @@ fn main() -> ! { log::trace!("Initialized but still waiting for my canvas Gids"); let imef_cid = xous::connect(imef_sid).unwrap(); + // the API token allows individual predictor back end uses to have their own history buffers + let mut api_token: Option<[u32; 4]> = None; loop { - let msg = xous::receive_message(imef_sid).unwrap(); + let mut msg = xous::receive_message(imef_sid).unwrap(); log::trace!("Message: {:?}", msg); match FromPrimitive::from_usize(msg.body.id()) { Some(ImefOpcode::ConnectBackend) => { - let buffer = unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) }; - let descriptor = buffer.to_original::().unwrap(); + let mut buffer = unsafe { Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap()) }; + let mut descriptor = buffer.to_original::().unwrap(); if let Some(input) = descriptor.input_canvas { if debug1 || dbgcanvas {info!("got input canvas {:?}", input);} @@ -703,7 +706,8 @@ fn main() -> ! { tracker.clear_pred_canvas(); } // disconnect any existing predictor, if we have one already - if let Some(_pred) = tracker.get_predictor() { + if let Some(pred) = tracker.get_predictor() { + pred.release(api_token.take().unwrap()); // api token *should* be Some() if pred is Some() if let Some((name, token)) = tracker.predictor_conn { xns.disconnect_with_token(name.as_str().unwrap(), token) .expect("couldn't disconnect from previous predictor. Something is wrong with internal state!"); @@ -715,7 +719,16 @@ fn main() -> ! { log::trace!("got prediction server: {}", s.as_str().unwrap()); match xns.request_connection_with_token(s.as_str().unwrap()) { Ok((pc, token)) => { - tracker.set_predictor( Some(ime_plugin_api::PredictionPlugin {connection: Some(pc)}) ); + let pred = ime_plugin_api::PredictionPlugin {connection: Some(pc)}; + match pred.acquire(descriptor.predictor_token) { + Ok(confirmation) => { + api_token = Some(confirmation); + // we are required to send back the returned token as confirmation of the connection + descriptor.predictor_token = Some(confirmation); + }, + Err(e) => log::error!("Internal error: {:?}", e), + } + tracker.set_predictor( Some(pred) ); tracker.predictor_conn = Some( (xous_ipc::String::<64>::from_str(s.as_str().unwrap()), token.expect("didn't get the disconnect token!")) @@ -725,6 +738,7 @@ fn main() -> ! { } } tracker.set_gam_token(descriptor.token); + buffer.replace(descriptor).unwrap(); } Some(ImefOpcode::RegisterListener) => msg_scalar_unpack!(msg, sid0, sid1, sid2, sid3, { let sid = xous::SID::from_u32(sid0 as _, sid1 as _, sid2 as _, sid3 as _); @@ -749,7 +763,7 @@ fn main() -> ! { if keys[0] == '😊' { tracker.activate_emoji(); } else { - if let Some(line) = tracker.update(keys, false).expect("couldn't update input tracker with latest key presses") { + if let Some(line) = tracker.update(keys, false, api_token.unwrap()).expect("couldn't update input tracker with latest key presses") { if dbglistener{info!("sending listeners {:?}", line);} if let Some(conn) = listener { if dbglistener{info!("sending to conn {:?}", conn);} @@ -783,7 +797,7 @@ fn main() -> ! { if tracker.is_init() { let force = if arg != 0 { true } else { false }; tracker.clear_area().expect("can't initially clear areas"); - tracker.update(['\u{0000}'; 4], force).expect("can't setup initial screen arrangement"); + tracker.update(['\u{0000}'; 4], force, api_token.unwrap()).expect("can't setup initial screen arrangement"); } else { log::trace!("got redraw, but we're not initialized"); // ignore keyboard events until we've fully initialized diff --git a/services/ime-plugin-api/src/lib.rs b/services/ime-plugin-api/src/lib.rs index f854899b2..901674fde 100644 --- a/services/ime-plugin-api/src/lib.rs +++ b/services/ime-plugin-api/src/lib.rs @@ -9,6 +9,11 @@ pub struct Prediction { pub index: u32, pub valid: bool, pub string: String<1000>, + pub api_token: [u32; 4], +} +#[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)] +pub struct AcquirePredictor { + pub token: Option<[u32; 4]>, } #[derive(Debug, Default, Copy, Clone)] @@ -66,6 +71,10 @@ pub enum Opcode { /// whole predictive unit has been entered. GetPredictionTriggers, + /// Access control & data cleanup + Acquire, + Release, + Quit, } @@ -80,7 +89,11 @@ pub trait PredictionApi { fn unpick(&self) -> Result<(), xous::Error>; fn set_input(&self, s: String<4000>) -> Result<(), xous::Error>; fn feedback_picked(&self, s: String<4000>) -> Result<(), xous::Error>; - fn get_prediction(&self, index: u32) -> Result>, xous::Error>; + fn get_prediction(&self, index: u32, api_token: [u32; 4]) -> Result>, xous::Error>; + /// gets an exclusive lock on the predictor. Returns an error if the predictor is already locked. + fn acquire(&self, api_token: Option<[u32; 4]>) -> Result<[u32; 4], xous::Error>; + /// releases the lock. Also clears any sensitive data that may be in the predictor. + fn release(&self, api_token: [u32; 4]); } // provide a convenience version of the API for generic/standard calls @@ -150,13 +163,15 @@ impl PredictionApi for PredictionPlugin { } } - fn get_prediction(&self, index: u32) -> Result>, xous::Error> { + /// this function could disclose sensitive data, so it requires an API token to call + fn get_prediction(&self, index: u32, api_token: [u32; 4]) -> Result>, xous::Error> { match self.connection { Some(cid) => { let prediction = Prediction { index, string: String::<1000>::new(), valid: false, + api_token, }; let mut buf = Buffer::into_buf(prediction).or(Err(xous::Error::InternalError))?; buf.lend_mut(cid, Opcode::Prediction.to_u32().unwrap()) @@ -185,6 +200,43 @@ impl PredictionApi for PredictionPlugin { _ => Err(xous::Error::UseBeforeInit), } } + + fn acquire(&self, api_token: Option<[u32; 4]>) -> Result<[u32; 4], xous::Error> { + match self.connection { + Some(cid) => { + let request = AcquirePredictor { + token: api_token, + }; + let mut buf = Buffer::into_buf(request).unwrap(); + buf.lend_mut( + cid, + Opcode::Acquire.to_u32().unwrap() + ).unwrap(); + let ret = buf.to_original::().unwrap(); + match ret.token { + Some(token) => Ok(token), + _ => Err(xous::Error::AccessDenied), + } + } + _ => Err(xous::Error::UseBeforeInit), + } + } + + fn release(&self, api_token: [u32; 4]) { + match self.connection { + Some(cid) => { + send_message( + cid, + Message::new_scalar(Opcode::Release.to_usize().unwrap(), + api_token[0] as usize, + api_token[1] as usize, + api_token[2] as usize, + api_token[3] as usize, + )).ok(); + } + _ => log::warn!("release called on a predictor with no connection"), + } + } } ////////////////////////////////////////////////////// @@ -225,10 +277,11 @@ pub struct ImefDescriptor { pub prediction_canvas: Option, pub predictor: Option>, pub token: [u32; 4], // token used to lookup our connected app inside the GAM + pub predictor_token: Option<[u32;4]>, } pub trait ImeFrontEndApi { - fn connect_backend(&self, descriptor: ImefDescriptor) -> Result<(), xous::Error>; + fn connect_backend(&self, descriptor: ImefDescriptor) -> Result<[u32; 4], xous::Error>; fn hook_listener_callback(&mut self, cb: fn(String<4000>)) -> Result<(), xous::Error>; fn redraw(&self, force_all: bool) -> Result<(), xous::Error>; fn send_keyevent(&self, keys: [char; 4]) -> Result<(), xous::Error>; @@ -291,11 +344,16 @@ impl ImeFrontEndApi for ImeFrontEnd { fn getop_process_keys(&self) -> u32 { ImefOpcode::ProcessKeys.to_u32().unwrap() } - fn connect_backend(&self, descriptor: ImefDescriptor) -> Result<(), xous::Error> { - let buf = Buffer::into_buf(descriptor).or(Err(xous::Error::InternalError))?; - buf.send(self.cid, ImefOpcode::ConnectBackend.to_u32().unwrap()) + fn connect_backend(&self, descriptor: ImefDescriptor) -> Result<[u32; 4], xous::Error> { + let mut buf = Buffer::into_buf(descriptor).or(Err(xous::Error::InternalError))?; + buf.lend_mut(self.cid, ImefOpcode::ConnectBackend.to_u32().unwrap()) .or(Err(xous::Error::InternalError)) - .map(|_| ()) + .map(|_| ())?; + let ret = buf.to_original::().unwrap(); + match ret.predictor_token { + Some(token) => Ok(token), + _ => Err(xous::Error::AccessDenied), + } } fn send_keyevent(&self, keys: [char; 4]) -> Result<(), xous::Error> { diff --git a/services/ime-plugin-shell/src/main.rs b/services/ime-plugin-shell/src/main.rs index 757620269..ddcec39bb 100644 --- a/services/ime-plugin-shell/src/main.rs +++ b/services/ime-plugin-shell/src/main.rs @@ -7,6 +7,8 @@ use log::{error, info}; use xous_ipc::{String, Buffer}; use num_traits::FromPrimitive; +use std::collections::HashMap; +use xous::msg_scalar_unpack; fn main() -> ! { log_server::init_wait().unwrap(); @@ -15,13 +17,14 @@ fn main() -> ! { let xns = xous_names::XousNames::new().unwrap(); // one connection only, should be the GAM - let ime_sh_sid = xns.register_name(ime_plugin_shell::SERVER_NAME_IME_PLUGIN_SHELL, Some(1)).expect("can't register server"); + let ime_sh_sid = xns.register_name(ime_plugin_shell::SERVER_NAME_IME_PLUGIN_SHELL, None).expect("can't register server"); log::trace!("registered with NS -- {:?}", ime_sh_sid); - let mut history: Vec> = Vec::new(); + let mut history_store: HashMap::<[u32;4], Vec>> = HashMap::new(); + let mut active_history: Option<([u32; 4], Vec>)> = None; let history_max = 4; - if false { // loads defaults into the predictor array to test things + /* use core::fmt::Write as CoreWriter; let mut test1: String::<64> = String::new(); write!(test1, "This〰should overflow the box").unwrap(); @@ -32,7 +35,7 @@ fn main() -> ! { let mut test3: String::<64> = String::new(); write!(test3, "未雨绸缪").unwrap(); history.push(test3); - } + */ let mytriggers = PredictionTriggers { newline: true, @@ -40,82 +43,139 @@ fn main() -> ! { whitespace: false, }; - info!("ready to accept requests"); loop { let mut msg = xous::receive_message(ime_sh_sid).unwrap(); log::trace!("received message {:?}", msg); match FromPrimitive::from_usize(msg.body.id()) { + Some(Opcode::Acquire) => { + let mut buffer = unsafe { + Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap()) + }; + let mut ret = buffer.to_original::().unwrap(); + if active_history.is_none() { + if let Some(token) = ret.token { + if let Some(h) = history_store.remove(&token) { + log::info!("existing API token: {:x?}", token); + active_history = Some((token, h)); + ret.token = Some(token); + } else { + ret.token = None; + log::warn!("invalid history token"); + } + } else { + let new_token = xous::create_server_id().unwrap().to_array(); + log::info!("new API token: {:x?}", new_token); + active_history = Some((new_token, Vec::new())); + ret.token = Some(new_token); + } + } else { + ret.token = None; + log::warn!("attempt to acquire lock on a predictor that was already locked"); + } + buffer.replace(ret).unwrap(); + } + Some(Opcode::Release) => msg_scalar_unpack!(msg, t0, t1, t2, t3, { + let token = [t0 as u32, t1 as u32, t2 as u32, t3 as u32]; + if let Some((t, h)) = active_history.take() { + if t == token { + history_store.insert(token, h); + } else { + log::warn!("Release had inconsistent api token!"); + } + } else { + log::warn!("Release called on a predictor that was in a released state"); + } + }), Some(Opcode::Input) => { // shell does nothing with the input, it only keeps track of // the picked results } Some(Opcode::Picked) => { - let buffer = unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) }; - let s = buffer.as_flat::, _>().unwrap(); - // the API allows for large picked feedback, but this implementation only keeps the first 64 characters - let mut local_s: String<64> = String::new(); - use core::fmt::Write; - write!(local_s, "{}", s.as_str()).expect("overflowed history variable"); - log::trace!("storing history value | {}", s.as_str()); - if history.len() == history_max { - history.remove(0); + if let Some((_token, history)) = &mut active_history { + let buffer = unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) }; + let s = buffer.as_flat::, _>().unwrap(); + // the API allows for large picked feedback, but this implementation only keeps the first 64 characters + let mut local_s: String<64> = String::new(); + use core::fmt::Write; + write!(local_s, "{}", s.as_str()).expect("overflowed history variable"); + log::trace!("storing history value | {}", s.as_str()); + if history.len() == history_max { + history.remove(0); + } + history.push(local_s); + log::trace!("history has length {}", history.len()); + } else { + log::warn!("predictor not acquired, ignoring"); } - history.push(local_s); - log::trace!("history has length {}", history.len()); } Some(Opcode::Prediction) => { let mut buffer = unsafe { Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap()) }; let mut prediction: Prediction = buffer.to_original::().unwrap(); - log::trace!("querying prediction index {}", prediction.index); - log::trace!("{:?}", prediction); - if history.len() > 0 && ((prediction.index as usize) < history.len()) { - let mut index = prediction.index; - if index >= history.len() as u32 { - index = history.len() as u32 - 1; - } - let mut i = 1; - for &s in history.iter() { - // iterator is from oldest to newest, so do some math to go from newest to oldest - // TIL: there is a .rev() feature in iterators. Next time maybe use that instead. - if (history.len() as u32 - i) == index { - // decompose the string into a character-by-character sequence - // and then stuff byte-by-byte, as fits, into the return array - prediction.string.clear(); - for ch in s.as_str().unwrap().chars() { - if let Ok(_) = prediction.string.push(ch) { - // it's ok, carry on. - } else { - // we ran out of space, stop copying + if let Some((token, history)) = &mut active_history { + if *token == prediction.api_token { + log::trace!("querying prediction index {}", prediction.index); + log::trace!("{:?}", prediction); + if history.len() > 0 && ((prediction.index as usize) < history.len()) { + let mut index = prediction.index; + if index >= history.len() as u32 { + index = history.len() as u32 - 1; + } + let mut i = 1; + for &s in history.iter() { + // iterator is from oldest to newest, so do some math to go from newest to oldest + // TIL: there is a .rev() feature in iterators. Next time maybe use that instead. + if (history.len() as u32 - i) == index { + // decompose the string into a character-by-character sequence + // and then stuff byte-by-byte, as fits, into the return array + prediction.string.clear(); + for ch in s.as_str().unwrap().chars() { + if let Ok(_) = prediction.string.push(ch) { + // it's ok, carry on. + } else { + // we ran out of space, stop copying + break; + } + } + prediction.valid = true; break; } + i = i + 1; } - prediction.valid = true; - break; + } else { // there is no history + prediction.valid = false; + log::trace!("no prediction found"); } - i = i + 1; + log::trace!("returning index {} string {:?}", prediction.index, prediction.string); + } else { + prediction.valid = false; + log::warn!("api token mismatch, ignoring"); } - } else { // there is no history + } else { prediction.valid = false; - log::trace!("no prediction found"); + log::warn!("predictor not acquired, ignoring"); } - log::trace!("returning index {} string {:?}", prediction.index, prediction.string); - // pack our data back into the buffer to return buffer.replace(Return::Prediction(prediction)).expect("couldn't return Prediction"); } Some(Opcode::Unpick) => { - if history.len() == 1 { - let _ = history.remove(0); - } else if history.len() > 1 { - let _ = history.pop(); // discard the last entry + if let Some((_token, history)) = &mut active_history { + if history.len() == 1 { + let _ = history.remove(0); + } else if history.len() > 1 { + let _ = history.pop(); // discard the last entry + } + // in case of 0 length, do nothing + } else { + log::warn!("predictor not acquired, ignoring"); } - // in case of 0 length, do nothing } Some(Opcode::GetPredictionTriggers) => { xous::return_scalar(msg.sender, mytriggers.into()).expect("couldn't return GetPredictionTriggers"); } Some(Opcode::Quit) => { - error!("received quit, goodbye!"); break; + if active_history.is_some() { + error!("received quit, goodbye!"); break; + } } None => {error!("unknown Opcode");} } diff --git a/services/ime-plugin-tts/src/main.rs b/services/ime-plugin-tts/src/main.rs index a279e41fd..1b4729421 100644 --- a/services/ime-plugin-tts/src/main.rs +++ b/services/ime-plugin-tts/src/main.rs @@ -6,6 +6,7 @@ use ime_plugin_api::*; use xous_ipc::{String, Buffer}; use num_traits::FromPrimitive; use tts_frontend::*; +use xous::msg_scalar_unpack; fn main() -> ! { log_server::init_wait().unwrap(); @@ -14,7 +15,7 @@ fn main() -> ! { let xns = xous_names::XousNames::new().unwrap(); // one connection only, should be the GAM - let ime_sh_sid = xns.register_name(ime_plugin_tts::SERVER_NAME_IME_PLUGIN_TTS, Some(1)).expect("can't register server"); + let ime_sh_sid = xns.register_name(ime_plugin_tts::SERVER_NAME_IME_PLUGIN_TTS, None).expect("can't register server"); log::trace!("registered with NS -- {:?}", ime_sh_sid); let tts = TtsFrontend::new(&xns).unwrap(); @@ -25,9 +26,41 @@ fn main() -> ! { }; log::trace!("ready to accept requests"); + let mut api_token: Option<[u32; 4]> = None; loop { let mut msg = xous::receive_message(ime_sh_sid).unwrap(); match FromPrimitive::from_usize(msg.body.id()) { + Some(Opcode::Acquire) => { + let mut buffer = unsafe { + Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap()) + }; + let mut ret = buffer.to_original::().unwrap(); + if api_token.is_none() { + if let Some(token) = ret.token { + api_token = Some(token); + } else { + let new_token = xous::create_server_id().unwrap().to_array(); + ret.token = Some(new_token); + api_token = Some(new_token); + } + } else { + ret.token = None; + log::warn!("attempt to acquire lock on a predictor that was already locked"); + } + buffer.replace(ret).unwrap(); + } + Some(Opcode::Release) => msg_scalar_unpack!(msg, t0, t1, t2, t3, { + let token = [t0 as u32, t1 as u32, t2 as u32, t3 as u32]; + if let Some(t) = api_token { + if t == token { + api_token.take(); + } else { + log::warn!("Release called with an invalid token"); + } + } else { + log::warn!("Release called on a predictor that was in a released state"); + } + }), Some(Opcode::Input) => { } Some(Opcode::Picked) => { @@ -36,6 +69,7 @@ fn main() -> ! { tts.tts_simple(s.as_str()).unwrap(); } Some(Opcode::Prediction) => { + // we don't check the API token, because we always return `false` let mut buffer = unsafe { Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap()) }; let mut prediction: Prediction = buffer.to_original::().unwrap(); prediction.valid = false; @@ -47,7 +81,9 @@ fn main() -> ! { xous::return_scalar(msg.sender, mytriggers.into()).expect("couldn't return GetPredictionTriggers"); } Some(Opcode::Quit) => { - log::error!("received quit, goodbye!"); break; + if api_token.is_some() { + log::error!("received quit, goodbye!"); break; + } } None => {log::error!("unknown Opcode");} }