refactor xous-names to permit only a fixed number of connections

this prevents less trusted processes from connecting to servers
after the kernel initializations are done.

this works so long as we don't have disconnects from the kernel
servers. In order to support disconnects we will also need a
way to re-enumerate the SID to guarantee that we don't have a re-use
problem. But for now, the kernel is not designed with any practical
disconnect mechanism; there is no code that calls the Quit mechanism
on any server.
This commit is contained in:
bunnie 2021-06-15 17:41:14 +08:00
parent 7e141aba91
commit eee9f4e765
20 changed files with 238 additions and 103 deletions

View file

@ -27,7 +27,8 @@ fn xmain() -> ! {
info!("my PID is {}", xous::process::id()); info!("my PID is {}", xous::process::id());
let xns = xous_names::XousNames::new().unwrap(); 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); log::trace!("registered with NS -- {:?}", codec_sid);
let codec_conn = xous::connect(codec_sid).expect("couldn't make connection for the codec implementation"); let codec_conn = xous::connect(codec_sid).expect("couldn't make connection for the codec implementation");

View file

@ -280,7 +280,8 @@ fn xmain() -> ! {
info!("my PID is {}", xous::process::id()); info!("my PID is {}", xous::process::id());
let xns = xous_names::XousNames::new().unwrap(); 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); trace!("registered with NS -- {:?}", com_sid);
// Create a new com object // Create a new com object

View file

@ -331,7 +331,8 @@ fn xmain() -> ! {
info!("my PID is {}", xous::process::id()); info!("my PID is {}", xous::process::id());
let xns = xous_names::XousNames::new().unwrap(); 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); log::trace!("registered with NS -- {:?}", engine512_sid);
let mut engine512 = Engine512::new(); let mut engine512 = Engine512::new();

View file

@ -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 /// 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 /// it basically checks that all tokens have been claimed by trusted OS procesess, thus blocking any further token creation
AllowLessTrustedCode, TrustedInitDone,
/////// planned /////// planned

View file

