From 7e32dbaaafb084344717102048287849499725a6 Mon Sep 17 00:00:00 2001 From: Martin Algesten Date: Sun, 16 Apr 2023 10:59:27 +0200 Subject: [PATCH] Read local_addr from socket --- src/http_interop.rs | 1 + src/response.rs | 20 ++++++++++++++++++++ 2 files changed, 21 insertions(+) diff --git a/src/http_interop.rs b/src/http_interop.rs index 1dc8604..d3e3cb3 100644 --- a/src/http_interop.rs +++ b/src/http_interop.rs @@ -48,6 +48,7 @@ impl + Send + Sync + 'static> From> for Respons .collect::>(), reader: Box::new(Cursor::new(value.into_body())), remote_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 80), + local_addr: None, history: vec![], } } diff --git a/src/response.rs b/src/response.rs index 89f435d..bc32907 100644 --- a/src/response.rs +++ b/src/response.rs @@ -78,6 +78,9 @@ pub struct Response { pub(crate) reader: Box, /// The socket address of the server that sent the response. pub(crate) remote_addr: SocketAddr, + /// Local address request was sent from. Only set if necessary since + /// it is an extra system call. + pub(crate) local_addr: Option, /// The redirect history of this response, if any. The history starts with /// the first response received and ends with the response immediately /// previous to this one. @@ -232,6 +235,13 @@ impl Response { self.remote_addr } + /// The local address the request was made from. + /// + /// This is only available if [`AgentBuilder::get_local_addr()`][crate::AgentBuilder] is set to true. + pub fn local_addr(&self) -> Option { + self.local_addr + } + /// Turn this response into a `impl Read` of the body. /// /// 1. If `Transfer-Encoding: chunked`, the returned reader will unchunk it @@ -533,6 +543,15 @@ impl Response { /// assert_eq!(resp.status(), 401); pub(crate) fn do_from_stream(stream: Stream, unit: Unit) -> Result { let remote_addr = stream.remote_addr; + + // Only read local_addr if configured to do so, since it's another syscall. + let mut local_addr = None; + if unit.agent.config.get_local_addr { + if let Some(socket) = stream.socket() { + local_addr = Some(socket.local_addr()?); + } + } + // // HTTP/1.1 200 OK\r\n let mut stream = stream::DeadlineStream::new(stream, unit.deadline); @@ -581,6 +600,7 @@ impl Response { headers, reader, remote_addr, + local_addr, history: vec![], }; Ok(response)