1#[cfg(feature = "tokio")]
2use crate::protocol::AsyncStreamOperation;
3use crate::protocol::StreamOperation;
4use bytes::BufMut;
5use std::{
6 io::Cursor,
7 net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr, ToSocketAddrs},
8};
9#[cfg(feature = "tokio")]
10use tokio::io::{AsyncRead, AsyncReadExt};
11
12#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd, Default)]
13#[repr(u8)]
14pub enum AddressType {
15 #[default]
16 IPv4 = 0x01,
17 Domain = 0x03,
18 IPv6 = 0x04,
19}
20
21impl TryFrom<u8> for AddressType {
22 type Error = std::io::Error;
23 fn try_from(code: u8) -> core::result::Result<Self, Self::Error> {
24 let err = format!("Unsupported address type code {code:#x}");
25 match code {
26 0x01 => Ok(AddressType::IPv4),
27 0x03 => Ok(AddressType::Domain),
28 0x04 => Ok(AddressType::IPv6),
29 _ => Err(std::io::Error::new(std::io::ErrorKind::InvalidInput, err)),
30 }
31 }
32}
33
34impl From<AddressType> for u8 {
35 fn from(addr_type: AddressType) -> Self {
36 match addr_type {
37 AddressType::IPv4 => 0x01,
38 AddressType::Domain => 0x03,
39 AddressType::IPv6 => 0x04,
40 }
41 }
42}
43
44#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
54#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
55pub enum Address {
56 SocketAddress(SocketAddr),
58 DomainAddress(Box<str>, u16),
60}
61
62impl Default for Address {
63 fn default() -> Self {
64 Address::unspecified()
65 }
66}
67
68impl Address {
69 pub fn unspecified() -> Self {
71 Address::SocketAddress(SocketAddr::from((Ipv4Addr::UNSPECIFIED, 0)))
72 }
73
74 pub fn get_type(&self) -> AddressType {
76 match self {
77 Self::SocketAddress(SocketAddr::V4(_)) => AddressType::IPv4,
78 Self::SocketAddress(SocketAddr::V6(_)) => AddressType::IPv6,
79 Self::DomainAddress(_, _) => AddressType::Domain,
80 }
81 }
82
83 pub fn port(&self) -> u16 {
85 match self {
86 Self::SocketAddress(addr) => addr.port(),
87 Self::DomainAddress(_, port) => *port,
88 }
89 }
90
91 pub fn domain(&self) -> String {
93 match self {
94 Self::SocketAddress(addr) => addr.ip().to_string(),
95 Self::DomainAddress(addr, _) => addr.to_string(),
96 }
97 }
98
99 pub fn is_ipv4(&self) -> bool {
101 matches!(self, Self::SocketAddress(SocketAddr::V4(_)))
102 }
103
104 pub fn is_ipv6(&self) -> bool {
106 matches!(self, Self::SocketAddress(SocketAddr::V6(_)))
107 }
108
109 pub fn is_domain(&self) -> bool {
111 matches!(self, Self::DomainAddress(_, _))
112 }
113
114 pub const fn max_serialized_len() -> usize {
116 1 + 1 + u8::MAX as usize + 2
117 }
118}
119
120impl StreamOperation for Address {
121 fn retrieve_from_stream<R: std::io::Read>(stream: &mut R) -> std::io::Result<Self> {
122 let mut atyp_buf = [0; 1];
123 stream.read_exact(&mut atyp_buf)?;
124 match AddressType::try_from(atyp_buf[0])? {
125 AddressType::IPv4 => {
126 let mut buf = [0; 6];
127 stream.read_exact(&mut buf)?;
128 let addr = Ipv4Addr::new(buf[0], buf[1], buf[2], buf[3]);
129 let port = u16::from_be_bytes([buf[4], buf[5]]);
130 Ok(Self::SocketAddress(SocketAddr::from((addr, port))))
131 }
132 AddressType::Domain => {
133 let mut len_buf = [0; 1];
134 stream.read_exact(&mut len_buf)?;
135 let len = len_buf[0] as usize;
136 let mut domain_buf = vec![0; len];
137 stream.read_exact(&mut domain_buf)?;
138
139 let mut port_buf = [0; 2];
140 stream.read_exact(&mut port_buf)?;
141 let port = u16::from_be_bytes(port_buf);
142
143 let addr = String::from_utf8(domain_buf)
144 .map_err(|err| std::io::Error::new(std::io::ErrorKind::InvalidData, format!("Invalid address encoding: {err}")))?;
145 Ok(Self::DomainAddress(addr.into_boxed_str(), port))
146 }
147 AddressType::IPv6 => {
148 let mut buf = [0; 18];
149 stream.read_exact(&mut buf)?;
150 let port = u16::from_be_bytes([buf[16], buf[17]]);
151 let mut addr_bytes = [0; 16];
152 addr_bytes.copy_from_slice(&buf[..16]);
153 Ok(Self::SocketAddress(SocketAddr::from((Ipv6Addr::from(addr_bytes), port))))
154 }
155 }
156 }
157
158 fn write_to_buf<B: BufMut>(&self, buf: &mut B) {
159 match self {
160 Self::SocketAddress(SocketAddr::V4(addr)) => {
161 buf.put_u8(AddressType::IPv4.into());
162 buf.put_slice(&addr.ip().octets());
163 buf.put_u16(addr.port());
164 }
165 Self::SocketAddress(SocketAddr::V6(addr)) => {
166 buf.put_u8(AddressType::IPv6.into());
167 buf.put_slice(&addr.ip().octets());
168 buf.put_u16(addr.port());
169 }
170 Self::DomainAddress(addr, port) => {
171 let addr = addr.as_bytes();
172 buf.put_u8(AddressType::Domain.into());
173 buf.put_u8(u8::try_from(addr.len()).expect("domain address too long for SOCKS5"));
174 buf.put_slice(addr);
175 buf.put_u16(*port);
176 }
177 }
178 }
179
180 fn len(&self) -> usize {
181 match self {
182 Address::SocketAddress(SocketAddr::V4(_)) => 1 + 4 + 2,
183 Address::SocketAddress(SocketAddr::V6(_)) => 1 + 16 + 2,
184 Address::DomainAddress(addr, _) => 1 + 1 + addr.len() + 2,
185 }
186 }
187}
188
189#[cfg(feature = "tokio")]
190#[async_trait::async_trait]
191impl AsyncStreamOperation for Address {
192 async fn retrieve_from_async_stream<R>(stream: &mut R) -> std::io::Result<Self>
193 where
194 R: AsyncRead + Unpin + Send + ?Sized,
195 {
196 let atyp = stream.read_u8().await?;
197 match AddressType::try_from(atyp)? {
198 AddressType::IPv4 => {
199 let mut addr_bytes = [0; 4];
200 stream.read_exact(&mut addr_bytes).await?;
201 let port = stream.read_u16().await?;
202 let addr = Ipv4Addr::from(addr_bytes);
203 Ok(Self::SocketAddress(SocketAddr::from((addr, port))))
204 }
205 AddressType::Domain => {
206 let len = stream.read_u8().await? as usize;
207 let mut domain_buf = vec![0; len];
208 stream.read_exact(&mut domain_buf).await?;
209 let port = stream.read_u16().await?;
210
211 let addr = String::from_utf8(domain_buf)
212 .map_err(|err| std::io::Error::new(std::io::ErrorKind::InvalidData, format!("Invalid address encoding: {err}")))?;
213 Ok(Self::DomainAddress(addr.into_boxed_str(), port))
214 }
215 AddressType::IPv6 => {
216 let mut addr_bytes = [0; 16];
217 stream.read_exact(&mut addr_bytes).await?;
218 let port = stream.read_u16().await?;
219 Ok(Self::SocketAddress(SocketAddr::from((Ipv6Addr::from(addr_bytes), port))))
220 }
221 }
222 }
223}
224
225impl ToSocketAddrs for Address {
226 type Iter = std::vec::IntoIter<SocketAddr>;
227
228 fn to_socket_addrs(&self) -> std::io::Result<Self::Iter> {
229 match self {
230 Address::SocketAddress(addr) => Ok(vec![*addr].into_iter()),
231 Address::DomainAddress(addr, port) => Ok((&**addr, *port).to_socket_addrs()?),
232 }
233 }
234}
235
236impl std::fmt::Display for Address {
237 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
238 match self {
239 Address::DomainAddress(hostname, port) => write!(f, "{hostname}:{port}"),
240 Address::SocketAddress(socket_addr) => write!(f, "{socket_addr}"),
241 }
242 }
243}
244
245impl TryFrom<Address> for SocketAddr {
246 type Error = std::io::Error;
247
248 fn try_from(address: Address) -> std::result::Result<Self, Self::Error> {
249 match address {
250 Address::SocketAddress(addr) => Ok(addr),
251 Address::DomainAddress(addr, port) => {
252 let addr = addr.as_ref();
253 if let Ok(addr) = addr.parse::<IpAddr>() {
254 Ok(SocketAddr::from((addr, port)))
255 } else {
256 let err = format!("domain address {addr} cannot be converted to a SocketAddr without DNS, use ToSocketAddrs instead");
257 Err(std::io::Error::new(std::io::ErrorKind::InvalidInput, err))
258 }
259 }
260 }
261 }
262}
263
264impl TryFrom<&Address> for SocketAddr {
265 type Error = std::io::Error;
266
267 fn try_from(address: &Address) -> std::result::Result<Self, Self::Error> {
268 TryFrom::<Address>::try_from(address.clone())
269 }
270}
271
272impl From<Address> for Vec<u8> {
273 fn from(addr: Address) -> Self {
274 let mut buf = Vec::with_capacity(addr.len());
275 addr.write_to_buf(&mut buf);
276 buf
277 }
278}
279
280impl TryFrom<Vec<u8>> for Address {
281 type Error = std::io::Error;
282
283 fn try_from(data: Vec<u8>) -> std::result::Result<Self, Self::Error> {
284 let mut rdr = Cursor::new(data);
285 Self::retrieve_from_stream(&mut rdr)
286 }
287}
288
289impl TryFrom<&[u8]> for Address {
290 type Error = std::io::Error;
291
292 fn try_from(data: &[u8]) -> std::result::Result<Self, Self::Error> {
293 let mut rdr = Cursor::new(data);
294 Self::retrieve_from_stream(&mut rdr)
295 }
296}
297
298impl From<SocketAddr> for Address {
299 fn from(addr: SocketAddr) -> Self {
300 Address::SocketAddress(addr)
301 }
302}
303
304impl From<&SocketAddr> for Address {
305 fn from(addr: &SocketAddr) -> Self {
306 Address::SocketAddress(*addr)
307 }
308}
309
310impl From<(Ipv4Addr, u16)> for Address {
311 fn from((addr, port): (Ipv4Addr, u16)) -> Self {
312 Address::SocketAddress(SocketAddr::from((addr, port)))
313 }
314}
315
316impl From<(Ipv6Addr, u16)> for Address {
317 fn from((addr, port): (Ipv6Addr, u16)) -> Self {
318 Address::SocketAddress(SocketAddr::from((addr, port)))
319 }
320}
321
322impl From<(IpAddr, u16)> for Address {
323 fn from((addr, port): (IpAddr, u16)) -> Self {
324 Address::SocketAddress(SocketAddr::from((addr, port)))
325 }
326}
327
328impl From<(String, u16)> for Address {
329 fn from((addr, port): (String, u16)) -> Self {
330 Address::from((addr.as_str(), port))
331 }
332}
333
334impl From<(&String, u16)> for Address {
335 fn from((addr, port): (&String, u16)) -> Self {
336 Address::from((addr.as_str(), port))
337 }
338}
339
340impl From<(&str, u16)> for Address {
341 fn from((addr, port): (&str, u16)) -> Self {
342 if let Ok(addr) = addr.parse::<IpAddr>() {
343 return Address::SocketAddress(SocketAddr::from((addr, port)));
344 }
345 Address::DomainAddress(addr.into(), port)
346 }
347}
348
349impl From<&Address> for Address {
350 fn from(addr: &Address) -> Self {
351 addr.clone()
352 }
353}
354
355impl TryFrom<&str> for Address {
356 type Error = crate::Error;
357
358 fn try_from(addr: &str) -> std::result::Result<Self, Self::Error> {
359 if let Ok(addr) = addr.parse::<SocketAddr>() {
360 Ok(Address::SocketAddress(addr))
361 } else {
362 if addr.matches(':').count() > 1 {
363 let err = format!("invalid socket address format: {addr}");
364 return Err(crate::Error::InvalidAddress(err));
365 }
366
367 let Some(pos) = addr.rfind(':') else {
368 let err = format!("missing port in address: {addr}");
369 return Err(crate::Error::InvalidAddress(err));
370 };
371
372 let (addr, port) = (&addr[..pos], &addr[pos + 1..]);
373 let port = port.parse::<u16>()?;
374 Ok(Address::from((addr, port)))
375 }
376 }
377}
378
379impl std::str::FromStr for Address {
380 type Err = crate::Error;
381
382 fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
383 Self::try_from(s)
384 }
385}
386
387#[test]
388fn test_address() {
389 let addr = Address::from((Ipv4Addr::new(127, 0, 0, 1), 8080));
390 let mut buf = Vec::new();
391 addr.write_to_buf(&mut buf);
392 assert_eq!(buf, vec![0x01, 127, 0, 0, 1, 0x1f, 0x90]);
393 let addr2 = Address::retrieve_from_stream(&mut Cursor::new(&buf)).unwrap();
394 assert_eq!(addr, addr2);
395
396 let addr = Address::from((Ipv6Addr::new(0x45, 0xff89, 0, 0, 0, 0, 0, 1), 8080));
397 let mut buf = Vec::new();
398 addr.write_to_buf(&mut buf);
399 assert_eq!(buf, vec![0x04, 0, 0x45, 0xff, 0x89, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0x1f, 0x90]);
400 let addr2 = Address::retrieve_from_stream(&mut Cursor::new(&buf)).unwrap();
401 assert_eq!(addr, addr2);
402
403 let addr = Address::from(("sex.com", 8080));
404 let mut buf = Vec::new();
405 addr.write_to_buf(&mut buf);
406 assert_eq!(buf, vec![0x03, 0x07, b's', b'e', b'x', b'.', b'c', b'o', b'm', 0x1f, 0x90]);
407 let addr2 = Address::retrieve_from_stream(&mut Cursor::new(&buf)).unwrap();
408 assert_eq!(addr, addr2);
409
410 let addr = Address::try_from("example.com:8080").unwrap();
411 assert_eq!(addr.domain(), "example.com");
412 assert!(Address::try_from("example.com").is_err());
413
414 let addr = Address::try_from("123.45.67.89:8080").unwrap();
415 assert!(addr.is_ipv4());
416 assert!(Address::try_from("123.45.67.89").is_err());
417
418 let addr = Address::try_from("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:8080").unwrap();
419 assert_eq!(addr.domain(), "2001:db8:85a3::8a2e:370:7334");
420 assert!(addr.is_ipv6());
421
422 assert!(Address::try_from("2001:0db8:85a3:0000:0000:8a2e:0370:7334:8080").is_err());
423}
424
425#[test]
426fn test_try_from_address_for_socketaddr() {
427 let addr = Address::from((Ipv4Addr::new(127, 0, 0, 1), 8080));
428 let socket_addr = SocketAddr::try_from(addr.clone()).unwrap();
429 assert_eq!(socket_addr, SocketAddr::from(([127, 0, 0, 1], 8080)));
430
431 let addr = Address::from(("192.168.1.1", 8080));
432 let socket_addr = SocketAddr::try_from(addr).unwrap();
433 assert_eq!(socket_addr, SocketAddr::from(([192, 168, 1, 1], 8080)));
434
435 let addr = Address::from(("example.com", 8080));
436 let err = SocketAddr::try_from(addr).unwrap_err();
437 assert!(format!("{err}").contains("cannot be converted to a SocketAddr without DNS"));
438
439 let addr = Address::from(("baidu.com", 8080));
440 let err = SocketAddr::try_from(addr).unwrap_err();
441 assert!(format!("{err}").contains("cannot be converted to a SocketAddr without DNS"));
442
443 let addr = Address::from(("baidu.com", 8080));
444 let socket_addrs: Vec<SocketAddr> = addr.to_socket_addrs().unwrap().collect();
445 assert!(!socket_addrs.is_empty());
446}
447
448#[cfg(feature = "tokio")]
449#[tokio::test]
450async fn test_address_async() {
451 let addr = Address::from((Ipv4Addr::new(127, 0, 0, 1), 8080));
452 let mut buf = Vec::new();
453 addr.write_to_async_stream(&mut buf).await.unwrap();
454 assert_eq!(buf, vec![0x01, 127, 0, 0, 1, 0x1f, 0x90]);
455 let addr2 = Address::retrieve_from_async_stream(&mut Cursor::new(&buf)).await.unwrap();
456 assert_eq!(addr, addr2);
457
458 let addr = Address::from((Ipv6Addr::new(0x45, 0xff89, 0, 0, 0, 0, 0, 1), 8080));
459 let mut buf = Vec::new();
460 addr.write_to_async_stream(&mut buf).await.unwrap();
461 assert_eq!(buf, vec![0x04, 0, 0x45, 0xff, 0x89, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0x1f, 0x90]);
462 let addr2 = Address::retrieve_from_async_stream(&mut Cursor::new(&buf)).await.unwrap();
463 assert_eq!(addr, addr2);
464
465 let addr = Address::from(("sex.com", 8080));
466 let mut buf = Vec::new();
467 addr.write_to_async_stream(&mut buf).await.unwrap();
468 assert_eq!(buf, vec![0x03, 0x07, b's', b'e', b'x', b'.', b'c', b'o', b'm', 0x1f, 0x90]);
469 let addr2 = Address::retrieve_from_async_stream(&mut Cursor::new(&buf)).await.unwrap();
470 assert_eq!(addr, addr2);
471}