1use std::{any::type_name, mem, pin::Pin, sync::OnceLock, task::Poll, time::Duration};
2
3use anyhow::anyhow;
4use bytes::{BufMut, Bytes, BytesMut};
5use futures::{AsyncRead, TryStreamExt as _};
6use http_client::{http, RedirectPolicy};
7use reqwest::{
8 header::{HeaderMap, HeaderValue},
9 redirect,
10};
11use smol::future::FutureExt;
12
13const DEFAULT_CAPACITY: usize = 4096;
14static RUNTIME: OnceLock<tokio::runtime::Runtime> = OnceLock::new();
15
16pub struct ReqwestClient {
17 client: reqwest::Client,
18 proxy: Option<http::Uri>,
19 handle: tokio::runtime::Handle,
20}
21
22impl ReqwestClient {
23 fn builder() -> reqwest::ClientBuilder {
24 reqwest::Client::builder()
25 .use_rustls_tls()
26 .connect_timeout(Duration::from_secs(10))
27 }
28
29 pub fn new() -> Self {
30 Self::builder()
31 .build()
32 .expect("Failed to initialize HTTP client")
33 .into()
34 }
35
36 pub fn user_agent(agent: &str) -> anyhow::Result<Self> {
37 let mut map = HeaderMap::new();
38 map.insert(http::header::USER_AGENT, HeaderValue::from_str(agent)?);
39 let client = Self::builder().default_headers(map).build()?;
40 Ok(client.into())
41 }
42
43 pub fn proxy_and_user_agent(proxy: Option<http::Uri>, agent: &str) -> anyhow::Result<Self> {
44 let mut map = HeaderMap::new();
45 map.insert(http::header::USER_AGENT, HeaderValue::from_str(agent)?);
46 let mut client = Self::builder().default_headers(map);
47 if let Some(proxy) = proxy.clone().and_then(|proxy_uri| {
48 reqwest::Proxy::all(proxy_uri.to_string())
49 .inspect_err(|e| log::error!("Failed to parse proxy URI {}: {}", proxy_uri, e))
50 .ok()
51 }) {
52 client = client.proxy(proxy);
53 }
54 let client = client.build()?;
55 let mut client: ReqwestClient = client.into();
56 client.proxy = proxy;
57 Ok(client)
58 }
59}
60
61impl From<reqwest::Client> for ReqwestClient {
62 fn from(client: reqwest::Client) -> Self {
63 let handle = tokio::runtime::Handle::try_current().unwrap_or_else(|_| {
64 log::debug!("no tokio runtime found, creating one for Reqwest...");
65 let runtime = RUNTIME.get_or_init(|| {
66 tokio::runtime::Builder::new_multi_thread()
67 // Since we now have two executors, let's try to keep our footprint small
68 .worker_threads(1)
69 .enable_all()
70 .build()
71 .expect("Failed to initialize HTTP client")
72 });
73
74 runtime.handle().clone()
75 });
76 Self {
77 client,
78 handle,
79 proxy: None,
80 }
81 }
82}
83
84// This struct is essentially a re-implementation of
85// https://docs.rs/tokio-util/0.7.12/tokio_util/io/struct.ReaderStream.html
86// except outside of Tokio's aegis
87struct StreamReader {
88 reader: Option<Pin<Box<dyn futures::AsyncRead + Send + Sync>>>,
89 buf: BytesMut,
90 capacity: usize,
91}
92
93impl StreamReader {
94 fn new(reader: Pin<Box<dyn futures::AsyncRead + Send + Sync>>) -> Self {
95 Self {
96 reader: Some(reader),
97 buf: BytesMut::new(),
98 capacity: DEFAULT_CAPACITY,
99 }
100 }
101}
102
103impl futures::Stream for StreamReader {
104 type Item = std::io::Result<Bytes>;
105
106 fn poll_next(
107 mut self: Pin<&mut Self>,
108 cx: &mut std::task::Context<'_>,
109 ) -> Poll<Option<Self::Item>> {
110 let mut this = self.as_mut();
111
112 let mut reader = match this.reader.take() {
113 Some(r) => r,
114 None => return Poll::Ready(None),
115 };
116
117 if this.buf.capacity() == 0 {
118 let capacity = this.capacity;
119 this.buf.reserve(capacity);
120 }
121
122 match poll_read_buf(&mut reader, cx, &mut this.buf) {
123 Poll::Pending => Poll::Pending,
124 Poll::Ready(Err(err)) => {
125 self.reader = None;
126
127 Poll::Ready(Some(Err(err)))
128 }
129 Poll::Ready(Ok(0)) => {
130 self.reader = None;
131 Poll::Ready(None)
132 }
133 Poll::Ready(Ok(_)) => {
134 let chunk = this.buf.split();
135 self.reader = Some(reader);
136 Poll::Ready(Some(Ok(chunk.freeze())))
137 }
138 }
139 }
140}
141
142/// Implementation from <https://docs.rs/tokio-util/0.7.12/src/tokio_util/util/poll_buf.rs.html>
143/// Specialized for this use case
144pub fn poll_read_buf(
145 io: &mut Pin<Box<dyn futures::AsyncRead + Send + Sync>>,
146 cx: &mut std::task::Context<'_>,
147 buf: &mut BytesMut,
148) -> Poll<std::io::Result<usize>> {
149 if !buf.has_remaining_mut() {
150 return Poll::Ready(Ok(0));
151 }
152
153 let n = {
154 let dst = buf.chunk_mut();
155
156 // Safety: `chunk_mut()` returns a `&mut UninitSlice`, and `UninitSlice` is a
157 // transparent wrapper around `[MaybeUninit<u8>]`.
158 let dst = unsafe { &mut *(dst as *mut _ as *mut [std::mem::MaybeUninit<u8>]) };
159 let mut buf = tokio::io::ReadBuf::uninit(dst);
160 let ptr = buf.filled().as_ptr();
161 let unfilled_portion = buf.initialize_unfilled();
162 // SAFETY: Pin projection
163 let io_pin = unsafe { Pin::new_unchecked(io) };
164 std::task::ready!(io_pin.poll_read(cx, unfilled_portion)?);
165
166 // Ensure the pointer does not change from under us
167 assert_eq!(ptr, buf.filled().as_ptr());
168 buf.filled().len()
169 };
170
171 // Safety: This is guaranteed to be the number of initialized (and read)
172 // bytes due to the invariants provided by `ReadBuf::filled`.
173 unsafe {
174 buf.advance_mut(n);
175 }
176
177 Poll::Ready(Ok(n))
178}
179
180impl http_client::HttpClient for ReqwestClient {
181 fn proxy(&self) -> Option<&http::Uri> {
182 self.proxy.as_ref()
183 }
184
185 fn type_name(&self) -> &'static str {
186 type_name::<Self>()
187 }
188
189 fn send(
190 &self,
191 req: http::Request<http_client::AsyncBody>,
192 ) -> futures::future::BoxFuture<
193 'static,
194 Result<http_client::Response<http_client::AsyncBody>, anyhow::Error>,
195 > {
196 let (parts, body) = req.into_parts();
197
198 let mut request = self.client.request(parts.method, parts.uri.to_string());
199 request = request.headers(parts.headers);
200 if let Some(redirect_policy) = parts.extensions.get::<RedirectPolicy>() {
201 request = request.redirect_policy(match redirect_policy {
202 RedirectPolicy::NoFollow => redirect::Policy::none(),
203 RedirectPolicy::FollowLimit(limit) => redirect::Policy::limited(*limit as usize),
204 RedirectPolicy::FollowAll => redirect::Policy::limited(100),
205 });
206 }
207 let request = request.body(match body.0 {
208 http_client::Inner::Empty => reqwest::Body::default(),
209 http_client::Inner::Bytes(cursor) => cursor.into_inner().into(),
210 http_client::Inner::AsyncReader(stream) => {
211 reqwest::Body::wrap_stream(StreamReader::new(stream))
212 }
213 });
214
215 let handle = self.handle.clone();
216 async move {
217 let mut response = handle.spawn(async { request.send().await }).await??;
218
219 let headers = mem::take(response.headers_mut());
220 let mut builder = http::Response::builder()
221 .status(response.status().as_u16())
222 .version(response.version());
223 *builder.headers_mut().unwrap() = headers;
224
225 let bytes = response
226 .bytes_stream()
227 .map_err(|e| futures::io::Error::new(futures::io::ErrorKind::Other, e))
228 .into_async_read();
229 let body = http_client::AsyncBody::from_reader(bytes);
230
231 builder.body(body).map_err(|e| anyhow!(e))
232 }
233 .boxed()
234 }
235}
236
237#[cfg(test)]
238mod tests {
239 use http_client::{http, HttpClient};
240
241 use crate::ReqwestClient;
242
243 #[test]
244 fn test_proxy_uri() {
245 let client = ReqwestClient::new();
246 assert_eq!(client.proxy(), None);
247
248 let proxy = http::Uri::from_static("http://localhost:10809");
249 let client = ReqwestClient::proxy_and_user_agent(Some(proxy.clone()), "test").unwrap();
250 assert_eq!(client.proxy(), Some(&proxy));
251
252 let proxy = http::Uri::from_static("https://localhost:10809");
253 let client = ReqwestClient::proxy_and_user_agent(Some(proxy.clone()), "test").unwrap();
254 assert_eq!(client.proxy(), Some(&proxy));
255
256 let proxy = http::Uri::from_static("socks4://localhost:10808");
257 let client = ReqwestClient::proxy_and_user_agent(Some(proxy.clone()), "test").unwrap();
258 assert_eq!(client.proxy(), Some(&proxy));
259
260 let proxy = http::Uri::from_static("socks4a://localhost:10808");
261 let client = ReqwestClient::proxy_and_user_agent(Some(proxy.clone()), "test").unwrap();
262 assert_eq!(client.proxy(), Some(&proxy));
263
264 let proxy = http::Uri::from_static("socks5://localhost:10808");
265 let client = ReqwestClient::proxy_and_user_agent(Some(proxy.clone()), "test").unwrap();
266 assert_eq!(client.proxy(), Some(&proxy));
267
268 let proxy = http::Uri::from_static("socks5h://localhost:10808");
269 let client = ReqwestClient::proxy_and_user_agent(Some(proxy.clone()), "test").unwrap();
270 assert_eq!(client.proxy(), Some(&proxy));
271 }
272
273 #[test]
274 #[should_panic]
275 fn test_invalid_proxy_uri() {
276 let proxy = http::Uri::from_static("file:///etc/hosts");
277 ReqwestClient::proxy_and_user_agent(Some(proxy), "test").unwrap();
278 }
279}