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/. */
45use error_support::{error, warn};
6use once_cell::sync::Lazy;
7use std::{io::Read, sync::Once};
8use viaduct::{settings::GLOBAL_SETTINGS, Backend};
910// 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.
1314static CLIENT: Lazy<reqwest::blocking::Client> = Lazy::new(|| {
15let settings = GLOBAL_SETTINGS.read();
16let 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 });
24if 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.
30builder = builder.user_agent("Firefox-iOS-FxA/24");
31 }
32// Note: no cookie or cache support.
33builder
34 .build()
35 .expect("Failed to initialize global reqwest::Client")
36});
3738#[allow(clippy::unnecessary_wraps)] // not worth the time to untangle
39fn into_reqwest(request: viaduct::Request) -> Result<reqwest::blocking::Request, viaduct::Error> {
40let 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 };
51let mut result = reqwest::blocking::Request::new(method, request.url);
52for h in request.headers {
53use reqwest::header::{HeaderName, HeaderValue};
54// Unwraps should be fine, we verify these in `Header`
55let 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);
61Ok(result)
62}
6364pub struct ReqwestBackend;
65impl Backend for ReqwestBackend {
66fn send(&self, request: viaduct::Request) -> Result<viaduct::Response, viaduct::Error> {
67 viaduct::note_backend("reqwest (untrusted)");
68let request_method = request.method;
69let req = into_reqwest(request)?;
70let mut resp = CLIENT
71 .execute(req)
72 .map_err(|e| viaduct::Error::NetworkError(e.to_string()))?;
73let status = resp.status().as_u16();
74let url = resp.url().clone();
75let mut body = Vec::with_capacity(resp.content_length().unwrap_or_default() as usize);
76 resp.read_to_end(&mut body).map_err(|e| {
77error!("Failed to get body from response: {:?}", e);
78 viaduct::Error::NetworkError(e.to_string())
79 })?;
80let mut headers = viaduct::Headers::with_capacity(resp.headers().len());
81for (k, v) in resp.headers() {
82let val = String::from_utf8_lossy(v.as_bytes()).to_string();
83let hname = match viaduct::HeaderName::new(k.as_str().to_owned()) {
84Ok(name) => name,
85Err(e) => {
86// Ignore headers with invalid names, since nobody can look for them anyway.
87warn!("Server sent back invalid header name: '{}'", e);
88continue;
89 }
90 };
91// Not using Header::new since the error it returns is for request headers.
92headers.insert_header(viaduct::Header::new_unchecked(hname, val));
93 }
94Ok(viaduct::Response {
95 request_method,
96 url,
97 status,
98 headers,
99 body,
100 })
101 }
102}
103104static INIT_REQWEST_BACKEND: Once = Once::new();
105106pub 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}
112113#[no_mangle]
114#[cfg(target_os = "ios")]
115pub extern "C" fn viaduct_use_reqwest_backend() {
116 use_reqwest_backend();
117}