Skip to content

Log request file with its remote address if available #112

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
May 24, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions docs/content/configuration/config-file.md
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,16 @@ grace-period = 0
#### Page fallback for 404s
# page-fallback = "some_page.html"

#### Log request Remote Address if available
log-remote-address = false


### Windows Only

#### Run the web server as a Windows Service
# windows-service = false



[advanced]

Expand Down
18 changes: 17 additions & 1 deletion src/handler.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use hyper::{header::WWW_AUTHENTICATE, Body, Method, Request, Response, StatusCode};
use std::{future::Future, path::PathBuf, sync::Arc};
use std::{future::Future, net::SocketAddr, path::PathBuf, sync::Arc};

use crate::{
basic_auth, compression, control_headers, cors, custom_headers, error_page, fallback_page,
Expand All @@ -20,6 +20,7 @@ pub struct RequestHandlerOpts {
pub page50x: Vec<u8>,
pub page_fallback: Vec<u8>,
pub basic_auth: String,
pub log_remote_address: bool,

// Advanced options
pub advanced_opts: Option<Advanced>,
Expand All @@ -35,6 +36,7 @@ impl RequestHandler {
pub fn handle<'a>(
&'a self,
req: &'a mut Request<Body>,
remote_addr: Option<SocketAddr>,
) -> impl Future<Output = Result<Response<Body>, Error>> + Send + 'a {
let method = req.method();
let headers = req.headers();
Expand All @@ -45,9 +47,23 @@ impl RequestHandler {
let uri_query = uri.query();
let dir_listing = self.opts.dir_listing;
let dir_listing_order = self.opts.dir_listing_order;
let log_remote_addr = self.opts.log_remote_address;

let mut cors_headers: Option<http::HeaderMap> = None;

// Log request information with its remote address if available
let mut remote_addr_str = String::new();
if log_remote_addr {
remote_addr_str.push_str(" remote_addr=");
remote_addr_str.push_str(&remote_addr.map_or("".to_owned(), |v| v.to_string()));
}
tracing::info!(
"incoming request: method={} uri={}{}",
method,
uri,
remote_addr_str,
);

async move {
// Check for disallowed HTTP methods and reject request accordently
if !(method == Method::GET || method == Method::HEAD || method == Method::OPTIONS) {
Expand Down
5 changes: 5 additions & 0 deletions src/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,10 @@ impl Server {
!general.basic_auth.is_empty()
);

// Log remote address option
let log_remote_address = general.log_remote_address;
tracing::info!("log remote address: enabled={}", log_remote_address);

// Grace period option
let grace_period = general.grace_period;
tracing::info!("grace period before graceful shutdown: {}s", grace_period);
Expand All @@ -180,6 +184,7 @@ impl Server {
page50x,
page_fallback,
basic_auth,
log_remote_address,
advanced_opts,
}),
});
Expand Down
17 changes: 10 additions & 7 deletions src/service.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
use hyper::{service::Service, Body, Request, Response};
use std::convert::Infallible;
use std::future::{ready, Future, Ready};
use std::net::SocketAddr;
use std::pin::Pin;
use std::sync::Arc;
use std::task::{Context, Poll};

use crate::handler::RequestHandler;
use crate::Error;
use crate::{handler::RequestHandler, transport::Transport, Error};

/// It defines the router service which is the main entry point for Hyper Server.
pub struct RouterService {
Expand All @@ -21,7 +21,7 @@ impl RouterService {
}
}

impl<T> Service<T> for RouterService {
impl<T: Transport + Send + 'static> Service<&T> for RouterService {
type Response = RequestService;
type Error = Infallible;
type Future = Ready<Result<Self::Response, Self::Error>>;
Expand All @@ -30,14 +30,15 @@ impl<T> Service<T> for RouterService {
Poll::Ready(Ok(()))
}

fn call(&mut self, _: T) -> Self::Future {
ready(Ok(self.builder.build()))
fn call(&mut self, conn: &T) -> Self::Future {
ready(Ok(self.builder.build(conn.remote_addr())))
}
}

/// It defines a Hyper service request which delegates a request handler.
pub struct RequestService {
handler: Arc<RequestHandler>,
remote_addr: Option<SocketAddr>,
}

impl Service<Request<Body>> for RequestService {
Expand All @@ -51,7 +52,8 @@ impl Service<Request<Body>> for RequestService {

fn call(&mut self, mut req: Request<Body>) -> Self::Future {
let handler = self.handler.clone();
Box::pin(async move { handler.handle(&mut req).await })
let remote_addr = self.remote_addr;
Box::pin(async move { handler.handle(&mut req, remote_addr).await })
}
}

Expand All @@ -67,9 +69,10 @@ impl RequestServiceBuilder {
}
}

pub fn build(&self) -> RequestService {
pub fn build(&self, remote_addr: Option<SocketAddr>) -> RequestService {
RequestService {
handler: self.handler.clone(),
remote_addr,
}
}
}
9 changes: 9 additions & 0 deletions src/settings/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,15 @@ pub struct General {
/// Server TOML configuration file path.
pub config_file: Option<PathBuf>,

#[structopt(
long,
parse(try_from_str),
default_value = "false",
env = "SERVER_LOG_REMOTE_ADDRESS"
)]
/// Log incoming requests information along with its remote address if available using the `info` log level.
pub log_remote_address: bool,

//
// Windows specific arguments and commands
//
Expand Down
2 changes: 2 additions & 0 deletions src/settings/file.rs
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,8 @@ pub struct General {
pub grace_period: Option<u8>,

pub page_fallback: Option<PathBuf>,

pub log_remote_address: Option<bool>,
}

/// Full server configuration
Expand Down
5 changes: 5 additions & 0 deletions src/settings/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ impl Settings {
let mut threads_multiplier = opts.threads_multiplier;
let mut grace_period = opts.grace_period;
let mut page_fallback = opts.page_fallback;
let mut log_remote_address = opts.log_remote_address;

// Define the advanced file options
let mut settings_advanced: Option<Advanced> = None;
Expand Down Expand Up @@ -145,6 +146,9 @@ impl Settings {
if let Some(v) = general.page_fallback {
page_fallback = Some(v)
}
if let Some(v) = general.log_remote_address {
log_remote_address = v
}
}

// Prepare the "advanced" options
Expand Down Expand Up @@ -206,6 +210,7 @@ impl Settings {
threads_multiplier,
grace_period,
page_fallback,
log_remote_address,

// NOTE:
// Windows-only options and commands
Expand Down
15 changes: 14 additions & 1 deletion tests/toml/config.toml
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,19 @@ grace-period = 0
#### Page fallback for 404s
page-fallback = ""

#### Page fallback for 404s
page-fallback = ""

#### Log request Remote Address if available
log-remote-address = false


### Windows Only

#### Run the web server as a Windows Service
# windows-service = false


[advanced]

#### HTTP Headers customization
Expand All @@ -56,7 +69,7 @@ headers = { Access-Control-Allow-Origin = "*", X-XSS-PROTECTION = "1; mode=block

# #### b. Multiline version
[[advanced.headers]]
source = "index.html"
source = "/index.html"
[advanced.headers.headers]
Cache-Control = "public, max-age=36000"
Content-Security-Policy = "frame-ancestors 'self'"
Expand Down
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy