karyon_net/layers/proxy/
socks5.rs1use std::net::{Ipv4Addr, Ipv6Addr};
2
3use karyon_core::async_runtime::io::{AsyncReadExt, AsyncWriteExt};
4
5use crate::{ByteStream, Error, Result, layer::ClientLayer};
6
7const SOCKS5_VERSION: u8 = 0x05;
8const NO_AUTH: u8 = 0x00;
9const CMD_CONNECT: u8 = 0x01;
10const ATYPE_IPV4: u8 = 0x01;
11const ATYPE_DOMAIN: u8 = 0x03;
12const ATYPE_IPV6: u8 = 0x04;
13const REPLY_SUCCESS: u8 = 0x00;
14
15#[derive(Clone)]
37pub struct Socks5Layer {
38 target_host: String,
39 target_port: u16,
40}
41
42impl Socks5Layer {
43 pub fn new(host: &str, port: u16) -> Self {
45 Self {
46 target_host: host.to_string(),
47 target_port: port,
48 }
49 }
50}
51
52impl ClientLayer<Box<dyn ByteStream>, Box<dyn ByteStream>> for Socks5Layer {
53 async fn handshake(&self, mut stream: Box<dyn ByteStream>) -> Result<Box<dyn ByteStream>> {
54 let host = self.target_host.as_bytes();
57 let host_len = u8::try_from(host.len())
58 .ok()
59 .filter(|len| *len > 0)
60 .ok_or_else(|| Error::Socks5(format!("invalid host length: {}", host.len())))?;
61
62 stream.write_all(&[SOCKS5_VERSION, 1, NO_AUTH]).await?;
64 stream.flush().await?;
65
66 let mut resp = [0u8; 2];
68 stream.read_exact(&mut resp).await?;
69 if resp[0] != SOCKS5_VERSION || resp[1] != NO_AUTH {
70 return Err(Error::Socks5("server rejected auth method".into()));
71 }
72
73 let port = self.target_port.to_be_bytes();
75
76 let mut req = vec![SOCKS5_VERSION, CMD_CONNECT, 0x00];
77 if let Ok(ip) = self.target_host.parse::<Ipv4Addr>() {
78 req.push(ATYPE_IPV4);
79 req.extend_from_slice(&ip.octets());
80 } else if let Ok(ip) = self.target_host.parse::<Ipv6Addr>() {
81 req.push(ATYPE_IPV6);
82 req.extend_from_slice(&ip.octets());
83 } else {
84 req.push(ATYPE_DOMAIN);
85 req.push(host_len);
86 req.extend_from_slice(host);
87 }
88 req.extend_from_slice(&port);
89
90 stream.write_all(&req).await?;
91 stream.flush().await?;
92
93 let mut reply = [0u8; 4];
95 stream.read_exact(&mut reply).await?;
96 if reply[0] != SOCKS5_VERSION {
97 return Err(Error::Socks5("invalid reply version".into()));
98 }
99 if reply[1] != REPLY_SUCCESS {
100 return Err(Error::Socks5(format!("connect failed (code {})", reply[1])));
101 }
102
103 match reply[3] {
105 ATYPE_IPV4 => {
106 let mut skip = [0u8; 4 + 2]; stream.read_exact(&mut skip).await?;
108 }
109 ATYPE_DOMAIN => {
110 let mut len = [0u8; 1];
111 stream.read_exact(&mut len).await?;
112 let mut skip = vec![0u8; len[0] as usize + 2];
113 stream.read_exact(&mut skip).await?;
114 }
115 ATYPE_IPV6 => {
116 let mut skip = [0u8; 16 + 2];
117 stream.read_exact(&mut skip).await?;
118 }
119 atype => {
120 return Err(Error::Socks5(format!(
121 "unknown address type in reply: {atype:#x}"
122 )));
123 }
124 }
125
126 Ok(stream)
127 }
128}