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
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
#![allow(dead_code)]
use async_std::future;
use async_std::io::{ReadExt, WriteExt};
use futures::channel::oneshot;
use futures::{stream, StreamExt};
use httparse::{Response, EMPTY_HEADER};
use rayon::prelude::*;
use regex::Regex;
use std::env;
use std::fs::File;
use std::io::{self, BufRead, Read, Write};
use std::path::Path;
use std::sync::{Arc, Mutex};
use std::time::Duration;
use tokio::net::TcpStream;
use tokio::task::JoinHandle;
#[derive(Default, Clone, PartialEq, Debug)]
pub enum Proto {
#[default]
HTTP,
HTTPS,
SOCKS4,
SOCKS5,
UNKNOWN,
}
impl Proto {
fn to_string(&self) -> String {
format!("{:?}", self).to_lowercase()
}
}
pub struct Port {
num: u16,
open: bool,
proto: Proto,
}
#[derive(Default, Clone, Debug)]
pub struct Proxy {
proto: Proto,
host: String,
port: u16,
}
impl Proxy {
pub fn check_host(&self) -> bool {
let re = Regex::new(r"^\d{3}.\d{3}.\d{3}.\d{3}$").unwrap();
return re.is_match(&self.host);
}
}
fn make_request(host: &str, port: u16) -> String {
format!(
"CONNECT {0}:{1} HTTP/1.1\r\n\
Host: {0}:{1}\r\n\
Proxy-Connection: Keep-Alive\r\n",
host, port
)
}
fn make_request_without_basic_auth(host: &str, port: u16) -> String {
let mut request = make_request(host, port);
request.push_str("\r\n");
request
}
pub async fn compute_proxy(proxy: Proxy, timeout: u64, retrys: usize) -> (bool, Proto) {
let dur = std::time::Duration::from_secs(timeout);
match proxy.proto {
Proto::HTTPS => {
let mut res = (false, Proto::HTTPS);
let connector = async_tls::TlsConnector::default();
let addrs = format!("{}:{}", proxy.host.as_str(), proxy.port);
if let Ok(Ok(socket)) =
future::timeout(dur, async_std::net::TcpStream::connect(addrs.clone())).await
{
let _connector = connector.clone();
if let Ok(Ok(mut stream_socket)) =
future::timeout(dur, _connector.connect(proxy.host.as_str(), socket)).await
{
let hello = format!(
"CONNECT {0}:{1} HTTP/1.1\r\n\
Host: {0}:{1}\r\n\
Proxy-Connection: Keep-Alive\r\n",
proxy.host.as_str(),
proxy.port
);
let request = hello.as_bytes();
if let Ok(_) = future::timeout(Duration::from_millis(900), async {
stream_socket.write_all(&request.clone())
})
.await
{
let mut buf = [0; 4096];
if let Ok(_) = future::timeout(Duration::from_millis(900), async {
stream_socket.read(&mut buf)
})
.await
{
const MAXIMUM_RESPONSE_HEADERS: usize = 16;
let mut response_headers = [EMPTY_HEADER; MAXIMUM_RESPONSE_HEADERS];
let mut response = Response::new(&mut response_headers[..]);
if let Ok(_) = response.parse(&buf) {
if response.code == Some(200) {
res = (true, Proto::HTTP);
}
}
}
}
}
}
return res;
}
Proto::HTTP => {
let mut res = (false, Proto::HTTP);
for _ in 0..retrys {
let addrs = format!("{}:{}", proxy.host.as_str(), proxy.port);
if let Ok(Ok(mut socket)) =
future::timeout(dur, async { std::net::TcpStream::connect(addrs.clone()) })
.await
{
let hello = format!(
"CONNECT {0}:{1} HTTP/1.1\r\n\
Host: {0}:{1}\r\n\
Proxy-Connection: Keep-Alive\r\n",
proxy.host.as_str(),
proxy.port
);
let request = hello.as_bytes();
if let Ok(_) = future::timeout(Duration::from_millis(900), async {
socket.write_all(&request.clone())
})
.await
{
let mut buf = [0; 4096];
if let Ok(_) = future::timeout(Duration::from_millis(900), async {
let _ = socket.set_ttl(255);
socket.read(&mut buf)
})
.await
{
const MAXIMUM_RESPONSE_HEADERS: usize = 16;
let mut response_headers = [EMPTY_HEADER; MAXIMUM_RESPONSE_HEADERS];
let mut response = Response::new(&mut response_headers[..]);
if let Ok(_) = response.parse(&buf) {
if response.code == Some(200) {
res = (true, Proto::HTTP);
break;
}
}
}
};
}
}
return res;
}
Proto::SOCKS5 => {
let mut res = (false, Proto::SOCKS5);
for _ in 0..retrys {
let addrs = format!("{}:{}", proxy.host.as_str(), proxy.port);
if let Ok(Ok(socket)) =
future::timeout(dur, TcpStream::connect(addrs.clone())).await
{
let packet_len = 3;
let packet = [
5, // protocol version
1, // method count
0, // method
0, // no auth (always offered)
];
if let Ok(_) = future::timeout(Duration::from_millis(900), async {
let _ = socket.writable().await;
socket.try_write(&packet[..packet_len])
})
.await
{
let mut buf = [0; 2];
if let Ok(Ok(_)) = future::timeout(Duration::from_millis(900), async {
let _ = socket.readable().await;
let _ = socket.set_ttl(255); // linux
socket.try_read(&mut buf)
})
.await
{
let response_version = buf[0];
if response_version == 5 {
res = (true, Proto::SOCKS5);
break;
}
}
};
}
}
return res;
}
Proto::SOCKS4 => {
let mut res = (false, Proto::SOCKS4);
for _ in 0..retrys {
let addrs = format!("{}:{}", proxy.host.as_str(), proxy.port);
if let Ok(Ok(socket)) =
future::timeout(dur, TcpStream::connect(addrs.clone())).await
{
let packet_len = 3;
let packet = [
4, // protocol version
1, // method count
0, // method
0, // no auth (always offered)
];
if let Ok(_) = future::timeout(Duration::from_millis(900), async {
let _ = socket.writable().await;
socket.try_write(&packet[..packet_len])
})
.await
{
let mut buf = [0; 2];
if let Ok(Ok(_)) = future::timeout(Duration::from_millis(900), async {
let _ = socket.readable().await;
let _ = socket.set_ttl(255);
socket.try_read(&mut buf)
})
.await
{
let response_version = buf[0];
if response_version == 5 {
res = (true, Proto::SOCKS4);
break;
}
}
};
}
}
return res;
}
Proto::UNKNOWN => {
let (tx1, rx1) = oneshot::channel::<bool>();
let (tx2, rx2) = oneshot::channel::<bool>();
let (tx3, rx3) = oneshot::channel::<bool>();
let (tx4, rx4) = oneshot::channel::<bool>();
let host = proxy.host.clone();
let mut handlers: Vec<JoinHandle<()>> = vec![];
handlers.push(tokio::spawn(async move {
let mut _retu = false;
for _ in 0..retrys {
let addrs = format!("{}:{}", host.as_str(), proxy.port);
if let Ok(Ok(socket)) = future::timeout(
Duration::from_millis(800),
TcpStream::connect(addrs.clone()),
)
.await
{
let packet_len = 3;
let packet = [
4, // protocol version
1, // method count
0, // method
0, // no auth (always offered)
];
if let Ok(_) = future::timeout(Duration::from_millis(900), async {
let _ = socket.writable().await;
socket.try_write(&packet[..packet_len])
})
.await
{
let mut buf = [0; 2];
if let Ok(Ok(_)) = future::timeout(Duration::from_millis(900), async {
let _ = socket.readable().await;
let _ = socket.set_ttl(255);
socket.try_read(&mut buf)
})
.await
{
let response_version = buf[0];
if response_version == 5 {
_retu = true;
break;
}
}
};
}
}
let _ = tx1.send(_retu);
}));
let host = proxy.host.clone();
handlers.push(tokio::spawn(async move {
let mut _retu = false;
for _ in 0..retrys {
let addrs = format!("{}:{}", host.as_str(), proxy.port);
if let Ok(Ok(socket)) =
future::timeout(dur, TcpStream::connect(addrs.clone())).await
{
let packet_len = 3;
let packet = [
5, // protocol version
1, // method count
0, // method
0, // no auth (always offered)
];
if let Ok(_) = future::timeout(Duration::from_millis(900), async {
let _ = socket.writable().await;
socket.try_write(&packet[..packet_len])
})
.await
{
let mut buf = [0; 2];
if let Ok(Ok(_)) = future::timeout(Duration::from_millis(900), async {
let _ = socket.readable().await;
let _ = socket.set_ttl(255); // linux
socket.try_read(&mut buf)
})
.await
{
let response_version = buf[0];
if response_version == 5 {
_retu = true;
break;
}
}
};
}
}
let _ = tx2.send(_retu);
}));
let host = proxy.host.clone();
handlers.push(tokio::spawn(async move {
let mut _retu = false;
for _ in 0..retrys {
let addrs = format!("{}:{}", host.as_str(), proxy.port);
if let Ok(Ok(socket)) =
future::timeout(dur.clone(), TcpStream::connect(addrs.clone())).await
{
let hello =
format!("CONNECT {}:{} HTTP/1.1\r\n\r\n", host.as_str(), proxy.port);
let request = hello.as_bytes();
if let Ok(_) = future::timeout(Duration::from_millis(900), async {
let _ = socket.writable().await;
socket.try_write(&request.clone())
})
.await
{
let mut buf = [0; 1024];
if let Ok(Ok(_)) = future::timeout(Duration::from_millis(900), async {
let _ = socket.set_ttl(255);
let _ = socket.readable().await;
socket.try_read(&mut buf)
})
.await
{
let ok = b"HTTP/1.1 200 OK\r\n";
if &buf[..ok.len()] == ok {
_retu = true
}
}
};
}
}
let _ = tx3.send(_retu);
}));
let host = proxy.host.clone();
handlers.push(tokio::spawn(async move {
let connector = async_tls::TlsConnector::default();
let mut _retu = false;
let addrs = format!("{}:{}", host.as_str(), proxy.port);
if let Ok(Ok(socket)) =
future::timeout(dur, async_std::net::TcpStream::connect(addrs.clone())).await
{
let _connector = connector.clone();
if let Ok(Ok(mut stream_socket)) =
future::timeout(dur, _connector.connect(host.as_str(), socket)).await
{
let hello =
format!("CONNECT {}:{} HTTP/1.1\r\n\r\n", host.as_str(), proxy.port);
let request = hello.as_bytes();
if let Ok(_) = future::timeout(Duration::from_millis(900), async {
stream_socket.write_all(&request.clone())
})
.await
{
let mut buf = [0; 1024];
if let Ok(_) = future::timeout(Duration::from_millis(900), async {
stream_socket.read(&mut buf)
})
.await
{
let ok = b"HTTP/1.1 200 OK\r\n";
if &buf[..ok.len()] == ok {
_retu = true
}
}
};
}
}
let _ = tx4.send(_retu);
}));
let mut res = None;
let sleep = tokio::time::sleep(Duration::from_secs(24));
tokio::pin!(sleep);
tokio::select! {
Ok(val) = rx2 => {
if val {
res = Some((true, Proto::SOCKS5));
let _ = handlers.iter().map(|h|{
if !h.is_finished() {
h.abort();
}
});
} else {
res = Some((false, Proto::UNKNOWN));
}
},
Ok(val) = rx1 => {
if val && res == None {
res = Some((true, Proto::SOCKS4));
let _ = handlers.iter().map(|h|{
if !h.is_finished() {
h.abort();
}
});
} else {
res = Some((false, Proto::UNKNOWN));
}
},
Ok(val) = rx3 => {
if val && res == None {
res = Some((true, Proto::HTTP));
let _ = handlers.iter().map(|h|{
if !h.is_finished() {
h.abort();
}
});
} else {
res = Some((false, Proto::UNKNOWN));
}
},
Ok(val) = rx4 => {
if val && res == None {
res = Some((true, Proto::HTTPS));
let _ = handlers.iter().map(|h|{
if !h.is_finished() {
h.abort();
}
});
} else {
res = Some((false, Proto::UNKNOWN));
}
},
_ = &mut sleep => {
println!("timeout!");
let _ = handlers.iter().map(|h|{
if !h.is_finished() {
h.abort();
}
});
res = Some((false, Proto::UNKNOWN));
}
}
match res {
Some(m) => m,
None => (false, Proto::UNKNOWN),
}
}
}
}
fn read_lines<P>(filename: P) -> io::Result<io::Lines<io::BufReader<File>>>
where
P: AsRef<Path>,
{
let file = File::open(filename)?;
Ok(io::BufReader::new(file).lines())
}
pub async fn readfile(path: String) -> Option<Vec<Proxy>> {
let pth = Path::new(&path);
if !pth.is_file() {
return None;
}
if let Ok(lines) = read_lines(pth) {
let mut _proxies = vec![];
let list = lines
.filter(|line| line.is_ok())
.map(|p| p.unwrap())
.collect::<Vec<String>>();
_proxies = list
.into_par_iter()
.enumerate()
.filter_map(|(_i, p)| {
let mut __proxy = p.split(":").map(|s| s.to_string()).collect::<Vec<String>>();
if __proxy.len() == 2 {
__proxy.insert(0, "UNKNOWN".into());
}
let _proto = match __proxy[0].to_uppercase().as_str() {
"HTTP" | "HTTPS" => Proto::HTTP,
"SOCKS4" => Proto::SOCKS4,
"SOCKS5" => Proto::SOCKS5,
"UNKNOWN" => Proto::UNKNOWN,
_ => Proto::UNKNOWN,
};
let _port = match __proxy[2].parse::<u16>() {
Ok(m) => m,
Err(_) => 0,
};
let current_proxy = Proxy {
proto: _proto.clone(),
host: __proxy[1].clone(),
port: _port,
};
if !__proxy[1].is_empty() && current_proxy.check_host() && _port != 0 {
Some(current_proxy)
} else {
None
}
})
.collect();
return Some(_proxies);
} else {
return None;
}
}
pub async fn concurrent_threads(
threads: Option<usize>,
proxies: Vec<Proxy>,
timeout: u64,
retrys: usize,
outfile: Option<String>,
) {
let max_threads = match std::thread::available_parallelism() {
Ok(s) => s.get(),
Err(_) => 5,
};
let thread_number = match threads {
Some(m) => {
if m > max_threads {
max_threads
} else {
m
}
}
None => max_threads,
};
let file = match outfile {
Some(m) => {
let directory = env::current_dir().unwrap();
let file = directory.join(m);
File::create(file).unwrap()
}
None => {
let directory = env::current_dir().unwrap();
let file = directory.join("live.txt");
File::create(file).unwrap()
}
};
// let (tx, rx) = channel::<Proxy>();
let _ = stream::iter(proxies)
.for_each_concurrent(thread_number, |mut proxie| {
let mut txn = file.try_clone().unwrap();
async move {
let is_valid = compute_proxy(proxie.clone(), timeout, retrys).await;
if is_valid.0 {
proxie.proto = is_valid.1;
println!("{:?} {}", proxie.clone(), "✅");
let res = proxie.clone();
let _ = txn.write(
format!("{:?}:{}:{}\n", res.proto, res.host, res.port)
.to_lowercase()
.as_bytes(),
);
} else {
println!("{:?} {}", proxie.clone(), "❌");
}
}
})
.await;
}
pub async fn check_proxies(
threads: Option<usize>,
proxies: Vec<Proxy>,
timeout: u64,
retrys: usize,
) -> Option<Vec<Proxy>> {
let max_threads = match std::thread::available_parallelism() {
Ok(s) => s.get(),
Err(_) => 5,
};
let thread_number = match threads {
Some(m) => {
if m > max_threads {
max_threads
} else {
m
}
}
None => max_threads,
};
let data = Arc::new(Mutex::new(vec![]));
let _ = stream::iter(proxies)
.for_each_concurrent(thread_number, |mut proxie| {
let mut result = data.lock().unwrap();
async move {
let is_valid = compute_proxy(proxie.clone(), timeout, retrys).await;
if is_valid.0 {
proxie.proto = is_valid.1;
println!("{:?} {}", proxie.clone(), "✅");
let res = proxie.clone();
result.push(res);
} else {
println!("{:?} {}", proxie.clone(), "❌");
}
}
})
.await;
match data.clone().lock() {
Ok(m) => Some(m.clone()),
Err(_) => None,
}
}
#[tokio::test]
async fn test_check_port() {
// check a working proxy to see returns type.
let proxies = readfile("./socks5.txt".into(), ).await;
if proxies.is_some() {
println!("🔥 start computing! 🔥");
for proxie in proxies.unwrap() {
let resy = compute_proxy(proxie.clone(), 1, 2).await;
println!("{:?}", resy);
}
}
}