diff --git a/services/xous-names/src/api.rs b/services/xous-names/src/api.rs deleted file mode 100644 index 5acff89da..000000000 --- a/services/xous-names/src/api.rs +++ /dev/null @@ -1,239 +0,0 @@ -#[allow(dead_code)] -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)] -#[non_exhaustive] -#[repr(C)] -pub(crate) enum Opcode { - /// Create a new server with the given name and return its SID. - Register = 0, - - /// Create a connection to the target server. - Lookup = 1, - - /// Create an authenticated connection to the target server. - AuthenticatedLookup = 2, - - /// unregister a server, given its cryptographically unique SID. - Unregister = 3, - - /// disconnect, given a server name and a cryptographically unique, one-time use token - Disconnect = 4, - - /// indicates if all inherentely trusted slots have been occupied. Should not run untrusted code until this is the case. - TrustedInitDone = 5, - - /// Connect to a Server, blocking if the Server does not exist. When the Server is started, - /// return with either the CID or an AuthenticationRequest - /// - /// # Message Types - /// - /// * MutableLend - /// - /// # Arguments - /// - /// The memory being pointed to should be a &str, and the length of the string should - /// be specified in the `valid` field. - /// - /// # Return Values - /// - /// Memory is overwritten to contain a return value. This return value can be defined - /// as the following enum: - /// - /// ```rust - /// #[repr(C)] - /// #[non_exhaustive] - /// enum ConnectResult { - /// Success(xous::CID /* connection ID */, [u32; 4] /* Disconnection token */), - /// Error(u32 /* error code */), - /// Unhandled, /* Catchall for future Results */ - /// } - /// ``` - BlockingConnect = 6, -} - -#[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)] -#[non_exhaustive] -#[repr(C)] -pub(crate) enum Return { - /// The caller must perform an AuthenticatedLookup using this challenge - 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; an optional "disconnect token" is provided - CID((xous::CID, Option<[u32; 4]>)), - - /// Operation requested was otherwise successful (currently only used by disconnect to ack the disconnect) - Success, -} - -#[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)] -pub(crate) struct Registration { - pub name: xous_ipc::String<64>, - pub conn_limit: Option, -} - -#[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)] -pub(crate) struct Disconnect { - 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 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)] -#[repr(C)] -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], -} - -////////////////////////////////////////////////////////////////////////////////////////////// -// 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 -////////////////////////////////////////////////////////////////////////////////////////////// - -// --------------------- Taken from rkyv docs https://docs.rs/rkyv/0.3.0/rkyv/trait.Archive.html // -#[derive(Debug, Copy, Clone)] -pub struct XousServerName { - value: [u8; 64], - length: usize, -} - -impl Default for XousServerName { - fn default() -> Self { - XousServerName { - value: [0u8; 64], - length: 0, - } - } -} - -#[allow(dead_code)] -impl XousServerName { - pub fn to_str(&self) -> &str { - core::str::from_utf8(unsafe { - core::slice::from_raw_parts(self.value.as_ptr(), self.length as usize) - }) - .unwrap() - } - pub fn new() -> XousServerName { - XousServerName { - value: [0; 64], - length: 0, - } - } - - pub fn from_str(src: &str) -> XousServerName { - let mut s = Self::new(); - // Copy the string into our backing store. - for (&src_byte, dest_byte) in src.as_bytes().iter().zip(&mut s.value) { - *dest_byte = src_byte; - } - // Set the string length to the length of the passed-in String, - // or the maximum possible length. Which ever is smaller. - s.length = s.value.len().min(src.as_bytes().len()); - - // If the string is not valid, set its length to 0. - if s.as_str().is_err() { - s.length = 0; - } - assert!(s.length < s.value.len(), "incorrect length derivation!"); - - s - } - - pub fn as_bytes(&self) -> [u8; 64] { - self.value - } - - pub fn as_str(&self) -> core::result::Result<&str, core::str::Utf8Error> { - core::str::from_utf8(&self.value[0..self.length as usize]) - } - - pub fn len(&self) -> usize { - self.length as usize - } - - pub fn is_empty(&self) -> bool { - self.length == 0 - } - - /// Clear the contents and set the length to 0 - pub fn clear(&mut self) { - self.length = 0; - self.value = [0; 64]; - } -} - -// Allow using the `write!()` macro to write into a `&XousServerName` -impl core::fmt::Write for XousServerName { - fn write_str(&mut self, s: &str) -> core::result::Result<(), core::fmt::Error> { - self.length = 0; - let b = s.bytes(); - - // Ensure the length is acceptable - if b.len() > self.value.len() { - Err(core::fmt::Error)?; - } - self.length = b.len(); - 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()) { - *dest = src; - } - - // Attempt to convert the string to UTF-8 to validate it's correct UTF-8 - core::str::from_utf8(unsafe { - core::slice::from_raw_parts(self.value.as_ptr(), self.length as usize) - }) - .map_err(|_| core::fmt::Error)?; - Ok(()) - } -} - -impl std::hash::Hash for XousServerName { - fn hash(&self, state: &mut H) - where - H: std::hash::Hasher, - { - assert!(self.length < self.value.len(), "incorret length on hash!"); - std::hash::Hash::hash(&self.value[..self.length as usize], state); - std::hash::Hash::hash(&self.length, state) - } -} - -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)!" - ); - self.value[..self.length as usize] == other.value[..other.length as usize] - && self.length == other.length - } -} - -impl Eq for XousServerName {} - -impl core::fmt::Display for XousServerName { - fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { - write!(f, "{}", self.to_str()) - } -} diff --git a/services/xous-names/src/lib.rs b/services/xous-names/src/lib.rs deleted file mode 100644 index 9d4af65cf..000000000 --- a/services/xous-names/src/lib.rs +++ /dev/null @@ -1,184 +0,0 @@ -#![cfg_attr(target_os = "none", no_std)] - -//! Detailed docs are parked under Structs/XousNames down below - -pub mod api; - -use api::Disconnect; -use core::fmt::Write; -use num_traits::ToPrimitive; -use xous_ipc::{Buffer, String}; - -#[doc = include_str!("../README.md")] -#[derive(Debug)] -pub struct XousNames { - conn: xous::CID, -} -impl XousNames { - pub fn new() -> Result { - REFCOUNT.fetch_add(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 }) - } - - pub fn unregister_server(&self, sid: xous::SID) -> Result<(), xous::Error> { - // searches the name table and removes a given SID from the table. - // It's considered "secure" because you'd have to guess a random 128-bit SID - // to destroy someone else's SID. - - // note that with the current implementation, the destroy call will have to be an O(N) search through - // the server table, but this is OK as we expect <100 servers on a device - 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, - max_conns: Option, - ) -> Result { - let mut registration = api::Registration { - name: String::<64>::new(), - conn_limit: max_conns, - }; - // could also do String::from_str() but in this case we want things to fail if the string is too long. - write!(registration.name, "{}", name).expect("name probably too long"); - - 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))?; - - match buf.to_original().unwrap() { - api::Return::SID(sid_raw) => { - let sid = sid_raw.into(); - 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"), - } - } - - 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))?; - - match buf.to_original().unwrap() { - api::Return::CID((cid, token)) => Ok((cid, token)), - // api::Return::AuthenticateRequest(_) => Err(xous::Error::AccessDenied), - _ => Err(xous::Error::ServerNotFound), - } - } - pub fn disconnect_with_token(&self, name: &str, token: [u32; 4]) -> Result<(), xous::Error> { - let disconnect = Disconnect { - name: String::<64>::from_str(name), - 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))?; - - match buf.to_original().unwrap() { - api::Return::Success => Ok(()), - _ => Err(xous::Error::ServerNotFound), - } - } - - pub fn request_connection(&self, name: &str) -> Result { - let mut lookup_name = xous_ipc::String::<64>::new(); - write!(lookup_name, "{}", name).expect("name problably too long"); - - 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))?; - - match buf.to_original().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 { - loop { - match self.request_connection(name) { - Ok(val) => return Ok(val), - Err(xous::Error::AccessDenied) => return Err(xous::Error::AccessDenied), - _ => (), - } - log::info!("connection to {} could not be established, retrying", name); - xous::yield_slice(); - } - } - - pub fn trusted_init_done(&self) -> Result { - let response = xous::send_message( - self.conn, - xous::Message::new_blocking_scalar( - api::Opcode::TrustedInitDone.to_usize().unwrap(), - 0, - 0, - 0, - 0, - ), - ) - .expect("couldn't query trusted_init_done"); - if let xous::Result::Scalar1(result) = response { - if result == 1 { - Ok(true) - } else { - Ok(false) - } - } else { - Err(xous::Error::InternalError) - } - } - - // todo: - // pub fn authenticated_connection(&self, name: &str, key: Authkey) - // this function will create an authenticated connection, if such are allowed - // it's intended for use by dynamically-loaded third-party apps. As of Xous 0.8 this isn't supported, so it's just a "todo" -} - -use core::sync::atomic::{AtomicU32, Ordering}; -static REFCOUNT: AtomicU32 = AtomicU32::new(0); -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.fetch_sub(1, Ordering::Relaxed) == 1 { - unsafe { - xous::disconnect(self.conn).unwrap(); - } - } - } -}