nurtex-proxy 1.1.0

Library for creating connections via SOCKS5 / SOCKS4 proxy.
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
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
use std::sync::Arc;
use std::time::Duration;

use bytes::{BufMut, BytesMut};
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::TcpStream;
use tokio::sync::RwLock;
use tokio::time::timeout;

use crate::ProxyAuth;
use crate::error::{ErrorName, ProxyError};
use crate::result::ProxyResult;

/// Структура SOCKS5 / SOCKS4 прокси.
///
/// ## Примеры
///
/// ```rust, ignore
/// use nurtex_proxy::{Proxy, ProxyAuth, ProxyType};
///
/// // Пример SOCKS5 прокси без авторизации
/// let proxy = Proxy::new("PROXY_IP:PROXY_PORT", ProxyType::Socks5);
///
/// // Пример SOCKS5 с авторизацией
/// let auth = ProxyAuth::new("USERNAME", "PASSWORD");
/// let proxy = Proxy::new_with_auth("PROXY_IP:PROXY_PORT", ProxyType::Socks5, auth);
///
/// // Пример SOCKS4 с авторизацией
/// let auth = ProxyAuth::new("USER_ID", ""); // В SOCKS4 не используется пароль
/// let proxy = Proxy::new_with_auth("PROXY_IP:PROXY_PORT", ProxyType::Socks4, auth);
/// ```
#[derive(Debug, Clone)]
pub struct Proxy {
  proxy_type: ProxyType,
  proxy_address: String,
  target: Arc<RwLock<TargetServer>>,
  timeout: u64,
  auth: Option<ProxyAuth>,
}

/// Тип прокси
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ProxyType {
  Socks5,
  Socks4,
}

/// Структура адреса целевого сервера
#[derive(Debug, Clone, PartialEq, Eq)]
struct TargetServer {
  host: Option<String>,
  port: Option<u16>,
}

impl Default for TargetServer {
  fn default() -> Self {
    Self { host: None, port: None }
  }
}

/// Вспомогательная функция записи данных в поток
async fn write_all_to(stream: &mut TcpStream, buffer: Vec<u8>) -> ProxyResult<()> {
  match timeout(Duration::from_secs(10), stream.write_all(&buffer)).await {
    Ok(result) => match result {
      Ok(_) => ProxyResult::Ok(()),
      Err(e) => ProxyResult::Err(ProxyError::new(ErrorName::StreamError, e.to_string())),
    },
    Err(_) => ProxyResult::Err(ProxyError::new(ErrorName::StreamError, "failed to write buffer to stream")),
  }
}

/// Вспомогательная функция чтения данных из потока
async fn read_exact_from<'a>(stream: &mut TcpStream, buffer: &'a mut [u8]) -> ProxyResult<()> {
  match timeout(Duration::from_secs(10), stream.read_exact(buffer)).await {
    Ok(result) => match result {
      Ok(_) => ProxyResult::Ok(()),
      Err(e) => ProxyResult::Err(ProxyError::new(ErrorName::StreamError, e.to_string())),
    },
    Err(_) => ProxyResult::Err(ProxyError::new(ErrorName::StreamError, "failed to read buffer from stream")),
  }
}

impl From<String> for Proxy {
  fn from(value: String) -> Self {
    let split = value.split("://").collect::<Vec<&str>>();
    let (protocol, proxy) = (split.get(0).unwrap_or(&"socks5"), split.get(1).unwrap_or(&"127.0.0.1"));

    Self {
      proxy_address: (*proxy).to_string(),
      proxy_type: match *protocol {
        "socks5" => ProxyType::Socks5,
        "socks4" => ProxyType::Socks4,
        _ => ProxyType::Socks5,
      },
      target: Arc::new(RwLock::new(TargetServer::default())),
      timeout: 20000,
      auth: None,
    }
  }
}

impl From<&str> for Proxy {
  fn from(value: &str) -> Self {
    let split = value.split("://").collect::<Vec<&str>>();
    let (protocol, proxy) = (split.get(0).unwrap_or(&"socks5"), split.get(1).unwrap_or(&"127.0.0.1"));

    Self {
      proxy_address: (*proxy).to_string(),
      proxy_type: match *protocol {
        "socks5" => ProxyType::Socks5,
        "socks4" => ProxyType::Socks4,
        _ => ProxyType::Socks5,
      },
      target: Arc::new(RwLock::new(TargetServer::default())),
      timeout: 20000,
      auth: None,
    }
  }
}

impl Proxy {
  /// Метод создания нового прокси
  pub fn new(proxy_address: impl Into<String>, proxy_type: ProxyType) -> Self {
    Self {
      proxy_address: proxy_address.into(),
      proxy_type: proxy_type,
      target: Arc::new(RwLock::new(TargetServer::default())),
      timeout: 20000,
      auth: None,
    }
  }

