Read local_addr from socket

This commit is contained in:
Martin Algesten
2023-04-16 10:59:27 +02:00
parent bfb0ef16e1
commit 7e32dbaaaf
2 changed files with 21 additions and 0 deletions

View File

@@ -48,6 +48,7 @@ impl<T: AsRef<[u8]> + Send + Sync + 'static> From<http::Response<T>> for Respons
.collect::<Vec<_>>(),
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![],
}
}

View File

@@ -78,6 +78,9 @@ pub struct Response {
pub(crate) reader: Box<dyn Read + Send + Sync + 'static>,
/// 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<SocketAddr>,
/// 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<SocketAddr> {
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<Response, Error> {
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)