zeloxy 0.4.0

A library for creating lightweight, async, and lag-free proxy connections.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
use std::sync::Arc;
use std::time::Duration;

use tokio::net::TcpStream;

#[cfg(feature = "https")]
use rustls::pki_types::ServerName;
#[cfg(feature = "https")]
use rustls::{ClientConfig, RootCertStore};
#[cfg(feature = "https")]
use tokio_rustls::TlsConnector;
#[cfg(feature = "https")]
use tokio_rustls::client::TlsStream;
#[cfg(feature = "https")]
use webpki_roots::TLS_SERVER_ROOTS;

use crate::connect::*;
use crate::connection::ProxyConnection;
use crate::validate_proxy_str;
use crate::{ErrorKind, ProxyAuth, ProxyError, ProxyResult};

/// Структура прокси.
///
/// Поддерживаемые протоколы прокси:
///
/// - **HTTP** (без авторизации / с базовой авторизацией)
/// - **HTTPS** (без авторизации / с базовой авторизацией)
/// - **SOCKS4** (без авторизации / с `ident` авторизацией)
/// - **SOCKS5** (без авторизации / с `user / pass` авторизацией)
///
/// ## Примеры
///
/// ```rust, ignore
/// use tokio::io::{AsyncReadExt, AsyncWriteExt};
/// use zeloxy::{Proxy, ProxyResult, ProxyProtocol};
///
/// #[tokio::main]
/// async fn main() -> std::io::Result<()> {
///   // Создаём HTTP-прокси и задаём адрес целевого сервера
///   let proxy = Proxy::new("91.132.92.231:80", ProxyProtocol::Http);
///
///   match proxy.connect("example.com", 80).await {
///     ProxyResult::Ok(mut conn) => {
///       // Отправляем GET-запрос
///       conn.write_all(b"GET / HTTP/1.0\r\nHost: example.com\r\n\r\n").await?;
///
///       // Читаем ответ
///       let mut resp = Vec::new();
///       conn.read_to_end(&mut resp).await?;
///     
///       // Логгируем ответ
///       println!("{}", String::from_utf8_lossy(&resp));
///     },
///     ProxyResult::Err(_) => {}, // Просто игнорируем ошибки
///   }
///
///   Ok(())
/// }
/// ```
///
/// Больше актуальных примеров: [смотреть](https://codeberg.org/nullclyze/zeloxy/src/branch/main/examples)
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Proxy {
  addr: String,
  protocol: ProxyProtocol,
  timeout: u64,
  auth: Option<ProxyAuth>,
}

/// Функция получения прокси по умолчанию опираясь на включенные фичи
#[allow(unused)]
fn default_proxy() -> Proxy {
  #[cfg(feature = "http")]
  return Proxy::new("127.0.0.1:80", ProxyProtocol::Http);
  #[cfg(feature = "https")]
  return Proxy::new("127.0.0.1:443", ProxyProtocol::Https);
  #[cfg(feature = "socks4")]
  return Proxy::new("127.0.0.1:4145", ProxyProtocol::Socks4);
  #[cfg(feature = "socks5")]
  return Proxy::new("127.0.0.1:1080", ProxyProtocol::Socks5);
}

/// Протокол прокси
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ProxyProtocol {
  #[cfg(feature = "http")]
  Http,

  #[cfg(feature = "https")]
  Https,

  #[cfg(feature = "socks4")]
  Socks4,

  #[cfg(feature = "socks5")]
  Socks5,
}

impl ProxyProtocol {
  /// Метод получения порта по умолчанию для текущего протокола
  pub fn default_port(&self) -> u16 {
    match self {
      #[cfg(feature = "http")]
      Self::Http => 80,
      #[cfg(feature = "https")]
      Self::Https => 443,
      #[cfg(feature = "socks4")]
      Self::Socks4 => 4145,
      #[cfg(feature = "socks5")]
      Self::Socks5 => 1080,
    }
  }
}

impl From<&str> for ProxyProtocol {
  fn from(value: &str) -> Self {
    match value {
      "http" => Self::Http,
      #[cfg(feature = "https")]
      "https" => Self::Https,
      "socks4" => Self::Socks4,
      "socks5" => Self::Socks5,
      #[cfg(not(feature = "https"))]
      "https" => Self::Http,
      _ => Self::Socks5,
    }
  }
}

impl From<String> for ProxyProtocol {
  fn from(value: String) -> Self {
    Self::from(value.as_str())
  }
}

impl Proxy {
  /// Метод создания нового прокси
  pub fn new(addr: impl Into<String>, protocol: impl Into<ProxyProtocol>) -> Self {
    Self {
      addr: addr.into(),
      protocol: protocol.into(),
      timeout: 20000,
      auth: None,
    }
  }

