1use std::{
61 future::Future,
62 net::SocketAddr,
63 pin::Pin,
64 sync::{
65 Arc,
66 atomic::{AtomicBool, AtomicUsize, Ordering},
67 },
68 task::{Context, Poll},
69 time::{Duration, Instant},
70};
71
72use axum::extract::connect_info::ConnectInfo;
73use bytes::Buf;
74use ctb_utilities::jiff::{Timestamp, Zoned};
75use http::{Request, Response, Version};
76use http_body::{Body, Frame};
77use pin_project::{pin_project, pinned_drop};
78use tower::{Layer, Service};
79
80use crate::logging::write_access_log_line;
81use crate::pc_settings::{self, AccessLogMode};
82
83#[derive(Clone, Debug, PartialEq, Eq)]
84pub enum ElfField {
85 ClientIp,
86 ClientDns,
87 ClientIdent,
88 ClientUser,
89 Date,
90 Time,
91 TimeTaken,
92 Bytes,
93 Method,
94 Uri,
95 UriStem,
96 UriQuery,
97 Version,
98 Status,
99 RequestHeader(String),
100 ResponseHeader(String),
101 Unknown(String),
102}
103
104#[derive(Clone, Debug)]
105pub enum LogMode {
106 Clf,
107 Elf(Arc<ElfConfig>),
108}
109
110#[derive(Debug)]
111pub struct ElfConfig {
112 pub raw_fields: String,
113 pub fields: Vec<ElfField>,
114}
115
116pub fn parse_fields(fields_str: &str) -> Vec<ElfField> {
117 let mut input = fields_str;
118 if let Some(stripped) = input.strip_prefix("#Fields:") {
119 input = stripped;
120 }
121 input
122 .split_whitespace()
123 .map(|token| {
124 if token.starts_with("cs(") && token.ends_with(')') {
125 let header = token
127 .get(3..token.len().saturating_sub(1))
128 .unwrap_or("")
129 .to_string();
130 ElfField::RequestHeader(header)
131 } else if token.starts_with("sc(") && token.ends_with(')') {
132 let header = token
134 .get(3..token.len().saturating_sub(1))
135 .unwrap_or("")
136 .to_string();
137 ElfField::ResponseHeader(header)
138 } else {
139 match token {
140 "date" => ElfField::Date,
141 "time" => ElfField::Time,
142 "time-taken" => ElfField::TimeTaken,
143 "bytes" | "sc-bytes" => ElfField::Bytes,
144 "c-ip" | "ip" => ElfField::ClientIp,
145 "c-dns" | "dns" => ElfField::ClientDns,
146 "c-ident" | "ident" => ElfField::ClientIdent,
147 "c-user" | "cs-username" | "cs-user" | "user" => {
148 ElfField::ClientUser
149 }
150 "cs-method" | "method" => ElfField::Method,
151 "cs-uri" | "uri" => ElfField::Uri,
152 "cs-uri-stem" | "uri-stem" => ElfField::UriStem,
153 "cs-uri-query" | "uri-query" => ElfField::UriQuery,
154 "cs-version" | "cs-protocol" => ElfField::Version,
155 "sc-status" | "status" => ElfField::Status,
156 other => ElfField::Unknown(other.to_string()),
157 }
158 }
159 })
160 .collect()
161}
162
163fn format_elf_string(val: &str) -> String {
164 let mut escaped = String::with_capacity(val.len().saturating_add(2));
165 escaped.push('"');
166 for c in val.chars() {
167 if c == '"' {
168 escaped.push('"');
169 escaped.push('"');
170 } else {
171 escaped.push(c);
172 }
173 }
174 escaped.push('"');
175 escaped
176}
177
178#[derive(Clone, Debug)]
183pub struct AccessLogLayer {
184 slow_ttfb: Duration,
185 mode: LogMode,
186}
187
188impl AccessLogLayer {
189 pub fn new(slow_ttfb: Duration) -> Self {
190 Self {
191 slow_ttfb,
192 mode: LogMode::Clf,
193 }
194 }
195
196 pub fn new_elf(slow_ttfb: Duration, fields_str: &str) -> Self {
197 let fields = parse_fields(fields_str);
198 Self {
199 slow_ttfb,
200 mode: LogMode::Elf(Arc::new(ElfConfig {
201 raw_fields: fields_str.to_string(),
202 fields,
203 })),
204 }
205 }
206}
207
208impl Default for AccessLogLayer {
209 fn default() -> Self {
210 Self::new(Duration::from_millis(150))
211 }
212}
213
214impl<S> Layer<S> for AccessLogLayer {
215 type Service = AccessLogService<S>;
216
217 fn layer(&self, inner: S) -> Self::Service {
218 AccessLogService {
219 inner,
220 slow_ttfb: self.slow_ttfb,
221 mode: self.mode.clone(),
222 }
223 }
224}
225
226#[derive(Clone, Debug)]
231pub struct AccessLogService<S> {
232 inner: S,
233 slow_ttfb: Duration,
234 mode: LogMode,
235}
236
237impl<S, B, ResponseBody> Service<Request<B>> for AccessLogService<S>
238where
239 S: Service<Request<B>, Response = Response<ResponseBody>>,
240 ResponseBody: Body + Send + 'static,
241 ResponseBody::Data: Buf,
242 <ResponseBody as Body>::Error: std::fmt::Display,
243{
244 type Response = Response<CountingBody<ResponseBody>>;
245 type Error = S::Error;
246 type Future = AccessLogFuture<S, B>;
247
248 fn poll_ready(
249 &mut self,
250 cx: &mut Context<'_>,
251 ) -> Poll<Result<(), Self::Error>> {
252 self.inner.poll_ready(cx)
253 }
254
255 fn call(&mut self, req: Request<B>) -> Self::Future {
256 let start_instant = Instant::now();
257 let start_time_local = Zoned::now();
258 let start_time_utc = start_time_local.timestamp();
259
260 let method = req.method().clone();
261 let uri_path = req
263 .uri()
264 .path_and_query()
265 .map_or_else(|| req.uri().path(), http::uri::PathAndQuery::as_str)
266 .to_string();
267 let version = req.version();
268
269 let headers = req.headers().clone();
271 let cloudflare_ip = headers
272 .get("CF-Connecting-IP")
273 .and_then(|h| h.to_str().ok());
274 let remote_host = if let Some(cloudflare_ip) = cloudflare_ip {
275 cloudflare_ip
276 } else {
277 &req.extensions()
278 .get::<ConnectInfo<SocketAddr>>()
279 .map_or_else(|| "-".into(), |c| c.0.ip().to_string())
281 };
282
283 let mut req_headers = Vec::new();
284 if let LogMode::Elf(ref config) = self.mode {
285 for field in &config.fields {
286 if let ElfField::RequestHeader(name) = field {
287 if let Some(val) =
288 req.headers().get(name).and_then(|h| h.to_str().ok())
289 {
290 req_headers.push((name.clone(), val.to_string()));
291 }
292 }
293 }
294 }
295
296 let fut = self.inner.call(req);
297
298 AccessLogFuture {
299 state: Some(AccessLogState {
300 start_instant,
301 start_time_local,
302 start_time_utc,
303 method,
304 path_and_query: uri_path,
305 version,
306 remote_host: remote_host.to_string(),
307 ident: "-".into(),
308 user: "-".into(),
309 ttfb_warn_threshold: self.slow_ttfb,
310 mode: self.mode.clone(),
311 req_headers,
312 }),
313 inner: fut,
314 }
315 }
316}
317
318struct AccessLogState {
323 remote_host: String,
324 ident: String,
326 user: String,
328 start_instant: Instant,
329 start_time_local: Zoned,
330 start_time_utc: Timestamp,
331 method: http::Method,
332 path_and_query: String,
333 version: Version,
334 ttfb_warn_threshold: Duration,
335 mode: LogMode,
336 req_headers: Vec<(String, String)>,
337}
338
339#[pin_project]
340pub struct AccessLogFuture<S, B>
341where
342 S: Service<Request<B>>,
343{
344 #[pin]
345 inner: S::Future,
346 state: Option<AccessLogState>,
347}
348
349impl<S, B, ResponseBody> Future for AccessLogFuture<S, B>
350where
351 S: Service<Request<B>, Response = Response<ResponseBody>>,
352 ResponseBody: Body + Send + 'static,
353 ResponseBody::Data: Buf,
354 <ResponseBody as Body>::Error: std::fmt::Display,
355{
356 type Output = Result<Response<CountingBody<ResponseBody>>, S::Error>;
357
358 fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
359 let this = self.project();
360 let Some(state) = this.state.as_ref() else {
361 return Poll::Pending;
362 };
363
364 match this.inner.poll(cx) {
365 Poll::Pending => Poll::Pending,
366 Poll::Ready(res) => {
367 let response = res?;
368 let ttfb = state.start_instant.elapsed();
369 let status = response.status();
370
371 let content_length_guess = response
373 .headers()
374 .get(http::header::CONTENT_LENGTH)
375 .and_then(|v| v.to_str().ok())
376 .and_then(|s| s.parse::<usize>().ok());
377
378 if ttfb > state.ttfb_warn_threshold {
380 tracing::warn!(
381 target:"access",
382 ttfb_ms = ttfb.as_millis(),
383 "Slow TTFB ({}ms) {} {}",
384 ttfb.as_millis(),
385 state.method,
386 state.path_and_query
387 );
388 }
389
390 let mut resp_headers = Vec::new();
391 if let LogMode::Elf(ref config) = state.mode {
392 for field in &config.fields {
393 if let ElfField::ResponseHeader(name) = field {
394 if let Some(val) = response
395 .headers()
396 .get(name)
397 .and_then(|h| h.to_str().ok())
398 {
399 resp_headers
400 .push((name.clone(), val.to_string()));
401 }
402 }
403 }
404 }
405
406 let shared = Arc::new(SharedLog {
408 remote_host: state.remote_host.clone(),
409 ident: state.ident.clone(),
410 user: state.user.clone(),
411 start_instant: state.start_instant,
412 start_time_local: state.start_time_local.clone(),
413 start_time_utc: state.start_time_utc,
414 method: state.method.clone(),
415 path_and_query: state.path_and_query.clone(),
416 protocol: http_version_str(state.version).to_string(),
417 status: status.as_u16(),
418 bytes: AtomicUsize::new(content_length_guess.unwrap_or(0)),
420 logged: AtomicBool::new(false),
421 mode: state.mode.clone(),
422 req_headers: state.req_headers.clone(),
423 resp_headers,
424 });
425
426 let headers = response.headers().clone();
427 let body = response.into_body();
428 let counting = CountingBody {
429 inner: body,
430 shared: shared.clone(),
431 };
432 let mut response_with_body =
434 Response::builder().status(status).version(state.version);
435 for (key, value) in &headers {
436 response_with_body = response_with_body.header(key, value);
437 }
438 #[expect(
439 clippy::expect_used,
440 reason = "Rebuilding response with cloned headers and status from existing valid response should in principle not fail"
441 )]
442 let response_with_body = response_with_body
443 .body(counting)
444 .expect("response rebuild with valid status and headers");
445
446 *this.state = None;
448
449 Poll::Ready(Ok(response_with_body))
450 }
451 }
452 }
453}
454
455#[pin_project(PinnedDrop)]
460pub struct CountingBody<B> {
461 #[pin]
462 inner: B,
463 shared: Arc<SharedLog>,
464}
465
466impl<B> Body for CountingBody<B>
467where
468 B: Body + Send + 'static,
469 B::Data: Buf,
470{
471 type Data = B::Data;
472 type Error = B::Error;
473
474 fn poll_frame(
475 self: Pin<&mut Self>,
476 cx: &mut Context<'_>,
477 ) -> Poll<Option<Result<Frame<Self::Data>, Self::Error>>> {
478 let this = self.project();
479 match this.inner.poll_frame(cx) {
480 Poll::Ready(Some(Ok(frame))) => {
481 if let Some(data) = frame.data_ref() {
482 this.shared
484 .bytes
485 .fetch_add(data.remaining(), Ordering::Relaxed);
486 }
487 Poll::Ready(Some(Ok(frame)))
488 }
489 other => other,
490 }
491 }
492
493 fn is_end_stream(&self) -> bool {
494 self.inner.is_end_stream()
495 }
496
497 fn size_hint(&self) -> http_body::SizeHint {
498 self.inner.size_hint()
499 }
500}
501
502#[pinned_drop]
503impl<B> PinnedDrop for CountingBody<B> {
504 fn drop(self: Pin<&mut Self>) {
505 if self
507 .shared
508 .logged
509 .compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst)
510 .is_ok()
511 {
512 let line = match &self.shared.mode {
513 LogMode::Clf => self.shared.clf_line(),
514 LogMode::Elf(config) => self.shared.elf_line(&config.fields),
515 };
516 let status = self.shared.status;
517 match status {
518 500..=599 => tracing::error!(target: "access", "{}", line),
519 400..=499 => tracing::warn!(target: "access", "{}", line),
520 _ => tracing::debug!(target: "access", "{}", line),
521 }
522
523 if let LogMode::Elf(ref config) = self.shared.mode {
524 let log_mode =
525 pc_settings::get_settings().get_access_log_mode();
526 let should_write = match log_mode {
527 AccessLogMode::Off => false,
528 AccessLogMode::Errors => status >= 400,
529 AccessLogMode::On => true,
530 };
531 if should_write {
532 let file_line = self.shared.elf_line(&config.fields);
533 write_access_log_line(&file_line);
534 }
535 }
536 }
537 }
538}
539
540struct SharedLog {
545 remote_host: String,
546 ident: String,
547 user: String,
548 start_instant: Instant,
549 start_time_local: Zoned,
550 start_time_utc: Timestamp,
551 method: http::Method,
552 path_and_query: String,
553 protocol: String,
554 status: u16,
555 bytes: AtomicUsize,
556 logged: AtomicBool,
557 mode: LogMode,
558 req_headers: Vec<(String, String)>,
559 resp_headers: Vec<(String, String)>,
560}
561
562impl SharedLog {
563 fn clf_line(&self) -> String {
564 let ts = self.start_time_local.strftime("%d/%b/%Y:%H:%M:%S %z");
566 let bytes = self.bytes.load(Ordering::Relaxed);
567 let bytes_owned;
568 let bytes_str: &str = if bytes == 0 {
569 "-"
570 } else {
571 bytes_owned = bytes.to_string();
572 &bytes_owned
573 };
574 format!(
575 r#"{remote} {ident} {user} [{ts}] "{method} {path} {proto}" {status} {bytes}"#,
576 remote = self.remote_host,
577 ident = self.ident,
578 user = self.user,
579 ts = ts,
580 method = self.method,
581 path = self.path_and_query,
582 proto = self.protocol,
583 status = self.status,
584 bytes = bytes_str,
585 )
586 }
587
588 fn elf_line(&self, fields: &[ElfField]) -> String {
589 let mut parts = Vec::with_capacity(fields.len());
590 for field in fields {
591 let val = match field {
592 ElfField::ClientIp => self.remote_host.clone(),
593 ElfField::ClientDns => "-".to_string(),
594 ElfField::ClientIdent => self.ident.clone(),
595 ElfField::ClientUser => self.user.clone(),
596 ElfField::Date => {
597 self.start_time_utc.strftime("%Y-%m-%d").to_string()
598 }
599 ElfField::Time => {
600 self.start_time_utc.strftime("%H:%M:%S").to_string()
601 }
602 ElfField::TimeTaken => {
603 let duration = self.start_instant.elapsed();
604 format!("{:.3}", duration.as_secs_f64())
605 }
606 ElfField::Bytes => {
607 let bytes = self.bytes.load(Ordering::Relaxed);
608 bytes.to_string()
609 }
610 ElfField::Method => self.method.to_string(),
611 ElfField::Uri => self.path_and_query.clone(),
612 ElfField::UriStem => self
613 .path_and_query
614 .split('?')
615 .next()
616 .unwrap_or("")
618 .to_string(),
619 ElfField::UriQuery => {
620 if let Some(pos) = self.path_and_query.find('?') {
621 self.path_and_query
622 .get(pos.saturating_add(1)..)
623 .unwrap_or("")
625 .to_string()
626 } else {
627 "-".to_string()
628 }
629 }
630 ElfField::Version => self.protocol.clone(),
631 ElfField::Status => self.status.to_string(),
632 ElfField::RequestHeader(name) => self
634 .req_headers
635 .iter()
636 .find(|(k, _)| k.eq_ignore_ascii_case(name))
637 .map_or_else(
638 || "-".to_string(),
639 |(_, v)| format_elf_string(v),
640 ),
641 ElfField::ResponseHeader(name) => self
643 .resp_headers
644 .iter()
645 .find(|(k, _)| k.eq_ignore_ascii_case(name))
646 .map_or_else(
647 || "-".to_string(),
648 |(_, v)| format_elf_string(v),
649 ),
650 ElfField::Unknown(_) => "-".to_string(),
651 };
652 parts.push(val);
653 }
654 parts.join(" ")
655 }
656}
657
658fn http_version_str(v: Version) -> &'static str {
659 match v {
660 Version::HTTP_09 => "HTTP/0.9",
661 Version::HTTP_10 => "HTTP/1.0",
662 Version::HTTP_11 => "HTTP/1.1",
663 Version::HTTP_2 => "HTTP/2.0",
664 Version::HTTP_3 => "HTTP/3.0",
665 _ => "HTTP/?",
666 }
667}
668
669pub mod prelude {
674 pub use super::AccessLogLayer;
675}
676
677#[cfg(test)]
682#[allow(
683 clippy::panic,
684 clippy::expect_used,
685 clippy::unwrap_used,
686 clippy::unwrap_in_result,
687 clippy::panic_in_result_fn,
688 clippy::indexing_slicing,
689 clippy::arithmetic_side_effects,
690 reason = "Standard repository test boilerplate"
691)]
692mod tests {
693 use super::*;
694 use bytes::Bytes;
695 use http::StatusCode;
696 use tower::{ServiceExt, service_fn};
697
698 #[crate::ctb_test("tokio")]
699 async fn test_basic_logging() {
700 let layer = AccessLogLayer::default();
701 let svc = layer.layer(service_fn(|_req: Request<()>| async {
702 Ok::<_, std::convert::Infallible>(
703 Response::builder()
704 .status(StatusCode::OK)
705 .body(http_body_util::Empty::<Bytes>::new())
707 .unwrap(),
708 )
709 }));
710
711 let _resp = svc
712 .clone()
713 .oneshot(Request::builder().uri("/test").body(()).unwrap())
714 .await
715 .unwrap();
716 }
719
720 #[crate::ctb_test("tokio")]
721 async fn test_elf_all_fields_logging() {
722 let fields_str = "c-ip c-dns c-ident c-user date time time-taken bytes cs-method cs-uri cs-uri-stem cs-uri-query cs-version sc-status cs(User-Agent) sc(Content-Type)";
723 let layer =
724 AccessLogLayer::new_elf(Duration::from_millis(150), fields_str);
725 let svc = layer.layer(service_fn(|_req: Request<()>| async {
726 Ok::<_, std::convert::Infallible>(
727 Response::builder()
728 .status(StatusCode::OK)
729 .header("Content-Type", "text/plain")
730 .body(http_body_util::Empty::<Bytes>::new())
731 .unwrap(),
732 )
733 }));
734
735 let req = Request::builder()
736 .uri("/test-path?query=123")
737 .header("User-Agent", "TestAgent/1.0")
738 .body(())
739 .unwrap();
740
741 let _resp = svc.clone().oneshot(req).await.unwrap();
742 }
743
744 #[crate::ctb_test]
745 fn test_elf_fields_parsing() {
746 let fields = parse_fields(
747 "#Fields: date time c-ip cs-method cs-uri sc-status cs(User-Agent)",
748 );
749 assert_eq!(fields.len(), 7);
750 assert_eq!(fields[0], ElfField::Date);
751 assert_eq!(fields[1], ElfField::Time);
752 assert_eq!(fields[2], ElfField::ClientIp);
753 assert_eq!(fields[3], ElfField::Method);
754 assert_eq!(fields[4], ElfField::Uri);
755 assert_eq!(fields[5], ElfField::Status);
756 assert_eq!(
757 fields[6],
758 ElfField::RequestHeader("User-Agent".to_string())
759 );
760 }
761
762 #[crate::ctb_test]
763 fn test_elf_string_escaping() {
764 assert_eq!(format_elf_string("hello"), "\"hello\"");
765 assert_eq!(
766 format_elf_string("hello \"world\""),
767 "\"hello \"\"world\"\"\""
768 );
769 }
770}