viaduct_reqwest/
lib.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
4
5use error_support::{error, warn};
6use once_cell::sync::Lazy;
7use std::{io::Read, sync::Once};
8use viaduct::{settings::GLOBAL_SETTINGS, Backend};
9
10// Note: we don't `use` things from reqwest or the viaduct crate because
11// it would be rather confusing given that we have the same name for
12// most things as them.
13
14static CLIENT: Lazy<reqwest::blocking::Client> = Lazy::new(|| {
15    let settings = GLOBAL_SETTINGS.read();
16    let mut builder = reqwest::blocking::ClientBuilder::new()
17        .timeout(settings.read_timeout)
18        .connect_timeout(settings.connect_timeout)
19        .redirect(if settings.follow_redirects {
20            reqwest::redirect::Policy::default()
21        } else {
22            reqwest::redirect::Policy::none()
23        });
24    if cfg!(target_os = "ios") {
25        // The FxA servers rely on the UA agent to filter
26        // some push messages directed to iOS devices.
27        // This is obviously a terrible hack and we should
28        // probably do https://github.com/mozilla/application-services/issues/1326
29        // instead, but this will unblock us for now.
30        builder = builder.user_agent("Firefox-iOS-FxA/24");
31    }
32    // Note: no cookie or cache support.
33    builder
34        .build()
35        .expect("Failed to initialize global reqwest::Client")
36});
37
38#[allow(clippy::unnecessary_wraps)] // not worth the time to untangle
39fn into_reqwest(request: viaduct::Request) -> Result<reqwest::blocking::Request, viaduct::Error> {
40    let method = match request.method {
41        viaduct::Method::Get => reqwest::Method::GET,
42        viaduct::Method::Head => reqwest::Method::HEAD,
43        viaduct::Method::Post => reqwest::Method::POST,
44        viaduct::Method::Put => reqwest::Method::PUT,
45        viaduct::Method::Delete => reqwest::Method::DELETE,
46        viaduct::Method::Connect => reqwest::Method::CONNECT,
47        viaduct::Method::Options => reqwest::Method::OPTIONS,
48        viaduct::Method::Trace => reqwest::Method::TRACE,
49        viaduct::Method::Patch => reqwest::Method::PATCH,
50    };
51    let mut result = reqwest::blocking::Request::new(method, request.url);
52    for h in request.headers {
53        use reqwest::header::{HeaderName, HeaderValue};
54        // Unwraps should be fine, we verify these in `Header`
55        let value = HeaderValue::from_str(h.value()).unwrap();
56        result
57            .headers_mut()
58            .insert(HeaderName::from_bytes(h.name().as_bytes()).unwrap(), value);
59    }
60    *result.body_mut() = request.body.map(reqwest::blocking::Body::from);
61    Ok(result)
62}
63
64pub struct ReqwestBackend;
65impl Backend for ReqwestBackend {
66    fn send(&self, request: viaduct::Request) -> Result<viaduct::Response, viaduct::Error> {
67        viaduct::note_backend("reqwest (untrusted)");
68        let request_method = request.method;
69        let req = into_reqwest(request)?;
70        let mut resp = CLIENT
71            .execute(req)
72            .map_err(|e| viaduct::Error::NetworkError(e.to_string()))?;
73        let status = resp.status().as_u16();
74        let url = resp.url().clone();
75        let mut body = Vec::with_capacity(resp.content_length().unwrap_or_default() as usize);
76        resp.read_to_end(&mut body).map_err(|e| {
77            error!("Failed to get body from response: {:?}", e);
78            viaduct::Error::NetworkError(e.to_string())
79        })?;
80        let mut headers = viaduct::Headers::with_capacity(resp.headers().len());
81        for (k, v) in resp.headers() {
82            let val = String::from_utf8_lossy(v.as_bytes()).to_string();
83            let hname = match viaduct::HeaderName::new(k.as_str().to_owned()) {
84                Ok(name) => name,
85                Err(e) => {
86                    // Ignore headers with invalid names, since nobody can look for them anyway.
87                    warn!("Server sent back invalid header name: '{}'", e);
88                    continue;
89                }
90            };
91            // Not using Header::new since the error it returns is for request headers.
92            headers.insert_header(viaduct::Header::new_unchecked(hname, val));
93        }
94        Ok(viaduct::Response {
95            request_method,
96            url,
97            status,
98            headers,
99            body,
100        })
101    }
102}
103
104static INIT_REQWEST_BACKEND: Once = Once::new();
105
106pub fn use_reqwest_backend() {
107    INIT_REQWEST_BACKEND.call_once(|| {
108        viaduct::set_backend(Box::leak(Box::new(ReqwestBackend)))
109            .expect("Backend already set (FFI)");
110    })
111}
112
113#[no_mangle]
114#[cfg(target_os = "ios")]
115pub extern "C" fn viaduct_use_reqwest_backend() {
116    use_reqwest_backend();
117}