  /// Метод создания нового прокси с авторизацией
  pub fn new_with_auth(addr: impl Into<String>, protocol: impl Into<ProxyProtocol>, auth: impl Into<ProxyAuth>) -> Self {
    Self {
      addr: addr.into(),
      protocol: protocol.into(),
      timeout: 20000,
      auth: Some(auth.into()),
    }
  }

  /// Метод установки авторизации прокси
  pub fn with_auth(mut self, auth: impl Into<ProxyAuth>) -> Self {
    self.auth = Some(auth.into());
    self
  }

  /// Метод установки таймаута подключения к прокси
  pub fn with_timeout(mut self, timeout: u64) -> Self {
    self.timeout = timeout;
    self
  }

  /// Метод установки протокола прокси
  pub fn with_protocol(mut self, protocol: impl Into<ProxyProtocol>) -> Self {
    self.protocol = protocol.into();
    self
  }

  /// Метод попытки создания соединения с прокси
  pub async fn is_available(&self) -> bool {
    match tokio::time::timeout(Duration::from_millis(self.timeout), TcpStream::connect(&self.addr)).await {
      Ok(result) => match result {
        Ok(_) => return true,
        Err(_) => return false,
      },
      Err(_) => return false,
    }
  }

  /// Метод получения протокола прокси
  #[deprecated = "method was renamed, use `.protocol()`"]
  pub fn get_protocol(&self) -> &ProxyProtocol {
    &self.protocol
  }

  /// Метод получения IP прокси
  #[deprecated = "method was renamed, use `.ip()`"]
  pub fn get_ip(&self) -> String {
    self.addr.split(":").collect::<Vec<&str>>()[0].to_string()
  }

  /// Метод получения порта прокси
  #[deprecated = "method was renamed, use `.port()`"]
  pub fn get_port(&self) -> u16 {
    let port_str = self.addr.split(":").collect::<Vec<&str>>()[1];
    port_str.parse::<u16>().unwrap_or(self.protocol.default_port())
  }

  /// Метод получения адреса прокси в формате `IP:PORT`
  #[deprecated = "method was renamed, use `.addr()`"]
  pub fn get_address(&self) -> &str {
    &self.addr
  }

  /// Метод получения полного адреса прокси в формате `PROTOCOL://IP:PORT`
  #[deprecated = "method was renamed, use `.full_addr()`"]
  pub fn get_full_address(&self) -> String {
    let protocol = match self.protocol {
      #[cfg(feature = "http")]
      ProxyProtocol::Http => "http",
      #[cfg(feature = "https")]
      ProxyProtocol::Https => "https",
      #[cfg(feature = "socks4")]
      ProxyProtocol::Socks4 => "socks4",
      #[cfg(feature = "socks5")]
      ProxyProtocol::Socks5 => "socks5",
    };

    format!("{}://{}", protocol, self.addr)
  }

  /// Метод получения протокола прокси
  pub fn protocol(&self) -> &ProxyProtocol {
    &self.protocol
  }

  /// Метод получения IP прокси
  pub fn ip(&self) -> String {
    self.addr.split(":").collect::<Vec<&str>>()[0].to_string()
  }

  /// Метод получения порта прокси
  pub fn port(&self) -> u16 {
    let port_str = self.addr.split(":").collect::<Vec<&str>>()[1];
    port_str.parse::<u16>().unwrap_or(self.protocol.default_port())
  }

  /// Метод получения адреса прокси в формате `IP:PORT`
  pub fn addr(&self) -> &str {
    &self.addr
  }

  /// Метод получения полного адреса прокси в формате `PROTOCOL://IP:PORT`
  pub fn full_addr(&self) -> String {
    let protocol = match self.protocol {
      #[cfg(feature = "http")]
      ProxyProtocol::Http => "http",
      #[cfg(feature = "https")]
      ProxyProtocol::Https => "https",
      #[cfg(feature = "socks4")]
      ProxyProtocol::Socks4 => "socks4",
      #[cfg(feature = "socks5")]
      ProxyProtocol::Socks5 => "socks5",
    };

    format!("{}://{}", protocol, self.addr)
  }

  /// Метод установки TCP-соединения
  async fn connect_tcp(&self) -> ProxyResult<TcpStream> {
    match tokio::time::timeout(Duration::from_millis(self.timeout), TcpStream::connect(&self.addr)).await {
      Ok(result) => match result {
        Ok(s) => Ok(s),
        Err(_) => Err(ProxyError::new(ErrorKind::NotConnected, "could not connect to specified server")),
      },
      Err(_) => Err(ProxyError::new(
        ErrorKind::Timeout,
        "failed to connect to server within specified time",
      )),
    }
  }

