1
0
Fork 0
mirror of https://github.com/actix/actix-web.git synced 2024-06-02 21:39:26 +00:00
actix-web/actix-http/src/config.rs

316 lines
7.5 KiB
Rust
Raw Normal View History

use std::cell::Cell;
2019-03-26 18:54:35 +00:00
use std::fmt::Write;
use std::rc::Rc;
2019-12-05 17:35:43 +00:00
use std::time::Duration;
2019-12-02 11:33:11 +00:00
use std::{fmt, net};
2019-03-26 18:54:35 +00:00
use actix_rt::time::{sleep, sleep_until, Instant, Sleep};
2019-03-26 18:54:35 +00:00
use bytes::BytesMut;
2019-12-13 05:24:57 +00:00
use futures_util::{future, FutureExt};
Upgrade `time` to 0.2.5 (#1254) * Use `OffsetDateTime` instead of `PrimitiveDateTime` * Parse time strings with `PrimitiveDateTime::parse` instead of `OffsetDateTime::parse` * Remove unused `time` dependency from actix-multipart * Fix a few errors with time related tests from the `time` upgrade * Implement logic to convert a RFC 850 two-digit year into a full length year, and organize time parsing related functions * Upgrade `time` to 0.2.2 * Correctly parse C's asctime time format using time 0.2's new format patterns * Update CHANGES.md * Use `time` without any of its deprecated functions * Enforce a UTC time offset when converting an `OffsetDateTime` into a Header value * Use the more readable version of `Duration::seconds(0)`, `Duration::zero()` * Remove unneeded conversion of time::Duration to std::time::Duration * Use `OffsetDateTime::as_seconds_f64` instead of manually calculating the amount of seconds from nanoseconds * Replace a few additional instances of `Duration::seconds(0)` with `Duration::zero()` * Truncate any nanoseconds from a supplied `Duration` within `Cookie::set_max_age` to ensure two Cookies with the same amount whole seconds equate to one another * Fix the actix-http::cookie::do_not_panic_on_large_max_ages test * Convert `Cookie::max_age` and `Cookie::expires` examples to `time` 0.2 Mainly minor changes. Type inference can be used alongside the new `time::parse` method, such that the type doesn't need to be specified. This will be useful if a refactoring takes place that changes the type. There are also new macros, which are used where possible. One change that is not immediately obvious, in `HttpDate`, there was an unnecessary conditional. As the time crate allows for negative durations (and can perform arithmetic with such), the if/else can be removed entirely. Time v0.2.3 also has some bug fixes, which is why I am not using a more general v0.2 in Cargo.toml. v0.2.3 has been yanked, as it was backwards imcompatible. This version reverts the breaking change, while still supporting rustc back to 1.34.0. * Add missing `time::offset` macro import * Fix type confusion when using `time::parse` followed by `using_offset` * Update `time` to 0.2.5 * Update CHANGES.md Co-authored-by: Jacob Pratt <the.z.cuber@gmail.com>
2020-01-28 11:44:22 +00:00
use time::OffsetDateTime;
2019-03-26 18:54:35 +00:00
2021-01-15 05:38:50 +00:00
/// "Sun, 06 Nov 1994 08:49:37 GMT".len()
2019-03-26 18:54:35 +00:00
const DATE_VALUE_LENGTH: usize = 29;
#[derive(Debug, PartialEq, Clone, Copy)]
/// Server keep-alive setting
pub enum KeepAlive {
/// Keep alive in seconds
Timeout(usize),
/// Rely on OS to shutdown tcp connection
2019-03-26 18:54:35 +00:00
Os,
/// Disabled
Disabled,
}
impl From<usize> for KeepAlive {
fn from(keepalive: usize) -> Self {
KeepAlive::Timeout(keepalive)
}
}
impl From<Option<usize>> for KeepAlive {
fn from(keepalive: Option<usize>) -> Self {
if let Some(keepalive) = keepalive {
KeepAlive::Timeout(keepalive)
} else {
KeepAlive::Disabled
}
}
}
/// Http service configuration
pub struct ServiceConfig(Rc<Inner>);
struct Inner {
keep_alive: Option<Duration>,
client_timeout: u64,
client_disconnect: u64,
ka_enabled: bool,
2019-12-02 11:33:11 +00:00
secure: bool,
local_addr: Option<std::net::SocketAddr>,
2019-03-26 18:54:35 +00:00
timer: DateService,
}
impl Clone for ServiceConfig {
fn clone(&self) -> Self {
ServiceConfig(self.0.clone())
}
}
impl Default for ServiceConfig {
fn default() -> Self {
2019-12-02 11:33:11 +00:00
Self::new(KeepAlive::Timeout(5), 0, 0, false, None)
2019-03-26 18:54:35 +00:00
}
}
impl ServiceConfig {
/// Create instance of `ServiceConfig`
pub fn new(
keep_alive: KeepAlive,
client_timeout: u64,
client_disconnect: u64,
2019-12-02 11:33:11 +00:00
secure: bool,
local_addr: Option<net::SocketAddr>,
2019-03-26 18:54:35 +00:00
) -> ServiceConfig {
let (keep_alive, ka_enabled) = match keep_alive {
KeepAlive::Timeout(val) => (val as u64, true),
KeepAlive::Os => (0, true),
KeepAlive::Disabled => (0, false),
};
let keep_alive = if ka_enabled && keep_alive > 0 {
Some(Duration::from_secs(keep_alive))
} else {
None
};
ServiceConfig(Rc::new(Inner {
keep_alive,
ka_enabled,
client_timeout,
client_disconnect,
2019-12-02 11:33:11 +00:00
secure,
local_addr,
2019-03-26 18:54:35 +00:00
timer: DateService::new(),
}))
}
2021-02-11 22:39:54 +00:00
/// Returns true if connection is secure (HTTPS)
2019-12-02 11:33:11 +00:00
#[inline]
pub fn secure(&self) -> bool {
self.0.secure
}
/// Returns the local address that this server is bound to.
2021-02-11 22:39:54 +00:00
#[inline]
2019-12-02 11:33:11 +00:00
pub fn local_addr(&self) -> Option<net::SocketAddr> {
self.0.local_addr
}
2019-03-26 18:54:35 +00:00
/// Keep alive duration if configured.
2021-02-11 22:39:54 +00:00
#[inline]
2019-03-26 18:54:35 +00:00
pub fn keep_alive(&self) -> Option<Duration> {
self.0.keep_alive
}
2020-04-21 03:09:35 +00:00
/// Return state of connection keep-alive functionality
2021-02-11 22:39:54 +00:00
#[inline]
2019-03-26 18:54:35 +00:00
pub fn keep_alive_enabled(&self) -> bool {
self.0.ka_enabled
}
/// Client timeout for first request.
2021-02-11 22:39:54 +00:00
#[inline]
pub fn client_timer(&self) -> Option<Sleep> {
let delay_time = self.0.client_timeout;
if delay_time != 0 {
Some(sleep_until(
self.0.timer.now() + Duration::from_millis(delay_time),
2019-03-26 18:54:35 +00:00
))
} else {
None
}
}
/// Client timeout for first request.
pub fn client_timer_expire(&self) -> Option<Instant> {
let delay = self.0.client_timeout;
if delay != 0 {
Some(self.0.timer.now() + Duration::from_millis(delay))
} else {
None
}
}
/// Client disconnect timer
pub fn client_disconnect_timer(&self) -> Option<Instant> {
let delay = self.0.client_disconnect;
if delay != 0 {
Some(self.0.timer.now() + Duration::from_millis(delay))
} else {
None
}
}
#[inline]
/// Return keep-alive timer delay is configured.
pub fn keep_alive_timer(&self) -> Option<Sleep> {
2019-03-26 18:54:35 +00:00
if let Some(ka) = self.0.keep_alive {
Some(sleep_until(self.0.timer.now() + ka))
2019-03-26 18:54:35 +00:00
} else {
None
}
}
/// Keep-alive expire time
pub fn keep_alive_expire(&self) -> Option<Instant> {
if let Some(ka) = self.0.keep_alive {
Some(self.0.timer.now() + ka)
} else {
None
}
}
#[inline]
pub(crate) fn now(&self) -> Instant {
self.0.timer.now()
}
2019-05-14 15:48:11 +00:00
#[doc(hidden)]
pub fn set_date(&self, dst: &mut BytesMut) {
2019-03-26 18:54:35 +00:00
let mut buf: [u8; 39] = [0; 39];
buf[..6].copy_from_slice(b"date: ");
2019-07-18 11:37:41 +00:00
self.0
.timer
.set_date(|date| buf[6..35].copy_from_slice(&date.bytes));
2019-03-26 18:54:35 +00:00
buf[35..].copy_from_slice(b"\r\n\r\n");
dst.extend_from_slice(&buf);
}
pub(crate) fn set_date_header(&self, dst: &mut BytesMut) {
2019-07-18 11:37:41 +00:00
self.0
.timer
.set_date(|date| dst.extend_from_slice(&date.bytes));
2019-03-26 18:54:35 +00:00
}
}
#[derive(Copy, Clone)]
2019-03-26 18:54:35 +00:00
struct Date {
bytes: [u8; DATE_VALUE_LENGTH],
pos: usize,
}
impl Date {
fn new() -> Date {
let mut date = Date {
bytes: [0; DATE_VALUE_LENGTH],
pos: 0,
};
date.update();
date
}
2019-03-26 18:54:35 +00:00
fn update(&mut self) {
self.pos = 0;
2020-02-27 02:10:55 +00:00
write!(
self,
"{}",
OffsetDateTime::now_utc().format("%a, %d %b %Y %H:%M:%S GMT")
2020-02-27 02:10:55 +00:00
)
.unwrap();
2019-03-26 18:54:35 +00:00
}
}
impl fmt::Write for Date {
fn write_str(&mut self, s: &str) -> fmt::Result {
let len = s.len();
self.bytes[self.pos..self.pos + len].copy_from_slice(s.as_bytes());
self.pos += len;
Ok(())
}
}
#[derive(Clone)]
struct DateService(Rc<DateServiceInner>);
struct DateServiceInner {
current: Cell<Option<(Date, Instant)>>,
2019-03-26 18:54:35 +00:00
}
impl DateServiceInner {
fn new() -> Self {
DateServiceInner {
current: Cell::new(None),
2019-03-26 18:54:35 +00:00
}
}
fn reset(&self) {
self.current.take();
2019-03-26 18:54:35 +00:00
}
fn update(&self) {
let now = Instant::now();
let date = Date::new();
self.current.set(Some((date, now)));
2019-03-26 18:54:35 +00:00
}
}
impl DateService {
fn new() -> Self {
DateService(Rc::new(DateServiceInner::new()))
}
fn check_date(&self) {
if self.0.current.get().is_none() {
2019-03-26 18:54:35 +00:00
self.0.update();
// periodic date update
let s = self.clone();
actix_rt::spawn(sleep(Duration::from_millis(500)).then(move |_| {
2019-11-26 05:25:50 +00:00
s.0.reset();
future::ready(())
}));
2019-03-26 18:54:35 +00:00
}
}
fn now(&self) -> Instant {
self.check_date();
self.0.current.get().unwrap().1
2019-03-26 18:54:35 +00:00
}
2019-07-18 11:37:41 +00:00
fn set_date<F: FnMut(&Date)>(&self, mut f: F) {
2019-03-26 18:54:35 +00:00
self.check_date();
f(&self.0.current.get().unwrap().0);
2019-03-26 18:54:35 +00:00
}
}
#[cfg(test)]
mod tests {
use super::*;
// Test modifying the date from within the closure
// passed to `set_date`
#[test]
fn test_evil_date() {
let service = DateService::new();
// Make sure that `check_date` doesn't try to spawn a task
service.0.update();
2020-02-27 02:10:55 +00:00
service.set_date(|_| service.0.reset());
}
2019-03-26 18:54:35 +00:00
#[test]
fn test_date_len() {
assert_eq!(DATE_VALUE_LENGTH, "Sun, 06 Nov 1994 08:49:37 GMT".len());
}
2019-11-26 05:25:50 +00:00
#[actix_rt::test]
async fn test_date() {
2019-12-02 11:33:11 +00:00
let settings = ServiceConfig::new(KeepAlive::Os, 0, 0, false, None);
2019-11-26 05:25:50 +00:00
let mut buf1 = BytesMut::with_capacity(DATE_VALUE_LENGTH + 10);
settings.set_date(&mut buf1);
let mut buf2 = BytesMut::with_capacity(DATE_VALUE_LENGTH + 10);
settings.set_date(&mut buf2);
assert_eq!(buf1, buf2);
2019-03-26 18:54:35 +00:00
}
}