Skip to main content

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    plugin::{Builder, TauriPlugin},
65    Manager, Runtime,
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
87pub fn init<R: Runtime>() -> TauriPlugin<R, Option<Config>> {
88    Builder::<R, Option<Config>>::new("http")
89        .setup(|app, api| {
90            #[cfg(feature = "cookies")]
91            let cookies_jar = {
92                use crate::reqwest_cookie_store::*;
93                use std::fs::File;
94                use std::io::BufReader;
95
96                let cache_dir = app.path().app_cache_dir()?;
97                std::fs::create_dir_all(&cache_dir)?;
98
99                let path = cache_dir.join(COOKIES_FILENAME);
100                let file = File::options()
101                    .create(true)
102                    .append(true)
103                    .read(true)
104                    .open(&path)?;
105
106                let reader = BufReader::new(file);
107                CookieStoreMutex::load(path.clone(), reader).unwrap_or_else(|_e| {
108                    #[cfg(feature = "tracing")]
109                    tracing::warn!(
110                        "failed to load cookie store: {_e}, falling back to empty store"
111                    );
112                    CookieStoreMutex::new(path, Default::default())
113                })
114            };
115
116            let state = Http {
117                config: api.config().clone().unwrap_or_default(),
118                #[cfg(feature = "cookies")]
119                cookies_jar: std::sync::Arc::new(cookies_jar),
120            };
121
122            app.manage(state);
123
124            Ok(())
125        })
126        .on_event(|app, event| {
127            #[cfg(feature = "cookies")]
128            if let tauri::RunEvent::Exit = event {
129                let state = app.state::<Http>();
130
131                match state.cookies_jar.request_save() {
132                    Ok(rx) => {
133                        let _ = rx.recv();
134                    }
135                    Err(_e) => {
136                        #[cfg(feature = "tracing")]
137                        tracing::error!("failed to save cookie jar: {_e}");
138                    }
139                }
140            }
141        })
142        .invoke_handler(tauri::generate_handler![
143            commands::fetch,
144            commands::fetch_cancel,
145            commands::fetch_send,
146            commands::fetch_read_body,
147            commands::fetch_cancel_body,
148        ])
149        .build()
150}