  /// Метод создания нового прокси с авторизацией
  pub fn new_with_auth(proxy_address: impl Into<String>, proxy_type: ProxyType, auth: ProxyAuth) -> Self {
    Self {
      proxy_address: proxy_address.into(),
      proxy_type: proxy_type,
      target: Arc::new(RwLock::new(TargetServer::default())),
      timeout: 20000,
      auth: Some(auth),
    }
  }

  /// Метод установки адреса целевого сервера
  pub fn bind(&self, target_host: String, target_port: u16) {
    match self.target.try_write() {
      Ok(mut g) => {
        g.host = Some(target_host);
        g.port = Some(target_port);
      }
      Err(_) => {}
    }
  }

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

  /// Метод установки типа прокси
  pub fn set_proxy_type(mut self, proxy_type: ProxyType) -> Self {
    self.proxy_type = proxy_type;
    self
  }

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

  /// Метод получения IP прокси
  pub fn get_ip(&self) -> Option<String> {
    if let Some(ip) = self.proxy_address.split(":").collect::<Vec<&str>>().get(0) {
      Some(ip.to_string())
    } else {
      None
    }
  }

  /// Метод подключения к прокси
  pub async fn connect(&self) -> ProxyResult<TcpStream> {
    let (target_host, target_port) = {
      let guard = self.target.read().await;

      let Some(host) = guard.host.clone() else {
        return ProxyResult::Err(ProxyError::new(ErrorName::InvalidData, "target server host not specified"));
      };

      let Some(port) = guard.port else {
        return ProxyResult::Err(ProxyError::new(ErrorName::InvalidData, "target server port not specified"));
      };

      (host, port)
    };

    let mut stream = match timeout(Duration::from_millis(self.timeout), TcpStream::connect(&self.proxy_address)).await {
      Ok(result) => match result {
        Ok(s) => s,
        Err(_) => return ProxyResult::Err(ProxyError::new(ErrorName::NotConnected, "could not connect to specified server")),
      },
      Err(_) => return ProxyResult::Err(ProxyError::new(ErrorName::Timeout, "failed to connect to server within specified time")),
    };

    match self.proxy_type {
      ProxyType::Socks5 => self.connect_socks5(&mut stream, target_host, target_port).await?,
      ProxyType::Socks4 => self.connect_socks4(&mut stream, target_host, target_port).await?,
    }

    ProxyResult::Ok(stream)
  }

  /// Метод создания подключения с SOCKS5 прокси
  async fn connect_socks5(&self, stream: &mut TcpStream, target_host: String, target_port: u16) -> ProxyResult<()> {
    let greet = if self.auth.is_some() { vec![0x05, 0x02, 0x00, 0x02] } else { vec![0x05, 0x01, 0x00] };

    write_all_to(stream, greet).await?;

    let mut response = [0u8; 2];

    read_exact_from(stream, &mut response).await?;

    if response[0] != 0x05 {
      return ProxyResult::Err(ProxyError::new(ErrorName::InvalidVersion, "invalid response version"));
    }

    match response[1] {
      0x00 => {}
      0x02 => {
        if let Some(auth) = &self.auth {
          let username = auth.username();
          let password = auth.password();

          if username.len() > 255 || password.len() > 255 {
            return Err(ProxyError::new(ErrorName::InvalidData, "username or password is too long"));
          }

          let mut buffer = BytesMut::with_capacity(2 + username.len() + password.len());
          buffer.put_u8(0x01);
          buffer.put_u8(username.len() as u8);
          buffer.put_slice(username.as_bytes());
          buffer.put_u8(password.len() as u8);
          buffer.put_slice(password.as_bytes());

          write_all_to(stream, buffer.into()).await?;

          let mut resp = [0u8; 2];

          read_exact_from(stream, &mut resp).await?;

          if resp[0] != 0x01 {
            return Err(ProxyError::new(ErrorName::AuthFailed, "invalid authorization version"));
          }

          if resp[1] != 0x00 {
            return Err(ProxyError::new(ErrorName::AuthFailed, "authorization failed (possibly incorrect password or username)"));
          }
        } else {
          return ProxyResult::Err(ProxyError::new(ErrorName::AuthFailed, "proxy requires authorization (username, password)"));
        }
      }
      _ => return ProxyResult::Err(ProxyError::new(ErrorName::Unsupported, "unsupported authorization method")),
    }

    let mut request = BytesMut::with_capacity(512);
    request.put_u8(0x05);
    request.put_u8(0x01);
    request.put_u8(0x00);

    if let Ok(ipv4) = target_host.parse::<std::net::Ipv4Addr>() {
      request.put_u8(0x01);
      request.put_slice(&ipv4.octets());
    } else if let Ok(ipv6) = target_host.parse::<std::net::Ipv6Addr>() {
      request.put_u8(0x04);
      request.put_slice(&ipv6.octets());
    } else {
      request.put_u8(0x03);
      let host_bytes = target_host.as_bytes();

      if host_bytes.len() > 255 {
        return ProxyResult::Err(ProxyError::new(ErrorName::InvalidData, "target host is too long"));
      }

      request.put_u8(host_bytes.len() as u8);
      request.put_slice(host_bytes);
    }

    request.put_u16(target_port);

    write_all_to(stream, request.into()).await?;

    let mut header = [0u8; 4];

    read_exact_from(stream, &mut header).await?;

    if header[0] != 0x05 {
      return ProxyResult::Err(ProxyError::new(ErrorName::InvalidVersion, "invalid response version"));
    }

    let rep = header[1];

    if rep != 0x00 {
      return ProxyResult::Err(ProxyError::new(ErrorName::NotConnected, format!("proxy connection error (rep: 0x{:02x})", rep)));
    }

    let atyp = header[3];

    match atyp {
      0x01 => {
        let mut addr = [0u8; 4 + 2];
        read_exact_from(stream, &mut addr).await?;
      }
      0x04 => {
        let mut addr = [0u8; 16 + 2];
        read_exact_from(stream, &mut addr).await?;
      }
      0x03 => {
        let mut len = [0u8; 1];
        read_exact_from(stream, &mut len).await?;
        let mut rest = vec![0u8; len[0] as usize + 2];
        read_exact_from(stream, &mut rest).await?;
      }
      _ => return ProxyResult::Err(ProxyError::new(ErrorName::InvalidData, format!("unknown address type in reply: 0x{:02x}", atyp))),
    }

    ProxyResult::Ok(())
  }

