Skip to content

Commit f4f6509

Browse files
committed
Handle REST IP addresses better
1 parent 00d7a8f commit f4f6509

1 file changed

Lines changed: 11 additions & 8 deletions

File tree

src/rest.rs

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -552,15 +552,23 @@ fn prepare_txs(
552552
.collect()
553553
}
554554

555+
// Get the first valid IP address in the X-Forwarded-For header
556+
// Supports multiple headers.
555557
fn get_client_ip(headers: &HeaderMap<HeaderValue>) -> Option<SocketAddr> {
556558
headers
557559
.get_all("X-Forwarded-For")
558560
.iter()
559561
.filter_map(|v| v.to_str().ok())
560562
.join(",")
561563
.split(',')
564+
.filter_map(|ip| ip.trim().parse::<SocketAddr>().ok())
562565
.next()
563-
.and_then(|ip| ip.trim().parse::<SocketAddr>().ok())
566+
}
567+
568+
fn get_client_ip_str() -> String {
569+
get_rest_addr()
570+
.map(|a| a.to_string())
571+
.unwrap_or_else(|| String::from("Unknown IP"))
564572
}
565573

566574
#[tokio::main]
@@ -591,7 +599,7 @@ async fn run_server(config: Arc<Config>, query: Arc<Query>, rx: oneshot::Receive
591599

592600
let mut resp = handle_request(method, uri, body, &query, &config)
593601
.unwrap_or_else(|err| {
594-
warn!("[client_ip: {:?}] {:?}", get_rest_addr(), err);
602+
warn!("[{}] {:?}", get_client_ip_str(), err);
595603
Response::builder()
596604
.status(err.0)
597605
.header("Content-Type", "text/plain")
@@ -688,12 +696,7 @@ fn handle_request(
688696
None => HashMap::new(),
689697
};
690698

691-
info!(
692-
"[client_ip: {:?}] handle {:?} {:?}",
693-
get_rest_addr(),
694-
method,
695-
uri
696-
);
699+
info!("[{}] handle {:?} {:?}", get_client_ip_str(), method, uri);
697700
match (
698701
&method,
699702
path.first(),

0 commit comments

Comments
 (0)