Repository: algesten/ureq
Pull request #153 (2020-09-20 21:03:35)

Remove DEFAULT_HOST
In a few places we relied on "localhost" as a default if a URL's host was not set, but I think it's better to error out in these cases.

In general, there are a few places in Unit that assumed there is a host as part of the URL. I've made that explicit by doing a check at the beginning of `connect()`. I've also tried to plumb through the semantics of "host is always present" by changing the parameter types of some of the functions that use the hostname.

I considered a more thorough way to express this with types - for instance implementing an `HttpUrl` struct that embeds a `Url`, and exports most of the same methods, but guarantees that host is always present. However, that was more invasive than this so I did a smaller change to start.


Patch:
diff --git a/src/agent.rs b/src/agent.rs
index b5b79da..1aa5929 100644
--- a/src/agent.rs
+++ b/src/agent.rs
@@ -6,6 +6,7 @@ use std::sync::Mutex;
 use crate::header::{self, Header};
 use crate::pool::ConnectionPool;
 use crate::request::Request;
+use crate::resolve::ArcResolver;
 
 /// Agents keep state between requests.
 ///
@@ -53,15 +54,12 @@ pub(crate) struct AgentState {
     /// Cookies saved between requests.
     #[cfg(feature = "cookie")]
     pub(crate) jar: CookieJar,
+    pub(crate) resolver: ArcResolver,
 }
 
 impl AgentState {
     fn new() -> Self {
-        AgentState {
-            pool: ConnectionPool::new(),
-            #[cfg(feature = "cookie")]
-            jar: CookieJar::new(),
-        }
+        Self::default()
     }
     pub fn pool(&mut self) -> &mut ConnectionPool {
         &mut self.pool
@@ -194,6 +192,29 @@ impl Agent {
             .set_max_idle_connections_per_host(max_connections);
     }
 
+    /// Configures a custom resolver to be used by this agent. By default,
+    /// address-resolution is done by std::net::ToSocketAddrs. This allows you
+    /// to override that resolution with your own alternative. Useful for
+    /// testing and special-cases like DNS-based load balancing.
+    ///
+    /// A `Fn(&str) -> io::Result<Vec<SocketAddr>>` is a valid resolver,
+    /// passing a closure is a simple way to override. Note that you might need
+    /// explicit type `&str` on the closure argument for type inference to
+    /// succeed.
+    /// ```
+    /// use std::net::ToSocketAddrs;
+    ///
+    /// let mut agent = ureq::agent();
+    /// agent.set_resolver(|addr: &str| match addr {
+    ///    "example.com" => Ok(vec![([127,0,0,1], 8096).into()]),
+    ///    addr => addr.to_socket_addrs().map(Iterator::collect),
+    /// });
+    /// ```
+    pub fn set_resolver(&mut self, resolver: impl crate::Resolver + 'static) -> &mut Self {
+        self.state.lock().unwrap().resolver = resolver.into();
+        self
+    }
+
     /// Gets a cookie in this agent by name. Cookies are available
     /// either by setting it in the agent, or by making requests
     /// that `Set-Cookie` in the agent.
diff --git a/src/body.rs b/src/body.rs
index b6b188f..a7a2d97 100644
--- a/src/body.rs
+++ b/src/body.rs
@@ -43,11 +43,21 @@ impl Default for Payload {
     }
 }
 
+/// The size of the body.
+///
+/// *Internal API*
+#[derive(Debug)]
+pub(crate) enum BodySize {
+    Empty,
+    Unknown,
+    Known(u64),
+}
+
 /// Payloads are turned into this type where we can hold both a size and the reader.
 ///
 /// *Internal API*
 pub(crate) struct SizedReader {
-    pub size: Option<usize>,
+    pub size: BodySize,
     pub reader: Box<dyn Read + 'static>,
 }
 
@@ -58,7 +68,7 @@ impl fmt::Debug for SizedReader {
 }
 
 impl SizedReader {
-    fn new(size: Option<usize>, reader: Box<dyn Read + 'static>) -> Self {
+    fn new(size: BodySize, reader: Box<dyn Read + 'static>) -> Self {
         SizedReader { size, reader }
     }
 }
@@ -66,7 +76,7 @@ impl SizedReader {
 impl Payload {
     pub fn into_read(self) -> SizedReader {
         match self {
-            Payload::Empty => SizedReader::new(None, Box::new(empty())),
+            Payload::Empty => SizedReader::new(BodySize::Empty, Box::new(empty())),
             Payload::Text(text, _charset) => {
                 #[cfg(feature = "charset")]
                 let bytes = {
@@ -79,20 +89,20 @@ impl Payload {
                 let bytes = text.into_bytes();
                 let len = bytes.len();
                 let cursor = Cursor::new(bytes);
-                SizedReader::new(Some(len), Box::new(cursor))
+                SizedReader::new(BodySize::Known(len as u64), Box::new(cursor))
             }
             #[cfg(feature = "json")]
             Payload::JSON(v) => {
                 let bytes = serde_json::to_vec(&v).expect("Bad JSON in payload");
                 let len = bytes.len();
                 let cursor = Cursor::new(bytes);
-                SizedReader::new(Some(len), Box::new(cursor))
+                SizedReader::new(BodySize::Known(len as u64), Box::new(cursor))
             }
-            Payload::Reader(read) => SizedReader::new(None, read),
+            Payload::Reader(read) => SizedReader::new(BodySize::Unknown, read),
             Payload::Bytes(bytes) => {
                 let len = bytes.len();
                 let cursor = Cursor::new(bytes);
-                SizedReader::new(Some(len), Box::new(cursor))
+                SizedReader::new(BodySize::Known(len as u64), Box::new(cursor))
             }
         }
     }
diff --git a/src/lib.rs b/src/lib.rs
index df3e1f2..829657e 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -47,7 +47,7 @@
 //! which follows a build pattern. The builders are finished using:
 //!
 //! * [`.call()`](struct.Request.html#method.call) without a request body.
-//! * [`.send()`](struct.Request.html#method.send) with a request body as `Read` (chunked encoding).
+//! * [`.send()`](struct.Request.html#method.send) with a request body as `Read` (chunked encoding support for non-known sized readers).
 //! * [`.send_string()`](struct.Request.html#method.send_string) body as string.
 //! * [`.send_bytes()`](struct.Request.html#method.send_bytes) body as bytes.
 //! * [`.send_form()`](struct.Request.html#method.send_form) key-value pairs as application/x-www-form-urlencoded.
@@ -125,6 +125,7 @@ mod header;
 mod pool;
 mod proxy;
 mod request;
+mod resolve;
 mod response;
 mod stream;
 mod unit;
@@ -140,6 +141,7 @@ pub use crate::error::Error;
 pub use crate::header::Header;
 pub use crate::proxy::Proxy;
 pub use crate::request::Request;
+pub use crate::resolve::Resolver;
 pub use crate::response::Response;
 
 // re-export
diff --git a/src/pool.rs b/src/pool.rs
index 571867f..b8a7e7e 100644
--- a/src/pool.rs
+++ b/src/pool.rs
@@ -8,7 +8,6 @@ use crate::Proxy;
 
 use url::Url;
 
-pub const DEFAULT_HOST: &str = "localhost";
 const DEFAULT_MAX_IDLE_CONNECTIONS: usize = 100;
 const DEFAULT_MAX_IDLE_CONNECTIONS_PER_HOST: usize = 1;
 
@@ -74,22 +73,11 @@ impl Default for ConnectionPool {
 }
 
 impl ConnectionPool {
-    pub fn new() -> Self {
-        Self::default()
-    }
-
     pub fn set_max_idle_connections(&mut self, max_connections: usize) {
         if self.max_idle_connections == max_connections {
             return;
         }
 
-        if max_connections == 0 {
-            // Clear the connection pool, caching is disabled.
-            self.lru.clear();
-            self.recycle.clear();
-            return;
-        }
-
         // Remove any extra connections if the number was decreased.
         while self.lru.len() > max_connections {
             self.remove_oldest();
@@ -251,7 +239,7 @@ fn pool_connections_limit() {
     // Test inserting connections with different keys into the pool,
     // filling and draining it. The pool should evict earlier connections
     // when the connection limit is reached.
-    let mut pool = ConnectionPool::new();
+    let mut pool = ConnectionPool::default();
     let hostnames = (0..DEFAULT_MAX_IDLE_CONNECTIONS * 2).map(|i| format!("{}.example", i));
     let poolkeys = hostnames.map(|hostname| PoolKey {
         scheme: "https".to_string(),
@@ -276,7 +264,7 @@ fn pool_per_host_connections_limit() {
     // Test inserting connections with the same key into the pool,
     // filling and draining it. The pool should evict earlier connections
     // when the per-host connection limit is reached.
-    let mut pool = ConnectionPool::new();
+    let mut pool = ConnectionPool::default();
     let poolkey = PoolKey {
         scheme: "https".to_string(),
         hostname: "example.com".to_string(),
@@ -301,7 +289,7 @@ fn pool_per_host_connections_limit() {
 
 #[test]
 fn pool_update_connection_limit() {
-    let mut pool = ConnectionPool::new();
+    let mut pool = ConnectionPool::default();
     pool.set_max_idle_connections(50);
 
     let hostnames = (0..pool.max_idle_connections).map(|i| format!("{}.example", i));
@@ -321,7 +309,7 @@ fn pool_update_connection_limit() {
 
 #[test]
 fn pool_update_per_host_connection_limit() {
-    let mut pool = ConnectionPool::new();
+    let mut pool = ConnectionPool::default();
     pool.set_max_idle_connections(50);
     pool.set_max_idle_connections_per_host(50);
 
@@ -347,7 +335,7 @@ fn pool_update_per_host_connection_limit() {
 fn pool_checks_proxy() {
     // Test inserting different poolkeys with same address but different proxies.
     // Each insertion should result in an additional entry in the pool.
-    let mut pool = ConnectionPool::new();
+    let mut pool = ConnectionPool::default();
     let url = Url::parse("zzz:///example.com").unwrap();
 
     pool.add(
@@ -426,9 +414,3 @@ impl<R: Read + Sized + Into<Stream>> Read for PoolReturnRead<R> {
         Ok(amount)
     }
 }
-
-impl<R: Read + Sized + Into<Stream>> Drop for PoolReturnRead<R> {
-    fn drop(&mut self) {
-        self.return_connection();
-    }
-}
diff --git a/src/request.rs b/src/request.rs
index 4f1e6aa..85bce0c 100644
--- a/src/request.rs
+++ b/src/request.rs
@@ -8,10 +8,10 @@ use qstring::QString;
 use url::{form_urlencoded, Url};
 
 use crate::agent::{self, Agent, AgentState};
+use crate::body::BodySize;
 use crate::body::{Payload, SizedReader};
 use crate::error::Error;
 use crate::header::{self, Header};
-use crate::pool;
 use crate::unit::{self, Unit};
 use crate::Response;
 
@@ -210,8 +210,10 @@ impl Request {
 
     /// Send data from a reader.
     ///
-    /// This uses [chunked transfer encoding](https://tools.ietf.org/html/rfc7230#section-4.1).
-    /// The caller is responsible for setting the Transfer-Encoding: chunked header.
+    /// If no Content-Length and Transfer-Encoding header has been set, it uses the [chunked transfer encoding](https://tools.ietf.org/html/rfc7230#section-4.1).
+    ///
+    /// The caller may set the Content-Length header to the expected byte size of the reader if is
+    /// known.
     ///
     /// The input from the reader is buffered into chunks of size 16,384, the max size of a TLS fragment.
     ///
@@ -222,7 +224,6 @@ impl Request {
     ///
     /// let resp = ureq::post("http://localhost/example-upload")
     ///     .set("Content-Type", "text/plain")
-    ///     .set("Transfer-Encoding", "chunked")
     ///     .send(read);
     /// ```
     pub fn send(&mut self, reader: impl Read + 'static) -> Response {
@@ -498,8 +499,13 @@ impl Request {
     /// assert_eq!(req2.get_host().unwrap(), "localhost");
     /// ```
     pub fn get_host(&self) -> Result<String, Error> {
-        self.to_url()
-            .map(|u| u.host_str().unwrap_or(pool::DEFAULT_HOST).to_string())
+        match self.to_url() {
+            Ok(u) => match u.host_str() {
+                Some(host) => Ok(host.to_string()),
+                None => Err(Error::BadUrl("No hostname in URL".into())),
+            },
+            Err(e) => Err(e),
+        }
     }
 
     /// Returns the scheme for this request.
@@ -603,8 +609,14 @@ impl Request {
         // Sized bodies are retryable only if they are zero-length because of
         // coincidences of the current implementation - the function responsible
         // for retries doesn't have a way to replay a Payload.
-        let no_body = body.size.is_none() || body.size.unwrap() > 0;
-        idempotent && no_body
+        let retryable_body = match body.size {
+            BodySize::Unknown => false,
+            BodySize::Known(0) => true,
+            BodySize::Known(_) => false,
+            BodySize::Empty => true,
+        };
+
+        idempotent && retryable_body
     }
 }
 
@@ -629,3 +641,13 @@ impl fmt::Debug for TLSConnector {
         f.debug_struct("TLSConnector").finish()
     }
 }
+
+#[test]
+fn no_hostname() {
+    let req = Request::new(
+        &Agent::default(),
+        "GET".to_string(),
+        "unix:/run/foo.socket".to_string(),
+    );
+    assert!(req.get_host().is_err());
+}
diff --git a/src/resolve.rs b/src/resolve.rs
new file mode 100644
index 0000000..ca6497d
--- /dev/null
+++ b/src/resolve.rs
@@ -0,0 +1,59 @@
+use std::fmt;
+use std::io::Result as IoResult;
+use std::net::{SocketAddr, ToSocketAddrs};
+use std::sync::Arc;
+
+pub trait Resolver: Send + Sync {
+    fn resolve(&self, netloc: &str) -> IoResult<Vec<SocketAddr>>;
+}
+
+#[derive(Debug)]
+pub(crate) struct StdResolver;
+
+impl Resolver for StdResolver {
+    fn resolve(&self, netloc: &str) -> IoResult<Vec<SocketAddr>> {
+        ToSocketAddrs::to_socket_addrs(netloc).map(|iter| iter.collect())
+    }
+}
+
+impl<F> Resolver for F
+where
+    F: Fn(&str) -> IoResult<Vec<SocketAddr>>,
+    F: Send + Sync,
+{
+    fn resolve(&self, netloc: &str) -> IoResult<Vec<SocketAddr>> {
+        self(netloc)
+    }
+}
+
+#[derive(Clone)]
+pub(crate) struct ArcResolver(Arc<dyn Resolver>);
+
+impl<R> From<R> for ArcResolver
+where
+    R: Resolver + 'static,
+{
+    fn from(r: R) -> Self {
+        Self(Arc::new(r))
+    }
+}
+
+impl fmt::Debug for ArcResolver {
+    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+        write!(f, "ArcResolver(...)")
+    }
+}
+
+impl std::ops::Deref for ArcResolver {
+    type Target = dyn Resolver;
+
+    fn deref(&self) -> &Self::Target {
+        self.0.as_ref()
+    }
+}
+
+impl Default for ArcResolver {
+    fn default() -> Self {
+        StdResolver.into()
+    }
+}
diff --git a/src/stream.rs b/src/stream.rs
index 7b42a6c..a38899c 100644
--- a/src/stream.rs
+++ b/src/stream.rs
@@ -4,7 +4,6 @@ use std::io::{
 };
 use std::net::SocketAddr;
 use std::net::TcpStream;
-use std::net::ToSocketAddrs;
 use std::time::Duration;
 use std::time::Instant;
 
@@ -302,9 +301,8 @@ impl Write for Stream {
     }
 }
 
-pub(crate) fn connect_http(unit: &Unit) -> Result<Stream, Error> {
+pub(crate) fn connect_http(unit: &Unit, hostname: &str) -> Result<Stream, Error> {
     //
-    let hostname = unit.url.host_str().unwrap();
     let port = unit.url.port().unwrap_or(80);
 
     connect_host(unit, hostname, port)
@@ -326,7 +324,7 @@ fn configure_certs(config: &mut rustls::ClientConfig) {
 }
 
 #[cfg(all(feature = "tls", not(feature = "native-tls")))]
-pub(crate) fn connect_https(unit: &Unit) -> Result<Stream, Error> {
+pub(crate) fn connect_https(unit: &Unit, hostname: &str) -> Result<Stream, Error> {
     use lazy_static::lazy_static;
     use std::sync::Arc;
 
@@ -338,7 +336,6 @@ pub(crate) fn connect_https(unit: &Unit) -> Result<Stream, Error> {
         };
     }
 
-    let hostname = unit.url.host_str().unwrap();
     let port = unit.url.port().unwrap_or(443);
 
     let sni = webpki::DNSNameRef::try_from_ascii_str(hostname)
@@ -359,10 +356,9 @@ pub(crate) fn connect_https(unit: &Unit) -> Result<Stream, Error> {
 }
 
 #[cfg(all(feature = "native-tls", not(feature = "tls")))]
-pub(crate) fn connect_https(unit: &Unit) -> Result<Stream, Error> {
+pub(crate) fn connect_https(unit: &Unit, hostname: &str) -> Result<Stream, Error> {
     use std::sync::Arc;
 
-    let hostname = unit.url.host_str().unwrap();
     let port = unit.url.port().unwrap_or(443);
     let sock = connect_host(unit, hostname, port)?;
 
@@ -386,15 +382,17 @@ pub(crate) fn connect_host(unit: &Unit, hostname: &str, port: u16) -> Result<Tcp
     } else {
         unit.deadline
     };
-
-    // TODO: Find a way to apply deadline to DNS lookup.
-    let sock_addrs: Vec<SocketAddr> = match unit.req.proxy {
+  
+    let netloc = match unit.req.proxy {
         Some(ref proxy) => format!("{}:{}", proxy.server, proxy.port),
         None => format!("{}:{}", hostname, port),
-    }
-    .to_socket_addrs()
-    .map_err(|e| Error::DnsFailed(format!("{}", e)))?
-    .collect();
+    };
+
+    // TODO: Find a way to apply deadline to DNS lookup.
+    let sock_addrs = unit
+        .resolver()
+        .resolve(&netloc)
+        .map_err(|e| Error::DnsFailed(format!("{}", e)))?;
 
     if sock_addrs.is_empty() {
         return Err(Error::DnsFailed(format!("No ip address for {}", hostname)));
@@ -419,6 +417,7 @@ pub(crate) fn connect_host(unit: &Unit, hostname: &str, port: u16) -> Result<Tcp
         // connect with a configured timeout.
         let stream = if Some(Proto::SOCKS5) == proto {
             connect_socks5(
+                &unit,
                 unit.req.proxy.to_owned().unwrap(),
                 deadline,
                 sock_addr,
@@ -496,11 +495,15 @@ pub(crate) fn connect_host(unit: &Unit, hostname: &str, port: u16) -> Result<Tcp
 }
 
 #[cfg(feature = "socks-proxy")]
-fn socks5_local_nslookup(hostname: &str, port: u16) -> Result<TargetAddr, std::io::Error> {
-    let addrs: Vec<SocketAddr> = format!("{}:{}", hostname, port)
-        .to_socket_addrs()
-        .map_err(|e| std::io::Error::new(ErrorKind::NotFound, format!("DNS failure: {}.", e)))?
-        .collect();
+fn socks5_local_nslookup(
+    unit: &Unit,
+    hostname: &str,
+    port: u16,
+) -> Result<TargetAddr, std::io::Error> {
+    let addrs: Vec<SocketAddr> = unit
+        .resolver()
+        .resolve(&format!("{}:{}", hostname, port))
+        .map_err(|e| std::io::Error::new(ErrorKind::NotFound, format!("DNS failure: {}.", e)))?;
 
     if addrs.is_empty() {
         return Err(std::io::Error::new(
@@ -522,6 +525,7 @@ fn socks5_local_nslookup(hostname: &str, port: u16) -> Result<TargetAddr, std::i
 
 #[cfg(feature = "socks-proxy")]
 fn connect_socks5(
+    unit: &Unit,
     proxy: Proxy,
     deadline: Option<Instant>,
     proxy_addr: SocketAddr,
@@ -533,7 +537,7 @@ fn connect_socks5(
     use std::str::FromStr;
 
     let host_addr = if Ipv4Addr::from_str(host).is_ok() || Ipv6Addr::from_str(host).is_ok() {
-        match socks5_local_nslookup(host, port) {
+        match socks5_local_nslookup(unit, host, port) {
             Ok(addr) => addr,
             Err(err) => return Err(err),
         }
@@ -625,6 +629,7 @@ fn get_socks5_stream(
 
 #[cfg(not(feature = "socks-proxy"))]
 fn connect_socks5(
+    _unit: &Unit,
     _proxy: Proxy,
     _deadline: Option<Instant>,
     _proxy_addr: SocketAddr,
@@ -649,6 +654,6 @@ pub(crate) fn connect_test(unit: &Unit) -> Result<Stream, Error> {
 }
 
 #[cfg(not(any(feature = "tls", feature = "native-tls")))]
-pub(crate) fn connect_https(unit: &Unit) -> Result<Stream, Error> {
+pub(crate) fn connect_https(unit: &Unit, _hostname: &str) -> Result<Stream, Error> {
     Err(Error::UnknownScheme(unit.url.scheme().to_string()))
 }
diff --git a/src/unit.rs b/src/unit.rs
index 13d03a8..58df934 100644
--- a/src/unit.rs
+++ b/src/unit.rs
@@ -8,14 +8,12 @@ use url::Url;
 use cookie::{Cookie, CookieJar};
 
 use crate::agent::AgentState;
-use crate::body::{self, Payload, SizedReader};
+use crate::body::{self, BodySize, Payload, SizedReader};
 use crate::header;
+use crate::resolve::ArcResolver;
 use crate::stream::{self, connect_test, Stream};
 use crate::{Error, Header, Request, Response};
 
-#[cfg(feature = "cookie")]
-use crate::pool::DEFAULT_HOST;
-
 /// It's a "unit of work". Maybe a bad name for it?
 ///
 /// *Internal API*
@@ -34,16 +32,25 @@ impl Unit {
     pub(crate) fn new(req: &Request, url: &Url, mix_queries: bool, body: &SizedReader) -> Self {
         //
 
-        let is_chunked = req
+        let (is_transfer_encoding_set, mut is_chunked) = req
             .header("transfer-encoding")
             // if the user has set an encoding header, obey that.
-            .map(|enc| !enc.is_empty())
+            .map(|enc| {
+                let is_transfer_encoding_set = !enc.is_empty();
+                let last_encoding = enc.split(',').last();
+                let is_chunked = last_encoding
+                    .map(|last_enc| last_enc.trim() == "chunked")
+                    .unwrap_or(false);
+                (is_transfer_encoding_set, is_chunked)
+            })
             // otherwise, no chunking.
-            .unwrap_or(false);
+            .unwrap_or((false, false));
 
         let query_string = combine_query(&url, &req.query, mix_queries);
 
-        let cookie_header: Option<Header> = extract_cookies(&req.agent, &url);
+        let cookie_header: Option<Header> = url
+            .host_str()
+            .and_then(|host_str| extract_cookies(&req.agent, &url.scheme(), host_str, &url.path()));
 
         let extra_headers = {
             let mut extra = vec![];
@@ -51,8 +58,21 @@ impl Unit {
             // chunking and Content-Length headers are mutually exclusive
             // also don't write this if the user has set it themselves
             if !is_chunked && !req.has("content-length") {
-                if let Some(size) = body.size {
-                    extra.push(Header::new("Content-Length", &format!("{}", size)));
+                // if the payload is of known size (everything beside an unsized reader), set
+                // Content-Length,
+                // otherwise, use the chunked Transfer-Encoding (only if no other Transfer-Encoding
+                // has been set
+                match body.size {
+                    BodySize::Known(size) => {
+                        extra.push(Header::new("Content-Length", &format!("{}", size)))
+                    }
+                    BodySize::Unknown => {
+                        if !is_transfer_encoding_set {
+                            extra.push(Header::new("Transfer-Encoding", "chunked"));
+                            is_chunked = true;
+                        }
+                    }
+                    BodySize::Empty => {}
                 }
             }
 
@@ -95,6 +115,10 @@ impl Unit {
         self.req.method.eq_ignore_ascii_case("head")
     }
 
+    pub fn resolver(&self) -> ArcResolver {
+        self.req.agent.lock().unwrap().resolver.clone()
+    }
+
     #[cfg(test)]
     pub fn header(&self, name: &str) -> Option<&str> {
         header::get_header(&self.headers, name)
@@ -120,8 +144,9 @@ pub(crate) fn connect(
 ) -> Result<Response, Error> {
     //
 
+    let host = req.get_host()?;
     // open socket
-    let (mut stream, is_recycled) = connect_socket(&unit, use_pooled)?;
+    let (mut stream, is_recycled) = connect_socket(&unit, &host, use_pooled)?;
 
     let send_result = send_prelude(&unit, &mut stream, redir);
 
@@ -213,16 +238,25 @@ pub(crate) fn connect(
 }
 
 #[cfg(feature = "cookie")]
-fn extract_cookies(state: &std::sync::Mutex<AgentState>, url: &Url) -> Option<Header> {
+fn extract_cookies(
+    state: &std::sync::Mutex<AgentState>,
+    scheme: &str,
+    host: &str,
+    path: &str,
+) -> Option<Header> {
     let state = state.lock().unwrap();
-    let is_secure = url.scheme().eq_ignore_ascii_case("https");
-    let hostname = url.host_str().unwrap_or(DEFAULT_HOST).to_string();
+    let is_secure = scheme.eq_ignore_ascii_case("https");
 
-    match_cookies(&state.jar, &hostname, url.path(), is_secure)
+    match_cookies(&state.jar, host, path, is_secure)
 }
 
 #[cfg(not(feature = "cookie"))]
-fn extract_cookies(_state: &std::sync::Mutex<AgentState>, _url: &Url) -> Option<Header> {
+fn extract_cookies(
+    _state: &std::sync::Mutex<AgentState>,
+    _scheme: &str,
+    _host: &str,
+    _path: &str,
+) -> Option<Header> {
     None
 }
 
@@ -273,7 +307,7 @@ pub(crate) fn combine_query(url: &Url, query: &QString, mix_queries: bool) -> St
 }
 
 /// Connect the socket, either by using the pool or grab a new one.
-fn connect_socket(unit: &Unit, use_pooled: bool) -> Result<(Stream, bool), Error> {
+fn connect_socket(unit: &Unit, hostname: &str, use_pooled: bool) -> Result<(Stream, bool), Error> {
     match unit.url.scheme() {
         "http" | "https" | "test" => (),
         _ => return Err(Error::UnknownScheme(unit.url.scheme().to_string())),
@@ -291,8 +325,8 @@ fn connect_socket(unit: &Unit, use_pooled: bool) -> Result<(Stream, bool), Error
         }
     }
     let stream = match unit.url.scheme() {
-        "http" => stream::connect_http(&unit),
-        "https" => stream::connect_https(&unit),
+        "http" => stream::connect_http(&unit, hostname),
+        "https" => stream::connect_https(&unit, hostname),
         "test" => connect_test(&unit),
         _ => Err(Error::UnknownScheme(unit.url.scheme().to_string())),
     };
@@ -383,7 +417,7 @@ fn save_cookies(unit: &Unit, resp: &Response) {
         let to_parse = if raw_cookie.to_lowercase().contains("domain=") {
             (*raw_cookie).to_string()
         } else {
-            let host = &unit.url.host_str().unwrap_or(DEFAULT_HOST).to_string();
+            let host = &unit.url.host_str().unwrap().to_string();
             format!("{}; Domain={}", raw_cookie, host)
         };
         match Cookie::parse_encoded(&to_parse[..]) {


Test patch:
diff --git a/src/test/agent_test.rs b/src/test/agent_test.rs
index f080352..97568b3 100644
--- a/src/test/agent_test.rs
+++ b/src/test/agent_test.rs
@@ -2,7 +2,7 @@
 
 use crate::test;
 use crate::test::testserver::{read_headers, TestServer};
-use std::io::{self, Write};
+use std::io::{self, Read, Write};
 use std::net::TcpStream;
 use std::time::Duration;
 
@@ -101,6 +101,31 @@ fn connection_reuse() {
     assert_eq!(resp.status(), 200);
 }
 
+#[test]
+fn custom_resolver() {
+    use std::io::Read;
+    use std::net::TcpListener;
+
+    let listener = TcpListener::bind("127.0.0.1:0").unwrap();
+
+    let local_addr = listener.local_addr().unwrap();
+
+    let server = std::thread::spawn(move || {
+        let (mut client, _) = listener.accept().unwrap();
+        let mut buf = vec![0u8; 16];
+        let read = client.read(&mut buf).unwrap();
+        buf.truncate(read);
+        buf
+    });
+
+    crate::agent()
+        .set_resolver(move |_: &str| Ok(vec![local_addr]))
+        .get("http://cool.server/")
+        .call();
+
+    assert_eq!(&server.join().unwrap(), b"GET / HTTP/1.1\r\n");
+}
+
 #[cfg(feature = "cookie")]
 #[cfg(test)]
 fn cookie_and_redirect(mut stream: TcpStream) -> io::Result<()> {
@@ -158,3 +183,49 @@ fn test_cookies_on_redirect() {
     assert!(agent.cookie("second").is_some());
     assert!(agent.cookie("third").is_some());
 }
+
+#[test]
+fn dirty_streams_not_returned() -> io::Result<()> {
+    let testserver = TestServer::new(|mut stream: TcpStream| -> io::Result<()> {
+        read_headers(&stream);
+        stream.write_all(b"HTTP/1.1 200 OK\r\n")?;
+        stream.write_all(b"Transfer-Encoding: chunked\r\n")?;
+        stream.write_all(b"\r\n")?;
+        stream.write_all(b"5\r\n")?;
+        stream.write_all(b"corgi\r\n")?;
+        stream.write_all(b"8\r\n")?;
+        stream.write_all(b"dachsund\r\n")?;
+        stream.write_all(b"0\r\n")?;
+        stream.write_all(b"\r\n")?;
+        Ok(())
+    });
+    let url = format!("http://localhost:{}/", testserver.port);
+    let agent = Agent::default().build();
+    let resp = agent.get(&url).call();
+    if let Some(err) = resp.synthetic_error() {
+        panic!("resp failed: {:?}", err);
+    }
+    let resp_str = resp.into_string()?;
+    assert_eq!(resp_str, "corgidachsund");
+
+    // Now fetch it again, but only read part of the body.
+    let resp_to_be_dropped = agent.get(&url).call();
+    if let Some(err) = resp_to_be_dropped.synthetic_error() {
+        panic!("resp_to_be_dropped failed: {:?}", err);
+    }
+    let mut reader = resp_to_be_dropped.into_reader();
+
+    // Read 9 bytes of the response and then drop the reader.
+    let mut buf = [0_u8; 4];
+    let n = reader.read(&mut buf)?;
+    assert_ne!(n, 0, "early EOF");
+    assert_eq!(&buf, b"corg");
+    drop(reader);
+
+    let resp_to_succeed = agent.get(&url).call();
+    if let Some(err) = resp_to_succeed.synthetic_error() {
+        panic!("resp_to_succeed failed: {:?}", err);
+    }
+
+    Ok(())
+}