diff --git a/services/codec/src/main.rs b/services/codec/src/main.rs index 25091c43f..62339b232 100644 --- a/services/codec/src/main.rs +++ b/services/codec/src/main.rs @@ -27,7 +27,8 @@ fn xmain() -> ! { info!("my PID is {}", xous::process::id()); let xns = xous_names::XousNames::new().unwrap(); - let codec_sid = xns.register_name(api::SERVER_NAME_CODEC).expect("can't register server"); + // unlimited connections allowed; authentication via token is used + let codec_sid = xns.register_name(api::SERVER_NAME_CODEC, None).expect("can't register server"); log::trace!("registered with NS -- {:?}", codec_sid); let codec_conn = xous::connect(codec_sid).expect("couldn't make connection for the codec implementation"); diff --git a/services/com/src/main.rs b/services/com/src/main.rs index cd3bc423c..7be531088 100644 --- a/services/com/src/main.rs +++ b/services/com/src/main.rs @@ -280,7 +280,8 @@ fn xmain() -> ! { info!("my PID is {}", xous::process::id()); let xns = xous_names::XousNames::new().unwrap(); - let com_sid = xns.register_name(api::SERVER_NAME_COM).expect("can't register server"); + // unlimited connections allowed -- any server is currently allowed to talk to COM. This might need to be revisited. + let com_sid = xns.register_name(api::SERVER_NAME_COM, None).expect("can't register server"); trace!("registered with NS -- {:?}", com_sid); // Create a new com object diff --git a/services/engine-sha512/src/main.rs b/services/engine-sha512/src/main.rs index b06178ed5..d083712ea 100644 --- a/services/engine-sha512/src/main.rs +++ b/services/engine-sha512/src/main.rs @@ -331,7 +331,8 @@ fn xmain() -> ! { info!("my PID is {}", xous::process::id()); let xns = xous_names::XousNames::new().unwrap(); - let engine512_sid = xns.register_name(api::SERVER_NAME_SHA512).expect("can't register server"); + // anyone is allowed to connect to this service; authentication by tokens used + let engine512_sid = xns.register_name(api::SERVER_NAME_SHA512, None).expect("can't register server"); log::trace!("registered with NS -- {:?}", engine512_sid); let mut engine512 = Engine512::new(); diff --git a/services/gam/src/api.rs b/services/gam/src/api.rs index 0fc547f31..5de17a9b8 100644 --- a/services/gam/src/api.rs +++ b/services/gam/src/api.rs @@ -71,7 +71,7 @@ pub(crate) enum Opcode { /// system-level API that can be called by the Xous process launcher to check if we're at a state where less trusted code could be run /// it basically checks that all tokens have been claimed by trusted OS procesess, thus blocking any further token creation - AllowLessTrustedCode, + TrustedInitDone, /////// planned diff --git a/services/gam/src/lib.rs b/services/gam/src/lib.rs index c43fb0cf2..513809248 100644 --- a/services/gam/src/lib.rs +++ b/services/gam/src/lib.rs @@ -172,9 +172,9 @@ impl Gam { Ok(returned_claim.token) } - pub fn allow_less_trusted_code(&self) -> Result { + pub fn trusted_init_done(&self) -> Result { let response = send_message(self.conn, - Message::new_blocking_scalar(Opcode::AllowLessTrustedCode.to_usize().unwrap(), 0, 0, 0, 0) + Message::new_blocking_scalar(Opcode::TrustedInitDone.to_usize().unwrap(), 0, 0, 0, 0) ).expect("couldn't run allow trusted code check"); if let xous::Result::Scalar1(result) = response { if result == 1 { diff --git a/services/gam/src/main.rs b/services/gam/src/main.rs index f4b7a8ab0..f061eeedd 100644 --- a/services/gam/src/main.rs +++ b/services/gam/src/main.rs @@ -27,9 +27,9 @@ use xous::{msg_scalar_unpack, msg_blocking_scalar_unpack}; pub trait LayoutApi { type Layout; - fn init(xns: &xous_names::XousNames, trng: &trng::Trng, canvases: &mut FnvIndexMap) -> Result; - fn clear(&self, canvases: &mut FnvIndexMap) -> Result<(), xous::Error>; - fn resize(&mut self, new_height: i16, canvases: &mut FnvIndexMap) -> Result; + fn init(xns: &xous_names::XousNames, trng: &trng::Trng, gfx: &graphics_server::Gfx, canvases: &mut FnvIndexMap) -> Result; + fn clear(&self, gfx: &graphics_server::Gfx, canvases: &mut FnvIndexMap) -> Result<(), xous::Error>; + fn resize(&mut self, gfx: &graphics_server::Gfx, new_height: i16, canvases: &mut FnvIndexMap) -> Result; } #[derive(Debug)] @@ -44,12 +44,10 @@ struct ChatLayout { // my internal bookkeeping records. Allow input area to grow into content area min_content_height: i16, min_input_height: i16, - gfx: graphics_server::Gfx, } impl LayoutApi for ChatLayout { type Layout = ChatLayout; - fn init(xns: &xous_names::XousNames, trng: &trng::Trng, canvases: &mut FnvIndexMap) -> Result { - let gfx = graphics_server::Gfx::new(&xns).unwrap(); + fn init(xns: &xous_names::XousNames, trng: &trng::Trng, gfx: &graphics_server::Gfx, canvases: &mut FnvIndexMap) -> Result { let screensize = gfx.screen_size().expect("Couldn't get screen size"); // get the height of various text regions to compute the layout let small_height: i16 = gfx.glyph_height_hint(GlyphStyle::Small).expect("couldn't get glyph height") as i16; @@ -90,10 +88,9 @@ impl LayoutApi for ChatLayout { input: input_canvas.gid(), min_content_height: 64, min_input_height, - gfx, }) } - fn clear(&self, canvases: &mut FnvIndexMap) -> Result<(), xous::Error> { + fn clear(&self, gfx: &graphics_server::Gfx, canvases: &mut FnvIndexMap) -> Result<(), xous::Error> { let input_canvas = canvases.get(&self.input).expect("couldn't find input canvas"); let content_canvas = canvases.get(&self.content).expect("couldn't find content canvas"); let predictive_canvas = canvases.get(&self.predictive).expect("couldn't find predictive canvas"); @@ -101,22 +98,22 @@ impl LayoutApi for ChatLayout { let mut rect = status_canvas.clip_rect(); rect.style = DrawStyle {fill_color: Some(PixelColor::Light), stroke_color: None, stroke_width: 0,}; - self.gfx.draw_rectangle(rect).expect("can't clear canvas"); + gfx.draw_rectangle(rect).expect("can't clear canvas"); let mut rect = content_canvas.clip_rect(); rect.style = DrawStyle {fill_color: Some(PixelColor::Light), stroke_color: None, stroke_width: 0,}; - self.gfx.draw_rectangle(rect).expect("can't clear canvas"); + gfx.draw_rectangle(rect).expect("can't clear canvas"); let mut rect = predictive_canvas.clip_rect(); rect.style = DrawStyle {fill_color: Some(PixelColor::Light), stroke_color: None, stroke_width: 0,}; - self.gfx.draw_rectangle(rect).expect("can't clear canvas"); + gfx.draw_rectangle(rect).expect("can't clear canvas"); let mut rect = input_canvas.clip_rect(); rect.style = DrawStyle {fill_color: Some(PixelColor::Light), stroke_color: None, stroke_width: 0,}; - self.gfx.draw_rectangle(rect).expect("can't clear canvas"); + gfx.draw_rectangle(rect).expect("can't clear canvas"); Ok(()) } - fn resize(&mut self, new_height: i16, canvases: &mut FnvIndexMap) -> Result { + fn resize(&mut self, gfx: &graphics_server::Gfx, new_height: i16, canvases: &mut FnvIndexMap) -> Result { let input_canvas = canvases.get(&self.input).expect("couldn't find input canvas"); let predictive_canvas = canvases.get(&self.predictive).expect("couldn't find predictive canvas"); let status_canvas = canvases.get(&self.status).expect("couldn't find status canvas"); @@ -133,13 +130,13 @@ impl LayoutApi for ChatLayout { let input_canvas_mut = canvases.get_mut(&self.input).expect("couldn't find input canvas"); input_canvas_mut.set_clip(new_input_rect); new_input_rect.style = DrawStyle {fill_color: Some(PixelColor::Light), stroke_color: None, stroke_width: 0,}; - self.gfx.draw_rectangle(new_input_rect).expect("can't clear canvas"); + gfx.draw_rectangle(new_input_rect).expect("can't clear canvas"); } { let content_canvas_mut = canvases.get_mut(&self.content).expect("couldn't find content canvas"); content_canvas_mut.set_clip(new_content_rect); new_content_rect.style = DrawStyle {fill_color: Some(PixelColor::Light), stroke_color: None, stroke_width: 0,}; - self.gfx.draw_rectangle(new_content_rect).expect("can't clear canvas"); + gfx.draw_rectangle(new_content_rect).expect("can't clear canvas"); } // we resized to this new height Ok(new_content_rect.br) @@ -153,15 +150,13 @@ impl LayoutApi for ChatLayout { // remember GIDs of the canvases for menus struct MenuLayout { pub menu: Gid, - gfx: graphics_server::Gfx, menu_y_pad: i16, menu_x_pad: i16, menu_min_height: i16, } impl LayoutApi for MenuLayout { type Layout = MenuLayout; - fn init(xns: &xous_names::XousNames, trng: &trng::Trng, canvases: &mut FnvIndexMap) -> Result { - let gfx = graphics_server::Gfx::new(&xns).unwrap(); + fn init(xns: &xous_names::XousNames, trng: &trng::Trng, gfx: &graphics_server::Gfx, canvases: &mut FnvIndexMap) -> Result { let screensize = gfx.screen_size().expect("Couldn't get screen size"); // get the height of various text regions to compute the layout let small_height: i16 = gfx.glyph_height_hint(GlyphStyle::Small).expect("couldn't get glyph height") as i16; @@ -177,22 +172,21 @@ impl LayoutApi for MenuLayout { Ok(MenuLayout { menu: menu_canvas.gid(), - gfx, menu_y_pad: MENU_Y_PAD, menu_x_pad: MENU_X_PAD, menu_min_height: small_height, }) } - fn clear(&self, canvases: &mut FnvIndexMap) -> Result<(), xous::Error> { + fn clear(&self, gfx: &graphics_server::Gfx, canvases: &mut FnvIndexMap) -> Result<(), xous::Error> { let menu_canvas = canvases.get(&self.menu).expect("couldn't find menu canvas"); let mut rect = menu_canvas.clip_rect(); rect.style = DrawStyle {fill_color: Some(PixelColor::Dark), stroke_color: None, stroke_width: 0,}; - self.gfx.draw_rectangle(rect) + gfx.draw_rectangle(rect) } - fn resize(&mut self, new_height: i16, canvases: &mut FnvIndexMap) -> Result { + fn resize(&mut self, gfx: &graphics_server::Gfx, new_height: i16, canvases: &mut FnvIndexMap) -> Result { let mut menu_canvas = canvases.get_mut(&self.menu).expect("couldn't find menu canvas"); - let screensize = self.gfx.screen_size().expect("Couldn't get screen size"); + let screensize = gfx.screen_size().expect("Couldn't get screen size"); let mut height: i16 = if new_height < self.menu_min_height { self.menu_min_height @@ -205,7 +199,7 @@ impl LayoutApi for MenuLayout { let mut menu_clip_rect = Rectangle::new_coords(self.menu_x_pad, self.menu_y_pad, screensize.x - self.menu_x_pad, height); menu_clip_rect.style = DrawStyle {fill_color: Some(PixelColor::Dark), stroke_color: None, stroke_width: 0,}; menu_canvas.set_clip(menu_clip_rect); - self.gfx.draw_rectangle(menu_clip_rect).expect("can't clear menu"); + gfx.draw_rectangle(menu_clip_rect).expect("can't clear menu"); Ok(menu_clip_rect.br) } } @@ -308,7 +302,8 @@ fn xmain() -> ! { info!("my PID is {}", xous::process::id()); let xns = xous_names::XousNames::new().unwrap(); - let gam_sid = xns.register_name(api::SERVER_NAME_GAM).expect("can't register server"); + // unlimited connections allowed; this is a gateway server + let gam_sid = xns.register_name(api::SERVER_NAME_GAM, None).expect("can't register server"); log::trace!("starting up..."); let ticktimer = ticktimer_server::Ticktimer::new().expect("Couldn't connect to Ticktimer"); @@ -322,9 +317,9 @@ fn xmain() -> ! { // a map of canvases accessable by Gid let mut canvases: FnvIndexMap = FnvIndexMap::new(); - let mut menulayout = MenuLayout::init(&xns, &trng, &mut canvases).expect("couldn't create menu layout"); - let mut chatlayout = ChatLayout::init(&xns, &trng, &mut canvases).expect("couldn't create chat layout"); - chatlayout.clear(&mut canvases).expect("couldn't clear initial chatlayout"); + let mut menulayout = MenuLayout::init(&xns, &trng, &gfx, &mut canvases).expect("couldn't create menu layout"); + let mut chatlayout = ChatLayout::init(&xns, &trng, &gfx, &mut canvases).expect("couldn't create chat layout"); + chatlayout.clear(&gfx, &mut canvases).expect("couldn't clear initial chatlayout"); // now that all the initial canvases have been allocated, compute what canvases are drawable // this _replaces_ the original canvas structure, to avoid complications of tracking mutable references through compound data structures @@ -486,7 +481,7 @@ fn xmain() -> ! { // ASSUME: // very few canvases allow dynamic resizing, so we special case these if cb.canvas == chatlayout.input { - let newheight = chatlayout.resize(cb.requested.y, &mut canvases).expect("SetCanvasBoundsRequest couldn't recompute input canvas height"); + let newheight = chatlayout.resize(&gfx, cb.requested.y, &mut canvases).expect("SetCanvasBoundsRequest couldn't recompute input canvas height"); cb.granted = Some(newheight); canvases = recompute_canvases(canvases, Rectangle::new(Point::new(0, 0), screensize)); @@ -575,7 +570,7 @@ fn xmain() -> ! { tokenclaim.token = tm.claim_token(tokenclaim.name.as_str().unwrap()); buffer.replace(tokenclaim).unwrap(); }, - Some(Opcode::AllowLessTrustedCode) => xous::msg_blocking_scalar_unpack!(msg, _, _, _, _, { + Some(Opcode::TrustedInitDone) => xous::msg_blocking_scalar_unpack!(msg, _, _, _, _, { if tm.allow_untrusted_code() { xous::return_scalar(msg.sender, 1).unwrap(); } else { diff --git a/services/gam/src/status.rs b/services/gam/src/status.rs index 4eeffaba3..6302eaede 100644 --- a/services/gam/src/status.rs +++ b/services/gam/src/status.rs @@ -63,7 +63,8 @@ pub fn status_thread(canvas_gid_0: usize, canvas_gid_1: usize, canvas_gid_2: usi log::trace!("|status: registering GAM|status thread"); let xns = xous_names::XousNames::new().unwrap(); - let status_sid = xns.register_name(SERVER_NAME_STATUS).expect("|status: can't register server"); + // should be only one connection here, from the status main loop + let status_sid = xns.register_name(SERVER_NAME_STATUS, Some(1)).expect("|status: can't register server"); // create a connection for callback hooks unsafe{CB_TO_MAIN_CONN = Some(xous::connect(status_sid).unwrap())}; let pump_conn = xous::connect(status_sid).unwrap(); diff --git a/services/graphics-server/src/main.rs b/services/graphics-server/src/main.rs index a756fb8ab..3431436d4 100644 --- a/services/graphics-server/src/main.rs +++ b/services/graphics-server/src/main.rs @@ -63,7 +63,9 @@ fn xmain() -> ! { log::info!("my PID is {}", xous::process::id()); let xns = xous_names::XousNames::new().unwrap(); - let sid = xns.register_name(api::SERVER_NAME_GFX).expect("can't register server"); + // these connections should be established: + // - GAM + let sid = xns.register_name(api::SERVER_NAME_GFX, Some(1)).expect("can't register server"); log::trace!("Server listening on address {:?}", sid); // Create a new monochrome simulator display. diff --git a/services/ime-frontend/src/main.rs b/services/ime-frontend/src/main.rs index 4316e5a94..fd495cb3d 100644 --- a/services/ime-frontend/src/main.rs +++ b/services/ime-frontend/src/main.rs @@ -605,7 +605,9 @@ fn xmain() -> ! { info!("my PID is {}", xous::process::id()); let xns = xous_names::XousNames::new().unwrap(); - let imef_sid = xns.register_name(ime_plugin_api::SERVER_NAME_IME_FRONT).expect("can't register server"); + // only one connection allowed: GAM + // however, currently have to refactor out the shellchat connection. revert this to 1 when that's done!! + let imef_sid = xns.register_name(ime_plugin_api::SERVER_NAME_IME_FRONT, Some(2)).expect("can't register server"); log::trace!("registered with NS -- {:?}", imef_sid); // hook the keyboard event server and have it forward keys to our local main loop diff --git a/services/ime-plugin-shell/src/main.rs b/services/ime-plugin-shell/src/main.rs index c2f701d98..5ccc829ca 100644 --- a/services/ime-plugin-shell/src/main.rs +++ b/services/ime-plugin-shell/src/main.rs @@ -17,7 +17,8 @@ fn xmain() -> ! { info!("my PID is {}", xous::process::id()); let xns = xous_names::XousNames::new().unwrap(); - let ime_sh_sid = xns.register_name(xous::names::SERVER_NAME_IME_PLUGIN_SHELL).expect("can't register server"); + // one connection only, should be the GAM + let ime_sh_sid = xns.register_name(xous::names::SERVER_NAME_IME_PLUGIN_SHELL, Some(1)).expect("can't register server"); log::trace!("registered with NS -- {:?}", ime_sh_sid); let mut history: Queue, U4> = Queue::new(); // this has 2^4 elements = 16??? or does it just have 4 elements. diff --git a/services/keyboard/src/main.rs b/services/keyboard/src/main.rs index 66f3ed436..7c1f51eaf 100644 --- a/services/keyboard/src/main.rs +++ b/services/keyboard/src/main.rs @@ -823,7 +823,14 @@ fn xmain() -> ! { info!("my PID is {}", xous::process::id()); let xns = xous_names::XousNames::new().unwrap(); - let kbd_sid = xns.register_name(api::SERVER_NAME_KBD).expect("can't register server"); + // connections expected: + // - GAM + // - shellchat (for vibe demo) + // - graphics (if building for hosted mode) + #[cfg(target_os = "none")] + let kbd_sid = xns.register_name(api::SERVER_NAME_KBD, Some(2)).expect("can't register server"); + #[cfg(not(target_os = "none"))] + let kbd_sid = xns.register_name(api::SERVER_NAME_KBD, Some(3)).expect("can't register server"); log::trace!("registered with NS -- {:?}", kbd_sid); // Create a new kbd object diff --git a/services/llio/src/main.rs b/services/llio/src/main.rs index 831c0571e..6340751bd 100644 --- a/services/llio/src/main.rs +++ b/services/llio/src/main.rs @@ -618,11 +618,18 @@ fn xmain() -> ! { info!("my PID is {}", xous::process::id()); let xns = xous_names::XousNames::new().unwrap(); - let llio_sid = xns.register_name(api::SERVER_NAME_LLIO).expect("can't register server"); + // connections expected: + // - codec + // - GAM + // - keyboard + // - shellchat/sleep + // - shellchat/environment + let llio_sid = xns.register_name(api::SERVER_NAME_LLIO, Some(5)).expect("can't register server"); log::trace!("registered with NS -- {:?}", llio_sid); // create the I2C handler thread - let i2c_sid = xns.register_name(api::SERVER_NAME_I2C).expect("can't register I2C thread"); + // each connection to llio also creates an i2c connection, so it has the same expectation list + let i2c_sid = xns.register_name(api::SERVER_NAME_I2C, Some(5)).expect("can't register I2C thread"); log::trace!("registered I2C thread with NS -- {:?}", i2c_sid); let (sid0, sid1, sid2, sid3) = i2c_sid.to_u32(); xous::create_thread_4(i2c_thread, sid0 as usize, sid1 as usize, sid2 as usize, sid3 as usize).expect("couldn't start I2C handler thread"); diff --git a/services/rtc/src/lib.rs b/services/rtc/src/lib.rs index 5ae6ff6c8..f3adf353f 100644 --- a/services/rtc/src/lib.rs +++ b/services/rtc/src/lib.rs @@ -12,7 +12,6 @@ use num_traits::{ToPrimitive, FromPrimitive}; pub struct Rtc { conn: CID, callback_sid: Option, - llio: llio::Llio, } static mut RTC_CB: Option = None; impl Rtc { @@ -22,7 +21,6 @@ impl Rtc { Ok(Rtc { conn, callback_sid: None, - llio: llio::Llio::new(&xns).expect("Can't connect to LLIO on behalf of RTC library"), }) } @@ -62,10 +60,6 @@ impl Rtc { )).unwrap(); Ok(()) } - // this simply forwards the hook on to the LLIO library, which actually owns the Event peripheral where the interrupt is generated - pub fn hook_rtc_alarm_callback(&mut self, id: u32, cid: CID) -> Result<(), xous::Error> { - self.llio.hook_rtc_alarm_callback(id, cid) - } pub fn request_datetime(&self) -> Result<(), xous::Error> { send_message(self.conn, diff --git a/services/rtc/src/main.rs b/services/rtc/src/main.rs index bff85cb73..06fd57707 100644 --- a/services/rtc/src/main.rs +++ b/services/rtc/src/main.rs @@ -526,7 +526,11 @@ fn xmain() -> ! { log::info!("my PID is {}", xous::process::id()); let xns = xous_names::XousNames::new().unwrap(); - let rtc_sid = xns.register_name(api::SERVER_NAME_RTC).expect("can't register server"); + // expected connections: + // - GAM + // - shellchat/rtc + // - shellchat/sleep x2 + let rtc_sid = xns.register_name(api::SERVER_NAME_RTC, Some(4)).expect("can't register server"); log::trace!("registered with NS -- {:?}", rtc_sid); CB_TO_MAIN_CONN.store(xous::connect(rtc_sid).unwrap(), Ordering::Relaxed); diff --git a/services/shellchat/src/main.rs b/services/shellchat/src/main.rs index 896b3f7e1..e9125222b 100644 --- a/services/shellchat/src/main.rs +++ b/services/shellchat/src/main.rs @@ -242,17 +242,6 @@ fn imef_cb(s: String::<4000>) { } ////////////////// -fn test_thread() { - let xns = xous_names::XousNames::new().unwrap(); - let ticktimer = ticktimer_server::Ticktimer::new().unwrap(); - ticktimer.sleep_ms(5000).unwrap(); - let rtc = rtc::Rtc::new(&xns).unwrap(); - loop { - rtc.request_datetime().unwrap(); - ticktimer.sleep_ms(2000).unwrap(); - } -} - pub(crate) const SERVER_NAME_SHELLCHAT: &str = "_Shell chat application_"; #[xous::xous_main] @@ -262,10 +251,12 @@ fn xmain() -> ! { info!("my PID is {}", xous::process::id()); let xns = xous_names::XousNames::new().unwrap(); - let shch_sid = xns.register_name(SERVER_NAME_SHELLCHAT).expect("can't register server"); + // unlimited connections allowed, this is a user app and it's up to the app to decide its policy + let shch_sid = xns.register_name(SERVER_NAME_SHELLCHAT, None).expect("can't register server"); log::trace!("registered with NS -- {:?}", shch_sid); unsafe{CB_TO_MAIN_CONN = Some(xous::connect(shch_sid).unwrap())}; + // decrement imef allowlist count when this is refactored! let mut imef = ImeFrontEnd::new(&xns).expect("can't connect to IMEF"); imef.hook_listener_callback(imef_cb).expect("couldn't request events from IMEF"); @@ -273,10 +264,6 @@ fn xmain() -> ! { let mut update_repl = false; let mut was_callback = false; - if false { - xous::create_thread_0(test_thread).unwrap(); - } - log::trace!("starting main loop"); loop { let msg = xous::receive_message(shch_sid).unwrap(); diff --git a/services/susres/src/main.rs b/services/susres/src/main.rs index 328575a30..91e9fb4df 100644 --- a/services/susres/src/main.rs +++ b/services/susres/src/main.rs @@ -463,7 +463,7 @@ static SHOULD_RESUME: AtomicBool = AtomicBool::new(false); static RESUME_EXEC: AtomicBool = AtomicBool::new(false); pub fn execution_gate() { let xns = xous_names::XousNames::new().unwrap(); - let execgate_sid = xns.register_name(api::SERVER_NAME_EXEC_GATE).expect("can't register execution gate"); + let execgate_sid = xns.register_name(api::SERVER_NAME_EXEC_GATE, None).expect("can't register execution gate"); log::trace!("execution_gate registered with NS -- {:?}", execgate_sid); loop { @@ -509,7 +509,8 @@ fn xmain() -> ! { xous::create_thread_0(execution_gate).unwrap(); let xns = xous_names::XousNames::new().unwrap(); - let susres_sid = xns.register_name(api::SERVER_NAME_SUSRES).expect("can't register server"); + // unlimited connections allowed + let susres_sid = xns.register_name(api::SERVER_NAME_SUSRES, None).expect("can't register server"); log::trace!("main loop registered with NS -- {:?}", susres_sid); // make a connection for the timeout thread to wake us up diff --git a/services/trng/src/main.rs b/services/trng/src/main.rs index d946c42b4..f0d142a67 100644 --- a/services/trng/src/main.rs +++ b/services/trng/src/main.rs @@ -668,7 +668,8 @@ fn xmain() -> ! { info!("my PID is {}", xous::process::id()); let xns = xous_names::XousNames::new().unwrap(); - let trng_sid = xns.register_name(api::SERVER_NAME_TRNG).expect("can't register server"); + // unlimited connections allowed, anyone including less-trusted processes can get a random number + let trng_sid = xns.register_name(api::SERVER_NAME_TRNG, None).expect("can't register server"); log::trace!("registered with NS -- {:?}", trng_sid); let mut trng = Trng::new(&xns); diff --git a/services/xous-names/src/api.rs b/services/xous-names/src/api.rs index 374c86db8..d522b22a7 100644 --- a/services/xous-names/src/api.rs +++ b/services/xous-names/src/api.rs @@ -11,6 +11,10 @@ pub(crate) enum Opcode { Lookup, /// Create an authenticated connection to the target server. AuthenticatedLookup, + /// unregister a server, given its cryptographically unique SID. + Unregister, + /// indicates if all inherentely trusted slots have been occupied. Should not run untrusted code until this is the case. + TrustedInitDone, } #[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)] @@ -25,6 +29,12 @@ pub(crate) enum Return { CID(xous::CID), } +#[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)] +pub(crate) struct Registration { + pub name: xous_ipc::String::<64>, + pub conn_limit: Option, +} + #[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)] pub(crate) struct AuthenticatedLookup { pub name: xous_ipc::String::<64>, diff --git a/services/xous-names/src/lib.rs b/services/xous-names/src/lib.rs index 010a92651..1353c0388 100644 --- a/services/xous-names/src/lib.rs +++ b/services/xous-names/src/lib.rs @@ -19,22 +19,37 @@ impl XousNames { }) } - pub fn unregister_server(&self, _sid: xous::SID) -> Result<(), xous::Error> { - // placeholder function for a future call that will search the name table and remove - // a given SID from the table. It's considered "secure" because you'd have to guess a random 128-bit SID + pub fn unregister_server(&self, sid: xous::SID) -> Result<(), xous::Error> { + // searches the name table and removes a given SID from the table. + // It's considered "secure" because you'd have to guess a random 128-bit SID // to destroy someone else's SID. // note that with the current implementation, the destroy call will have to be an O(N) search through // the server table, but this is OK as we expect <100 servers on a device - Ok(()) + let s = sid.to_array(); + let response = xous::send_message(self.conn, + xous::Message::new_blocking_scalar(api::Opcode::Unregister.to_usize().unwrap(), s[0] as usize, s[1] as usize, s[2] as usize, s[3] as usize) + ).expect("unregistration failed"); + if let xous::Result::Scalar1(result) = response { + if result != 0 { + Ok(()) + } else { + Err(xous::Error::ServerNotFound) + } + } else { + Err(xous::Error::InternalError) + } } - pub fn register_name(&self, name: &str) -> Result { - let mut registration_name = String::<64>::new(); + pub fn register_name(&self, name: &str, max_conns: Option) -> Result { + let mut registration = api::Registration { + name: String::<64>::new(), + conn_limit: max_conns, + }; // could also do String::from_str() but in this case we want things to fail if the string is too long. - write!(registration_name, "{}", name).expect("name probably too long"); + write!(registration.name, "{}", name).expect("name probably too long"); - let mut buf = Buffer::into_buf(registration_name).or(Err(xous::Error::InternalError))?; + let mut buf = Buffer::into_buf(registration).or(Err(xous::Error::InternalError))?; buf.lend_mut( self.conn, @@ -55,7 +70,6 @@ impl XousNames { } } - /// note: if this throws an AccessDenied error, you can retry with a request_authenticate_connection() call (to be written) pub fn request_connection(&self, name: &str) -> Result { let mut lookup_name = xous_ipc::String::<64>::new(); write!(lookup_name, "{}", name).expect("name problably too long"); @@ -87,6 +101,26 @@ impl XousNames { xous::yield_slice(); } } + + pub fn trusted_init_done(&self) -> Result { + let response = xous::send_message(self.conn, + xous::Message::new_blocking_scalar(api::Opcode::TrustedInitDone.to_usize().unwrap(), 0, 0, 0, 0) + ).expect("couldn't query trusted_init_done"); + if let xous::Result::Scalar1(result) = response { + if result == 1 { + Ok(true) + } else { + Ok(false) + } + } else { + Err(xous::Error::InternalError) + } + } + + // todo: + // pub fn authenticated_connection(&self, name: &str, key: Authkey) + // this function will create an authenticated connection, if such are allowed + // it's intended for use by dynamically-loaded third-party apps. As of Xous 0.8 this isn't supported, so it's just a "todo" } use core::sync::atomic::{AtomicU32, Ordering}; diff --git a/services/xous-names/src/main.rs b/services/xous-names/src/main.rs index 8a9270ef6..01c90cd06 100644 --- a/services/xous-names/src/main.rs +++ b/services/xous-names/src/main.rs @@ -7,6 +7,7 @@ mod api; use api::*; use num_traits::FromPrimitive; +use xous::msg_blocking_scalar_unpack; use xous_ipc::{String, Buffer}; use log::{error, info}; @@ -72,8 +73,17 @@ I'll take safety over speed in this case. Eventually, we shall endeavor to remove Heapless entirely, once we have a `libstd` in place and we can use heap-allocated Rust primitives... */ +#[derive(Debug, Copy, Clone)] +struct Connection { + pub name: XousServerName, + pub sid: xous::SID, + pub current_conns: u32, // number of unauthenticated (inherentely trusted) connections + pub max_conns: Option, // if None, unlimited connections allowed + pub allow_authenticate: bool, + pub auth_conns: u32, // number of authenticated connections +} struct SlowMap { - pub map: [Option<(XousServerName, xous::SID)>; 128], + pub map: [Option; 128], } impl SlowMap { pub fn new() -> Self { @@ -81,11 +91,18 @@ impl SlowMap { map: [None; 128], } } - pub fn insert(&mut self, name: XousServerName, sid: xous::SID) -> Result<(), xous::Error> { + pub fn insert(&mut self, name: XousServerName, sid: xous::SID, max_conns: Option) -> Result<(), xous::Error> { let mut ok = false; for entry in self.map.iter_mut() { if entry.is_none() { - *entry = Some((name, sid)); + *entry = Some(Connection { + name, + sid, + current_conns: 0, + max_conns, + allow_authenticate: false, // for now, we don't support authenticated connections + auth_conns: 0, + }); ok = true; break; } @@ -96,23 +113,77 @@ impl SlowMap { Ok(()) } } + pub fn remove(&mut self, sid: xous::SID) -> Option { + let mut name: Option = None; + for entry in self.map.iter_mut() { + if let Some(mapping) = entry { + if mapping.sid == sid { + name = Some(mapping.name); + *entry = None; + } + break; + } + } + name + } pub fn contains_key(&self, name: &XousServerName) -> bool { for maybe_entry in self.map.iter() { if let Some(entry) = maybe_entry { - let (key, _value) = entry; - if name == key { + if entry.name == *name { return true } } } return false } - pub fn get(&self, name: &XousServerName) -> Option<&xous::SID> { + pub fn connect(&mut self, name: &XousServerName) -> Option<&xous::SID> { + for maybe_entry in self.map.iter_mut() { + if let Some(entry) = maybe_entry { + if *name == entry.name { + if let Some(max) = entry.max_conns { + if entry.current_conns < max { + (*entry).current_conns += 1; + return Some(&entry.sid); + } else { + return None; + } + } else { + // unlimited connections allowed + (*entry).current_conns += 1; + return Some(&entry.sid); + } + } + } + } + None + } + pub fn trusted_init_done(&self) -> bool { + let mut trusted_done = true; for maybe_entry in self.map.iter() { if let Some(entry) = maybe_entry { - let (key, value) = entry; - if name == key { - return Some(value) + if let Some(max) = entry.max_conns { + if max != entry.current_conns { + trusted_done = false; + } + } + } + } + trusted_done + } + // this function is slightly unsafe because we can't guarantee that the presenter of the SID + // has actually discarded the SID. However, we don't currently anticipate using this path a lot. + // If it does get used in security-critical routes, it should be refactored to regenerate the SID + // and publish it to the server every time a disconnect is called, to ensure that after a disconnection + // the caller can never talk to the server again. + #[allow(dead_code)] + pub fn disconnect(&mut self, sid: xous::SID) -> Option { + for entry in self.map.iter_mut() { + if let Some(mapping) = entry { + if mapping.sid == sid { + if mapping.current_conns > 0 { + mapping.current_conns -= 1; + } + return Some(mapping.name); } } } @@ -123,7 +194,6 @@ impl SlowMap { #[xous::xous_main] fn xmain() -> ! { use implementation::*; - let debug1 = false; log_server::init_wait().unwrap(); log::set_max_level(log::LevelFilter::Info); info!("my PID is {}", xous::process::id()); @@ -140,24 +210,24 @@ fn xmain() -> ! { info!("started"); loop { let mut msg = xous::receive_message(name_server).unwrap(); - if debug1{info!("received message");} + log::trace!("received message"); match FromPrimitive::from_usize(msg.body.id()) { Some(api::Opcode::Register) => { let mem = msg.body.memory_message_mut().unwrap(); let mut buffer = unsafe { Buffer::from_memory_message_mut(mem) }; - let xous_string = buffer.to_original::, _>().unwrap(); - let name = XousServerName::from_str(xous_string.as_str().expect("couldn't convert server name to string")); + let registration = buffer.to_original::().unwrap(); + let name = XousServerName::from_str(registration.name.as_str().expect("couldn't convert server name to string")); let response: api::Return; - if debug1{info!("registration request for '{}'", name);} + log::trace!("registration request for '{}'", name); if !name_table.contains_key(&name) { let new_sid = xous::create_server_id().expect("create server failed, maybe OOM?"); name_table - .insert(name, new_sid) + .insert(name, new_sid, registration.conn_limit) .expect("register name failure, maybe out of HashMap capacity?"); - if debug1{info!("request successful, SID is {:?}", new_sid);} + log::trace!("request successful, SID is {:?}", new_sid); response = api::Return::SID(new_sid.into()); } else { @@ -168,14 +238,23 @@ fn xmain() -> ! { } buffer.replace(response).expect("Register can't serialize return value"); } + Some(api::Opcode::Unregister) => msg_blocking_scalar_unpack!(msg, s0, s1, s2, s3, { + let gid = xous::SID::from_u32(s0 as u32, s1 as u32, s2 as u32, s3 as u32); + if let Some(name) = name_table.remove(gid) { + info!("{} server has unregistered", name); + xous::return_scalar(msg.sender, 1).unwrap(); + } else { + xous::return_scalar(msg.sender, 0).unwrap(); + } + }), Some(api::Opcode::Lookup) => { let mem = msg.body.memory_message_mut().unwrap(); let mut buffer = unsafe { Buffer::from_memory_message_mut(mem) }; let name_string = buffer.to_original::, _>().unwrap(); let name = XousServerName::from_str(name_string.as_str().expect("couldn't convert server name to string")); - if debug1{info!("Lookup request for '{}'", name);} + log::trace!("Lookup request for '{}'", name); let response: api::Return; - if let Some(server_sid) = name_table.get(&name) { + if let Some(server_sid) = name_table.connect(&name) { let sender_pid = msg .sender .pid() @@ -184,7 +263,7 @@ fn xmain() -> ! { .expect("can't broker connection") { xous::Result::ConnectionID(connection_id) => { - if debug1{info!("lookup success, returning connection {}", connection_id);} + log::trace!("lookup success, returning connection {}", connection_id); response = api::Return::CID(connection_id) } _ => { @@ -192,9 +271,9 @@ fn xmain() -> ! { "Can't find request '{}' in table, dumping table:", name ); - for kv_tuple in name_table.map.iter() { - if let Some((key, val)) = kv_tuple { - log::debug!("name: '{}', sid: '{:?}'", key, val); + for maybe_conn in name_table.map.iter() { + if let Some(connection) = maybe_conn { + log::debug!("{:?}", connection); } } d11ctimeout.hosted_delay(); @@ -206,9 +285,9 @@ fn xmain() -> ! { "Can't find request '{}' in table, dumping table:", name ); - for kv_tuple in name_table.map.iter() { - if let Some((key, val)) = kv_tuple { - log::debug!("name: '{}', sid: '{:?}'", key, val); + for maybe_conn in name_table.map.iter() { + if let Some(connection) = maybe_conn { + log::debug!("{:?}", connection); } } // no authenticate remedy currently supported, but we'd put that code somewhere around here eventually. @@ -231,6 +310,13 @@ fn xmain() -> ! { error!("AuthenticatedLookup not yet implemented"); unimplemented!("AuthenticatedLookup not yet implemented"); } + Some(api::Opcode::TrustedInitDone) => { + if name_table.trusted_init_done() { + xous::return_scalar(msg.sender, 1).expect("couldn't return trusted_init_done"); + } else { + xous::return_scalar(msg.sender, 0).expect("couldn't return trusted_init_done"); + } + } None => {error!("couldn't decode message: {:?}", msg); break} } }