use std::fmt;
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Proto {
Http,
Https,
Socks4,
Socks5,
Connect80,
Connect25,
}
impl Proto {
pub const ALL: [Proto; 6] = [
Proto::Http,
Proto::Https,
Proto::Socks4,
Proto::Socks5,
Proto::Connect80,
Proto::Connect25,
];
pub const fn as_str(self) -> &'static str {
match self {
Proto::Http => "HTTP",
Proto::Https => "HTTPS",
Proto::Socks4 => "SOCKS4",
Proto::Socks5 => "SOCKS5",
Proto::Connect80 => "CONNECT:80",
Proto::Connect25 => "CONNECT:25",
}
}
pub const fn checks_anon_level(self) -> bool {
matches!(self, Proto::Http)
}
pub const fn uses_full_path(self) -> bool {
matches!(self, Proto::Http)
}
pub const fn judge_scheme(self) -> JudgeScheme {
match self {
Proto::Https => JudgeScheme::Https,
Proto::Connect25 => JudgeScheme::Smtp,
_ => JudgeScheme::Http,
}
}
pub fn display_order_key(self) -> (usize, u8) {
let s = self.as_str();
(s.len(), s.as_bytes()[s.len() - 1])
}
}
impl fmt::Display for Proto {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
impl std::str::FromStr for Proto {
type Err = ParseProtoError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Proto::ALL
.into_iter()
.find(|p| p.as_str().eq_ignore_ascii_case(s))
.ok_or_else(|| ParseProtoError(s.to_owned()))
}
}
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[error("unknown protocol: {0}")]
pub struct ParseProtoError(pub String);
impl serde::Serialize for Proto {
fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
s.serialize_str(self.as_str())
}
}
impl<'de> serde::Deserialize<'de> for Proto {
fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
let s = String::deserialize(d)?;
s.parse().map_err(serde::de::Error::custom)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum AnonLevel {
Transparent,
Anonymous,
High,
}
impl serde::Serialize for AnonLevel {
fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
s.serialize_str(self.as_str())
}
}
impl AnonLevel {
pub const fn as_str(self) -> &'static str {
match self {
AnonLevel::Transparent => "Transparent",
AnonLevel::Anonymous => "Anonymous",
AnonLevel::High => "High",
}
}
}
impl fmt::Display for AnonLevel {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
impl std::str::FromStr for AnonLevel {
type Err = ParseProtoError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
for l in [
AnonLevel::Transparent,
AnonLevel::Anonymous,
AnonLevel::High,
] {
if l.as_str().eq_ignore_ascii_case(s) {
return Ok(l);
}
}
Err(ParseProtoError(s.to_owned()))
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Scheme {
Http,
Https,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum JudgeScheme {
Http,
Https,
Smtp,
}
impl JudgeScheme {
pub const fn default_port(self) -> u16 {
match self {
JudgeScheme::Http => 80,
JudgeScheme::Https => 443,
JudgeScheme::Smtp => 25,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TypeSpec {
pub proto: Proto,
pub levels: Option<Vec<AnonLevel>>,
}
impl TypeSpec {
pub fn any(proto: Proto) -> Self {
Self {
proto,
levels: None,
}
}
pub fn accepts(&self, proto: Proto, level: Option<AnonLevel>) -> bool {
if self.proto != proto {
return false;
}
match (&self.levels, level) {
(None, _) => true,
(Some(want), Some(got)) => want.contains(&got),
(Some(_), None) => false,
}
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct Caps {
pub cookie_echo: bool,
pub referer_echo: bool,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn proto_roundtrips_through_its_wire_name() {
for p in Proto::ALL {
assert_eq!(p.as_str().parse::<Proto>().unwrap(), p);
}
assert_eq!("connect:80".parse::<Proto>().unwrap(), Proto::Connect80);
assert!("NOPE".parse::<Proto>().is_err());
}
#[test]
fn anon_level_serializes_as_wire_name() {
assert_eq!(serde_json::to_string(&AnonLevel::High).unwrap(), "\"High\"");
assert_eq!(
serde_json::to_string(&AnonLevel::Transparent).unwrap(),
"\"Transparent\""
);
}
#[test]
fn display_order_matches_python() {
let mut all = Proto::ALL;
all.sort_by_key(|p| p.display_order_key());
let got: Vec<_> = all.iter().map(|p| p.as_str()).collect();
assert_eq!(
got,
[
"HTTP",
"HTTPS",
"SOCKS4",
"SOCKS5",
"CONNECT:80",
"CONNECT:25"
],
"CONNECT:80 must precede CONNECT:25 ('0' < '5')"
);
}
#[test]
fn only_http_carries_anonymity() {
assert!(Proto::Http.checks_anon_level());
assert!(Proto::Http.uses_full_path());
for p in Proto::ALL.into_iter().filter(|p| *p != Proto::Http) {
assert!(!p.checks_anon_level(), "{p} must not check anon level");
assert!(!p.uses_full_path(), "{p} must not use full path");
}
}
#[test]
fn judge_scheme_routing_matches_python() {
assert_eq!(Proto::Https.judge_scheme(), JudgeScheme::Https);
assert_eq!(Proto::Connect25.judge_scheme(), JudgeScheme::Smtp);
for p in [Proto::Http, Proto::Socks4, Proto::Socks5, Proto::Connect80] {
assert_eq!(p.judge_scheme(), JudgeScheme::Http, "{p}");
}
}
#[test]
fn anon_levels_order_worst_to_best() {
assert!(AnonLevel::Transparent < AnonLevel::Anonymous);
assert!(AnonLevel::Anonymous < AnonLevel::High);
}
#[test]
fn type_spec_accepts() {
let any = TypeSpec::any(Proto::Socks5);
assert!(any.accepts(Proto::Socks5, None));
assert!(!any.accepts(Proto::Socks4, None));
let strict = TypeSpec {
proto: Proto::Http,
levels: Some(vec![AnonLevel::High]),
};
assert!(strict.accepts(Proto::Http, Some(AnonLevel::High)));
assert!(!strict.accepts(Proto::Http, Some(AnonLevel::Transparent)));
assert!(!strict.accepts(Proto::Http, None));
}
#[test]
fn missing_comma_bug_is_unrepresentable() {
let one = [Proto::Socks4];
assert_eq!(one.len(), 1);
assert!(one.contains(&Proto::Socks4));
}
}