  /// Метод создания подключения с SOCKS4 прокси
  async fn connect_socks4(&self, stream: &mut TcpStream, target_host: String, target_port: u16) -> ProxyResult<()> {
    let mut request = BytesMut::with_capacity(512);
    request.put_u8(0x04);
    request.put_u8(0x01);
    request.put_u16(target_port);

    if let Ok(ipv4) = target_host.parse::<std::net::Ipv4Addr>() {
      request.put_slice(&ipv4.octets());

      if let Some(auth) = &self.auth {
        request.put_slice(auth.username().as_bytes());
      } else {
        request.put_u8(0x00);
      }
    } else {
      request.put_slice(&[0x00, 0x00, 0x00, 0x01]);

      if let Some(auth) = &self.auth {
        request.put_slice(auth.username().as_bytes());
      } else {
        request.put_u8(0x00);
      }

      if target_host.len() > 255 {
        return Err(ProxyError::new(ErrorName::InvalidData, "target host is too long"));
      }

      request.put_slice(target_host.as_bytes());
      request.put_u8(0x00);
    }

    write_all_to(stream, request.into()).await?;

    let mut response = [0u8; 8];
    read_exact_from(stream, &mut response).await?;

    if response[0] != 0x00 {
      return Err(ProxyError::new(ErrorName::InvalidVersion, "invalid response version"));
    }

    match response[1] {
      0x5a => Ok(()),
      0x5b => Err(ProxyError::new(ErrorName::NotConnected, "request rejected or failed")),
      0x5c => Err(ProxyError::new(ErrorName::AuthFailed, "client not identd-authenticated")),
      0x5d => Err(ProxyError::new(ErrorName::AuthFailed, "client identd-user mismatch")),
      _ => Err(ProxyError::new(ErrorName::Unsupported, format!("unknown response code 0x{:02x}", response[1]))),
    }
  }
}

#[cfg(test)]
mod tests {
  use std::io::{Error, ErrorKind};

  use tokio::io::{AsyncReadExt, AsyncWriteExt};

  use crate::result::ProxyResult;
  use crate::{Proxy, ProxyType};

  #[tokio::test]
  async fn test_socks5_proxy() -> std::io::Result<()> {
    let proxy = Proxy::new("212.58.132.5:1080", ProxyType::Socks5);
    proxy.bind("ipinfo.io".to_string(), 80);

    let mut conn = match proxy.connect().await {
      ProxyResult::Ok(s) => s,
      ProxyResult::Err(e) => return Err(Error::new(ErrorKind::NotConnected, e.text())),
    };

    conn.write_all(b"GET / HTTP/1.0\r\nHost: ipinfo.io\r\n\r\n").await?;

    let mut buf = Vec::new();
    conn.read_to_end(&mut buf).await?;

    println!("{}", String::from_utf8_lossy(&buf));

    Ok(())
  }

  #[tokio::test]
  async fn test_socks4_proxy() -> std::io::Result<()> {
    let proxy = Proxy::new("68.71.242.118:4145", ProxyType::Socks4);
    proxy.bind("ipinfo.io".to_string(), 80);

    let mut conn = match proxy.connect().await {
      ProxyResult::Ok(s) => s,
      ProxyResult::Err(e) => return Err(Error::new(ErrorKind::NotConnected, e.text())),
    };

    conn.write_all(b"GET / HTTP/1.0\r\nHost: ipinfo.io\r\n\r\n").await?;

    let mut buf = Vec::new();
    conn.read_to_end(&mut buf).await?;

    println!("{}", String::from_utf8_lossy(&buf));

    Ok(())
  }
}