-
-
Notifications
You must be signed in to change notification settings - Fork 117
Expand file tree
/
Copy pathcookie.rs
More file actions
235 lines (199 loc) · 6.4 KB
/
Copy pathcookie.rs
File metadata and controls
235 lines (199 loc) · 6.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
//! HTTP Cookies
use std::{convert::TryInto, fmt, sync::Arc, time::SystemTime};
use bytes::BufMut;
use cookie_crate::{Cookie as RawCookie, Expiration, SameSite};
use crate::{
error::Error,
header::{HeaderValue, SET_COOKIE},
sync::RwLock,
};
/// Actions for a persistent cookie store providing session support.
pub trait CookieStore: Send + Sync {
/// Store a set of Set-Cookie header values received from `url`
fn set_cookies(&self, cookie_headers: &mut dyn Iterator<Item = &HeaderValue>, url: &url::Url);
/// Get any Cookie values in the store for `url`
fn cookies(&self, url: &url::Url) -> Vec<HeaderValue>;
}
/// Trait for converting types into a shared cookie store ([`Arc<dyn CookieStore>`]).
///
/// Implemented for any [`CookieStore`] type, [`Arc<T>`] where `T: CookieStore`, and [`Arc<dyn
/// CookieStore>`]. Enables ergonomic conversion to a trait object for use in APIs without manual
/// boxing.
pub trait IntoCookieStore {
/// Converts the implementor into an [`Arc<dyn CookieStore>`].
///
/// This method allows ergonomic conversion of concrete cookie stores, [`Arc<T>`], or
/// existing [`Arc<dyn CookieStore>`] into a trait object suitable for APIs that expect
/// a shared cookie store.
fn into_cookie_store(self) -> Arc<dyn CookieStore>;
}
/// A single HTTP cookie.
#[derive(Debug, Clone)]
pub struct Cookie<'a>(RawCookie<'a>);
/// A good default `CookieStore` implementation.
///
/// This is the implementation used when simply calling `cookie_store(true)`.
/// This type is exposed to allow creating one and filling it with some
/// existing cookies more easily, before creating a `Client`.
#[derive(Debug)]
pub struct Jar(RwLock<cookie_store::CookieStore>);
// ===== impl IntoCookieStore =====
impl IntoCookieStore for Arc<dyn CookieStore> {
#[inline]
fn into_cookie_store(self) -> Arc<dyn CookieStore> {
self
}
}
impl<R> IntoCookieStore for Arc<R>
where
R: CookieStore + 'static,
{
#[inline]
fn into_cookie_store(self) -> Arc<dyn CookieStore> {
self
}
}
impl<R> IntoCookieStore for R
where
R: CookieStore + 'static,
{
#[inline]
fn into_cookie_store(self) -> Arc<dyn CookieStore> {
Arc::new(self)
}
}
// ===== impl Cookie =====
impl<'a> Cookie<'a> {
fn parse(value: &'a HeaderValue) -> crate::Result<Cookie<'a>> {
std::str::from_utf8(value.as_bytes())
.map_err(cookie_crate::ParseError::from)
.and_then(cookie_crate::Cookie::parse)
.map_err(Error::decode)
.map(Cookie)
}
/// The name of the cookie.
#[inline]
pub fn name(&self) -> &str {
self.0.name()
}
/// The value of the cookie.
#[inline]
pub fn value(&self) -> &str {
self.0.value()
}
/// Returns true if the 'HttpOnly' directive is enabled.
#[inline]
pub fn http_only(&self) -> bool {
self.0.http_only().unwrap_or(false)
}
/// Returns true if the 'Secure' directive is enabled.
#[inline]
pub fn secure(&self) -> bool {
self.0.secure().unwrap_or(false)
}
/// Returns true if 'SameSite' directive is 'Lax'.
#[inline]
pub fn same_site_lax(&self) -> bool {
self.0.same_site() == Some(SameSite::Lax)
}
/// Returns true if 'SameSite' directive is 'Strict'.
#[inline]
pub fn same_site_strict(&self) -> bool {
self.0.same_site() == Some(SameSite::Strict)
}
/// Returns the path directive of the cookie, if set.
#[inline]
pub fn path(&self) -> Option<&str> {
self.0.path()
}
/// Returns the domain directive of the cookie, if set.
#[inline]
pub fn domain(&self) -> Option<&str> {
self.0.domain()
}
/// Get the Max-Age information.
#[inline]
pub fn max_age(&self) -> Option<std::time::Duration> {
self.0.max_age().and_then(|d| d.try_into().ok())
}
/// The cookie expiration time.
#[inline]
pub fn expires(&self) -> Option<SystemTime> {
match self.0.expires() {
Some(Expiration::DateTime(offset)) => Some(SystemTime::from(offset)),
None | Some(Expiration::Session) => None,
}
}
/// Converts `self` into a `Cookie` with a static lifetime with as few
/// allocations as possible.
#[inline]
pub fn into_owned(self) -> Cookie<'static> {
Cookie(self.0.into_owned())
}
}
impl fmt::Display for Cookie<'_> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.0.fmt(f)
}
}
pub(crate) fn extract_response_cookies(
headers: &http::HeaderMap,
) -> impl Iterator<Item = crate::Result<Cookie<'_>>> {
headers.get_all(SET_COOKIE).iter().map(Cookie::parse)
}
// ===== impl Jar =====
impl Jar {
/// Add a cookie str to this jar.
///
/// # Example
///
/// ```
/// use wreq::{
/// Url,
/// cookie::Jar,
/// };
///
/// let cookie = "foo=bar; Domain=yolo.local";
/// let url = "https://yolo.local".parse::<Url>().unwrap();
///
/// let jar = Jar::default();
/// jar.add_cookie_str(cookie, &url);
///
/// // and now add to a `ClientBuilder`?
/// ```
pub fn add_cookie_str(&self, cookie: &str, url: &url::Url) {
let cookies = cookie_crate::Cookie::parse(cookie)
.ok()
.map(|c| c.into_owned())
.into_iter();
self.0.write().store_response_cookies(cookies, url);
}
}
impl CookieStore for Jar {
fn set_cookies(&self, cookie_headers: &mut dyn Iterator<Item = &HeaderValue>, url: &url::Url) {
let iter =
cookie_headers.filter_map(|val| Cookie::parse(val).map(|c| c.0.into_owned()).ok());
self.0.write().store_response_cookies(iter, url);
}
fn cookies(&self, url: &url::Url) -> Vec<HeaderValue> {
const COOKIE_SEPARATOR: &[u8] = b"=";
self.0
.read()
.get_request_values(url)
.filter_map(|(name, value)| {
let name = name.as_bytes();
let value = value.as_bytes();
let mut cookie = bytes::BytesMut::with_capacity(name.len() + 1 + value.len());
cookie.put(name);
cookie.put(COOKIE_SEPARATOR);
cookie.put(value);
HeaderValue::from_maybe_shared(cookie).ok()
})
.collect()
}
}
impl Default for Jar {
fn default() -> Self {
Self(RwLock::new(cookie_store::CookieStore::default()))
}
}