Skip to main content

http_request/request/proxy/
impl.rs

1use super::*;
2
3/// Inherent implementation of [`ProxyTunnelStream`].
4impl ProxyTunnelStream {
5    /// Creates an asynchronous proxy tunnel stream.
6    ///
7    /// # Arguments
8    ///
9    /// - `BoxAsyncReadWrite` - The boxed inner stream carrying the tunneled bytes.
10    /// - `Vec<u8>` - The data already read from the proxy during the handshake.
11    pub(crate) fn new(stream: BoxAsyncReadWrite, pre_read_data: Vec<u8>) -> Self {
12        Self {
13            inner: stream,
14            pre_read_data,
15        }
16    }
17}
18
19/// Implements [`AsyncRead`] for [`ProxyTunnelStream`].
20impl AsyncRead for ProxyTunnelStream {
21    /// Reads the pre-read handshake data before delegating to the inner stream.
22    ///
23    /// # Arguments
24    ///
25    /// - `Pin<&mut Self>` - A pinned mutable reference to the tunnel stream.
26    /// - `&mut Context<'_>` - The task context used to register the read interest.
27    /// - `&mut ReadBuf<'_>` - The buffer that receives the read bytes.
28    ///
29    /// # Returns
30    ///
31    /// - `Poll<io::Result<()>>` - The poll outcome carrying any read error.
32    fn poll_read(
33        mut self: Pin<&mut Self>,
34        cx: &mut Context<'_>,
35        buf: &mut ReadBuf<'_>,
36    ) -> Poll<io::Result<()>> {
37        if !self.get_pre_read_data().is_empty() {
38            let len: usize = cmp::min(self.get_pre_read_data().len(), buf.remaining());
39            buf.put_slice(&self.get_pre_read_data()[..len]);
40            self.get_mut_pre_read_data().drain(..len);
41            return Poll::Ready(Ok(()));
42        }
43        Pin::new(self.get_mut_inner()).poll_read(cx, buf)
44    }
45}
46
47/// Implements [`AsyncWrite`] for [`ProxyTunnelStream`].
48impl AsyncWrite for ProxyTunnelStream {
49    /// Writes bytes to the inner stream through the proxy tunnel.
50    ///
51    /// # Arguments
52    ///
53    /// - `Pin<&mut Self>` - A pinned mutable reference to the tunnel stream.
54    /// - `&mut Context<'_>` - The task context used to register the write interest.
55    /// - `&[u8]` - The buffer of bytes to write.
56    ///
57    /// # Returns
58    ///
59    /// - `Poll<Result<usize, io::Error>>` - The poll outcome carrying the written byte count or any error.
60    fn poll_write(
61        mut self: Pin<&mut Self>,
62        cx: &mut Context<'_>,
63        buf: &[u8],
64    ) -> Poll<Result<usize, io::Error>> {
65        Pin::new(self.get_mut_inner()).poll_write(cx, buf)
66    }
67
68    /// Flushes the inner stream through the proxy tunnel.
69    ///
70    /// # Arguments
71    ///
72    /// - `Pin<&mut Self>` - A pinned mutable reference to the tunnel stream.
73    /// - `&mut Context<'_>` - The task context used to register the flush interest.
74    ///
75    /// # Returns
76    ///
77    /// - `Poll<Result<(), io::Error>>` - The poll outcome carrying any flush error.
78    fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), io::Error>> {
79        Pin::new(self.get_mut_inner()).poll_flush(cx)
80    }
81
82    /// Shuts down the inner stream through the proxy tunnel.
83    ///
84    /// # Arguments
85    ///
86    /// - `Pin<&mut Self>` - A pinned mutable reference to the tunnel stream.
87    /// - `&mut Context<'_>` - The task context used to register the shutdown interest.
88    ///
89    /// # Returns
90    ///
91    /// - `Poll<Result<(), io::Error>>` - The poll outcome carrying any shutdown error.
92    fn poll_shutdown(
93        mut self: Pin<&mut Self>,
94        cx: &mut Context<'_>,
95    ) -> Poll<Result<(), io::Error>> {
96        Pin::new(self.get_mut_inner()).poll_shutdown(cx)
97    }
98}
99
100/// Implements [`Unpin`] for [`ProxyTunnelStream`].
101impl Unpin for ProxyTunnelStream {}
102
103/// Inherent implementation of [`SyncProxyTunnelStream`].
104impl SyncProxyTunnelStream {
105    /// Creates a synchronous proxy tunnel stream.
106    ///
107    /// # Arguments
108    ///
109    /// - `BoxReadWrite` - The boxed inner stream carrying the tunneled bytes.
110    /// - `Vec<u8>` - The data already read from the proxy during the handshake.
111    pub(crate) fn new(stream: BoxReadWrite, pre_read_data: Vec<u8>) -> Self {
112        Self {
113            inner: stream,
114            pre_read_data,
115        }
116    }
117}
118
119/// Implements [`Read`] for [`SyncProxyTunnelStream`].
120impl Read for SyncProxyTunnelStream {
121    /// Reads the pre-read handshake data before delegating to the inner stream.
122    ///
123    /// # Arguments
124    ///
125    /// - `&mut [u8]` - The buffer that receives the read bytes.
126    ///
127    /// # Returns
128    ///
129    /// - `io::Result<usize>` - The read outcome carrying the number of bytes read or any error.
130    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
131        if !self.get_pre_read_data().is_empty() {
132            let len: usize = cmp::min(self.get_pre_read_data().len(), buf.len());
133            buf[..len].copy_from_slice(&self.get_pre_read_data()[..len]);
134            self.get_mut_pre_read_data().drain(..len);
135            return Ok(len);
136        }
137        self.get_mut_inner().read(buf)
138    }
139}
140
141/// Implements [`Write`] for [`SyncProxyTunnelStream`].
142impl Write for SyncProxyTunnelStream {
143    /// Writes bytes to the inner stream through the proxy tunnel.
144    ///
145    /// # Arguments
146    ///
147    /// - `&[u8]` - The buffer of bytes to write.
148    ///
149    /// # Returns
150    ///
151    /// - `io::Result<usize>` - The write outcome carrying the number of bytes written or any error.
152    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
153        self.get_mut_inner().write(buf)
154    }
155
156    /// Flushes the inner stream through the proxy tunnel.
157    ///
158    /// # Returns
159    ///
160    /// - `io::Result<()>` - The flush outcome carrying any flush error.
161    fn flush(&mut self) -> io::Result<()> {
162        self.get_mut_inner().flush()
163    }
164}
165
166/// Inherent implementation of [`Proxy`].
167impl Proxy {
168    /// Creates a plain HTTP proxy.
169    ///
170    /// # Arguments
171    ///
172    /// - `H` - The proxy host, converted to a string slice.
173    /// - `u16` - The proxy port.
174    ///
175    /// # Returns
176    ///
177    /// - `Self` - The configured HTTP proxy.
178    pub fn http<H>(host: H, port: u16) -> Self
179    where
180        H: AsRef<str>,
181    {
182        Self::new(ProxyType::Http, host, port)
183    }
184
185    /// Creates an HTTPS (TLS-wrapped) proxy.
186    ///
187    /// # Arguments
188    ///
189    /// - `H` - The proxy host, converted to a string slice.
190    /// - `u16` - The proxy port.
191    ///
192    /// # Returns
193    ///
194    /// - `Self` - The configured HTTPS proxy.
195    pub fn https<H>(host: H, port: u16) -> Self
196    where
197        H: AsRef<str>,
198    {
199        Self::new(ProxyType::Https, host, port)
200    }
201
202    /// Creates a SOCKS5 proxy.
203    ///
204    /// # Arguments
205    ///
206    /// - `H` - The proxy host, converted to a string slice.
207    /// - `u16` - The proxy port.
208    ///
209    /// # Returns
210    ///
211    /// - `Self` - The configured SOCKS5 proxy.
212    pub fn socks5<H>(host: H, port: u16) -> Self
213    where
214        H: AsRef<str>,
215    {
216        Self::new(ProxyType::Socks5, host, port)
217    }
218
219    /// Attaches a username and password to this proxy.
220    ///
221    /// # Arguments
222    ///
223    /// - `U` - The proxy username, converted to a string slice.
224    /// - `P` - The proxy password, converted to a string slice.
225    ///
226    /// # Returns
227    ///
228    /// - `Self` - The proxy updated with credentials.
229    pub fn auth<U, P>(mut self, username: U, password: P) -> Self
230    where
231        U: AsRef<str>,
232        P: AsRef<str>,
233    {
234        self.set_username(Some(username.as_ref().to_owned()));
235        self.set_password(Some(password.as_ref().to_owned()));
236        self
237    }
238
239    /// Creates a proxy of the given type for a host and port.
240    ///
241    /// # Arguments
242    ///
243    /// - `ProxyType` - The protocol used to reach the proxy.
244    /// - `H` - The proxy host, converted to a string slice.
245    /// - `u16` - The proxy port.
246    ///
247    /// # Returns
248    ///
249    /// - `Self` - The newly constructed proxy.
250    fn new<H>(proxy_type: ProxyType, host: H, port: u16) -> Self
251    where
252        H: AsRef<str>,
253    {
254        Self {
255            proxy_type,
256            host: host.as_ref().to_owned(),
257            port,
258            username: None,
259            password: None,
260        }
261    }
262}