  /// Функция установки TLS-соединения
  #[cfg(feature = "https")]
  async fn connect_tls(&self) -> ProxyResult<TlsStream<TcpStream>> {
    let tcp_stream = self.connect_tcp().await?;
    let server_name = if let Ok(ip) = self.ip().parse::<std::net::IpAddr>() {
      ServerName::IpAddress(ip.into())
    } else {
      ServerName::try_from(self.ip()).map_err(|_| ProxyError::new(ErrorKind::InvalidData, "invalid proxy server name"))?
    };

    let mut root_store = RootCertStore::empty();
    root_store.extend(TLS_SERVER_ROOTS.iter().cloned());

    let config = ClientConfig::builder().with_root_certificates(root_store).with_no_client_auth();

    let connector = TlsConnector::from(Arc::new(config));

    connector
      .connect(server_name, tcp_stream)
      .await
      .map_err(|e| ProxyError::new(ErrorKind::NotConnected, format!("TLS handshake with proxy failed: {}", e)))
  }

  /// Метод подключения к прокси
  pub async fn connect(&self, target_host: impl Into<String>, target_port: u16) -> ProxyResult<ProxyConnection> {
    let target_host = target_host.into();

    match self.protocol {
      #[cfg(feature = "https")]
      ProxyProtocol::Https => {
        let mut stream = self.connect_tls().await?;
        connect_https(&mut stream, target_host, target_port, &self.auth).await?;
        Ok(ProxyConnection::Tls(stream))
      }
      _ => {
        let mut stream = self.connect_tcp().await?;

        match self.protocol {
          #[cfg(feature = "http")]
          ProxyProtocol::Http => connect_http(&mut stream, target_host, target_port, &self.auth).await?,
          #[cfg(feature = "socks5")]
          ProxyProtocol::Socks5 => connect_socks5(&mut stream, target_host, target_port, &self.auth).await?,
          #[cfg(feature = "socks4")]
          ProxyProtocol::Socks4 => connect_socks4(&mut stream, target_host, target_port, &self.auth).await?,
          #[allow(unreachable_patterns)]
          _ => {}
        }

        Ok(ProxyConnection::Tcp(stream))
      }
    }
  }

  /// Метод подключения к прокси с ранее созданным TCP-соединением
  pub async fn connect_with_stream(&self, stream: &mut TcpStream, target_host: impl Into<String>, target_port: u16) -> ProxyResult<()> {
    match self.protocol {
      #[cfg(feature = "http")]
      ProxyProtocol::Http => connect_http(stream, target_host.into(), target_port, &self.auth).await?,
      #[cfg(feature = "https")]
      ProxyProtocol::Https => {
        return Err(ProxyError::new(
          ErrorKind::Unsupported,
          "this method does not support the HTTPS protocol",
        ));
      }
      #[cfg(feature = "socks4")]
      ProxyProtocol::Socks4 => connect_socks4(stream, target_host.into(), target_port, &self.auth).await?,
      #[cfg(feature = "socks5")]
      ProxyProtocol::Socks5 => connect_socks5(stream, target_host.into(), target_port, &self.auth).await?,
    }

    Ok(())
  }
}

impl From<String> for Proxy {
  fn from(value: String) -> Self {
    if !validate_proxy_str(&value) {
      return default_proxy();
    }

    let proxy_split = value.split("://").collect::<Vec<&str>>();
    let without_protocol = proxy_split[1].split("@").collect::<Vec<&str>>();

    let (protocol, possible_auth, addr) = {
      if without_protocol.len() == 2 {
        (proxy_split[0], Some(without_protocol[0]), without_protocol[1])
      } else {
        (proxy_split[0], None, without_protocol[0])
      }
    };

    if let Some(auth) = possible_auth {
      Self::new_with_auth(addr, protocol, auth)
    } else {
      Self::new(addr, protocol)
    }
  }
}

impl From<&str> for Proxy {
  fn from(value: &str) -> Self {
    if !validate_proxy_str(value) {
      return default_proxy();
    }

    let proxy_split = value.split("://").collect::<Vec<&str>>();
    let without_protocol = proxy_split[1].split("@").collect::<Vec<&str>>();

    let (protocol, possible_auth, addr) = {
      if without_protocol.len() == 2 {
        (proxy_split[0], Some(without_protocol[0]), without_protocol[1])
      } else {
        (proxy_split[0], None, without_protocol[0])
      }
    };

    if let Some(auth) = possible_auth {
      Self::new_with_auth(addr, protocol, auth)
    } else {
      Self::new(addr, protocol)
    }
  }
}

impl From<Arc<Proxy>> for Proxy {
  fn from(value: Arc<Proxy>) -> Self {
    Self {
      addr: value.addr.clone(),
      protocol: value.protocol.clone(),
      timeout: value.timeout,
      auth: value.auth.clone(),
    }
  }
}