@ -172,9 +172,9 @@ impl Gam {
Ok(returned_claim.token) Ok(returned_claim.token)
} }
pub fn allow_less_trusted_code(&self) -> Result<bool, xous::Error> { pub fn trusted_init_done(&self) -> Result<bool, xous::Error> {
let response = send_message(self.conn, 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"); ).expect("couldn't run allow trusted code check");
if let xous::Result::Scalar1(result) = response { if let xous::Result::Scalar1(result) = response {
if result == 1 { if result == 1 {

View file

@ -27,9 +27,9 @@ use xous::{msg_scalar_unpack, msg_blocking_scalar_unpack};
pub trait LayoutApi { pub trait LayoutApi {
type Layout; type Layout;
fn init(xns: &xous_names::XousNames, trng: &trng::Trng, canvases: &mut FnvIndexMap<Gid, Canvas, 32>) -> Result<Self::Layout, xous::Error>; fn init(xns: &xous_names::XousNames, trng: &trng::Trng, gfx: &graphics_server::Gfx, canvases: &mut FnvIndexMap<Gid, Canvas, 32>) -> Result<Self::Layout, xous::Error>;
fn clear(&self, canvases: &mut FnvIndexMap<Gid, Canvas, 32>) -> Result<(), xous::Error>; fn clear(&self, gfx: &graphics_server::Gfx, canvases: &mut FnvIndexMap<Gid, Canvas, 32>) -> Result<(), xous::Error>;
fn resize(&mut self, new_height: i16, canvases: &mut FnvIndexMap<Gid, Canvas, 32>) -> Result<Point, xous::Error>; fn resize(&mut self, gfx: &graphics_server::Gfx, new_height: i16, canvases: &mut FnvIndexMap<Gid, Canvas, 32>) -> Result<Point, xous::Error>;
} }
#[derive(Debug)] #[derive(Debug)]
@ -44,12 +44,10 @@ struct ChatLayout {
// my internal bookkeeping records. Allow input area to grow into content area // my internal bookkeeping records. Allow input area to grow into content area
min_content_height: i16, min_content_height: i16,
min_input_height: i16, min_input_height: i16,
gfx: graphics_server::Gfx,
} }
impl LayoutApi for ChatLayout { impl LayoutApi for ChatLayout {
type Layout = ChatLayout; type Layout = ChatLayout;
fn init(xns: &xous_names::XousNames, trng: &trng::Trng, canvases: &mut FnvIndexMap<Gid, Canvas, 32>) -> Result<ChatLayout, xous::Error> { fn init(xns: &xous_names::XousNames, trng: &trng::Trng, gfx: &graphics_server::Gfx, canvases: &mut FnvIndexMap<Gid, Canvas, 32>) -> Result<ChatLayout, xous::Error> {
let gfx = graphics_server::Gfx::new(&xns).unwrap();
let screensize = gfx.screen_size().expect("Couldn't get screen size"); let screensize = gfx.screen_size().expect("Couldn't get screen size");
// get the height of various text regions to compute the layout // 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; 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(), input: input_canvas.gid(),
min_content_height: 64, min_content_height: 64,
min_input_height, min_input_height,
gfx,
}) })
} }
fn clear(&self, canvases: &mut FnvIndexMap<Gid, Canvas, 32>) -> Result<(), xous::Error> { fn clear(&self, gfx: &graphics_server::Gfx, canvases: &mut FnvIndexMap<Gid, Canvas, 32>) -> Result<(), xous::Error> {
let input_canvas = canvases.get(&self.input).expect("couldn't find input canvas"); 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 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"); 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(); let mut rect = status_canvas.clip_rect();
rect.style = DrawStyle {fill_color: Some(PixelColor::Light), stroke_color: None, stroke_width: 0,}; 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(); let mut rect = content_canvas.clip_rect();
rect.style = DrawStyle {fill_color: Some(PixelColor::Light), stroke_color: None, stroke_width: 0,}; 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(); let mut rect = predictive_canvas.clip_rect();
rect.style = DrawStyle {fill_color: Some(PixelColor::Light), stroke_color: None, stroke_width: 0,}; 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(); let mut rect = input_canvas.clip_rect();
rect.style = DrawStyle {fill_color: Some(PixelColor::Light), stroke_color: None, stroke_width: 0,}; 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(()) Ok(())
} }
fn resize(&mut self, new_height: i16, canvases: &mut FnvIndexMap<Gid, Canvas, 32>) -> Result<Point, xous::Error> { fn resize(&mut self, gfx: &graphics_server::Gfx, new_height: i16, canvases: &mut FnvIndexMap<Gid, Canvas, 32>) -> Result<Point, xous::Error> {
let input_canvas = canvases.get(&self.input).expect("couldn't find input canvas"); 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 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"); 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"); let input_canvas_mut = canvases.get_mut(&self.input).expect("couldn't find input canvas");
input_canvas_mut.set_clip(new_input_rect); input_canvas_mut.set_clip(new_input_rect);
new_input_rect.style = DrawStyle {fill_color: Some(PixelColor::Light), stroke_color: None, stroke_width: 0,}; 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"); let content_canvas_mut = canvases.get_mut(&self.content).expect("couldn't find content canvas");
content_canvas_mut.set_clip(new_content_rect); content_canvas_mut.set_clip(new_content_rect);
new_content_rect.style = DrawStyle {fill_color: Some(PixelColor::Light), stroke_color: None, stroke_width: 0,}; 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 // we resized to this new height
Ok(new_content_rect.br) Ok(new_content_rect.br)
@ -153,15 +150,13 @@ impl LayoutApi for ChatLayout {
// remember GIDs of the canvases for menus // remember GIDs of the canvases for menus
struct MenuLayout { struct MenuLayout {
pub menu: Gid, pub menu: Gid,
gfx: graphics_server::Gfx,
menu_y_pad: i16, menu_y_pad: i16,
menu_x_pad: i16, menu_x_pad: i16,
menu_min_height: i16, menu_min_height: i16,
} }
impl LayoutApi for MenuLayout { impl LayoutApi for MenuLayout {
type Layout = MenuLayout; type Layout = MenuLayout;
fn init(xns: &xous_names::XousNames, trng: &trng::Trng, canvases: &mut FnvIndexMap<Gid, Canvas, 32>) -> Result<MenuLayout, xous::Error> { fn init(xns: &xous_names::XousNames, trng: &trng::Trng, gfx: &graphics_server::Gfx, canvases: &mut FnvIndexMap<Gid, Canvas, 32>) -> Result<MenuLayout, xous::Error> {
let gfx = graphics_server::Gfx::new(&xns).unwrap();
let screensize = gfx.screen_size().expect("Couldn't get screen size"); let screensize = gfx.screen_size().expect("Couldn't get screen size");
// get the height of various text regions to compute the layout // 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; 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 { Ok(MenuLayout {
menu: menu_canvas.gid(), menu: menu_canvas.gid(),
gfx,
menu_y_pad: MENU_Y_PAD, menu_y_pad: MENU_Y_PAD,
menu_x_pad: MENU_X_PAD, menu_x_pad: MENU_X_PAD,
menu_min_height: small_height, menu_min_height: small_height,
}) })
} }
fn clear(&self, canvases: &mut FnvIndexMap<Gid, Canvas, 32>) -> Result<(), xous::Error> { fn clear(&self, gfx: &graphics_server::Gfx, canvases: &mut FnvIndexMap<Gid, Canvas, 32>) -> Result<(), xous::Error> {
let menu_canvas = canvases.get(&self.menu).expect("couldn't find menu canvas"); let menu_canvas = canvases.get(&self.menu).expect("couldn't find menu canvas");
let mut rect = menu_canvas.clip_rect(); let mut rect = menu_canvas.clip_rect();
rect.style = DrawStyle {fill_color: Some(PixelColor::Dark), stroke_color: None, stroke_width: 0,}; 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<Gid, Canvas, 32>) -> Result<Point, xous::Error> { fn resize(&mut self, gfx: &graphics_server::Gfx, new_height: i16, canvases: &mut FnvIndexMap<Gid, Canvas, 32>) -> Result<Point, xous::Error> {
let mut menu_canvas = canvases.get_mut(&self.menu).expect("couldn't find menu canvas"); 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 { let mut height: i16 = if new_height < self.menu_min_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); 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_clip_rect.style = DrawStyle {fill_color: Some(PixelColor::Dark), stroke_color: None, stroke_width: 0,};
menu_canvas.set_clip(menu_clip_rect); 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) Ok(menu_clip_rect.br)
} }
} }
@ -308,7 +302,8 @@ fn xmain() -> ! {
info!("my PID is {}", xous::process::id()); info!("my PID is {}", xous::process::id());
let xns = xous_names::XousNames::new().unwrap(); 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..."); log::trace!("starting up...");
let ticktimer = ticktimer_server::Ticktimer::new().expect("Couldn't connect to Ticktimer"); 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 // a map of canvases accessable by Gid
let mut canvases: FnvIndexMap<Gid, Canvas, 32> = FnvIndexMap::new(); let mut canvases: FnvIndexMap<Gid, Canvas, 32> = FnvIndexMap::new();
let mut menulayout = MenuLayout::init(&xns, &trng, &mut canvases).expect("couldn't create menu layout"); let mut menulayout = MenuLayout::init(&xns, &trng, &gfx, &mut canvases).expect("couldn't create menu layout");
let mut chatlayout = ChatLayout::init(&xns, &trng, &mut canvases).expect("couldn't create chat layout"); let mut chatlayout = ChatLayout::init(&xns, &trng, &gfx, &mut canvases).expect("couldn't create chat layout");
chatlayout.clear(&mut canvases).expect("couldn't clear initial chatlayout"); 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 // 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 // this _replaces_ the original canvas structure, to avoid complications of tracking mutable references through compound data structures
@ -486,7 +481,7 @@ fn xmain() -> ! {
// ASSUME: // ASSUME:
// very few canvases allow dynamic resizing, so we special case these // very few canvases allow dynamic resizing, so we special case these
if cb.canvas == chatlayout.input { 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); cb.granted = Some(newheight);
canvases = recompute_canvases(canvases, Rectangle::new(Point::new(0, 0), screensize)); 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()); tokenclaim.token = tm.claim_token(tokenclaim.name.as_str().unwrap());
buffer.replace(tokenclaim).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() { if tm.allow_untrusted_code() {
xous::return_scalar(msg.sender, 1).unwrap(); xous::return_scalar(msg.sender, 1).unwrap();
} else { } else {

View file

@ -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"); log::trace!("|status: registering GAM|status thread");
let xns = xous_names::XousNames::new().unwrap(); 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 // create a connection for callback hooks
unsafe{CB_TO_MAIN_CONN = Some(xous::connect(status_sid).unwrap())}; unsafe{CB_TO_MAIN_CONN = Some(xous::connect(status_sid).unwrap())};
let pump_conn = xous::connect(status_sid).unwrap(); let pump_conn = xous::connect(status_sid).unwrap();

View file

@ -63,7 +63,9 @@ fn xmain() -> ! {
log::info!("my PID is {}", xous::process::id()); log::info!("my PID is {}", xous::process::id());
let xns = xous_names::XousNames::new().unwrap(); 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); log::trace!("Server listening on address {:?}", sid);
// Create a new monochrome simulator display. // Create a new monochrome simulator display.

View file

@ -605,7 +605,9 @@ fn xmain() -> ! {
info!("my PID is {}", xous::process::id()); info!("my PID is {}", xous::process::id());
let xns = xous_names::XousNames::new().unwrap(); 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); log::trace!("registered with NS -- {:?}", imef_sid);
// hook the keyboard event server and have it forward keys to our local main loop // hook the keyboard event server and have it forward keys to our local main loop

View file

@ -17,7 +17,8 @@ fn xmain() -> ! {
info!("my PID is {}", xous::process::id()); info!("my PID is {}", xous::process::id());
let xns = xous_names::XousNames::new().unwrap(); 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); log::trace!("registered with NS -- {:?}", ime_sh_sid);
let mut history: Queue<String<64>, U4> = Queue::new(); // this has 2^4 elements = 16??? or does it just have 4 elements. let mut history: Queue<String<64>, U4> = Queue::new(); // this has 2^4 elements = 16??? or does it just have 4 elements.

View file

@ -823,7 +823,14 @@ fn xmain() -> ! {
info!("my PID is {}", xous::process::id()); info!("my PID is {}", xous::process::id());
let xns = xous_names::XousNames::new().unwrap(); 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); log::trace!("registered with NS -- {:?}", kbd_sid);
// Create a new kbd object // Create a new kbd object

View file

@ -618,11 +618,18 @@ fn xmain() -> ! {
info!("my PID is {}", xous::process::id()); info!("my PID is {}", xous::process::id());
let xns = xous_names::XousNames::new().unwrap(); 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); log::trace!("registered with NS -- {:?}", llio_sid);
// create the I2C handler thread // 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); log::trace!("registered I2C thread with NS -- {:?}", i2c_sid);
let (sid0, sid1, sid2, sid3) = i2c_sid.to_u32(); 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"); 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");

View file

@ -12,7 +12,6 @@ use num_traits::{ToPrimitive, FromPrimitive};
pub struct Rtc { pub struct Rtc {
conn: CID, conn: CID,
callback_sid: Option<xous::SID>, callback_sid: Option<xous::SID>,
llio: llio::Llio,
} }
static mut RTC_CB: Option<fn(DateTime)> = None; static mut RTC_CB: Option<fn(DateTime)> = None;
impl Rtc { impl Rtc {
@ -22,7 +21,6 @@ impl Rtc {
Ok(Rtc { Ok(Rtc {
conn, conn,
callback_sid: None, 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(); )).unwrap();
Ok(()) 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> { pub fn request_datetime(&self) -> Result<(), xous::Error> {
send_message(self.conn, send_message(self.conn,

View file

@ -526,7 +526,11 @@ fn xmain() -> ! {
log::info!("my PID is {}", xous::process::id()); log::info!("my PID is {}", xous::process::id());
let xns = xous_names::XousNames::new().unwrap(); 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); log::trace!("registered with NS -- {:?}", rtc_sid);
CB_TO_MAIN_CONN.store(xous::connect(rtc_sid).unwrap(), Ordering::Relaxed); CB_TO_MAIN_CONN.store(xous::connect(rtc_sid).unwrap(), Ordering::Relaxed);

View file

@ -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_"; pub(crate) const SERVER_NAME_SHELLCHAT: &str = "_Shell chat application_";
#[xous::xous_main] #[xous::xous_main]
@ -262,10 +251,12 @@ fn xmain() -> ! {
info!("my PID is {}", xous::process::id()); info!("my PID is {}", xous::process::id());
let xns = xous_names::XousNames::new().unwrap(); 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); log::trace!("registered with NS -- {:?}", shch_sid);
unsafe{CB_TO_MAIN_CONN = Some(xous::connect(shch_sid).unwrap())}; 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"); 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"); 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 update_repl = false;
let mut was_callback = false; let mut was_callback = false;
if false {
xous::create_thread_0(test_thread).unwrap();
}
log::trace!("starting main loop"); log::trace!("starting main loop");
loop { loop {
let msg = xous::receive_message(shch_sid).unwrap(); let msg = xous::receive_message(shch_sid).unwrap();

View file

@ -463,7 +463,7 @@ static SHOULD_RESUME: AtomicBool = AtomicBool::new(false);
static RESUME_EXEC: AtomicBool = AtomicBool::new(false); static RESUME_EXEC: AtomicBool = AtomicBool::new(false);
pub fn execution_gate() { pub fn execution_gate() {
let xns = xous_names::XousNames::new().unwrap(); 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); log::trace!("execution_gate registered with NS -- {:?}", execgate_sid);
loop { loop {
@ -509,7 +509,8 @@ fn xmain() -> ! {
xous::create_thread_0(execution_gate).unwrap(); xous::create_thread_0(execution_gate).unwrap();
let xns = xous_names::XousNames::new().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); log::trace!("main loop registered with NS -- {:?}", susres_sid);
// make a connection for the timeout thread to wake us up // make a connection for the timeout thread to wake us up

View file

@ -668,7 +668,8 @@ fn xmain() -> ! {
info!("my PID is {}", xous::process::id()); info!("my PID is {}", xous::process::id());
let xns = xous_names::XousNames::new().unwrap(); 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); log::trace!("registered with NS -- {:?}", trng_sid);
let mut trng = Trng::new(&xns); let mut trng = Trng::new(&xns);

View file

@ -11,6 +11,10 @@ pub(crate) enum Opcode {
Lookup, Lookup,
/// Create an authenticated connection to the target server. /// Create an authenticated connection to the target server.
AuthenticatedLookup, 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)] #[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)]
@ -25,6 +29,12 @@ pub(crate) enum Return {
CID(xous::CID), 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<u32>,
}
#[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)] #[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)]
pub(crate) struct AuthenticatedLookup { pub(crate) struct AuthenticatedLookup {
pub name: xous_ipc::String::<64>, pub name: xous_ipc::String::<64>,

View file

@ -19,22 +19,37 @@ impl XousNames {
}) })
} }
pub fn unregister_server(&self, _sid: xous::SID) -> Result<(), xous::Error> { 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 // searches the name table and removes a given SID from the table.
// a given SID from the table. It's considered "secure" because you'd have to guess a random 128-bit SID // It's considered "secure" because you'd have to guess a random 128-bit SID
// to destroy someone else's 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 // 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 // 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<xous::SID, xous::Error> { pub fn register_name(&self, name: &str, max_conns: Option<u32>) -> Result<xous::SID, xous::Error> {
let mut registration_name = String::<64>::new(); 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. // 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( buf.lend_mut(
self.conn, 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<xous::CID, xous::Error> { pub fn request_connection(&self, name: &str) -> Result<xous::CID, xous::Error> {
let mut lookup_name = xous_ipc::String::<64>::new(); let mut lookup_name = xous_ipc::String::<64>::new();
write!(lookup_name, "{}", name).expect("name problably too long"); write!(lookup_name, "{}", name).expect("name problably too long");
@ -87,6 +101,26 @@ impl XousNames {
xous::yield_slice(); xous::yield_slice();
} }
} }
pub fn trusted_init_done(&self) -> Result<bool, xous::Error> {
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}; use core::sync::atomic::{AtomicU32, Ordering};

View file

@ -7,6 +7,7 @@ mod api;
use api::*; use api::*;
use num_traits::FromPrimitive; use num_traits::FromPrimitive;
use xous::msg_blocking_scalar_unpack;
use xous_ipc::{String, Buffer}; use xous_ipc::{String, Buffer};
use log::{error, info}; 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 Eventually, we shall endeavor to remove Heapless entirely, once we have a `libstd` in place
and we can use heap-allocated Rust primitives... 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<u32>, // if None, unlimited connections allowed
pub allow_authenticate: bool,
pub auth_conns: u32, // number of authenticated connections
}
struct SlowMap { struct SlowMap {
pub map: [Option<(XousServerName, xous::SID)>; 128], pub map: [Option<Connection>; 128],
} }
impl SlowMap { impl SlowMap {
pub fn new() -> Self { pub fn new() -> Self {
@ -81,11 +91,18 @@ impl SlowMap {
map: [None; 128], 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<u32>) -> Result<(), xous::Error> {
let mut ok = false; let mut ok = false;
for entry in self.map.iter_mut() { for entry in self.map.iter_mut() {
if entry.is_none() { 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; ok = true;
break; break;
} }
@ -96,23 +113,77 @@ impl SlowMap {
Ok(()) Ok(())
} }
} }
pub fn remove(&mut self, sid: xous::SID) -> Option<XousServerName> {
let mut name: Option<XousServerName> = 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 { pub fn contains_key(&self, name: &XousServerName) -> bool {
for maybe_entry in self.map.iter() { for maybe_entry in self.map.iter() {
if let Some(entry) = maybe_entry { if let Some(entry) = maybe_entry {
let (key, _value) = entry; if entry.name == *name {
if name == key {
return true return true
} }
} }
} }
return false 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() { for maybe_entry in self.map.iter() {
if let Some(entry) = maybe_entry { if let Some(entry) = maybe_entry {
let (key, value) = entry; if let Some(max) = entry.max_conns {
if name == key { if max != entry.current_conns {
return Some(value) 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<XousServerName> {
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] #[xous::xous_main]
fn xmain() -> ! { fn xmain() -> ! {
use implementation::*; use implementation::*;
let debug1 = false;
log_server::init_wait().unwrap(); log_server::init_wait().unwrap();
log::set_max_level(log::LevelFilter::Info); log::set_max_level(log::LevelFilter::Info);
info!("my PID is {}", xous::process::id()); info!("my PID is {}", xous::process::id());
@ -140,24 +210,24 @@ fn xmain() -> ! {
info!("started"); info!("started");
loop { loop {
let mut msg = xous::receive_message(name_server).unwrap(); 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()) { match FromPrimitive::from_usize(msg.body.id()) {
Some(api::Opcode::Register) => { Some(api::Opcode::Register) => {
let mem = msg.body.memory_message_mut().unwrap(); let mem = msg.body.memory_message_mut().unwrap();
let mut buffer = unsafe { Buffer::from_memory_message_mut(mem) }; let mut buffer = unsafe { Buffer::from_memory_message_mut(mem) };
let xous_string = buffer.to_original::<String::<64>, _>().unwrap(); let registration = buffer.to_original::<Registration, _>().unwrap();
let name = XousServerName::from_str(xous_string.as_str().expect("couldn't convert server name to string")); let name = XousServerName::from_str(registration.name.as_str().expect("couldn't convert server name to string"));
let response: api::Return; let response: api::Return;
if debug1{info!("registration request for '{}'", name);} log::trace!("registration request for '{}'", name);
if !name_table.contains_key(&name) { if !name_table.contains_key(&name) {
let new_sid = let new_sid =
xous::create_server_id().expect("create server failed, maybe OOM?"); xous::create_server_id().expect("create server failed, maybe OOM?");
name_table name_table
.insert(name, new_sid) .insert(name, new_sid, registration.conn_limit)
.expect("register name failure, maybe out of HashMap capacity?"); .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()); response = api::Return::SID(new_sid.into());
} else { } else {
@ -168,14 +238,23 @@ fn xmain() -> ! {
} }
buffer.replace(response).expect("Register can't serialize return value"); 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) => { Some(api::Opcode::Lookup) => {
let mem = msg.body.memory_message_mut().unwrap(); let mem = msg.body.memory_message_mut().unwrap();
let mut buffer = unsafe { Buffer::from_memory_message_mut(mem) }; let mut buffer = unsafe { Buffer::from_memory_message_mut(mem) };
let name_string = buffer.to_original::<String::<64>, _>().unwrap(); let name_string = buffer.to_original::<String::<64>, _>().unwrap();
let name = XousServerName::from_str(name_string.as_str().expect("couldn't convert server name to string")); 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; 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 let sender_pid = msg
.sender .sender
.pid() .pid()
@ -184,7 +263,7 @@ fn xmain() -> ! {
.expect("can't broker connection") .expect("can't broker connection")
{ {
xous::Result::ConnectionID(connection_id) => { 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) response = api::Return::CID(connection_id)
} }
_ => { _ => {
@ -192,9 +271,9 @@ fn xmain() -> ! {
"Can't find request '{}' in table, dumping table:", "Can't find request '{}' in table, dumping table:",
name name
); );
for kv_tuple in name_table.map.iter() { for maybe_conn in name_table.map.iter() {
if let Some((key, val)) = kv_tuple { if let Some(connection) = maybe_conn {
log::debug!("name: '{}', sid: '{:?}'", key, val); log::debug!("{:?}", connection);
} }
} }
d11ctimeout.hosted_delay(); d11ctimeout.hosted_delay();
@ -206,9 +285,9 @@ fn xmain() -> ! {
"Can't find request '{}' in table, dumping table:", "Can't find request '{}' in table, dumping table:",
name name
); );
for kv_tuple in name_table.map.iter() { for maybe_conn in name_table.map.iter() {
if let Some((key, val)) = kv_tuple { if let Some(connection) = maybe_conn {
log::debug!("name: '{}', sid: '{:?}'", key, val); log::debug!("{:?}", connection);
} }
} }
// no authenticate remedy currently supported, but we'd put that code somewhere around here eventually. // 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"); error!("AuthenticatedLookup not yet implemented");
unimplemented!("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} None => {error!("couldn't decode message: {:?}", msg); break}
} }
} }