mirror of
https://github.com/saymrwulf/xous-core.git
synced 2026-11-16 08:38:26 +00:00
attempt to refactor xous_names
This commit is contained in:
parent
88d66f4fd2
commit
f35d478cf0
14 changed files with 196 additions and 229 deletions
|
|
@ -57,30 +57,27 @@ fn stopwatch_thread(_arg: xous::SID) {
|
|||
let ticktimer = ticktimer_server::Ticktimer::new().expect("Couldn't connect to Ticktimer");
|
||||
|
||||
let shell_conn = xous_names::request_connection_blocking(xous::names::SERVER_NAME_SHELL).expect("BENCHMARK|stopwatch: can't connect to main program");
|
||||
let mut last_time: u64 = ticktimer.elapsed_ms().unwrap();
|
||||
let mut last_time: u64 = ticktimer.elapsed_ms();
|
||||
let mut start_sent = false;
|
||||
loop {
|
||||
if let Ok(elapsed_time) = ticktimer.elapsed_ms() {
|
||||
if elapsed_time - last_time > 500 && !start_sent {
|
||||
last_time = elapsed_time;
|
||||
xous::send_message(shell_conn, Opcode::Start.into()).expect("BENCHMARK|stopwatch: couldn't send Start message");
|
||||
start_sent = true;
|
||||
} else if elapsed_time - last_time > 10_000 && start_sent {
|
||||
last_time = elapsed_time;
|
||||
start_sent = false;
|
||||
xous::send_message(shell_conn, Opcode::Stop.into()).expect("BENCHMARK|stopwatch: couldn't send Stop message");
|
||||
}
|
||||
} else {
|
||||
error!("error requesting ticktimer!")
|
||||
elapsed_time = ticktimer.elapsed_ms();
|
||||
if elapsed_time - last_time > 500 && !start_sent {
|
||||
last_time = elapsed_time;
|
||||
xous::send_message(shell_conn, Opcode::Start.into()).expect("BENCHMARK|stopwatch: couldn't send Start message");
|
||||
start_sent = true;
|
||||
} else if elapsed_time - last_time > 10_000 && start_sent {
|
||||
last_time = elapsed_time;
|
||||
start_sent = false;
|
||||
xous::send_message(shell_conn, Opcode::Stop.into()).expect("BENCHMARK|stopwatch: couldn't send Stop message");
|
||||
}
|
||||
if false {
|
||||
// send a start loop message
|
||||
xous::send_message(shell_conn, Opcode::Start.into()).expect("BENCHMARK|stopwatch: couldn't send Start message");
|
||||
ticktimer.sleep_ms(ticktimer_conn, 10_000).expect("couldn't sleep");
|
||||
ticktimer.sleep_ms(10_000).expect("couldn't sleep");
|
||||
// send a stop loop message
|
||||
xous::send_message(shell_conn, Opcode::Stop.into()).expect("BENCHMARK|stopwatch: couldn't send Stop message");
|
||||
// give a moment for the result to update
|
||||
ticktimer.sleep_ms(ticktimer_conn, 500).expect("couldn't sleep");
|
||||
ticktimer.sleep_ms(500).expect("couldn't sleep");
|
||||
}
|
||||
xous::yield_slice();
|
||||
}
|
||||
|
|
@ -135,10 +132,10 @@ fn shell_main() -> ! {
|
|||
if let Ok(opcode) = Opcode::try_from(&envelope.body) {
|
||||
match opcode {
|
||||
Opcode::Start => {
|
||||
start_time = ticktimer.elapsed_ms().unwrap();
|
||||
start_time = ticktimer.elapsed_ms();
|
||||
},
|
||||
Opcode::Stop => {
|
||||
stop_time = ticktimer.elapsed_ms().unwrap();
|
||||
stop_time = ticktimer.elapsed_ms();
|
||||
update_result = true;
|
||||
},
|
||||
}
|
||||
|
|
|
|||
|
|
@ -107,15 +107,11 @@ mod implementation {
|
|||
|
||||
pub fn wait_txrx(&mut self, tx: u16, timeout: Option<u32>) -> u16 {
|
||||
if timeout.is_some() {
|
||||
let curtime = self.ticktimer.elapsed_ms()
|
||||
.expect("couldn't connect to ticktimer");
|
||||
let curtime = self.ticktimer.elapsed_ms();
|
||||
let mut timed_out = false;
|
||||
let to = timeout.unwrap() as u64;
|
||||
while self.csr.rf(utra::com::STATUS_HOLD) == 1 && !timed_out {
|
||||
if (self.ticktimer.elapsed_ms()
|
||||
.expect("couldn't connect to ticktimer")
|
||||
- curtime)
|
||||
> to
|
||||
if (self.ticktimer.elapsed_ms() - curtime) > to
|
||||
{
|
||||
timed_out = true;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -378,7 +378,7 @@ fn do_agent(cmd: &mut String<U2048>, com_cid: xous::CID, pds_list: &mut Vec<Stri
|
|||
} else if tokens[1].trim() == "commit_pds" {
|
||||
let ticktimer = ticktimer_server::Ticktimer::new().expect("Couldn't connect to Ticktimer");
|
||||
|
||||
let mut last_time: u64 = ticktimer.elapsed_ms().unwrap();
|
||||
let mut last_time: u64 = ticktimer.elapsed_ms();
|
||||
for pds in pds_list.iter() {
|
||||
let mut sendable_string = xous::String::<512>::new();
|
||||
write!(&mut sendable_string, "{}", pds);
|
||||
|
|
@ -499,7 +499,7 @@ fn xmain() -> ! {
|
|||
uart.enable_rx();
|
||||
|
||||
print!("\n\r\n\r*** FCC agent ***\n\r\n\r");
|
||||
let mut last_time: u64 = ticktimer.elapsed_ms().unwrap();
|
||||
let mut last_time: u64 = ticktimer.elapsed_ms();
|
||||
let mut pds_list: Vec<String<U512>, U16> = Vec::new();
|
||||
let mut repeat = false;
|
||||
let mut phase = 0;
|
||||
|
|
|
|||
|
|
@ -227,7 +227,7 @@ fn xmain() -> ! {
|
|||
xous::create_thread_4(status_thread, gid[0] as _, gid[1] as _, gid[2] as _, gid[3] as _).expect("GAM: couldn't create status thread");
|
||||
|
||||
let mut powerdown_requested = false;
|
||||
let mut last_time: u64 = ticktimer.elapsed_ms().unwrap();
|
||||
let mut last_time: u64 = ticktimer.elapsed_ms();
|
||||
info!("GAM: entering main loop");
|
||||
loop {
|
||||
let envelope = xous::receive_message(gam_sid).unwrap();
|
||||
|
|
|
|||
|
|
@ -46,7 +46,7 @@ pub fn status_thread(canvas_gid_0: usize, canvas_gid_1: usize, canvas_gid_2: usi
|
|||
battstats_tv.margin = Point::new(0, 0);
|
||||
|
||||
let mut stats: BattStats;
|
||||
let mut last_time: u64 = ticktimer.elapsed_ms().unwrap();
|
||||
let mut last_time: u64 = ticktimer.elapsed_ms();
|
||||
let mut stats_phase: usize = 0;
|
||||
let mut last_seconds: usize = ((last_time / 1000) % 60) as usize;
|
||||
|
||||
|
|
|
|||
|
|
@ -24,9 +24,9 @@ fn sleep_loop_4(main_conn: usize, sleep_ms: usize, ticktimer_conn: usize, pid: u
|
|||
// sleep_ms,
|
||||
// loop_count
|
||||
// );
|
||||
let start_time = ticktimer.elapsed_ms().unwrap();
|
||||
let start_time = ticktimer.elapsed_ms();
|
||||
ticktimer.sleep_ms(ticktimer_conn, sleep_ms).unwrap();
|
||||
let end_time = ticktimer.elapsed_ms().unwrap();
|
||||
let end_time = ticktimer.elapsed_ms();
|
||||
log::info!(
|
||||
"TEST THREAD {}:{}: target {}ms, {} loops: Sleep finished (uptime: {}, took {} ms)",
|
||||
pid,
|
||||
|
|
|
|||
|
|
@ -229,7 +229,7 @@ mod implementation {
|
|||
|
||||
let mut ticktimer = XousTickTimer::new(ticktimer_client).expect("KBD: couldn't connect to ticktimer");
|
||||
|
||||
let timestamp = ticktimer.elapsed_ms().unwrap();
|
||||
let timestamp = ticktimer.elapsed_ms();
|
||||
let kbd = Keyboard {
|
||||
csr: CSR::new(csr.as_mut_ptr() as *mut u32),
|
||||
debounce: [[0; KBD_COLS]; KBD_ROWS],
|
||||
|
|
@ -341,7 +341,7 @@ mod implementation {
|
|||
// clear the pending bit
|
||||
self.csr.wfo(utra::keyboard::EV_PENDING_KEYPRESSED, 1);
|
||||
|
||||
let elapsed = self.ticktimer.elapsed_ms().unwrap() - self.timestamp;
|
||||
let elapsed = self.ticktimer.elapsed_ms() - self.timestamp;
|
||||
if elapsed <= 1 {
|
||||
// skip debounce processing if time elapsed is too short
|
||||
(None, None)
|
||||
|
|
@ -435,7 +435,7 @@ mod implementation {
|
|||
let mut keystates: Vec<char, U4> = Vec::new();
|
||||
|
||||
if self.chord_active || keydowns.is_some() {
|
||||
let now = self.ticktimer.elapsed_ms().unwrap();
|
||||
let now = self.ticktimer.elapsed_ms();
|
||||
|
||||
if !self.chord_active && keydowns.is_some() {
|
||||
self.chord_active = true;
|
||||
|
|
@ -622,7 +622,7 @@ mod implementation {
|
|||
|
||||
// interpret keys in the context of the shift/alt modifiers
|
||||
if let Some(kds) = &keydowns {
|
||||
self.chord_timestamp = self.ticktimer.elapsed_ms().unwrap();
|
||||
self.chord_timestamp = self.ticktimer.elapsed_ms();
|
||||
// if more than one is held, the key that gets picked for the repeat function is arbitrary!
|
||||
for &rc in kds.iter() {
|
||||
let code = match self.map {
|
||||
|
|
@ -637,7 +637,7 @@ mod implementation {
|
|||
}
|
||||
}
|
||||
}
|
||||
let now = self.ticktimer.elapsed_ms().unwrap();
|
||||
let now = self.ticktimer.elapsed_ms();
|
||||
let hold: bool;
|
||||
if (now - self.chord_timestamp) >= self.delay as u64 {
|
||||
if self.rate_timestamp <= self.chord_timestamp {
|
||||
|
|
|
|||
|
|
@ -47,7 +47,7 @@ impl I2cStateMachine {
|
|||
I2cStateMachine {
|
||||
transaction: I2cTransaction::new(),
|
||||
state: I2cState::Idle,
|
||||
timestamp: ticktimer.elapsed_ms().unwrap(),
|
||||
timestamp: ticktimer.elapsed_ms(),
|
||||
ticktimer,
|
||||
i2c_csr: CSR::new(i2c_base),
|
||||
index: 0,
|
||||
|
|
@ -60,7 +60,7 @@ impl I2cStateMachine {
|
|||
return I2cStatus::ResponseFormatError
|
||||
}
|
||||
|
||||
let now = self.ticktimer.elapsed_ms().unwrap();
|
||||
let now = self.ticktimer.elapsed_ms();
|
||||
if self.state != I2cState::Idle && ((now - self.timestamp) < self.transaction.timeout_ms as u64) {
|
||||
// we're in a transaction that hadn't timed out, can't accept a new one
|
||||
I2cStatus::ResponseBusy
|
||||
|
|
@ -145,7 +145,7 @@ impl I2cStateMachine {
|
|||
}
|
||||
pub fn handler(&mut self) {
|
||||
// check if the transaction had actually timed out
|
||||
let now = self.ticktimer.elapsed_ms().unwrap();
|
||||
let now = self.ticktimer.elapsed_ms();
|
||||
if now - self.timestamp > self.transaction.timeout_ms as u64 {
|
||||
// previous transaction had timed out...
|
||||
self.report_timeout();
|
||||
|
|
|
|||
|
|
@ -15,7 +15,8 @@ static SERVER_CID: AtomicU32 = AtomicU32::new(0);
|
|||
fn ensure_connection() -> xous::CID {
|
||||
let mut cid = SERVER_CID.load(Ordering::Relaxed);
|
||||
if cid == 0 {
|
||||
cid = xous_names::request_connection_blocking(api::SERVER_NAME).unwrap();
|
||||
let ns = xous_names::XousNames::new().unwrap();
|
||||
cid = ns.request_connection_blocking(api::SERVER_NAME).unwrap();
|
||||
SERVER_CID.store(cid, Ordering::Relaxed);
|
||||
}
|
||||
cid
|
||||
|
|
|
|||
|
|
@ -174,8 +174,8 @@ fn shell_main() -> ! {
|
|||
// make a thread to catch responses from the COM
|
||||
xous::create_thread_simple(event_thread, 0).unwrap();
|
||||
info!("SHELL: COM responder thread started");
|
||||
let start_time: u64 = ticktimer.elapsed_ms().unwrap();
|
||||
while ticktimer.elapsed_ms().unwrap() - start_time < 1000 {
|
||||
let start_time: u64 = ticktimer.elapsed_ms();
|
||||
while ticktimer.elapsed_ms() - start_time < 1000 {
|
||||
xous::yield_slice();
|
||||
}
|
||||
|
||||
|
|
@ -217,7 +217,7 @@ fn shell_main() -> ! {
|
|||
graphics_server::draw_rectangle(graphics_conn, work_clipregion)
|
||||
.expect("unable to clear region");
|
||||
|
||||
let mut last_time: u64 = ticktimer.elapsed_ms().unwrap();
|
||||
let mut last_time: u64 = ticktimer.elapsed_ms();
|
||||
let mut first_time = true;
|
||||
loop {
|
||||
//////////////// status bar
|
||||
|
|
|
|||
|
|
@ -16,17 +16,18 @@ impl Ticktimer {
|
|||
})
|
||||
}
|
||||
|
||||
pub fn elapsed_ms(&self) -> Result<u64, Error> {
|
||||
/// note special case for elapsed_ms() is "infalliable". it really should never fail so get rid of the Error
|
||||
pub fn elapsed_ms(&self) -> u64 {
|
||||
let response = send_message(self.conn,
|
||||
xous::Message::BlockingScalar(xous::ScalarMessage {
|
||||
id: api::Opcode::ElapsedMs.to_usize().unwrap(),
|
||||
arg1: 0, arg2: 0, arg3: 0, arg4: 0
|
||||
})
|
||||
)?;
|
||||
).expect("Ticktimer: failure to send message to Ticktimer");
|
||||
if let xous::Result::Scalar2(upper, lower) = response {
|
||||
Ok(upper as u64 | ((lower as u64) << 32))
|
||||
upper as u64 | ((lower as u64) << 32)
|
||||
} else {
|
||||
panic!("unexpected return value: {:#?}", response);
|
||||
panic!("Ticktimer elapsed_ms(): unexpected return value: {:#?}", response);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -3,68 +3,39 @@ use hash32::{Hash, Hasher};
|
|||
pub const AUTHENTICATE_TIMEOUT: u32 = 10_000; // time in ms that a process has to respond to an authentication request
|
||||
|
||||
#[derive(num_derive::FromPrimitive, num_derive::ToPrimitive)]
|
||||
pub(crate) enum Request {
|
||||
pub(crate) enum Opcode {
|
||||
/// Create a new server with the given name and return its SID.
|
||||
Register,
|
||||
|
||||
/// Create a connection to the target server.
|
||||
Lookup,
|
||||
|
||||
/// Create an authenticated connection to the target server.
|
||||
AuthenticatedLookup,
|
||||
|
||||
// Return values
|
||||
|
||||
/// The caller must perform an AuthenticatedLookup using this challenge
|
||||
AuthenticateRequest,
|
||||
|
||||
/// The connection failed for some reason
|
||||
Failure,
|
||||
|
||||
/// A server was successfully created with the given SID
|
||||
SID,
|
||||
|
||||
/// A connection was successfully made with the given CID
|
||||
CID,
|
||||
}
|
||||
/*
|
||||
pub(crate) enum Request {
|
||||
/// Create a new server with the given name and return its SID.
|
||||
Register(xous_ipc::String::<64>),
|
||||
|
||||
/// Create a connection to the target server.
|
||||
Lookup(xous_ipc::String::<64>),
|
||||
|
||||
/// Create an authenticated connection to the target server.
|
||||
AuthenticatedLookup(AuthenticatedLookup),
|
||||
|
||||
// Return values
|
||||
|
||||
#[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)]
|
||||
pub(crate) enum Return {
|
||||
/// The caller must perform an AuthenticatedLookup using this challenge
|
||||
AuthenticateRequest(AuthenticatedRequest),
|
||||
|
||||
AuthenticateRequest(AuthenticateRequest),
|
||||
/// The connection failed for some reason
|
||||
Failure,
|
||||
|
||||
/// A server was successfully created with the given SID
|
||||
SID([u32; 4]),
|
||||
|
||||
/// A connection was successfully made with the given CID
|
||||
CID(CID),
|
||||
}*/
|
||||
CID(xous::CID),
|
||||
}
|
||||
|
||||
#[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)]
|
||||
pub(crate) struct AuthenticatedLookup {
|
||||
pub name: xous_ipc::String::<64>,
|
||||
pub pubkey_id: [u8; 20], // 160-bit pubkey ID encoded in network order (big endian)
|
||||
pub challenge: [u32; 8],
|
||||
pub response: [u32; 8],
|
||||
}
|
||||
|
||||
#[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)]
|
||||
pub(crate) struct AuthenticatedRequest {
|
||||
pub request: AuthenicatedLookup, // a copy of the original request. We don't trust it, but it's helpful to have for reference
|
||||
pub nonce: [u32; 4],
|
||||
pub response: [u32; 8],
|
||||
pub(crate) struct AuthenticateRequest {
|
||||
pub name: xous_ipc::String::<64>, // a copy of the originally requested lookup
|
||||
pub pubkey_id: [u8; 20], // 160-bit pubkey ID encoded in network order (big endian)
|
||||
pub challenge: [u32; 4],
|
||||
}
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -3,90 +3,75 @@
|
|||
pub mod api;
|
||||
|
||||
use core::fmt::Write;
|
||||
use xous_ipc::{String, Buffer};
|
||||
use num_traits::{FromPrimitive, ToPrimitive};
|
||||
|
||||
pub struct XousNames {
|
||||
conn: xous::CID,
|
||||
}
|
||||
impl XousNames {
|
||||
pub fn new() -> Result<Self, Error> {
|
||||
pub fn new() -> Result<Self, xous::Error> {
|
||||
let conn = xous::connect(xous::SID::from_bytes(b"xous-name-server").unwrap()).expect("Couldn't connect to XousNames");
|
||||
Ok(XousNames {
|
||||
conn,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn register_name(&self, name: &str) -> Result<xous::SID, xous::Error> {
|
||||
let mut registration_name = String::<64>::new();
|
||||
// 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("NS: name probably too long");
|
||||
|
||||
}
|
||||
}
|
||||
let mut buf = Buffer::try_from(registration_name).or(Err(xous::Error::InternalError))?;
|
||||
|
||||
pub fn register_name(name: &str) -> Result<xous::SID, xous::Error> {
|
||||
// Ensure we have a connection to the nameserver. If one exists, this is a no-op.
|
||||
let ns_id = xous::SID::from_bytes(b"xous-name-server").unwrap();
|
||||
let ns_conn = xous::connect(ns_id).unwrap();
|
||||
buf.lend_mut(
|
||||
self.conn,
|
||||
api::Opcode::Register.to_u32().unwrap()
|
||||
)
|
||||
.or(Err(xous::Error::InternalError))?;
|
||||
|
||||
let mut registration_name = xous_ipc::String::<64>::new();
|
||||
write!(registration_name, "{}", name).expect("namserver: name probably too long");
|
||||
let request = api::Request::Register(registration_name);
|
||||
let mut writer = rkyv::ser::serializers::BufferSerializer::new(xous::XousBuffer::new(4096));
|
||||
let pos = {
|
||||
use rkyv::ser::Serializer;
|
||||
writer.serialize_value(&request).expect("nameserver: couldn't archive name")
|
||||
};
|
||||
let mut xous_buffer = writer.into_inner();
|
||||
|
||||
xous_buffer
|
||||
.lend_mut(ns_conn, pos as u32)
|
||||
.expect("nameserver registration failure");
|
||||
|
||||
let archived = unsafe { rkyv::archived_value::<api::Request>(xous_buffer.as_ref(), pos) };
|
||||
|
||||
if let rkyv::Archived::<api::Request>::SID(sid) = archived {
|
||||
let sid = sid.into();
|
||||
xous::create_server_with_sid(sid).expect("can't auto-register server");
|
||||
Ok(sid)
|
||||
} else if let rkyv::Archived::<api::Request>::Failure = archived {
|
||||
return Err(xous::Error::InternalError);
|
||||
} else {
|
||||
panic!("Invalid response from the server -- corruption occurred");
|
||||
}
|
||||
}
|
||||
|
||||
/// note: if this throws an AccessDenied error, you can retry with a request_authenticat_connection() call (to be written)
|
||||
pub fn request_connection(name: &str) -> Result<xous::CID, xous::Error> {
|
||||
let ns_id = xous::SID::from_bytes(b"xous-name-server").unwrap();
|
||||
let ns_conn = xous::connect(ns_id).unwrap();
|
||||
|
||||
let mut lookup_name = xous_ipc::String::<64>::new();
|
||||
write!(lookup_name, "{}", name).expect("nameserver: name problably too long");
|
||||
let request = api::Request::Lookup(lookup_name);
|
||||
|
||||
let mut writer = rkyv::ser::serializers::BufferSerializer::new(xous::XousBuffer::new(4096));
|
||||
let pos = {
|
||||
use rkyv::ser::Serializer;
|
||||
writer.serialize_value(&request).expect("nameserver: couldn't archive name")
|
||||
};
|
||||
let mut xous_buffer = writer.into_inner();
|
||||
|
||||
xous_buffer
|
||||
.lend_mut(ns_conn, pos as u32)
|
||||
.expect("nameserver lookup failure!");
|
||||
|
||||
let archived = unsafe { rkyv::archived_value::<api::Request>(xous_buffer.as_ref(), pos) };
|
||||
match archived {
|
||||
rkyv::Archived::<api::Request>::CID(cid) => Ok(*cid),
|
||||
rkyv::Archived::<api::Request>::AuthenticateRequest(_) => Err(xous::Error::AccessDenied),
|
||||
_ => Err(xous::Error::ServerNotFound),
|
||||
}
|
||||
}
|
||||
|
||||
/// note: you probably want to use this one, to avoid synchronization issues on startup as servers register asynhcronously
|
||||
pub fn request_connection_blocking(name: &str) -> Result<xous::CID, xous::Error> {
|
||||
loop {
|
||||
match request_connection(name) {
|
||||
Ok(val) => return Ok(val),
|
||||
Err(xous::Error::AccessDenied) => return Err(xous::Error::AccessDenied),
|
||||
_ => (),
|
||||
match buf.deserialize().unwrap() {
|
||||
api::Return::SID(sid_raw) => {
|
||||
let sid = sid_raw.into();
|
||||
xous::create_server_with_sid(sid).expect("NS: can't auto-register server");
|
||||
Ok(sid)
|
||||
}
|
||||
api::Return::Failure => {
|
||||
Err(xous::Error::InternalError)
|
||||
}
|
||||
_ => unimplemented!("NS: unimplemented return codes")
|
||||
}
|
||||
}
|
||||
|
||||
/// 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> {
|
||||
let mut lookup_name = xous_ipc::String::<64>::new();
|
||||
write!(lookup_name, "{}", name).expect("NS: name problably too long");
|
||||
|
||||
let mut buf = Buffer::try_from(lookup_name).or(Err(xous::Error::InternalError))?;
|
||||
|
||||
buf.lend_mut(
|
||||
self.conn,
|
||||
api::Opcode::Lookup.to_u32().unwrap()
|
||||
)
|
||||
.or(Err(xous::Error::InternalError))?;
|
||||
|
||||
match buf.deserialize().unwrap() {
|
||||
api::Return::CID(cid) => Ok(cid),
|
||||
api::Return::AuthenticateRequest(_) => Err(xous::Error::AccessDenied),
|
||||
_ => Err(xous::Error::ServerNotFound),
|
||||
}
|
||||
}
|
||||
|
||||
/// note: you probably want to use this one, to avoid synchronization issues on startup as servers register asynhcronously
|
||||
pub fn request_connection_blocking(&self, name: &str) -> Result<xous::CID, xous::Error> {
|
||||
loop {
|
||||
match self.request_connection(name) {
|
||||
Ok(val) => return Ok(val),
|
||||
Err(xous::Error::AccessDenied) => return Err(xous::Error::AccessDenied),
|
||||
_ => (),
|
||||
}
|
||||
xous::yield_slice();
|
||||
}
|
||||
xous::yield_slice();
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -5,17 +5,20 @@ extern crate hash32_derive;
|
|||
|
||||
mod api;
|
||||
use api::*;
|
||||
use xous::buffer;
|
||||
|
||||
// use heapless::String;
|
||||
use heapless::consts::*;
|
||||
use heapless::FnvIndexMap;
|
||||
|
||||
use core::convert::TryInto;
|
||||
use num_traits::{FromPrimitive, ToPrimitive};
|
||||
use xous_ipc::{String, Buffer};
|
||||
|
||||
use log::{error, info};
|
||||
|
||||
const FAIL_TIMEOUT_MS: u64 = 100;
|
||||
|
||||
|
||||
#[xous::xous_main]
|
||||
fn xmain() -> ! {
|
||||
let debug1 = false;
|
||||
|
|
@ -31,87 +34,100 @@ fn xmain() -> ! {
|
|||
let mut name_table = FnvIndexMap::<_, _, U128>::new();
|
||||
|
||||
info!("NS: started");
|
||||
use core::pin::Pin;
|
||||
use rkyv::archived_value_mut;
|
||||
|
||||
loop {
|
||||
let envelope = xous::receive_message(name_server).unwrap();
|
||||
let mut msg = xous::receive_message(name_server).unwrap();
|
||||
if debug1{info!("NS: received message");}
|
||||
if let xous::Message::MutableBorrow(m) = &envelope.body {
|
||||
let mut buf = unsafe { buffer::XousBuffer::from_memory_message(m) };
|
||||
let value = unsafe {
|
||||
archived_value_mut::<api::Request>(Pin::new(buf.as_mut()), m.id.try_into().unwrap())
|
||||
};
|
||||
let new_value = match &*value {
|
||||
rkyv::Archived::<api::Request>::Register(registration_name) => {
|
||||
let name = XousServerName::from_str(registration_name.as_str());
|
||||
if debug1{info!("NS: registration request for '{}'", name);}
|
||||
if !name_table.contains_key(&name) {
|
||||
let new_sid =
|
||||
xous::create_server_id().expect("NS: create server failed, maybe OOM?");
|
||||
name_table
|
||||
.insert(name, new_sid)
|
||||
.expect("NS: register name failure, maybe out of HashMap capacity?");
|
||||
if debug1{info!("NS: request successful, SID is {:?}", new_sid);}
|
||||
rkyv::Archived::<api::Request>::SID(new_sid.into())
|
||||
} else {
|
||||
// compute the next interval, rounded to a multiple of FAIL_TIMEOUT_MS to reduce timing side channels
|
||||
let target_time: u64 = ((ticktimer.elapsed_ms()
|
||||
.unwrap()
|
||||
/ FAIL_TIMEOUT_MS)
|
||||
+ 1)
|
||||
* FAIL_TIMEOUT_MS;
|
||||
info!("NS: request failed, waiting for deterministic timeout");
|
||||
while ticktimer.elapsed_ms().unwrap() < target_time {
|
||||
xous::yield_slice();
|
||||
}
|
||||
info!("NS: deterministic timeout done");
|
||||
rkyv::Archived::<api::Request>::Failure
|
||||
match FromPrimitive::from_usize(msg.body.id()) {
|
||||
Some(api::Opcode::Register) => {
|
||||
let mut mem = msg.body.memory_message_mut().unwrap();
|
||||
let mut buffer = unsafe { Buffer::from_memory_message_mut(mem) };
|
||||
let xous_string = buffer.try_into::<xous_ipc::String::<64>, _>().unwrap();
|
||||
let name = XousServerName::from_str(xous_string.as_str().unwrap());
|
||||
|
||||
let mut response: api::Return;
|
||||
|
||||
if debug1{info!("NS: registration request for '{}'", name);}
|
||||
if !name_table.contains_key(&name) {
|
||||
let new_sid =
|
||||
xous::create_server_id().expect("NS: create server failed, maybe OOM?");
|
||||
name_table
|
||||
.insert(name, new_sid)
|
||||
.expect("NS: register name failure, maybe out of HashMap capacity?");
|
||||
if debug1{info!("NS: request successful, SID is {:?}", new_sid);}
|
||||
|
||||
response = api::Return::SID(new_sid.into());
|
||||
} else {
|
||||
// compute the next interval, rounded to a multiple of FAIL_TIMEOUT_MS to reduce timing side channels
|
||||
let target_time: u64 = ((ticktimer.elapsed_ms()
|
||||
/ FAIL_TIMEOUT_MS)
|
||||
+ 1)
|
||||
* FAIL_TIMEOUT_MS;
|
||||
info!("NS: request failed, waiting for deterministic timeout");
|
||||
while ticktimer.elapsed_ms() < target_time {
|
||||
xous::yield_slice();
|
||||
}
|
||||
info!("NS: deterministic timeout done");
|
||||
response = api::Return::Failure
|
||||
}
|
||||
rkyv::Archived::<api::Request>::Lookup(lookup_name) => {
|
||||
let name = XousServerName::from_str(lookup_name.as_str());
|
||||
if debug1{info!("NS: Lookup request for '{}'", name);}
|
||||
if let Some(server_sid) = name_table.get(&name) {
|
||||
let sender_pid = envelope
|
||||
.sender
|
||||
.pid()
|
||||
.expect("NS: can't extract sender PID on Lookup");
|
||||
match xous::connect_for_process(sender_pid, *server_sid)
|
||||
.expect("NS: can't broker connection")
|
||||
{
|
||||
xous::Result::ConnectionID(connection_id) => {
|
||||
if debug1{info!("NS: lookup success, returning connection {}", connection_id);}
|
||||
rkyv::Archived::<api::Request>::CID(connection_id)
|
||||
}
|
||||
_ => {
|
||||
info!(
|
||||
"NS: Can't find request '{}' in table, dumping table:",
|
||||
name
|
||||
);
|
||||
for (key, val) in name_table.iter() {
|
||||
info!("NS: name: '{}', sid: '{:?}'", key, val);
|
||||
}
|
||||
rkyv::Archived::<api::Request>::Failure
|
||||
}
|
||||
buffer.serialize_from(response).unwrap();
|
||||
}
|
||||
Some(api::Opcode::Lookup) => {
|
||||
let mut mem = msg.body.memory_message_mut().unwrap();
|
||||
let mut buffer = unsafe { Buffer::from_memory_message_mut(mem) };
|
||||
let name_string = buffer.try_into::<xous_ipc::String::<64>, _>().unwrap();
|
||||
let name = XousServerName::from_str(name_string.as_str().unwrap());
|
||||
if debug1{info!("NS: Lookup request for '{}'", name);}
|
||||
let mut response: api::Return;
|
||||
if let Some(server_sid) = name_table.get(&name) {
|
||||
let sender_pid = msg
|
||||
.sender
|
||||
.pid()
|
||||
.expect("NS: can't extract sender PID on Lookup");
|
||||
match xous::connect_for_process(sender_pid, *server_sid)
|
||||
.expect("NS: can't broker connection")
|
||||
{
|
||||
xous::Result::ConnectionID(connection_id) => {
|
||||
if debug1{info!("NS: lookup success, returning connection {}", connection_id);}
|
||||
response = api::Return::CID(connection_id)
|
||||
}
|
||||
} else {
|
||||
info!(
|
||||
"NS: Can't find request '{}' in table, dumping table:",
|
||||
name
|
||||
);
|
||||
for (key, val) in name_table.iter() {
|
||||
info!("NS: name: '{}', sid: '{:?}'", key, val);
|
||||
_ => {
|
||||
info!(
|
||||
"NS: Can't find request '{}' in table, dumping table:",
|
||||
name
|
||||
);
|
||||
for (key, val) in name_table.iter() {
|
||||
info!("NS: name: '{}', sid: '{:?}'", key, val);
|
||||
}
|
||||
response = api::Return::Failure
|
||||
}
|
||||
// no authenticate remedy currently supported, but we'd put that code somewhere around here eventually.
|
||||
rkyv::Archived::<api::Request>::Failure
|
||||
}
|
||||
} else {
|
||||
info!(
|
||||
"NS: Can't find request '{}' in table, dumping table:",
|
||||
name
|
||||
);
|
||||
for (key, val) in name_table.iter() {
|
||||
info!("NS: name: '{}', sid: '{:?}'", key, val);
|
||||
}
|
||||
// no authenticate remedy currently supported, but we'd put that code somewhere around here eventually.
|
||||
let auth_request = AuthenticateRequest {
|
||||
name: name_string,
|
||||
pubkey_id: [0; 20], // placeholder
|
||||
challenge: xous::create_server_id().to_u32().unwrap(),
|
||||
};
|
||||
response = api::Return::AuthenticateRequest(auth_request) // this code just exists to exercise the return path
|
||||
}
|
||||
_ => panic!("Invalid response from the server -- corruption occurred"),
|
||||
};
|
||||
unsafe { *value.get_unchecked_mut() = new_value };
|
||||
} else {
|
||||
error!("NS: couldn't convert opcode");
|
||||
buffer.serialize_from(response).unwrap();
|
||||
}
|
||||
Some(api::Opcode::AuthenticatedLookup) => {
|
||||
let mut mem = msg.body.memory_message_mut().unwrap();
|
||||
let buffer = unsafe { Buffer::from_memory_message_mut(mem) };
|
||||
let auth_lookup = buffer.try_into::<api::AuthenticatedLookup>().unwrap();
|
||||
info!("NS: AuthenticatedLookup request {:?}", auth_lookup);
|
||||
error!("NS: AuthenticatedLookup not yet implemented");
|
||||
unimplemented!("NS: AuthenticatedLookup not yet implemented");
|
||||
}
|
||||
None => error!("NS: couldn't decode message: {:?}", msg)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in a new issue