use std::fmt;
use serde::Deserialize;
use serde::Serialize;
use crate::error::Error;
use crate::error::Result;
macro_rules! onion_signature {
(
world_facing: [
$($(#[doc = $doc:literal])* $variant:ident $field:ident $name:literal,)+
] $(,)?
) => {
const WORLD_FACING_SYMBOLS: usize = [$(onion_signature!(@unit $variant),)+].len();
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
#[repr(u8)]
enum OnionWorldSymbol {
$($(#[doc = $doc])* $variant,)+
}
impl OnionWorldSymbol {
const ALL: [Self; WORLD_FACING_SYMBOLS] = [$(Self::$variant,)+];
const fn name(self) -> &'static str {
match self {
$(Self::$variant => $name,)+
}
}
}
impl OnionServiceName {
pub fn world_facing() -> impl Iterator<Item = Self> {
OnionWorldSymbol::ALL.into_iter().map(Self)
}
$(
#[doc = concat!("Return the name of the world-facing `", $name, "` symbol.")]
pub const fn $field() -> Self {
Self(OnionWorldSymbol::$variant)
}
)+
}
};
(@unit $variant:ident) => {
()
};
}
onion_signature! {
world_facing: [
Tcp tcp "tcp",
Https https "https",
],
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub(crate) enum OnionSymbol {
Relay,
WorldFacing(OnionServiceName),
}
impl OnionSymbol {
pub(crate) const fn code(&self) -> u8 {
match self {
Self::Relay => 0,
Self::WorldFacing(OnionServiceName(symbol)) => 1 + *symbol as u8,
}
}
pub(crate) fn from_code(code: u8) -> Option<Self> {
match code.checked_sub(1) {
None => Some(Self::Relay),
Some(world) => OnionWorldSymbol::ALL
.into_iter()
.nth(usize::from(world))
.map(|symbol| Self::WorldFacing(OnionServiceName(symbol))),
}
}
}
#[derive(Clone, Deserialize, Eq, Hash, PartialEq, Serialize)]
#[serde(try_from = "String", into = "String")]
pub struct OnionServiceName(OnionWorldSymbol);
impl OnionServiceName {
pub fn parse(name: impl AsRef<str>) -> Result<Self> {
let name = name.as_ref();
let trimmed = name.trim();
if trimmed.is_empty() || trimmed != name {
return Err(Error::InvalidConfig(
"onion exit service name must be non-empty and trimmed".to_string(),
));
}
OnionServiceName::world_facing()
.find(|service| service.as_str().eq_ignore_ascii_case(trimmed))
.ok_or_else(|| {
Error::InvalidConfig(format!(
"unknown onion service {name:?}; the onion signature is closed: expected one of {}",
OnionServiceName::world_facing()
.map(|service| service.as_str())
.collect::<Vec<_>>()
.join(", ")
))
})
}
pub const fn as_str(&self) -> &'static str {
self.0.name()
}
pub fn matches(&self, service: &str) -> bool {
Self::parse(service).is_ok_and(|candidate| candidate == *self)
}
}
impl fmt::Debug for OnionServiceName {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_tuple("OnionServiceName")
.field(&self.as_str())
.finish()
}
}
impl PartialOrd for OnionServiceName {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
Some(self.cmp(other))
}
}
impl Ord for OnionServiceName {
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
self.as_str().cmp(other.as_str())
}
}
impl TryFrom<String> for OnionServiceName {
type Error = String;
fn try_from(value: String) -> std::result::Result<Self, Self::Error> {
Self::parse(&value).map_err(|error| error.to_string())
}
}
impl From<OnionServiceName> for String {
fn from(name: OnionServiceName) -> Self {
name.as_str().to_string()
}
}
#[cfg(test)]
mod tests {
use super::OnionServiceName;
use super::OnionSymbol;
#[test]
fn test_service_names_are_exactly_the_world_facing_signature() {
for service in OnionServiceName::world_facing() {
assert_eq!(
OnionServiceName::parse(service.as_str()).ok(),
Some(service.clone())
);
assert_eq!(
OnionServiceName::parse(service.as_str().to_ascii_uppercase()).ok(),
Some(service)
);
}
for outside in ["relay", "web", "api", "custom", "tcp2", "", " tcp", "tcp!"] {
assert!(OnionServiceName::parse(outside).is_err());
}
}
#[test]
fn test_codec_is_the_name_string_and_rejects_names_outside_the_world_facing_signature() {
let encoded = rings_codec::serialize(&OnionServiceName::https()).expect("encode name");
assert_eq!(
encoded,
rings_codec::serialize(&"https").expect("encode string")
);
for outside in ["web", "relay"] {
let bytes = rings_codec::serialize(&outside).expect("encode string");
assert!(rings_codec::deserialize::<OnionServiceName>(bytes.as_slice()).is_err());
}
}
#[test]
fn test_from_code_inverts_code() {
let decoded = (0..=u8::MAX)
.filter_map(|code| OnionSymbol::from_code(code).map(|symbol| (code, symbol)))
.collect::<Vec<_>>();
let table = std::iter::once(OnionSymbol::Relay)
.chain(OnionServiceName::world_facing().map(OnionSymbol::WorldFacing))
.collect::<Vec<_>>();
assert_eq!(decoded.len(), table.len());
for ((position, (code, symbol)), expected) in decoded.iter().enumerate().zip(&table) {
assert_eq!(usize::from(*code), position);
assert_eq!(symbol.code(), *code);
assert_eq!(symbol, expected);
}
}
#[test]
fn test_service_names_order_by_name() {
assert!(OnionServiceName::https() < OnionServiceName::tcp());
}
}