ss_rs/net/
mod.rs

1//! Networking facilities for shadowsocks communication.
2
3pub mod stream;
4
5mod buf;
6
7use std::{
8    io,
9    net::SocketAddr,
10    pin::Pin,
11    task::{Context, Poll},
12};
13
14use futures_core::ready;
15use tokio::io::{AsyncRead, ReadBuf};
16
17use crate::net::buf::OwnedReadBuf;
18
19/// Shadowsocks constant values.
20pub mod constants {
21    /// The maximum payload size of shadowsocks.
22    pub const MAXIMUM_PAYLOAD_SIZE: usize = 0x3FFF;
23    // const MAXIMUM_TAG_SIZE: usize = 16;
24    // const MAXIMUM_MESSAGE_SIZE: usize = 2 + MAXIMUM_PAYLOAD_SIZE + 2 * MAXIMUM_TAG_SIZE;
25}
26
27/// Resolves target socket address.
28///
29/// Returns the first resolved ipv4 socket address.
30pub async fn lookup_host(host: &str) -> io::Result<SocketAddr> {
31    tokio::net::lookup_host(host)
32        .await?
33        .find(|x| x.is_ipv4())
34        .ok_or(io::Error::from(io::ErrorKind::NotFound))
35}
36
37pub(crate) fn poll_read_exact<R>(
38    reader: &mut R,
39    owned_read_buf: &mut OwnedReadBuf,
40    cx: &mut Context<'_>,
41    buf: &mut [u8],
42) -> Poll<io::Result<()>>
43where
44    R: AsyncRead + Unpin + ?Sized,
45{
46    if owned_read_buf.is_full() {
47        // The last call to `poll_read_exact()` has returned `Ready`,
48        // Now there is a brand new call to `poll_read_exact()`.
49        owned_read_buf.require(buf.len());
50    }
51
52    debug_assert_eq!(owned_read_buf.capacity(), buf.len());
53
54    while !owned_read_buf.is_full() {
55        let mut read_buf = ReadBuf::new(owned_read_buf.uninitialized_mut());
56        let remaining = read_buf.remaining();
57
58        ready!(Pin::new(&mut *reader).poll_read(cx, &mut read_buf))?;
59
60        let nread = remaining - read_buf.remaining();
61        if nread == 0 {
62            return Err(io::ErrorKind::UnexpectedEof.into()).into();
63        }
64
65        owned_read_buf.add_filled(nread);
66    }
67
68    buf.copy_from_slice(owned_read_buf.filled());
69
70    Ok(()).into()
71}