2021-06-22 18:32:03 +02:00
|
|
|
use std::{cell::Ref, convert::Infallible, net::SocketAddr};
|
2019-03-02 07:51:32 +01:00
|
|
|
|
2021-06-22 18:32:03 +02:00
|
|
|
use actix_utils::future::{err, ok, Ready};
|
|
|
|
use derive_more::{Display, Error};
|
|
|
|
|
|
|
|
use crate::{
|
|
|
|
dev::{AppConfig, Payload, RequestHead},
|
|
|
|
http::header::{self, HeaderName},
|
|
|
|
FromRequest, HttpRequest, ResponseError,
|
|
|
|
};
|
2017-12-06 02:09:15 +01:00
|
|
|
|
2018-06-25 06:58:04 +02:00
|
|
|
const X_FORWARDED_FOR: &[u8] = b"x-forwarded-for";
|
|
|
|
const X_FORWARDED_HOST: &[u8] = b"x-forwarded-host";
|
|
|
|
const X_FORWARDED_PROTO: &[u8] = b"x-forwarded-proto";
|
2017-12-06 02:09:15 +01:00
|
|
|
|
2021-06-22 18:32:03 +02:00
|
|
|
/// HTTP connection information.
|
|
|
|
///
|
|
|
|
/// `ConnectionInfo` implements `FromRequest` and can be extracted in handlers.
|
|
|
|
///
|
|
|
|
/// # Examples
|
|
|
|
/// ```
|
|
|
|
/// # use actix_web::{HttpResponse, Responder};
|
|
|
|
/// use actix_web::dev::ConnectionInfo;
|
|
|
|
///
|
|
|
|
/// async fn handler(conn: ConnectionInfo) -> impl Responder {
|
|
|
|
/// match conn.host() {
|
|
|
|
/// "actix.rs" => HttpResponse::Ok().body("Welcome!"),
|
|
|
|
/// "admin.actix.rs" => HttpResponse::Ok().body("Admin portal."),
|
|
|
|
/// _ => HttpResponse::NotFound().finish()
|
|
|
|
/// }
|
|
|
|
/// }
|
|
|
|
/// # let _svc = actix_web::web::to(handler);
|
|
|
|
/// ```
|
2019-03-09 23:06:24 +01:00
|
|
|
#[derive(Debug, Clone, Default)]
|
2018-06-17 20:01:41 +02:00
|
|
|
pub struct ConnectionInfo {
|
|
|
|
scheme: String,
|
|
|
|
host: String,
|
2020-05-15 02:07:27 +02:00
|
|
|
realip_remote_addr: Option<String>,
|
|
|
|
remote_addr: Option<String>,
|
2017-12-06 02:09:15 +01:00
|
|
|
}
|
|
|
|
|
2018-06-17 20:01:41 +02:00
|
|
|
impl ConnectionInfo {
|
2017-12-06 02:09:15 +01:00
|
|
|
/// Create *ConnectionInfo* instance for a request.
|
2019-03-09 23:06:24 +01:00
|
|
|
pub fn get<'a>(req: &'a RequestHead, cfg: &AppConfig) -> Ref<'a, Self> {
|
2019-03-02 07:51:32 +01:00
|
|
|
if !req.extensions().contains::<ConnectionInfo>() {
|
2019-03-09 23:06:24 +01:00
|
|
|
req.extensions_mut().insert(ConnectionInfo::new(req, cfg));
|
2019-03-02 07:51:32 +01:00
|
|
|
}
|
|
|
|
Ref::map(req.extensions(), |e| e.get().unwrap())
|
|
|
|
}
|
|
|
|
|
2020-06-22 21:09:48 +02:00
|
|
|
#[allow(clippy::cognitive_complexity, clippy::borrow_interior_mutable_const)]
|
2019-03-09 23:06:24 +01:00
|
|
|
fn new(req: &RequestHead, cfg: &AppConfig) -> ConnectionInfo {
|
2017-12-06 02:09:15 +01:00
|
|
|
let mut host = None;
|
|
|
|
let mut scheme = None;
|
2020-05-15 02:07:27 +02:00
|
|
|
let mut realip_remote_addr = None;
|
2017-12-06 02:09:15 +01:00
|
|
|
|
|
|
|
// load forwarded header
|
2019-04-07 00:02:02 +02:00
|
|
|
for hdr in req.headers.get_all(&header::FORWARDED) {
|
2017-12-06 02:09:15 +01:00
|
|
|
if let Ok(val) = hdr.to_str() {
|
|
|
|
for pair in val.split(';') {
|
|
|
|
for el in pair.split(',') {
|
2017-12-06 06:38:52 +01:00
|
|
|
let mut items = el.trim().splitn(2, '=');
|
2017-12-06 02:09:15 +01:00
|
|
|
if let Some(name) = items.next() {
|
|
|
|
if let Some(val) = items.next() {
|
|
|
|
match &name.to_lowercase() as &str {
|
2019-03-02 07:51:32 +01:00
|
|
|
"for" => {
|
2020-05-15 02:07:27 +02:00
|
|
|
if realip_remote_addr.is_none() {
|
|
|
|
realip_remote_addr = Some(val.trim());
|
2019-03-02 07:51:32 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
"proto" => {
|
|
|
|
if scheme.is_none() {
|
|
|
|
scheme = Some(val.trim());
|
|
|
|
}
|
|
|
|
}
|
|
|
|
"host" => {
|
|
|
|
if host.is_none() {
|
|
|
|
host = Some(val.trim());
|
|
|
|
}
|
|
|
|
}
|
2021-01-04 02:01:35 +01:00
|
|
|
_ => {}
|
2017-12-06 02:09:15 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// scheme
|
|
|
|
if scheme.is_none() {
|
2018-05-17 21:20:20 +02:00
|
|
|
if let Some(h) = req
|
2019-03-02 07:51:32 +01:00
|
|
|
.headers
|
2019-04-07 00:02:02 +02:00
|
|
|
.get(&HeaderName::from_lowercase(X_FORWARDED_PROTO).unwrap())
|
2018-04-14 01:02:01 +02:00
|
|
|
{
|
2017-12-06 02:09:15 +01:00
|
|
|
if let Ok(h) = h.to_str() {
|
|
|
|
scheme = h.split(',').next().map(|v| v.trim());
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if scheme.is_none() {
|
2019-12-05 18:35:43 +01:00
|
|
|
scheme = req.uri.scheme().map(|a| a.as_str());
|
2019-03-09 23:06:24 +01:00
|
|
|
if scheme.is_none() && cfg.secure() {
|
2018-06-25 06:58:04 +02:00
|
|
|
scheme = Some("https")
|
2017-12-08 18:48:53 +01:00
|
|
|
}
|
2017-12-06 02:09:15 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// host
|
|
|
|
if host.is_none() {
|
2018-05-17 21:20:20 +02:00
|
|
|
if let Some(h) = req
|
2019-03-02 07:51:32 +01:00
|
|
|
.headers
|
2019-04-07 00:02:02 +02:00
|
|
|
.get(&HeaderName::from_lowercase(X_FORWARDED_HOST).unwrap())
|
2018-04-14 01:02:01 +02:00
|
|
|
{
|
2017-12-06 02:09:15 +01:00
|
|
|
if let Ok(h) = h.to_str() {
|
|
|
|
host = h.split(',').next().map(|v| v.trim());
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if host.is_none() {
|
2019-04-07 00:02:02 +02:00
|
|
|
if let Some(h) = req.headers.get(&header::HOST) {
|
2017-12-06 06:53:00 +01:00
|
|
|
host = h.to_str().ok();
|
2017-12-06 02:09:15 +01:00
|
|
|
}
|
|
|
|
if host.is_none() {
|
2019-12-05 18:35:43 +01:00
|
|
|
host = req.uri.authority().map(|a| a.as_str());
|
2017-12-08 18:48:53 +01:00
|
|
|
if host.is_none() {
|
2019-03-09 23:06:24 +01:00
|
|
|
host = Some(cfg.host());
|
2017-12-08 18:48:53 +01:00
|
|
|
}
|
2017-12-06 02:09:15 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-05-15 02:07:27 +02:00
|
|
|
// get remote_addraddr from socketaddr
|
|
|
|
let remote_addr = req.peer_addr.map(|addr| format!("{}", addr));
|
|
|
|
|
|
|
|
if realip_remote_addr.is_none() {
|
2018-05-17 21:20:20 +02:00
|
|
|
if let Some(h) = req
|
2019-03-02 07:51:32 +01:00
|
|
|
.headers
|
2019-04-07 00:02:02 +02:00
|
|
|
.get(&HeaderName::from_lowercase(X_FORWARDED_FOR).unwrap())
|
2018-04-14 01:02:01 +02:00
|
|
|
{
|
2017-12-06 06:38:52 +01:00
|
|
|
if let Ok(h) = h.to_str() {
|
2020-05-15 02:07:27 +02:00
|
|
|
realip_remote_addr = h.split(',').next().map(|v| v.trim());
|
2017-12-06 06:38:52 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-03-02 07:51:32 +01:00
|
|
|
ConnectionInfo {
|
2020-05-15 02:07:27 +02:00
|
|
|
remote_addr,
|
2019-03-02 07:51:32 +01:00
|
|
|
scheme: scheme.unwrap_or("http").to_owned(),
|
|
|
|
host: host.unwrap_or("localhost").to_owned(),
|
2020-05-15 02:07:27 +02:00
|
|
|
realip_remote_addr: realip_remote_addr.map(|s| s.to_owned()),
|
2019-03-02 07:51:32 +01:00
|
|
|
}
|
2017-12-06 02:09:15 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Scheme of the request.
|
|
|
|
///
|
|
|
|
/// Scheme is resolved through the following headers, in this order:
|
|
|
|
///
|
|
|
|
/// - Forwarded
|
|
|
|
/// - X-Forwarded-Proto
|
|
|
|
/// - Uri
|
|
|
|
#[inline]
|
|
|
|
pub fn scheme(&self) -> &str {
|
2018-06-17 20:01:41 +02:00
|
|
|
&self.scheme
|
2017-12-06 02:09:15 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Hostname of the request.
|
|
|
|
///
|
|
|
|
/// Hostname is resolved through the following headers, in this order:
|
|
|
|
///
|
|
|
|
/// - Forwarded
|
|
|
|
/// - X-Forwarded-Host
|
|
|
|
/// - Host
|
|
|
|
/// - Uri
|
2017-12-26 23:36:03 +01:00
|
|
|
/// - Server hostname
|
2017-12-06 02:09:15 +01:00
|
|
|
pub fn host(&self) -> &str {
|
2018-06-17 20:01:41 +02:00
|
|
|
&self.host
|
2017-12-06 02:09:15 +01:00
|
|
|
}
|
|
|
|
|
2020-05-15 02:07:27 +02:00
|
|
|
/// remote_addr address of the request.
|
|
|
|
///
|
|
|
|
/// Get remote_addr address from socket address
|
|
|
|
pub fn remote_addr(&self) -> Option<&str> {
|
|
|
|
if let Some(ref remote_addr) = self.remote_addr {
|
|
|
|
Some(remote_addr)
|
|
|
|
} else {
|
|
|
|
None
|
|
|
|
}
|
|
|
|
}
|
|
|
|
/// Real ip remote addr of client initiated HTTP request.
|
2017-12-06 02:09:15 +01:00
|
|
|
///
|
2019-09-27 03:03:12 +02:00
|
|
|
/// The addr is resolved through the following headers, in this order:
|
2017-12-06 02:09:15 +01:00
|
|
|
///
|
|
|
|
/// - Forwarded
|
|
|
|
/// - X-Forwarded-For
|
2020-05-15 02:07:27 +02:00
|
|
|
/// - remote_addr name of opened socket
|
2019-11-14 03:32:47 +01:00
|
|
|
///
|
|
|
|
/// # Security
|
|
|
|
/// Do not use this function for security purposes, unless you can ensure the Forwarded and
|
|
|
|
/// X-Forwarded-For headers cannot be spoofed by the client. If you want the client's socket
|
|
|
|
/// address explicitly, use
|
2020-12-13 14:28:39 +01:00
|
|
|
/// [`HttpRequest::peer_addr()`](super::web::HttpRequest::peer_addr()) instead.
|
2017-12-06 02:09:15 +01:00
|
|
|
#[inline]
|
2020-05-15 02:07:27 +02:00
|
|
|
pub fn realip_remote_addr(&self) -> Option<&str> {
|
|
|
|
if let Some(ref r) = self.realip_remote_addr {
|
2017-12-06 06:38:52 +01:00
|
|
|
Some(r)
|
2020-05-15 02:07:27 +02:00
|
|
|
} else if let Some(ref remote_addr) = self.remote_addr {
|
|
|
|
Some(remote_addr)
|
2017-12-06 06:38:52 +01:00
|
|
|
} else {
|
|
|
|
None
|
|
|
|
}
|
2017-12-06 02:09:15 +01:00
|
|
|
}
|
2017-12-06 06:38:52 +01:00
|
|
|
}
|
2017-12-06 02:09:15 +01:00
|
|
|
|
2021-06-22 18:32:03 +02:00
|
|
|
impl FromRequest for ConnectionInfo {
|
|
|
|
type Error = Infallible;
|
|
|
|
type Future = Ready<Result<Self, Self::Error>>;
|
|
|
|
type Config = ();
|
|
|
|
|
|
|
|
fn from_request(req: &HttpRequest, _: &mut Payload) -> Self::Future {
|
|
|
|
ok(req.connection_info().clone())
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Extractor for peer's socket address.
|
|
|
|
///
|
|
|
|
/// Also see [`HttpRequest::peer_addr`].
|
|
|
|
///
|
|
|
|
/// # Examples
|
|
|
|
/// ```
|
|
|
|
/// # use actix_web::Responder;
|
|
|
|
/// use actix_web::dev::PeerAddr;
|
|
|
|
///
|
|
|
|
/// async fn handler(peer_addr: PeerAddr) -> impl Responder {
|
|
|
|
/// let socket_addr = peer_addr.0;
|
|
|
|
/// socket_addr.to_string()
|
|
|
|
/// }
|
|
|
|
/// # let _svc = actix_web::web::to(handler);
|
|
|
|
/// ```
|
|
|
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Display)]
|
|
|
|
#[display(fmt = "{}", _0)]
|
|
|
|
pub struct PeerAddr(pub SocketAddr);
|
|
|
|
|
|
|
|
impl PeerAddr {
|
|
|
|
/// Unwrap into inner `SocketAddr` value.
|
|
|
|
pub fn into_inner(self) -> SocketAddr {
|
|
|
|
self.0
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[derive(Debug, Display, Error)]
|
|
|
|
#[non_exhaustive]
|
|
|
|
#[display(fmt = "Missing peer address")]
|
|
|
|
pub struct MissingPeerAddr;
|
|
|
|
|
|
|
|
impl ResponseError for MissingPeerAddr {}
|
|
|
|
|
|
|
|
impl FromRequest for PeerAddr {
|
|
|
|
type Error = MissingPeerAddr;
|
|
|
|
type Future = Ready<Result<Self, Self::Error>>;
|
|
|
|
type Config = ();
|
|
|
|
|
|
|
|
fn from_request(req: &HttpRequest, _: &mut Payload) -> Self::Future {
|
|
|
|
match req.peer_addr() {
|
|
|
|
Some(addr) => ok(PeerAddr(addr)),
|
|
|
|
None => {
|
|
|
|
log::error!("Missing peer address.");
|
|
|
|
err(MissingPeerAddr)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-12-06 06:38:52 +01:00
|
|
|
#[cfg(test)]
|
|
|
|
mod tests {
|
|
|
|
use super::*;
|
2019-03-02 07:51:32 +01:00
|
|
|
use crate::test::TestRequest;
|
2017-12-06 02:09:15 +01:00
|
|
|
|
2017-12-06 06:38:52 +01:00
|
|
|
#[test]
|
|
|
|
fn test_forwarded() {
|
2019-03-09 23:06:24 +01:00
|
|
|
let req = TestRequest::default().to_http_request();
|
|
|
|
let info = req.connection_info();
|
2017-12-06 06:38:52 +01:00
|
|
|
assert_eq!(info.scheme(), "http");
|
2018-06-25 06:58:04 +02:00
|
|
|
assert_eq!(info.host(), "localhost:8080");
|
2017-12-06 06:38:52 +01:00
|
|
|
|
2018-06-25 06:58:04 +02:00
|
|
|
let req = TestRequest::default()
|
2021-01-15 03:11:10 +01:00
|
|
|
.insert_header((
|
2018-06-25 06:58:04 +02:00
|
|
|
header::FORWARDED,
|
2018-04-14 01:02:01 +02:00
|
|
|
"for=192.0.2.60; proto=https; by=203.0.113.43; host=rust-lang.org",
|
2021-01-15 03:11:10 +01:00
|
|
|
))
|
2019-03-09 23:06:24 +01:00
|
|
|
.to_http_request();
|
2017-12-06 06:38:52 +01:00
|
|
|
|
2019-03-09 23:06:24 +01:00
|
|
|
let info = req.connection_info();
|
2017-12-06 06:38:52 +01:00
|
|
|
assert_eq!(info.scheme(), "https");
|
|
|
|
assert_eq!(info.host(), "rust-lang.org");
|
2020-05-15 02:07:27 +02:00
|
|
|
assert_eq!(info.realip_remote_addr(), Some("192.0.2.60"));
|
2017-12-06 06:38:52 +01:00
|
|
|
|
2018-06-25 06:58:04 +02:00
|
|
|
let req = TestRequest::default()
|
2021-01-15 03:11:10 +01:00
|
|
|
.insert_header((header::HOST, "rust-lang.org"))
|
2019-03-09 23:06:24 +01:00
|
|
|
.to_http_request();
|
2017-12-06 06:38:52 +01:00
|
|
|
|
2019-03-09 23:06:24 +01:00
|
|
|
let info = req.connection_info();
|
2017-12-06 06:38:52 +01:00
|
|
|
assert_eq!(info.scheme(), "http");
|
|
|
|
assert_eq!(info.host(), "rust-lang.org");
|
2020-05-15 02:07:27 +02:00
|
|
|
assert_eq!(info.realip_remote_addr(), None);
|
2017-12-06 06:38:52 +01:00
|
|
|
|
2018-06-25 06:58:04 +02:00
|
|
|
let req = TestRequest::default()
|
2021-01-15 03:11:10 +01:00
|
|
|
.insert_header((X_FORWARDED_FOR, "192.0.2.60"))
|
2019-03-09 23:06:24 +01:00
|
|
|
.to_http_request();
|
|
|
|
let info = req.connection_info();
|
2020-05-15 02:07:27 +02:00
|
|
|
assert_eq!(info.realip_remote_addr(), Some("192.0.2.60"));
|
2017-12-06 06:38:52 +01:00
|
|
|
|
2018-06-25 06:58:04 +02:00
|
|
|
let req = TestRequest::default()
|
2021-01-15 03:11:10 +01:00
|
|
|
.insert_header((X_FORWARDED_HOST, "192.0.2.60"))
|
2019-03-09 23:06:24 +01:00
|
|
|
.to_http_request();
|
|
|
|
let info = req.connection_info();
|
2017-12-06 06:38:52 +01:00
|
|
|
assert_eq!(info.host(), "192.0.2.60");
|
2020-05-15 02:07:27 +02:00
|
|
|
assert_eq!(info.realip_remote_addr(), None);
|
2017-12-06 06:38:52 +01:00
|
|
|
|
2018-07-04 17:01:27 +02:00
|
|
|
let req = TestRequest::default()
|
2021-01-15 03:11:10 +01:00
|
|
|
.insert_header((X_FORWARDED_PROTO, "https"))
|
2019-03-09 23:06:24 +01:00
|
|
|
.to_http_request();
|
|
|
|
let info = req.connection_info();
|
2017-12-06 06:38:52 +01:00
|
|
|
assert_eq!(info.scheme(), "https");
|
2017-12-06 02:09:15 +01:00
|
|
|
}
|
2021-06-22 18:32:03 +02:00
|
|
|
|
|
|
|
#[actix_rt::test]
|
|
|
|
async fn test_conn_info() {
|
|
|
|
let req = TestRequest::default()
|
|
|
|
.uri("http://actix.rs/")
|
|
|
|
.to_http_request();
|
|
|
|
let conn_info = ConnectionInfo::extract(&req).await.unwrap();
|
|
|
|
assert_eq!(conn_info.scheme(), "http");
|
|
|
|
}
|
|
|
|
|
|
|
|
#[actix_rt::test]
|
|
|
|
async fn test_peer_addr() {
|
|
|
|
let addr = "127.0.0.1:8080".parse().unwrap();
|
|
|
|
let req = TestRequest::default().peer_addr(addr).to_http_request();
|
|
|
|
let peer_addr = PeerAddr::extract(&req).await.unwrap();
|
|
|
|
assert_eq!(peer_addr, PeerAddr(addr));
|
|
|
|
|
|
|
|
let req = TestRequest::default().to_http_request();
|
|
|
|
let res = PeerAddr::extract(&req).await;
|
|
|
|
assert!(res.is_err());
|
|
|
|
}
|
2017-12-06 02:09:15 +01:00
|
|
|
}
|