1use std::{any::type_name, mem, pin::Pin, sync::OnceLock, task::Poll};
2
3use anyhow::anyhow;
4use bytes::{BufMut, Bytes, BytesMut};
5use futures::{AsyncRead, TryStreamExt as _};
6use http_client::{http, ReadTimeout, 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 pub fn new() -> Self {
24 reqwest::Client::builder()
25 .use_rustls_tls()
26 .build()
27 .expect("Failed to initialize HTTP client")
28 .into()
29 }
30
31 pub fn user_agent(agent: &str) -> anyhow::Result<Self> {
32 let mut map = HeaderMap::new();
33 map.insert(http::header::USER_AGENT, HeaderValue::from_str(agent)?);
34 let client = reqwest::Client::builder()
35 .default_headers(map)
36 .use_rustls_tls()
37 .build()?;
38 Ok(client.into())
39 }
40
41 pub fn proxy_and_user_agent(proxy: Option<http::Uri>, agent: &str) -> anyhow::Result<Self> {
42 let mut map = HeaderMap::new();
43 map.insert(http::header::USER_AGENT, HeaderValue::from_str(agent)?);
44 let mut client = reqwest::Client::builder()
45 .use_rustls_tls()
46 .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::info!("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 if let Some(ReadTimeout(timeout)) = parts.extensions.get::<ReadTimeout>() {
208 request = request.timeout(*timeout);
209 }
210 let request = request.body(match body.0 {
211 http_client::Inner::Empty => reqwest::Body::default(),
212 http_client::Inner::Bytes(cursor) => cursor.into_inner().into(),
213 http_client::Inner::AsyncReader(stream) => {
214 reqwest::Body::wrap_stream(StreamReader::new(stream))
215 }
216 });
217
218 let handle = self.handle.clone();
219 async move {
220 let mut response = handle.spawn(async { request.send().await }).await??;
221
222 let headers = mem::take(response.headers_mut());
223 let mut builder = http::Response::builder()
224 .status(response.status().as_u16())
225 .version(response.version());
226 *builder.headers_mut().unwrap() = headers;
227
228 let bytes = response
229 .bytes_stream()
230 .map_err(|e| futures::io::Error::new(futures::io::ErrorKind::Other, e))
231 .into_async_read();
232 let body = http_client::AsyncBody::from_reader(bytes);
233
234 builder.body(body).map_err(|e| anyhow!(e))
235 }
236 .boxed()
237 }
238}
239
240#[cfg(test)]
241mod tests {
242 use http_client::{http, HttpClient};
243
244 use crate::ReqwestClient;
245
246 #[test]
247 fn test_proxy_uri() {
248 let client = ReqwestClient::new();
249 assert_eq!(client.proxy(), None);
250
251 let proxy = http::Uri::from_static("http://localhost:10809");
252 let client = ReqwestClient::proxy_and_user_agent(Some(proxy.clone()), "test").unwrap();
253 assert_eq!(client.proxy(), Some(&proxy));
254
255 let proxy = http::Uri::from_static("https://localhost:10809");
256 let client = ReqwestClient::proxy_and_user_agent(Some(proxy.clone()), "test").unwrap();
257 assert_eq!(client.proxy(), Some(&proxy));
258
259 let proxy = http::Uri::from_static("socks4://localhost:10808");
260 let client = ReqwestClient::proxy_and_user_agent(Some(proxy.clone()), "test").unwrap();
261 assert_eq!(client.proxy(), Some(&proxy));
262
263 let proxy = http::Uri::from_static("socks4a://localhost:10808");
264 let client = ReqwestClient::proxy_and_user_agent(Some(proxy.clone()), "test").unwrap();
265 assert_eq!(client.proxy(), Some(&proxy));
266
267 let proxy = http::Uri::from_static("socks5://localhost:10808");
268 let client = ReqwestClient::proxy_and_user_agent(Some(proxy.clone()), "test").unwrap();
269 assert_eq!(client.proxy(), Some(&proxy));
270
271 let proxy = http::Uri::from_static("socks5h://localhost:10808");
272 let client = ReqwestClient::proxy_and_user_agent(Some(proxy.clone()), "test").unwrap();
273 assert_eq!(client.proxy(), Some(&proxy));
274 }
275
276 #[test]
277 #[should_panic]
278 fn test_invalid_proxy_uri() {
279 let proxy = http::Uri::from_static("file:///etc/hosts");
280 ReqwestClient::proxy_and_user_agent(Some(proxy), "test").unwrap();
281 }
282}