Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

WIP: Cookies and CookieJar support #126

Open
wants to merge 12 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@ repository = "https://github.com/sbstp/attohttpc"

[dependencies]
base64 = {version = "0.13.0", optional = true}
bytes = "1.2.1"
cookie = "0.16.0"
cookie_store = "0.16.1"
encoding_rs = {version = "0.8.31", optional = true}
encoding_rs_io = {version = "0.1.7", optional = true}
flate2 = {version = "1.0.24", optional = true}
Expand Down
105 changes: 105 additions & 0 deletions src/cookies.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
#[cfg(feature = "cookies")]
use std::sync::Arc;
#[cfg(feature = "cookies")]
use std::sync::RwLock;

#[cfg(feature = "cookies")]
use bytes::Bytes;
#[cfg(feature = "cookies")]
use cookie::Cookie as RawCookie;
#[cfg(feature = "cookies")]
use cookie_store::CookieStore;
#[cfg(feature = "cookies")]
use cookie_store::CookieStore;
use url::Url;

use crate::header::HeaderValue;

pub(crate) trait InternalJar: Clone + Default {
fn new() -> Self;

fn header_value_for_url(&self, url: &Url) -> Option<HeaderValue>;

fn store_cookies_for_url<'a>(&self, url: &Url, set_cookie_headers: impl Iterator<Item = &'a HeaderValue>);
}

#[cfg(feature = "cookies")]
#[derive(Clone, Debug)]
pub struct CookieJarImpl {
inner: Arc<RwLock<CookieStore>>,
}

#[derive(Clone, Debug)]
pub struct NoOpJar {}

#[cfg(feature = "cookies")]
pub type CookieJar = CookieJarImpl;

#[cfg(not(feature = "cookies"))]
pub type CookieJar = NoOpJar;

#[cfg(feature = "cookies")]
impl InternalJar for CookieJarImpl {
fn new() -> Self {
CookieJarImpl {
inner: Arc::new(RwLock::new(CookieStore::default())),
}
}

fn header_value_for_url(&self, url: &Url) -> Option<HeaderValue> {
// Credit: This code is basically taken from reqwest's CookieJar as-is.
// https://docs.rs/reqwest/latest/src/reqwest/cookie.rs.html

let hvalue = self
.inner
.read()
.unwrap()
.get_request_values(url)
.map(|(name, value)| format!("{}={}", name, value))
.collect::<Vec<_>>()
.join("; ");

if hvalue.is_empty() {
return None;
}

HeaderValue::from_maybe_shared(Bytes::from(hvalue)).ok()
}

fn store_cookies_for_url<'a>(&self, url: &Url, set_cookie_headers: impl Iterator<Item = &'a HeaderValue>) {
let iter =
set_cookie_headers.filter_map(|v| match RawCookie::parse(std::str::from_utf8(v.as_bytes()).unwrap()) {
sbstp marked this conversation as resolved.
Show resolved Hide resolved
Ok(c) => Some(c.into_owned()),
Err(err) => {
warn!("Invalid cookie could not be stored to jar: {}", err);
None
}
});
self.inner.write().unwrap().store_response_cookies(iter, url)
}
}

#[cfg(feature = "cookies")]
impl Default for CookieJarImpl {
fn default() -> Self {
Self::new()
}
}

impl InternalJar for NoOpJar {
fn new() -> Self {
NoOpJar {}
}

fn header_value_for_url(&self, _: &Url) -> Option<HeaderValue> {
None
}

fn store_cookies_for_url<'a>(&self, _: &Url, _: impl Iterator<Item = &'a HeaderValue>) {}
}

