oxidepath 0.1.0-alpha.1

An experimental Rust proxy core targeting mihomo configuration compatibility
use std::{
    future, io,
    net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr},
    sync::Arc,
    time::Duration,
};

use tokio::{
    io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader, copy_bidirectional},
    net::{TcpListener, TcpStream, lookup_host},
    task::JoinSet,
    time::timeout,
};

use crate::config::{Config, LogLevel, Policy, Protocol};

const HANDSHAKE_TIMEOUT: Duration = Duration::from_secs(10);
const DIAL_TIMEOUT: Duration = Duration::from_secs(10);
const MAX_HTTP_HEADER: u64 = 32 * 1024;

struct Target {
    host: String,
    port: u16,
}

fn invalid_request(message: &'static str) -> io::Error {
    io::Error::new(io::ErrorKind::InvalidData, message)
}

impl Target {
    fn from_authority(authority: &str) -> io::Result<Self> {
        let (host, port) = authority
            .rsplit_once(':')
            .ok_or_else(|| invalid_request("CONNECT authority needs a port"))?;
        let host = if let Some(ipv6) = host
            .strip_prefix('[')
            .and_then(|value| value.strip_suffix(']'))
        {
            ipv6.parse::<Ipv6Addr>()
                .map_err(|_| invalid_request("invalid IPv6 address"))?;
            ipv6
        } else if host.is_empty() || host.contains([':', '/', '[', ']', '@', '?', '#']) {
            return Err(invalid_request("invalid CONNECT authority"));
        } else {
            host
        };
        let port = port
            .parse()
            .map_err(|_| invalid_request("invalid CONNECT port"))?;
        Ok(Self {
            host: host.to_owned(),
            port,
        })
    }
}

async fn http_connect(client: &mut BufReader<TcpStream>) -> io::Result<Target> {
    let mut header = Vec::new();
    let mut limited = (&mut *client).take(MAX_HTTP_HEADER);
    loop {
        let previous = header.len();
        if limited.read_until(b'\n', &mut header).await? == 0 {
            return Err(invalid_request("incomplete or oversized HTTP header"));
        }
        if matches!(&header[previous..], b"\r\n" | b"\n") {
            break;
        }
    }

    let mut fields = [httparse::EMPTY_HEADER; 128];
    let mut request = httparse::Request::new(&mut fields);
    let status = request
        .parse(&header)
        .map_err(|_| invalid_request("invalid HTTP request"))?;
    if status.is_partial() {
        return Err(invalid_request("incomplete HTTP request"));
    }
    let version = request
        .version
        .ok_or_else(|| invalid_request("missing HTTP version"))?;
    if request.method != Some("CONNECT") {
        let reply = format!(
            "HTTP/1.{version} 501 Not Implemented\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"
        );
        client.write_all(reply.as_bytes()).await?;
        return Err(invalid_request("only HTTP CONNECT is supported"));
    }

    let authority = request
        .path
        .ok_or_else(|| invalid_request("missing CONNECT authority"))?;
    let target = Target::from_authority(authority)?;
    let reply = format!("HTTP/1.{version} 200 Connection established\r\n\r\n");
    client.write_all(reply.as_bytes()).await?;
    Ok(target)
}

async fn socks5_connect(client: &mut BufReader<TcpStream>) -> io::Result<Target> {
    let mut greeting = [0; 2];
    client.read_exact(&mut greeting).await?;
    if greeting[0] != 5 {
        return Err(invalid_request("expected SOCKS5"));
    }
    let mut methods = [0; 255];
    let methods = &mut methods[..usize::from(greeting[1])];
    client.read_exact(methods).await?;
    if !methods.contains(&0) {
        client.write_all(&[5, 255]).await?;
        return Err(invalid_request("no supported SOCKS5 authentication method"));
    }
    client.write_all(&[5, 0]).await?;

    let mut request = [0; 4];
    client.read_exact(&mut request).await?;
    let [version, command, reserved, address_type] = request;
    if version != 5 || reserved != 0 {
        return Err(invalid_request("invalid SOCKS5 request"));
    }
    if command != 1 {
        client.write_all(&[5, 7, 0, 1, 0, 0, 0, 0, 0, 0]).await?;
        return Err(invalid_request("only SOCKS5 CONNECT is supported"));
    }
    let host = match address_type {
        1 => {
            let mut address = [0; 4];
            client.read_exact(&mut address).await?;
            Ipv4Addr::from(address).to_string()
        }
        3 => {
            let length = usize::from(client.read_u8().await?);
            let mut address = vec![0; length];
            client.read_exact(&mut address).await?;
            String::from_utf8(address).map_err(|_| invalid_request("invalid SOCKS5 host"))?
        }
        4 => {
            let mut address = [0; 16];
            client.read_exact(&mut address).await?;
            Ipv6Addr::from(address).to_string()
        }
        _ => return Err(invalid_request("invalid SOCKS5 address type")),
    };
    let port = client.read_u16().await?;
    if host.is_empty() {
        return Err(invalid_request("empty SOCKS5 host"));
    }

    let local = client.get_ref().local_addr()?;
    let mut reply = vec![5, 0, 0];
    match local.ip().to_canonical() {
        IpAddr::V4(address) => {
            reply.push(1);
            reply.extend(address.octets());
        }
        IpAddr::V6(address) => {
            reply.push(4);
            reply.extend(address.octets());
        }
    }
    reply.extend(local.port().to_be_bytes());
    client.write_all(&reply).await?;
    Ok(Target { host, port })
}

