Skip to main content

lreqwest_cookie_store/
lib.rs

1#![allow(unused_imports)]
2#![deny(warnings, missing_debug_implementations, rust_2018_idioms)]
3#![cfg_attr(docsrs, feature(doc_cfg))]
4//! # Example
5//! The following example demonstrates loading a [`cookie_store::CookieStore`] (re-exported in this crate) from disk, and using it within a
6//! [`CookieStoreMutex`]. It then makes a series of requests, examining and modifying the contents
7//! of the underlying [`cookie_store::CookieStore`] in between.
8//! ```
9//! # tokio_test::block_on(async {
10//! // Load an existing set of cookies, serialized as json, if it is available
11//! let cookie_store = {
12//!   if let Ok(file) = std::fs::File::open("cookies.json")
13//!     .map(std::io::BufReader::new) {
14//!       cookie_store::serde::json::load(file).unwrap()
15//!     }
16//!     else {
17//!       reqwest_cookie_store::CookieStore::new()
18//!     }
19//! };
20//! let cookie_store = reqwest_cookie_store::CookieStoreMutex::new(cookie_store);
21//! let cookie_store = std::sync::Arc::new(cookie_store);
22//! {
23//!   // Examine initial contents
24//!   println!("initial load");
25//!   let store = cookie_store.lock().unwrap();
26//!   for c in store.iter_any() {
27//!     println!("{:?}", c);
28//!   }
29//! }
30//!
31//! // Build a `reqwest` Client, providing the deserialized store
32//! let client = reqwest::Client::builder()
33//!     .cookie_provider(std::sync::Arc::clone(&cookie_store))
34//!     .build()
35//!     .unwrap();
36//!
37//! // Make a sample request
38//! client.get("https://google.com").send().await.unwrap();
39//! {
40//!   // Examine the contents of the store.
41//!   println!("after google.com GET");
42//!   let store = cookie_store.lock().unwrap();
43//!   for c in store.iter_any() {
44//!     println!("{:?}", c);
45//!   }
46//! }
47//!
48//! // Make another request from another domain
49//! println!("GET from msn");
50//! client.get("https://msn.com").send().await.unwrap();
51//! {
52//!   // Examine the contents of the store.
53//!   println!("after msn.com GET");
54//!   let mut store = cookie_store.lock().unwrap();
55//!   for c in store.iter_any() {
56//!     println!("{:?}", c);
57//!   }
58//!   // Clear the store, and examine again
59//!   store.clear();
60//!   println!("after clear");
61//!   for c in store.iter_any() {
62//!     println!("{:?}", c);
63//!   }
64//! }
65//!
66//! // Get some new cookies
67//! client.get("https://google.com").send().await.unwrap();
68//! {
69//!   // Show serialized contents of the store. Alternatively, using
70//!   // a `std::fs::File` for `writer` could be used to serialize
71//!   // the store to disk:
72//!   // let mut writer = std::fs::File::create("output_cookies.json")
73//!   //     .map(std::io::BufWriter::new)
74//!   //     .unwrap();
75//!   let mut writer = std::io::BufWriter::new(Vec::new());
76//!   let store = cookie_store.lock().unwrap();
77//!   cookie_store::serde::json::save(&store, &mut writer).unwrap();
78//!   let cookies_json = String::from_utf8(writer.into_inner().unwrap()).unwrap();
79//!   println!("JSON serialization of cookies contents: {cookies_json}");
80//!   assert!(cookies_json.contains("Domain=google.com"));
81//! }
82//! # });
83//!```
84
85use std::{
86    ops::Deref,
87    sync::{LockResult, Mutex, MutexGuard, PoisonError, RwLock, RwLockReadGuard, RwLockWriteGuard},
88};
89
90use bytes::Bytes;
91pub use cookie_store::{CookieStore, RawCookie, RawCookieParseError};
92use reqwest::header::HeaderValue;
93#[cfg(feature = "serde")]
94use serde_derive::{Deserialize, Serialize};
95use url;
96
97fn set_cookies(
98    cookie_store: &mut CookieStore,
99    cookie_headers: &mut dyn Iterator<Item = &HeaderValue>,
100    url: &url::Url,
101) {
102    let cookies = cookie_headers.filter_map(|val| {
103        std::str::from_utf8(val.as_bytes())
104            .map_err(RawCookieParseError::from)
105            .and_then(RawCookie::parse)
106            .map(|c| c.into_owned())
107            .ok()
108    });
109    cookie_store.store_response_cookies(cookies, url);
110}
111
112fn cookies(cookie_store: &CookieStore, url: &url::Url) -> Option<HeaderValue> {
113    let s = cookie_store
114        .get_request_values(url)
115        .map(|(name, value)| format!("{}={}", name, value))
116        .collect::<Vec<_>>()
117        .join("; ");
118
119    if s.is_empty() {
120        return None;
121    }
122
123    HeaderValue::from_maybe_shared(Bytes::from(s)).ok()
124}
125
126/// A [`cookie_store::CookieStore`] wrapped internally by a [`std::sync::Mutex`], suitable for use in
127/// async/concurrent contexts.
128#[derive(Debug)]
129#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
130pub struct CookieStoreMutex(Mutex<CookieStore>);
131
132impl Default for CookieStoreMutex {
133    /// Create a new, empty [`CookieStoreMutex`]
134    fn default() -> Self {
135        CookieStoreMutex::new(CookieStore::default())
136    }
137}
138
139impl CookieStoreMutex {
140    /// Create a new [`CookieStoreMutex`] from an existing [`cookie_store::CookieStore`].
141    pub const fn new(cookie_store: CookieStore) -> CookieStoreMutex {
142        CookieStoreMutex(Mutex::new(cookie_store))
143    }
144
145    /// Lock and get a handle to the contained [`cookie_store::CookieStore`].
146    pub fn lock(
147        &self,
148    ) -> Result<MutexGuard<'_, CookieStore>, PoisonError<MutexGuard<'_, CookieStore>>> {
149        self.0.lock()
150    }
151
152    /// Consumes this [`CookieStoreMutex`], returning the underlying [`cookie_store::CookieStore`]
153    pub fn into_inner(self) -> LockResult<CookieStore> {
154        self.0.into_inner()
155    }
156}
157
158impl reqwest::cookie::CookieStore for CookieStoreMutex {
159    fn set_cookies(&self, cookie_headers: &mut dyn Iterator<Item = &HeaderValue>, url: &url::Url) {
160        let mut store = self.0.lock().unwrap();
161        set_cookies(&mut store, cookie_headers, url);
162    }
163
164    fn cookies(&self, url: &url::Url) -> Option<HeaderValue> {
165        let store = self.0.lock().unwrap();
166        cookies(&store, url)
167    }
168}
169
170/// A [`cookie_store::CookieStore`] wrapped internally by a [`std::sync::RwLock`], suitable for use in
171/// async/concurrent contexts.
172#[derive(Debug)]
173#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
174pub struct CookieStoreRwLock(RwLock<CookieStore>);
175
176impl Default for CookieStoreRwLock {
177    /// Create a new, empty [`CookieStoreRwLock`].
178    fn default() -> Self {
179        CookieStoreRwLock::new(CookieStore::default())
180    }
181}
182
183impl CookieStoreRwLock {
184    /// Create a new [`CookieStoreRwLock`] from an existing [`cookie_store::CookieStore`].
185    pub const fn new(cookie_store: CookieStore) -> CookieStoreRwLock {
186        CookieStoreRwLock(RwLock::new(cookie_store))
187    }
188
189    /// Lock and get a read (non-exclusive) handle to the contained [`cookie_store::CookieStore`].
190    pub fn read(
191        &self,
192    ) -> Result<RwLockReadGuard<'_, CookieStore>, PoisonError<RwLockReadGuard<'_, CookieStore>>>
193    {
194        self.0.read()
195    }
196
197    /// Lock and get a write (exclusive) handle to the contained [`cookie_store::CookieStore`].
198    pub fn write(
199        &self,
200    ) -> Result<RwLockWriteGuard<'_, CookieStore>, PoisonError<RwLockWriteGuard<'_, CookieStore>>>
201    {
202        self.0.write()
203    }
204
205    /// Consume this [`CookieStoreRwLock`], returning the underlying [`cookie_store::CookieStore`]
206    pub fn into_inner(self) -> LockResult<CookieStore> {
207        self.0.into_inner()
208    }
209}
210
211impl reqwest::cookie::CookieStore for CookieStoreRwLock {
212    fn set_cookies(&self, cookie_headers: &mut dyn Iterator<Item = &HeaderValue>, url: &url::Url) {
213        let mut write = self.0.write().unwrap();
214        set_cookies(&mut write, cookie_headers, url);
215    }
216
217    fn cookies(&self, url: &url::Url) -> Option<HeaderValue> {
218        let read = self.0.read().unwrap();
219        cookies(&read, url)
220    }
221}