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/graphics-server",
"services/com",
"services/xous-names",
"services/keyboard",
"services/trng",
"services/gam",

View file

@ -33,31 +33,30 @@ pub(crate) enum Return {
#[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)]
pub(crate) struct Registration {
pub name: xous_ipc::String::<64>,
pub name: xous_ipc::String<64>,
pub conn_limit: Option<u32>,
}
#[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)]
pub(crate) struct Disconnect {
pub name: xous_ipc::String::<64>,
pub name: xous_ipc::String<64>,
pub token: [u32; 4],
}
#[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)]
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 response: [u32; 8],
}
#[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)]
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 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],
}
//////////////////////////////////////////////////////////////////////////////////////////////
// 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
@ -147,7 +146,10 @@ impl core::fmt::Write for XousServerName {
Err(core::fmt::Error)?;
}
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
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 {
fn eq(&self, other: &Self) -> bool {
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.length == other.length
}

View file

@ -4,10 +4,10 @@
pub mod api;
use core::fmt::Write;
use api::Disconnect;
use xous_ipc::{String, Buffer};
use core::fmt::Write;
use num_traits::ToPrimitive;
use xous_ipc::{Buffer, String};
#[doc = include_str!("../README.md")]
#[derive(Debug)]
@ -17,10 +17,9 @@ pub struct XousNames {
impl XousNames {
pub fn new() -> Result<Self, xous::Error> {
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");
Ok(XousNames {
conn,
})
let conn = xous::connect(xous::SID::from_bytes(b"xous-name-server").unwrap())
.expect("Couldn't connect to XousNames");
Ok(XousNames { conn })
}
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
// the server table, but this is OK as we expect <100 servers on a device
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");
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(())
@ -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 {
name: String::<64>::new(),
conn_limit: max_conns,
@ -55,11 +66,8 @@ impl XousNames {
let mut buf = Buffer::into_buf(registration).or(Err(xous::Error::InternalError))?;
buf.lend_mut(
self.conn,
api::Opcode::Register.to_u32().unwrap()
)
.or(Err(xous::Error::InternalError))?;
buf.lend_mut(self.conn, api::Opcode::Register.to_u32().unwrap())
.or(Err(xous::Error::InternalError))?;
match buf.to_original().unwrap() {
api::Return::SID(sid_raw) => {
@ -67,23 +75,21 @@ impl XousNames {
xous::create_server_with_sid(sid).expect("can't auto-register server");
Ok(sid)
}
api::Return::Failure => {
Err(xous::Error::InternalError)
}
_ => unimplemented!("unimplemented return codes")
api::Return::Failure => Err(xous::Error::InternalError),
_ => 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();
write!(lookup_name, "{}", name).expect("name problably too long");
let mut buf = Buffer::into_buf(lookup_name).or(Err(xous::Error::InternalError))?;
buf.lend_mut(
self.conn,
api::Opcode::Lookup.to_u32().unwrap()
)
.or(Err(xous::Error::InternalError))?;
buf.lend_mut(self.conn, api::Opcode::Lookup.to_u32().unwrap())
.or(Err(xous::Error::InternalError))?;
match buf.to_original().unwrap() {
api::Return::CID((cid, token)) => Ok((cid, token)),
@ -97,10 +103,8 @@ impl XousNames {
token,
};
let mut buf = Buffer::into_buf(disconnect).or(Err(xous::Error::InternalError))?;
buf.lend_mut(
self.conn,
api::Opcode::Disconnect.to_u32().unwrap()
).or(Err(xous::Error::InternalError))?;
buf.lend_mut(self.conn, api::Opcode::Disconnect.to_u32().unwrap())
.or(Err(xous::Error::InternalError))?;
match buf.to_original().unwrap() {
api::Return::Success => Ok(()),
@ -114,11 +118,8 @@ impl XousNames {
let mut buf = Buffer::into_buf(lookup_name).or(Err(xous::Error::InternalError))?;
buf.lend_mut(
self.conn,
api::Opcode::Lookup.to_u32().unwrap()
)
.or(Err(xous::Error::InternalError))?;
buf.lend_mut(self.conn, api::Opcode::Lookup.to_u32().unwrap())
.or(Err(xous::Error::InternalError))?;
match buf.to_original().unwrap() {
api::Return::CID((cid, _)) => Ok(cid),
@ -141,9 +142,17 @@ impl XousNames {
}
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");
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)
@ -167,7 +176,9 @@ impl Drop for XousNames {
fn drop(&mut self) {
// 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 {
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 xous::msg_blocking_scalar_unpack;
use xous_ipc::{String, Buffer};
use xous_ipc::{Buffer, String};
use log::{error, info};
@ -79,12 +79,12 @@ struct Connection {
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
pub token: Option<[u32; 4]>, // a random number that must be presented to allow for disconnection for single-connection servers
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
}
#[derive(Debug)]
struct CheckedHashMap {
pub map: HashMap::<XousServerName, Connection>,
pub map: HashMap<XousServerName, Connection>,
}
impl CheckedHashMap {
pub fn new() -> Self {
@ -92,21 +92,33 @@ impl CheckedHashMap {
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) {
// 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 {
None
};
self.map.insert(name, Connection {
sid,
current_conns: 0,
max_conns,
allow_authenticate: false, // for now, we don't support authenticated connections
auth_conns: 0,
token,
});
self.map.insert(
name,
Connection {
sid,
current_conns: 0,
max_conns,
allow_authenticate: false, // for now, we don't support authenticated connections
auth_conns: 0,
token,
},
);
Ok(())
}
pub fn remove(&mut self, sid: xous::SID) -> Option<XousServerName> {
@ -136,9 +148,9 @@ impl CheckedHashMap {
// single-connection case
if entry.current_conns < 1 {
(*entry).current_conns = 1;
return (Some(&entry.sid), entry.token)
return (Some(&entry.sid), entry.token);
} else {
return (None, None)
return (None, None);
}
}
if let Some(max) = entry.max_conns {
@ -161,7 +173,12 @@ impl CheckedHashMap {
for (name, entry) in self.map.iter() {
if let Some(max) = entry.max_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;
}
}
@ -193,8 +210,12 @@ impl CheckedHashMap {
if (token == old_token) && (entry.current_conns == 1) {
(*entry).current_conns = 0;
// generate the token -- we should never re-use these!
(*entry).token = Some(xous::create_server_id().expect("couldn't create token").to_array());
return true
(*entry).token = Some(
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 mut buffer = unsafe { Buffer::from_memory_message_mut(mem) };
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;
@ -247,7 +273,9 @@ fn xmain() -> ! {
info!("deterministic timeout done");
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, {
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) => {
let mem = msg.body.memory_message_mut().unwrap();
let mut buffer = unsafe { Buffer::from_memory_message_mut(mem) };
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_string = buffer.to_original::<String<64>, _>().unwrap();
let name = XousServerName::from_str(
name_string
.as_str()
.expect("couldn't convert server name to string"),
);
log::trace!("Lookup request for '{}'", name);
let response: api::Return;
if let (Some(server_sid), token) = name_table.connect(&name) {
@ -280,10 +312,7 @@ fn xmain() -> ! {
response = api::Return::CID((connection_id, token))
}
_ => {
log::debug!(
"Can't find request '{}' in table, dumping table:",
name
);
log::debug!("Can't find request '{}' in table, dumping table:", name);
for (_name, conn) in name_table.map.iter() {
log::debug!("{:?}", conn);
}
@ -292,24 +321,27 @@ fn xmain() -> ! {
}
}
} else {
log::debug!(
"Can't find request '{}' in table, dumping table:",
name
);
log::debug!("Can't find request '{}' in table, dumping table:", name);
for (_name, conn) in name_table.map.iter() {
log::debug!("{:?}", conn);
}
// 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 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
challenge: [c1, c2, c3, c4],
};
d11ctimeout.hosted_delay();
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) => {
let mem = msg.body.memory_message_mut().unwrap();
@ -338,7 +370,10 @@ fn xmain() -> ! {
};
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