async fn handshake(client: &mut BufReader<TcpStream>, protocol: Protocol) -> io::Result<Target> {
    let protocol = if protocol == Protocol::Mixed {
        match client.fill_buf().await?.first() {
            Some(5) => Protocol::Socks5,
            Some(_) => Protocol::HttpConnect,
            None => return Err(io::ErrorKind::UnexpectedEof.into()),
        }
    } else {
        protocol
    };
    match protocol {
        Protocol::Socks5 => socks5_connect(client).await,
        _ => http_connect(client).await,
    }
}

async fn dial(target: Target, config: &Config) -> io::Result<TcpStream> {
    let addresses = lookup_host((target.host.as_str(), target.port))
        .await?
        .filter(|address| {
            let canonical = SocketAddr::new(address.ip().to_canonical(), address.port());
            !config
                .listeners
                .iter()
                .any(|(local, _)| *local == canonical)
        })
        .collect::<Vec<_>>();
    TcpStream::connect(addresses.as_slice()).await
}

async fn handle(stream: TcpStream, config: &Config, protocol: Protocol) -> io::Result<()> {
    let source = stream.peer_addr()?.ip().to_canonical();
    let mut client = BufReader::new(stream);
    let mut target = timeout(HANDSHAKE_TIMEOUT, handshake(&mut client, protocol)).await??;
    target.host = target.host.trim_end_matches('.').to_owned();
    let literal = target
        .host
        .parse::<IpAddr>()
        .ok()
        .map(|address| address.to_canonical());
    let (host, static_ip) = if literal.is_some() {
        ("", literal)
    } else {
        config.hosts.resolve(&target.host)
    };
    if config.policy(host, target.port, source, static_ip).await == Policy::Reject {
        return client.shutdown().await;
    }
    if let Some(address) = static_ip {
        target.host = address.to_string();
    } else if !host.is_empty() {
        target.host = host.to_owned();
    }
    let mut origin = timeout(DIAL_TIMEOUT, dial(target, config)).await??;
    copy_bidirectional(&mut client, &mut origin).await?;
    Ok(())
}

async fn listen(listener: TcpListener, protocol: Protocol, config: Arc<Config>) -> io::Result<()> {
    loop {
        let (stream, peer) = listener.accept().await?;
        let config = Arc::clone(&config);
        tokio::spawn(async move {
            if let Err(error) = handle(stream, &config, protocol).await
                && config.log_level == LogLevel::Debug
            {
                eprintln!("oxidepath: {peer}: {error}");
            }
        });
    }
}

pub async fn run(config: Config) -> io::Result<()> {
    let config = Arc::new(config);
    let mut listeners = Vec::new();
    for &(address, protocol) in &config.listeners {
        let socket = TcpListener::bind(address)
            .await
            .map_err(|error| io::Error::new(error.kind(), format!("bind {address}: {error}")))?;
        listeners.push((socket, protocol));
    }

    let mut tasks = JoinSet::new();
    for (socket, protocol) in listeners {
        if config.log_level >= LogLevel::Info {
            eprintln!("oxidepath: listening on {}", socket.local_addr()?);
        }
        tasks.spawn(listen(socket, protocol, Arc::clone(&config)));
    }
    match tasks.join_next().await {
        Some(result) => result?,
        None => future::pending().await,
    }
}