move xous-names into standard formatting

This commit is contained in:
bunnie 2021-08-19 23:51:20 +08:00
parent 323b2ed261
commit 7f3d2e3ce3
4 changed files with 131 additions and 81 deletions

View file

@ -2,7 +2,6 @@ ignore = [
"services/aes-test", "services/aes-test",
"services/graphics-server", "services/graphics-server",
"services/com", "services/com",
"services/xous-names",
"services/keyboard", "services/keyboard",
"services/trng", "services/trng",
"services/gam", "services/gam",

View file

@ -33,31 +33,30 @@ pub(crate) enum Return {
#[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)] #[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)]
pub(crate) struct Registration { pub(crate) struct Registration {
pub name: xous_ipc::String::<64>, pub name: xous_ipc::String<64>,
pub conn_limit: Option<u32>, pub conn_limit: Option<u32>,
} }
#[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)] #[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)]
pub(crate) struct Disconnect { pub(crate) struct Disconnect {
pub name: xous_ipc::String::<64>, pub name: xous_ipc::String<64>,
pub token: [u32; 4], pub token: [u32; 4],
} }
#[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>,
pub pubkey_id: [u8; 20], // 160-bit pubkey ID encoded in network order (big endian) pub pubkey_id: [u8; 20], // 160-bit pubkey ID encoded in network order (big endian)
pub response: [u32; 8], pub response: [u32; 8],
} }
#[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)] #[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)]
pub(crate) struct AuthenticateRequest { pub(crate) struct AuthenticateRequest {
pub name: xous_ipc::String::<64>, // a copy of the originally requested lookup 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 pubkey_id: [u8; 20], // 160-bit pubkey ID encoded in network order (big endian)
pub challenge: [u32; 4], pub challenge: [u32; 4],
} }
////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////
// We keep XousServerName around because want to be able to index off the server name, without // We keep XousServerName around because want to be able to index off the server name, without
// burdening the Kernel String type with the Hash32 methods // burdening the Kernel String type with the Hash32 methods
@ -147,7 +146,10 @@ impl core::fmt::Write for XousServerName {
Err(core::fmt::Error)?; Err(core::fmt::Error)?;
} }
self.length = b.len(); self.length = b.len();
assert!(self.length < self.value.len(), "incorrect length derivation!"); assert!(
self.length < self.value.len(),
"incorrect length derivation!"
);
// Copy the string into this variable // Copy the string into this variable
for (dest, src) in self.value.iter_mut().zip(s.bytes()) { for (dest, src) in self.value.iter_mut().zip(s.bytes()) {
@ -177,7 +179,10 @@ impl std::hash::Hash for XousServerName {
impl PartialEq for XousServerName { impl PartialEq for XousServerName {
fn eq(&self, other: &Self) -> bool { fn eq(&self, other: &Self) -> bool {
assert!(self.length < self.value.len(), "incorret length on Eq!"); assert!(self.length < self.value.len(), "incorret length on Eq!");
assert!(other.length < other.value.len(), "incorrect length on Eq (other)!"); assert!(
other.length < other.value.len(),
"incorrect length on Eq (other)!"
);
self.value[..self.length as usize] == other.value[..other.length as usize] self.value[..self.length as usize] == other.value[..other.length as usize]
&& self.length == other.length && self.length == other.length
} }

View file

@ -4,10 +4,10 @@
pub mod api; pub mod api;
use core::fmt::Write;
use api::Disconnect; use api::Disconnect;
use xous_ipc::{String, Buffer}; use core::fmt::Write;
use num_traits::ToPrimitive; use num_traits::ToPrimitive;
use xous_ipc::{Buffer, String};
#[doc = include_str!("../README.md")] #[doc = include_str!("../README.md")]
#[derive(Debug)] #[derive(Debug)]
@ -17,10 +17,9 @@ pub struct XousNames {
impl XousNames { impl XousNames {
pub fn new() -> Result<Self, xous::Error> { pub fn new() -> Result<Self, xous::Error> {
REFCOUNT.store(REFCOUNT.load(Ordering::Relaxed) + 1, Ordering::Relaxed); REFCOUNT.store(REFCOUNT.load(Ordering::Relaxed) + 1, Ordering::Relaxed);
let conn = xous::connect(xous::SID::from_bytes(b"xous-name-server").unwrap()).expect("Couldn't connect to XousNames"); let conn = xous::connect(xous::SID::from_bytes(b"xous-name-server").unwrap())
Ok(XousNames { .expect("Couldn't connect to XousNames");
conn, Ok(XousNames { conn })
})
} }
pub fn unregister_server(&self, sid: xous::SID) -> Result<(), xous::Error> { pub fn unregister_server(&self, sid: xous::SID) -> Result<(), xous::Error> {
@ -31,9 +30,17 @@ impl XousNames {
// 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
let s = sid.to_array(); let s = sid.to_array();
let response = xous::send_message(self.conn, let response = xous::send_message(
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) self.conn,
).expect("unregistration failed"); 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 let xous::Result::Scalar1(result) = response {
if result != 0 { if result != 0 {
Ok(()) Ok(())
@ -45,7 +52,11 @@ impl XousNames {
} }
} }
pub fn register_name(&self, name: &str, max_conns: Option<u32>) -> Result<xous::SID, xous::Error> { pub fn register_name(
&self,
name: &str,
max_conns: Option<u32>,
) -> Result<xous::SID, xous::Error> {
let mut registration = api::Registration { let mut registration = api::Registration {
name: String::<64>::new(), name: String::<64>::new(),
conn_limit: max_conns, conn_limit: max_conns,
@ -55,11 +66,8 @@ impl XousNames {
let mut buf = Buffer::into_buf(registration).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, api::Opcode::Register.to_u32().unwrap())
self.conn, .or(Err(xous::Error::InternalError))?;
api::Opcode::Register.to_u32().unwrap()
)
.or(Err(xous::Error::InternalError))?;
match buf.to_original().unwrap() { match buf.to_original().unwrap() {
api::Return::SID(sid_raw) => { api::Return::SID(sid_raw) => {
@ -67,23 +75,21 @@ impl XousNames {
xous::create_server_with_sid(sid).expect("can't auto-register server"); xous::create_server_with_sid(sid).expect("can't auto-register server");
Ok(sid) Ok(sid)
} }
api::Return::Failure => { api::Return::Failure => Err(xous::Error::InternalError),
Err(xous::Error::InternalError) _ => unimplemented!("unimplemented return codes"),
}
_ => unimplemented!("unimplemented return codes")
} }
} }
pub fn request_connection_with_token(&self, name: &str) -> Result<(xous::CID, Option<[u32; 4]>), xous::Error> { pub fn request_connection_with_token(
&self,
name: &str,
) -> Result<(xous::CID, Option<[u32; 4]>), 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");
let mut buf = Buffer::into_buf(lookup_name).or(Err(xous::Error::InternalError))?; let mut buf = Buffer::into_buf(lookup_name).or(Err(xous::Error::InternalError))?;
buf.lend_mut( buf.lend_mut(self.conn, api::Opcode::Lookup.to_u32().unwrap())
self.conn, .or(Err(xous::Error::InternalError))?;
api::Opcode::Lookup.to_u32().unwrap()
)
.or(Err(xous::Error::InternalError))?;
match buf.to_original().unwrap() { match buf.to_original().unwrap() {
api::Return::CID((cid, token)) => Ok((cid, token)), api::Return::CID((cid, token)) => Ok((cid, token)),
@ -97,10 +103,8 @@ impl XousNames {
token, token,
}; };
let mut buf = Buffer::into_buf(disconnect).or(Err(xous::Error::InternalError))?; let mut buf = Buffer::into_buf(disconnect).or(Err(xous::Error::InternalError))?;
buf.lend_mut( buf.lend_mut(self.conn, api::Opcode::Disconnect.to_u32().unwrap())
self.conn, .or(Err(xous::Error::InternalError))?;
api::Opcode::Disconnect.to_u32().unwrap()
).or(Err(xous::Error::InternalError))?;
match buf.to_original().unwrap() { match buf.to_original().unwrap() {
api::Return::Success => Ok(()), api::Return::Success => Ok(()),
@ -114,11 +118,8 @@ impl XousNames {
let mut buf = Buffer::into_buf(lookup_name).or(Err(xous::Error::InternalError))?; let mut buf = Buffer::into_buf(lookup_name).or(Err(xous::Error::InternalError))?;
buf.lend_mut( buf.lend_mut(self.conn, api::Opcode::Lookup.to_u32().unwrap())
self.conn, .or(Err(xous::Error::InternalError))?;
api::Opcode::Lookup.to_u32().unwrap()
)
.or(Err(xous::Error::InternalError))?;
match buf.to_original().unwrap() { match buf.to_original().unwrap() {
api::Return::CID((cid, _)) => Ok(cid), api::Return::CID((cid, _)) => Ok(cid),
@ -141,9 +142,17 @@ impl XousNames {
} }
pub fn trusted_init_done(&self) -> Result<bool, xous::Error> { pub fn trusted_init_done(&self) -> Result<bool, xous::Error> {
let response = xous::send_message(self.conn, let response = xous::send_message(
xous::Message::new_blocking_scalar(api::Opcode::TrustedInitDone.to_usize().unwrap(), 0, 0, 0, 0) self.conn,
).expect("couldn't query trusted_init_done"); 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 let xous::Result::Scalar1(result) = response {
if result == 1 { if result == 1 {
Ok(true) Ok(true)
@ -167,7 +176,9 @@ impl Drop for XousNames {
fn drop(&mut self) { fn drop(&mut self) {
// de-allocate myself. It's unsafe because we are responsible to make sure nobody else is using the connection. // de-allocate myself. It's unsafe because we are responsible to make sure nobody else is using the connection.
if REFCOUNT.load(Ordering::Relaxed) == 0 { if REFCOUNT.load(Ordering::Relaxed) == 0 {
unsafe{xous::disconnect(self.conn).unwrap();} unsafe {
xous::disconnect(self.conn).unwrap();
}
} }
} }
} }

View file

@ -6,7 +6,7 @@ use api::*;
use num_traits::FromPrimitive; use num_traits::FromPrimitive;
use xous::msg_blocking_scalar_unpack; use xous::msg_blocking_scalar_unpack;
use xous_ipc::{String, Buffer}; use xous_ipc::{Buffer, String};
use log::{error, info}; use log::{error, info};
@ -79,12 +79,12 @@ struct Connection {
pub current_conns: u32, // number of unauthenticated (inherentely trusted) connections pub current_conns: u32, // number of unauthenticated (inherentely trusted) connections
pub max_conns: Option<u32>, // if None, unlimited connections allowed pub max_conns: Option<u32>, // if None, unlimited connections allowed
pub allow_authenticate: bool, pub allow_authenticate: bool,
pub auth_conns: u32, // number of authenticated connections pub auth_conns: u32, // number of authenticated connections
pub token: Option<[u32; 4]>, // a random number that must be presented to allow for disconnection for single-connection servers pub token: Option<[u32; 4]>, // a random number that must be presented to allow for disconnection for single-connection servers
} }
#[derive(Debug)] #[derive(Debug)]
struct CheckedHashMap { struct CheckedHashMap {
pub map: HashMap::<XousServerName, Connection>, pub map: HashMap<XousServerName, Connection>,
} }
impl CheckedHashMap { impl CheckedHashMap {
pub fn new() -> Self { pub fn new() -> Self {
@ -92,21 +92,33 @@ impl CheckedHashMap {
map: HashMap::new(), map: HashMap::new(),
} }
} }
pub fn insert(&mut self, name: XousServerName, sid: xous::SID, max_conns: Option<u32>) -> Result<(), xous::Error> { pub fn insert(
&mut self,
name: XousServerName,
sid: xous::SID,
max_conns: Option<u32>,
) -> Result<(), xous::Error> {
let token = if max_conns == Some(1) { let token = if max_conns == Some(1) {
// for the special case of 1-connection servers, provision a one-time use token for disconnects // for the special case of 1-connection servers, provision a one-time use token for disconnects
Some(xous::create_server_id().expect("couldn't create token").to_array()) Some(
xous::create_server_id()
.expect("couldn't create token")
.to_array(),
)
} else { } else {
None None
}; };
self.map.insert(name, Connection { self.map.insert(
sid, name,
current_conns: 0, Connection {
max_conns, sid,
allow_authenticate: false, // for now, we don't support authenticated connections current_conns: 0,
auth_conns: 0, max_conns,
token, allow_authenticate: false, // for now, we don't support authenticated connections
}); auth_conns: 0,
token,
},
);
Ok(()) Ok(())
} }
pub fn remove(&mut self, sid: xous::SID) -> Option<XousServerName> { pub fn remove(&mut self, sid: xous::SID) -> Option<XousServerName> {
@ -136,9 +148,9 @@ impl CheckedHashMap {
// single-connection case // single-connection case
if entry.current_conns < 1 { if entry.current_conns < 1 {
(*entry).current_conns = 1; (*entry).current_conns = 1;
return (Some(&entry.sid), entry.token) return (Some(&entry.sid), entry.token);
} else { } else {
return (None, None) return (None, None);
} }
} }
if let Some(max) = entry.max_conns { if let Some(max) = entry.max_conns {
@ -161,7 +173,12 @@ impl CheckedHashMap {
for (name, entry) in self.map.iter() { for (name, entry) in self.map.iter() {
if let Some(max) = entry.max_conns { if let Some(max) = entry.max_conns {
if max != entry.current_conns { if max != entry.current_conns {
log::info!("server {} has {} conns but expects {}", name, entry.current_conns, max); log::info!(
"server {} has {} conns but expects {}",
name,
entry.current_conns,
max
);
trusted_done = false; trusted_done = false;
} }
} }
@ -193,8 +210,12 @@ impl CheckedHashMap {
if (token == old_token) && (entry.current_conns == 1) { if (token == old_token) && (entry.current_conns == 1) {
(*entry).current_conns = 0; (*entry).current_conns = 0;
// generate the token -- we should never re-use these! // generate the token -- we should never re-use these!
(*entry).token = Some(xous::create_server_id().expect("couldn't create token").to_array()); (*entry).token = Some(
return true xous::create_server_id()
.expect("couldn't create token")
.to_array(),
);
return true;
} }
} }
} }
@ -227,7 +248,12 @@ fn xmain() -> ! {
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 registration = buffer.to_original::<Registration, _>().unwrap(); let registration = buffer.to_original::<Registration, _>().unwrap();
let name = XousServerName::from_str(registration.name.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;
@ -247,7 +273,9 @@ fn xmain() -> ! {
info!("deterministic timeout done"); info!("deterministic timeout done");
response = api::Return::Failure response = api::Return::Failure
} }
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, { 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); let gid = xous::SID::from_u32(s0 as u32, s1 as u32, s2 as u32, s3 as u32);
@ -263,8 +291,12 @@ fn xmain() -> ! {
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"),
);
log::trace!("Lookup request for '{}'", name); log::trace!("Lookup request for '{}'", name);
let response: api::Return; let response: api::Return;
if let (Some(server_sid), token) = name_table.connect(&name) { if let (Some(server_sid), token) = name_table.connect(&name) {
@ -280,10 +312,7 @@ fn xmain() -> ! {
response = api::Return::CID((connection_id, token)) response = api::Return::CID((connection_id, token))
} }
_ => { _ => {
log::debug!( log::debug!("Can't find request '{}' in table, dumping table:", name);
"Can't find request '{}' in table, dumping table:",
name
);
for (_name, conn) in name_table.map.iter() { for (_name, conn) in name_table.map.iter() {
log::debug!("{:?}", conn); log::debug!("{:?}", conn);
} }
@ -292,24 +321,27 @@ fn xmain() -> ! {
} }
} }
} else { } else {
log::debug!( log::debug!("Can't find request '{}' in table, dumping table:", name);
"Can't find request '{}' in table, dumping table:",
name
);
for (_name, conn) in name_table.map.iter() { for (_name, conn) in name_table.map.iter() {
log::debug!("{:?}", conn); log::debug!("{:?}", conn);
} }
// 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.
let (c1, c2, c3, c4) = xous::create_server_id().unwrap().to_u32(); let (c1, c2, c3, c4) = xous::create_server_id().unwrap().to_u32();
let auth_request = AuthenticateRequest { let auth_request = AuthenticateRequest {
name: String::<64>::from_str(name_string.as_str().expect("couldn't convert server name to string")), name: String::<64>::from_str(
name_string
.as_str()
.expect("couldn't convert server name to string"),
),
pubkey_id: [0; 20], // placeholder pubkey_id: [0; 20], // placeholder
challenge: [c1, c2, c3, c4], challenge: [c1, c2, c3, c4],
}; };
d11ctimeout.hosted_delay(); d11ctimeout.hosted_delay();
response = api::Return::AuthenticateRequest(auth_request) // this code just exists to exercise the return path response = api::Return::AuthenticateRequest(auth_request) // this code just exists to exercise the return path
} }
buffer.replace(response).expect("Lookup can't serialize return value"); buffer
.replace(response)
.expect("Lookup can't serialize return value");
} }
Some(api::Opcode::AuthenticatedLookup) => { Some(api::Opcode::AuthenticatedLookup) => {
let mem = msg.body.memory_message_mut().unwrap(); let mem = msg.body.memory_message_mut().unwrap();
@ -338,7 +370,10 @@ fn xmain() -> ! {
}; };
buffer.replace(response).expect("Can't return buffer"); buffer.replace(response).expect("Can't return buffer");
} }
None => {error!("couldn't decode message: {:?}", msg); break} None => {
error!("couldn't decode message: {:?}", msg);
break;
}
} }
} }
// clean up our program // clean up our program