aioduct 0.2.5

Async-native HTTP client built directly on hyper 1.x — no hyper-util, no legacy
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
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
use std::io;
#[cfg(test)]
use std::io::{Read, Write};
use std::net::Ipv4Addr;
#[cfg(test)]
use std::net::TcpStream;

use crate::proxy::ProxyAuth;

const SOCKS4_VERSION: u8 = 0x04;
const CMD_CONNECT: u8 = 0x01;
const REPLY_GRANTED: u8 = 0x5A;

#[derive(Debug)]
pub(crate) enum Socks4HandshakeError {
    Io(io::Error),
    Protocol(io::Error),
    ConnectRejected { code: u8, message: &'static str },
}

impl Socks4HandshakeError {
    pub(crate) fn is_target_connect_failure(&self) -> bool {
        matches!(self, Self::ConnectRejected { code: 0x5B, .. })
    }

    pub(crate) fn into_io(self) -> io::Error {
        match self {
            Self::Io(error) | Self::Protocol(error) => error,
            Self::ConnectRejected { code, message } => {
                io::Error::other(format!("SOCKS4: {message} (code 0x{code:02X})"))
            }
        }
    }
}

impl From<io::Error> for Socks4HandshakeError {
    fn from(error: io::Error) -> Self {
        Self::Io(error)
    }
}

/// SOCKS4a handshake: connects through a SOCKS4 proxy using domain name resolution on the proxy.
#[cfg(test)]
pub(crate) fn socks4a_handshake(
    stream: &mut TcpStream,
    host: &str,
    port: u16,
    auth: Option<&ProxyAuth>,
) -> io::Result<()> {
    let userid = auth.map(|a| a.username.as_bytes()).unwrap_or(b"");

    // SOCKS4a: set DSTIP to 0.0.0.1 to signal domain-based addressing
    let dstip = Ipv4Addr::new(0, 0, 0, 1);

    let mut msg = Vec::with_capacity(10 + userid.len() + host.len());
    msg.push(SOCKS4_VERSION);
    msg.push(CMD_CONNECT);
    msg.push((port >> 8) as u8);
    msg.push(port as u8);
    msg.extend_from_slice(&dstip.octets());
    msg.extend_from_slice(userid);
    msg.push(0x00); // NULL terminator for userid
    msg.extend_from_slice(host.as_bytes());
    msg.push(0x00); // NULL terminator for domain
    stream.write_all(&msg)?;

    let mut reply = [0u8; 8];
    stream.read_exact(&mut reply)?;

    if reply[1] != REPLY_GRANTED {
        let msg = match reply[1] {
            0x5B => "request rejected or failed",
            0x5C => "cannot connect to identd on the client",
            0x5D => "client's identd reported different user-id",
            _ => "unknown error",
        };
        return Err(io::Error::other(format!(
            "SOCKS4: {msg} (code 0x{:02X})",
            reply[1]
        )));
    }

    Ok(())
}

async fn write_all_async<S: hyper::rt::Write + Unpin>(
    stream: &mut S,
    buf: &[u8],
) -> io::Result<()> {
    use std::future::poll_fn;
    use std::pin::Pin;

    let mut written = 0;
    while written < buf.len() {
        let count = poll_fn(|cx| Pin::new(&mut *stream).poll_write(cx, &buf[written..])).await?;
        if count == 0 {
            return Err(io::Error::new(
                io::ErrorKind::WriteZero,
                "SOCKS4: proxy closed connection",
            ));
        }
        written += count;
    }
    poll_fn(|cx| Pin::new(&mut *stream).poll_flush(cx)).await
}

async fn read_exact_async<S: hyper::rt::Read + Unpin>(
    stream: &mut S,
    buf: &mut [u8],
) -> io::Result<()> {
    use std::future::poll_fn;
    use std::pin::Pin;

    let mut read = 0;
    while read < buf.len() {
        let mut remaining = hyper::rt::ReadBuf::new(&mut buf[read..]);
        poll_fn(|cx| Pin::new(&mut *stream).poll_read(cx, remaining.unfilled())).await?;
        let count = remaining.filled().len();
        if count == 0 {
            return Err(io::Error::new(
                io::ErrorKind::UnexpectedEof,
                "SOCKS4: proxy closed connection",
            ));
        }
        read += count;
    }
    Ok(())
}

async fn finish_handshake_async<S>(
    stream: &mut S,
    request: &[u8],
) -> Result<(), Socks4HandshakeError>
where
    S: hyper::rt::Read + hyper::rt::Write + Unpin,
{
    write_all_async(stream, request).await?;

    let mut reply = [0u8; 8];
    read_exact_async(stream, &mut reply).await?;
    if reply[0] != 0 {
        return Err(Socks4HandshakeError::Protocol(io::Error::new(
            io::ErrorKind::InvalidData,
            format!("SOCKS4: unexpected reply version {}", reply[0]),
        )));
    }
    if reply[1] != REPLY_GRANTED {
        let message = match reply[1] {
            0x5B => "request rejected or failed",
            0x5C => "cannot connect to identd on the client",
            0x5D => "client's identd reported different user-id",
            _ => "unknown error",
        };
        return Err(Socks4HandshakeError::ConnectRejected {
            code: reply[1],
            message,
        });
    }

    Ok(())
}

/// Async SOCKS4 handshake using a locally resolved IPv4 destination.
pub(crate) async fn socks4_handshake_async<S>(
    stream: &mut S,
    addr: Ipv4Addr,
    port: u16,
    auth: Option<&ProxyAuth>,
) -> Result<(), Socks4HandshakeError>
where
    S: hyper::rt::Read + hyper::rt::Write + Unpin,
{
    let userid = auth.map(|auth| auth.username.as_bytes()).unwrap_or(b"");
    if userid.contains(&0) {
        return Err(Socks4HandshakeError::Protocol(io::Error::new(
            io::ErrorKind::InvalidInput,
            "SOCKS4: user ID cannot contain NUL bytes",
        )));
    }

    let mut request = Vec::with_capacity(9 + userid.len());
    request.extend_from_slice(&[SOCKS4_VERSION, CMD_CONNECT]);
    request.extend_from_slice(&port.to_be_bytes());
    request.extend_from_slice(&addr.octets());
    request.extend_from_slice(userid);
    request.push(0);
    finish_handshake_async(stream, &request).await
}

/// Async SOCKS4a handshake using proxy-side hostname resolution.
pub(crate) async fn socks4a_handshake_async<S>(
    stream: &mut S,
    host: &str,
    port: u16,
    auth: Option<&ProxyAuth>,
) -> Result<(), Socks4HandshakeError>
where
    S: hyper::rt::Read + hyper::rt::Write + Unpin,
{
    let userid = auth.map(|auth| auth.username.as_bytes()).unwrap_or(b"");
    if userid.contains(&0) || host.as_bytes().contains(&0) {
        return Err(Socks4HandshakeError::Protocol(io::Error::new(
            io::ErrorKind::InvalidInput,
            "SOCKS4: user ID and hostname cannot contain NUL bytes",
        )));
    }

    let mut request = Vec::with_capacity(10 + userid.len() + host.len());
    request.extend_from_slice(&[SOCKS4_VERSION, CMD_CONNECT]);
    request.extend_from_slice(&port.to_be_bytes());
    request.extend_from_slice(&[0, 0, 0, 1]);
    request.extend_from_slice(userid);
    request.push(0);
    request.extend_from_slice(host.as_bytes());
    request.push(0);
    finish_handshake_async(stream, &request).await
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::io::{Read, Write};
    use std::net::TcpListener;

    fn make_reply(code: u8) -> [u8; 8] {
        [0x00, code, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]
    }

    #[test]
    fn identd_and_protocol_failures_are_not_retryable_targets() {
        assert!(
            Socks4HandshakeError::ConnectRejected {
                code: 0x5B,
                message: "request rejected or failed",
            }
            .is_target_connect_failure()
        );
        for code in [0x5C, 0x5D, 0xFF] {
            assert!(
                !Socks4HandshakeError::ConnectRejected {
                    code,
                    message: "fatal rejection",
                }
                .is_target_connect_failure()
            );
        }
        assert!(
            !Socks4HandshakeError::Protocol(io::Error::new(
                io::ErrorKind::InvalidData,
                "malformed reply",
            ))
            .is_target_connect_failure()
        );
        assert!(
            !Socks4HandshakeError::Io(io::Error::new(
                io::ErrorKind::UnexpectedEof,
                "transport closed",
            ))
            .is_target_connect_failure()
        );
    }

    fn run_test<F>(server_fn: F, client_fn: impl FnOnce(&mut TcpStream) + Send + 'static)
    where
        F: FnOnce(&mut std::net::TcpStream) + Send + 'static,
    {
        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
        let addr = listener.local_addr().unwrap();

        let server = std::thread::spawn(move || {
            let (mut stream, _) = listener.accept().unwrap();
            server_fn(&mut stream);
        });

        let mut client = TcpStream::connect(addr).unwrap();
        client_fn(&mut client);
        server.join().unwrap();
    }

    #[test]
    fn handshake_success() {
        run_test(
            |server| {
                let mut buf = [0u8; 256];
                let n = server.read(&mut buf).unwrap();
                assert!(n > 0);
                assert_eq!(buf[0], SOCKS4_VERSION);
                assert_eq!(buf[1], CMD_CONNECT);
                assert_eq!(buf[2], 0x00);
                assert_eq!(buf[3], 80);
                server.write_all(&make_reply(0x5A)).unwrap();
            },
            |client| {
                let result = socks4a_handshake(client, "example.com", 80, None);
                assert!(result.is_ok());
            },
        );
    }

    #[test]
    fn handshake_success_with_auth() {
        run_test(
            |server| {
                let mut buf = [0u8; 256];
                let n = server.read(&mut buf).unwrap();
                let msg = &buf[..n];
                // Verify userid is present
                assert_eq!(&msg[8..12], b"user");
                assert_eq!(msg[12], 0x00);
                assert_eq!(&msg[13..24], b"example.com");
                assert_eq!(msg[24], 0x00);
                server.write_all(&make_reply(0x5A)).unwrap();
            },
            |client| {
                let auth = ProxyAuth {
                    username: "user".into(),
                    password: "pass".into(),
                };
                let result = socks4a_handshake(client, "example.com", 443, Some(&auth));
                assert!(result.is_ok());
            },
        );
    }

    #[test]
    fn handshake_rejected() {
        run_test(
            |server| {
                let mut buf = [0u8; 256];
                let _ = server.read(&mut buf).unwrap();
                server.write_all(&make_reply(0x5B)).unwrap();
            },
            |client| {
                let err = socks4a_handshake(client, "example.com", 80, None).unwrap_err();
                assert!(err.to_string().contains("request rejected or failed"));
            },
        );
    }

    #[test]
    fn handshake_identd_error() {
        run_test(
            |server| {
                let mut buf = [0u8; 256];
                let _ = server.read(&mut buf).unwrap();
                server.write_all(&make_reply(0x5C)).unwrap();
            },
            |client| {
                let err = socks4a_handshake(client, "example.com", 80, None).unwrap_err();
                assert!(err.to_string().contains("identd"));
            },
        );
    }

    #[test]
    fn handshake_different_userid() {
        run_test(
            |server| {
                let mut buf = [0u8; 256];
                let _ = server.read(&mut buf).unwrap();
                server.write_all(&make_reply(0x5D)).unwrap();
            },
            |client| {
                let err = socks4a_handshake(client, "example.com", 80, None).unwrap_err();
                assert!(err.to_string().contains("different user-id"));
            },
        );
    }

    #[test]
    fn handshake_unknown_error_code() {
        run_test(
            |server| {
                let mut buf = [0u8; 256];
                let _ = server.read(&mut buf).unwrap();
                server.write_all(&make_reply(0xFF)).unwrap();
            },
            |client| {
                let err = socks4a_handshake(client, "example.com", 80, None).unwrap_err();
                assert!(err.to_string().contains("unknown error"));
            },
        );
    }

    #[test]
    fn handshake_port_encoding() {
        run_test(
            |server| {
                let mut buf = [0u8; 256];
                let n = server.read(&mut buf).unwrap();
                assert!(n > 0);
                // Port 8080 = 0x1F90
                assert_eq!(buf[2], 0x1F);
                assert_eq!(buf[3], 0x90);
                server.write_all(&make_reply(0x5A)).unwrap();
            },
            |client| {
                socks4a_handshake(client, "host.test", 8080, None).unwrap();
            },
        );
    }

    #[test]
    fn handshake_eof_during_reply() {
        run_test(
            |server| {
                let mut buf = [0u8; 256];
                let _ = server.read(&mut buf).unwrap();
                // Only send 4 of the 8 expected reply bytes
                server.write_all(&[0x00, 0x5A, 0x00, 0x00]).unwrap();
                // Closing connection — the owned TcpStream drops when this closure returns
            },
            |client| {
                let err = socks4a_handshake(client, "example.com", 80, None).unwrap_err();
                assert_eq!(err.kind(), io::ErrorKind::UnexpectedEof);
            },
        );
    }

    #[test]
    fn handshake_socks4a_message_format_no_auth() {
        run_test(
            |server| {
                let mut buf = [0u8; 256];
                let n = server.read(&mut buf).unwrap();
                let msg = &buf[..n];
                assert_eq!(msg[0], SOCKS4_VERSION);
                assert_eq!(msg[1], CMD_CONNECT);
                // Port 443 = 0x01BB
                assert_eq!(msg[2], 0x01);
                assert_eq!(msg[3], 0xBB);
                // DSTIP = 0.0.0.1 (SOCKS4a indicator)
                assert_eq!(&msg[4..8], &[0, 0, 0, 1]);
                // Empty userid followed by NULL
                assert_eq!(msg[8], 0x00);
                // Domain name followed by NULL
                assert_eq!(&msg[9..20], b"target.host");
                assert_eq!(msg[20], 0x00);
                server.write_all(&make_reply(0x5A)).unwrap();
            },
            |client| {
                socks4a_handshake(client, "target.host", 443, None).unwrap();
            },
        );
    }

    #[test]
    fn handshake_socks4a_message_format_with_auth() {
        run_test(
            |server| {
                let mut buf = [0u8; 256];
                let n = server.read(&mut buf).unwrap();
                let msg = &buf[..n];
                assert_eq!(msg[0], SOCKS4_VERSION);
                assert_eq!(msg[1], CMD_CONNECT);
                // Port 8080 = 0x1F90
                assert_eq!(msg[2], 0x1F);
                assert_eq!(msg[3], 0x90);
                // DSTIP
                assert_eq!(&msg[4..8], &[0, 0, 0, 1]);
                // Userid "testuser" followed by NULL
                assert_eq!(&msg[8..16], b"testuser");
                assert_eq!(msg[16], 0x00);
                // Domain "host.io" followed by NULL
                assert_eq!(&msg[17..24], b"host.io");
                assert_eq!(msg[24], 0x00);
                server.write_all(&make_reply(0x5A)).unwrap();
            },
            |client| {
                let auth = ProxyAuth {
                    username: "testuser".into(),
                    password: "ignored-in-socks4".into(),
                };
                socks4a_handshake(client, "host.io", 8080, Some(&auth)).unwrap();
            },
        );
    }

    #[test]
    fn handshake_eof_immediately() {
        run_test(
            |server| {
                let mut buf = [0u8; 256];
                let _ = server.read(&mut buf);
                // Closing connection — the owned TcpStream drops when this closure returns
            },
            |client| {
                let err = socks4a_handshake(client, "example.com", 80, None).unwrap_err();
                assert_eq!(err.kind(), io::ErrorKind::UnexpectedEof);
            },
        );
    }

    #[test]
    fn handshake_respects_read_timeout() {
        use std::time::{Duration, Instant};

        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
        let addr = listener.local_addr().unwrap();

        let _server = std::thread::spawn(move || {
            let (_stream, _) = listener.accept().unwrap();
            std::thread::sleep(Duration::from_secs(10));
        });

        let mut client = TcpStream::connect(addr).unwrap();
        client
            .set_read_timeout(Some(Duration::from_millis(100)))
            .unwrap();
        client
            .set_write_timeout(Some(Duration::from_millis(100)))
            .unwrap();

        let start = Instant::now();
        let err = socks4a_handshake(&mut client, "example.com", 80, None).unwrap_err();
        let elapsed = start.elapsed();

        assert!(
            elapsed < Duration::from_secs(2),
            "handshake should have timed out quickly, took {elapsed:?}"
        );
        assert!(
            err.kind() == io::ErrorKind::WouldBlock || err.kind() == io::ErrorKind::TimedOut,
            "expected timeout error, got: {err:?}"
        );
    }
}