tauri_plugin_http/lib.rs
1// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
2// SPDX-License-Identifier: Apache-2.0
3// SPDX-License-Identifier: MIT
4
5//! Access the HTTP client written in Rust.
6//!
7//! ## Cargo features
8//!
9//! ### Reqwest feature forwards
10//!
11//! These features forwards [`reqwest`](https://docs.rs/reqwest/0.12.28/reqwest/index.html) features:
12//!
13//! - **http2** *(enabled by default)*: Enables HTTP/2 support.
14//! - **native-tls**: Enables TLS functionality provided by native-tls.
15//! - **native-tls-vendored**: Enables the vendored feature of native-tls.
16//! - **native-tls-alpn**: Enables the alpn feature of native-tls.
17//! - **rustls-tls** *(enabled by default)*: Enables TLS functionality provided by rustls. Equivalent to
18//! rustls-tls-webpki-roots.
19//! - **rustls-tls-manual-roots**: Enables TLS functionality provided by rustls, without setting any root
20//! certificates. Roots have to be specified manually.
21//! - **rustls-tls-webpki-roots**: Enables TLS functionality provided by rustls, while using root certificates
22//! from the webpki-roots crate.
23//! - **rustls-tls-native-roots**: Enables TLS functionality provided by rustls, while using root certificates
24//! from the rustls-native-certs crate.
25//! - **blocking**: Provides the [blocking](https://docs.rs/reqwest/0.12.28/reqwest/blocking/index.html) client API.
26//! - **charset** *(enabled by default)*: Improved support for decoding text.
27//! - **cookies** *(enabled by default)*: Provides cookie session support.
28//! - **gzip**: Provides response body gzip decompression.
29//! - **brotli**: Provides response body brotli decompression.
30//! - **zstd**: Provides response body zstd decompression.
31//! - **deflate**: Provides response body deflate decompression.
32//! - **json**: Provides serialization and deserialization for JSON bodies.
33//! - **multipart**: Provides functionality for multipart forms.
34//! - **stream**: Adds support for futures::Stream.
35//! - **socks**: Provides SOCKS5 proxy support.
36//! - **trust-dns**: Enables a trust-dns/Hickory DNS async resolver instead of the default threadpool using
37//! getaddrinfo.
38//! - **macos-system-configuration** *(deprecated, use `system-proxy` instead)*: Use Windows and macOS system proxy settings automatically.
39//! - **system-proxy** *(enabled by default)*: Use Windows and macOS system proxy settings automatically.
40//!
41//! ### tauri-plugin-http features
42//!
43//! - **tracing**: Adds request, response, and cookie-store diagnostics through `tracing`.
44//! - **unsafe-headers**: Allows webview requests to send any headers.
45//! - **dangerous-settings**: Allows dangerous client settings such as accepting invalid certificates or hostnames.
46//!
47//! ## Configuration
48//!
49//! See [`Config`] for the options that can be set on the `plugins > http` object of your
50//! `tauri.conf.json`:
51//!
52//! ```json
53//! {
54//! "plugins": {
55//! "http": {
56//! "scopeRedirects": true
57//! }
58//! }
59//! }
60//! ```
61
62pub use reqwest;
63use tauri::{
64 Manager, Runtime,
65 plugin::{Builder, TauriPlugin},
66};
67
68pub use config::Config;
69pub use error::{Error, Result};
70
71mod commands;
72mod config;
73mod error;
74#[cfg(feature = "cookies")]
75mod reqwest_cookie_store;
76mod scope;
77
78#[cfg(feature = "cookies")]
79const COOKIES_FILENAME: &str = ".cookies";
80
81pub(crate) struct Http {
82 pub(crate) config: Config,
83 #[cfg(feature = "cookies")]
84 cookies_jar: std::sync::Arc<crate::reqwest_cookie_store::CookieStoreMutex>,
85}
86
87/// Initializes the plugin.
88///
89/// The plugin reads its [`Config`] from the `plugins > http` object of the `tauri.conf.json` file;
90/// when that object is missing, [`Config::default`] is used.
91///
92/// With the `cookies` Cargo feature (enabled by default), a cookie jar is loaded from a `.cookies`
93/// file in the application cache directory on setup and written back to it when the application
94/// exits. A jar that cannot be read is replaced by an empty one.
95///
96/// Register it on the Tauri builder with `.plugin(tauri_plugin_http::init())`.
97pub fn init<R: Runtime>() -> TauriPlugin<R, Option<Config>> {
98 Builder::<R, Option<Config>>::new("http")
99 .setup(|app, api| {
100 #[cfg(feature = "cookies")]
101 let cookies_jar = {
102 use crate::reqwest_cookie_store::*;
103 use std::fs::File;
104 use std::io::BufReader;
105
106 let cache_dir = app.path().app_cache_dir()?;
107 std::fs::create_dir_all(&cache_dir)?;
108
109 let path = cache_dir.join(COOKIES_FILENAME);
110 let file = File::options()
111 .create(true)
112 .append(true)
113 .read(true)
114 .open(&path)?;
115
116 let reader = BufReader::new(file);
117 CookieStoreMutex::load(path.clone(), reader).unwrap_or_else(|_e| {
118 #[cfg(feature = "tracing")]
119 tracing::warn!(
120 "failed to load cookie store: {_e}, falling back to empty store"
121 );
122 CookieStoreMutex::new(path, Default::default())
123 })
124 };
125
126 let state = Http {
127 config: api.config().clone().unwrap_or_default(),
128 #[cfg(feature = "cookies")]
129 cookies_jar: std::sync::Arc::new(cookies_jar),
130 };
131
132 app.manage(state);
133
134 Ok(())
135 })
136 .on_event(|app, event| {
137 #[cfg(feature = "cookies")]
138 if let tauri::RunEvent::Exit = event {
139 let state = app.state::<Http>();
140
141 match state.cookies_jar.request_save() {
142 Ok(rx) => {
143 let _ = rx.recv();
144 }
145 Err(_e) => {
146 #[cfg(feature = "tracing")]
147 tracing::error!("failed to save cookie jar: {_e}");
148 }
149 }
150 }
151 })
152 .invoke_handler(tauri::generate_handler![
153 commands::fetch,
154 commands::fetch_cancel,
155 commands::fetch_send,
156 commands::fetch_read_body,
157 commands::fetch_cancel_body,
158 ])
159 .build()
160}