impl Default for NoOpJar {
fn default() -> Self {
Self::new()
}
}
1 change: 1 addition & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@ macro_rules! warn {

#[cfg(feature = "charsets")]
pub mod charsets;
mod cookies;
mod error;
mod happy;
#[cfg(feature = "multipart")]
Expand Down
10 changes: 5 additions & 5 deletions src/parsing/compressed_reader.rs
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,7 @@ mod tests {
let _ = write!(buf, "HTTP/1.1 200 OK\r\nContent-Length: {}\r\n\r\n", payload.len());
buf.extend(payload);

let req = PreparedRequest::new(Method::GET, "http://google.ca");
let req = PreparedRequest::new(Method::GET, "http://google.ca", None);

let sock = BaseStream::mock(buf);
let response = parse_response(sock, &req).unwrap();
Expand All @@ -178,7 +178,7 @@ mod tests {
);
buf.extend(payload);

let req = PreparedRequest::new(Method::GET, "http://google.ca");
let req = PreparedRequest::new(Method::GET, "http://google.ca", None);

let sock = BaseStream::mock(buf);
let response = parse_response(sock, &req).unwrap();
Expand All @@ -201,7 +201,7 @@ mod tests {
);
buf.extend(payload);

let req = PreparedRequest::new(Method::GET, "http://google.ca");
let req = PreparedRequest::new(Method::GET, "http://google.ca", None);

let sock = BaseStream::mock(buf);
let response = parse_response(sock, &req).unwrap();
Expand All @@ -214,7 +214,7 @@ mod tests {
fn test_no_body_with_gzip() {
let buf = b"HTTP/1.1 200 OK\r\ncontent-encoding: gzip\r\n\r\n";

let req = PreparedRequest::new(Method::GET, "http://google.ca");
let req = PreparedRequest::new(Method::GET, "http://google.ca", None);
let sock = BaseStream::mock(buf.to_vec());
// Fixed by the move from libflate to flate2
assert!(parse_response(sock, &req).is_ok());
Expand All @@ -225,7 +225,7 @@ mod tests {
fn test_no_body_with_gzip_head() {
let buf = b"HTTP/1.1 200 OK\r\ncontent-encoding: gzip\r\n\r\n";

let req = PreparedRequest::new(Method::HEAD, "http://google.ca");
let req = PreparedRequest::new(Method::HEAD, "http://google.ca", None);
let sock = BaseStream::mock(buf.to_vec());
assert!(parse_response(sock, &req).is_ok());
}
Expand Down
30 changes: 26 additions & 4 deletions src/request/builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ use std::fs;
use std::str;
use std::time::Duration;

use http::header::COOKIE;
use http::{
header::{
HeaderMap, HeaderValue, IntoHeaderName, ACCEPT, CONNECTION, CONTENT_LENGTH, CONTENT_TYPE, TRANSFER_ENCODING,
Expand All @@ -15,6 +16,7 @@ use url::Url;

#[cfg(feature = "charsets")]
use crate::charsets::Charset;
use crate::cookies::{CookieJar, InternalJar};
use crate::error::{Error, ErrorKind, Result};
use crate::parsing::Response;
use crate::request::{
Expand All @@ -37,6 +39,7 @@ pub struct RequestBuilder<B = body::Empty> {
url: Url,
method: Method,
body: B,
cookie_jar: Option<CookieJar>,
base_settings: BaseSettings,
}

Expand All @@ -60,17 +63,27 @@ impl RequestBuilder {
where
U: AsRef<str>,
{
Self::try_with_settings(method, base_url, BaseSettings::default())
Self::try_with_settings(method, base_url, None, BaseSettings::default())
}

pub(crate) fn with_settings<U>(method: Method, base_url: U, base_settings: BaseSettings) -> Self
pub(crate) fn with_settings<U>(
method: Method,
base_url: U,
cookie_jar: Option<CookieJar>,
base_settings: BaseSettings,
) -> Self
where
U: AsRef<str>,
{
Self::try_with_settings(method, base_url, base_settings).expect("invalid url or method")
Self::try_with_settings(method, base_url, cookie_jar, base_settings).expect("invalid url or method")
}

pub(crate) fn try_with_settings<U>(method: Method, base_url: U, base_settings: BaseSettings) -> Result<Self>
pub(crate) fn try_with_settings<U>(
method: Method,
base_url: U,
cookie_jar: Option<CookieJar>,
base_settings: BaseSettings,
) -> Result<Self>
where
U: AsRef<str>,
{
Expand All @@ -85,6 +98,7 @@ impl RequestBuilder {
method,
body: body::Empty,
base_settings,
cookie_jar,
})
}
}
Expand Down Expand Up @@ -152,6 +166,7 @@ impl<B> RequestBuilder<B> {
method: self.method,
body,
base_settings: self.base_settings,
cookie_jar: self.cookie_jar,
}
}

Expand Down Expand Up @@ -414,6 +429,7 @@ impl<B: Body> RequestBuilder<B> {
url: self.url,
method: self.method,
body: self.body,
cookie_jar: self.cookie_jar.clone(),
base_settings: self.base_settings,
};

Expand All @@ -436,6 +452,12 @@ impl<B: Body> RequestBuilder<B> {
header_insert_if_missing(&mut prepped.base_settings.headers, ACCEPT, "*/*")?;
header_insert_if_missing(&mut prepped.base_settings.headers, USER_AGENT, DEFAULT_USER_AGENT)?;

if let Some(cookie_jar) = self.cookie_jar {
if let Some(header_val) = cookie_jar.header_value_for_url(&prepped.url) {
header_insert(&mut prepped.base_settings.headers, COOKIE, header_val)?;
}
}

Ok(prepped)
}

Expand Down
12 changes: 11 additions & 1 deletion src/request/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,14 @@ use std::time::Instant;

#[cfg(feature = "compress")]
use http::header::ACCEPT_ENCODING;
use http::header::SET_COOKIE;
use http::{
header::{HeaderValue, IntoHeaderName, HOST},
HeaderMap, Method, StatusCode, Version,
};
use url::Url;

use crate::cookies::{CookieJar, InternalJar};
use crate::error::{Error, ErrorKind, InvalidResponseKind, Result};
use crate::parsing::{parse_response, Response};
use crate::streams::{BaseStream, ConnectInfo};
Expand Down Expand Up @@ -66,19 +68,21 @@ pub struct PreparedRequest<B> {
url: Url,
method: Method,
body: B,
cookie_jar: Option<CookieJar>,
pub(crate) base_settings: BaseSettings,
}

#[cfg(test)]
impl PreparedRequest<body::Empty> {
pub(crate) fn new<U>(method: Method, base_url: U) -> Self
pub(crate) fn new<U>(method: Method, base_url: U, cookie_jar: Option<CookieJar>) -> Self
where
U: AsRef<str>,
{
PreparedRequest {
url: Url::parse(base_url.as_ref()).unwrap(),
method,
body: body::Empty,
cookie_jar: cookie_jar,
base_settings: BaseSettings::default(),
}
}
Expand Down Expand Up @@ -232,6 +236,10 @@ impl<B: Body> PreparedRequest<B> {

debug!("status code {}", resp.status().as_u16());

if let Some(cookie_jar) = &self.cookie_jar {
cookie_jar.store_cookies_for_url(&url, resp.headers().get_all(SET_COOKIE).iter());
}

let is_redirect = matches!(
resp.status(),
StatusCode::MOVED_PERMANENTLY
Expand Down Expand Up @@ -333,6 +341,7 @@ mod test {
method: Method::GET,
url: Url::parse("http://reddit.com/r/rust").unwrap(),
body: Empty,
cookie_jar: None,
base_settings: BaseSettings::default(),
};

Expand All @@ -352,6 +361,7 @@ mod test {
method: Method::GET,
url: Url::parse("http://reddit.com/r/rust").unwrap(),
body: Empty,
cookie_jar: None,
base_settings: BaseSettings::default(),
};

Expand Down
Loading