1
0
mirror of https://github.com/fafhrd91/actix-web synced 2025-07-17 15:06:51 +02:00

Compare commits

..

1 Commits

Author SHA1 Message Date
Rob Ede
dd8692e000 add send error response state
add changelog

add send error response state

remove comment
2022-07-24 15:27:54 +01:00
48 changed files with 534 additions and 615 deletions

View File

@@ -16,7 +16,7 @@ jobs:
- { name: macOS, os: macos-latest, triple: x86_64-apple-darwin }
- { name: Windows, os: windows-2022, triple: x86_64-pc-windows-msvc }
version:
- 1.59.0 # MSRV
- 1.57.0 # MSRV
- stable
name: ${{ matrix.target.name }} / ${{ matrix.version }}

View File

@@ -28,7 +28,8 @@ jobs:
run: echo '<meta http-equiv="refresh" content="0;url=actix_web/index.html">' > target/doc/index.html
- name: Deploy to GitHub Pages
uses: JamesIves/github-pages-deploy-action@v4.4.0
uses: JamesIves/github-pages-deploy-action@3.7.1
with:
folder: target/doc
single-commit: true
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
BRANCH: gh-pages
FOLDER: target/doc

View File

@@ -1,7 +1,6 @@
# Changes
## Unreleased - 2022-xx-xx
- Minimum supported Rust version (MSRV) is now 1.59 due to transitive `time` dependency.
## 0.6.2 - 2022-07-23

View File

@@ -27,6 +27,7 @@ actix-service = "2"
actix-utils = "3"
actix-web = { version = "4", default-features = false }
askama_escape = "0.10"
bitflags = "1"
bytes = "1"
derive_more = "0.99.5"
@@ -37,7 +38,6 @@ mime = "0.3"
mime_guess = "2.0.1"
percent-encoding = "2.1"
pin-project-lite = "0.2.7"
v_htmlescape= "0.15"
# experimental-io-uring
[target.'cfg(target_os = "linux")'.dependencies]

View File

@@ -4,7 +4,7 @@
[![crates.io](https://img.shields.io/crates/v/actix-files?label=latest)](https://crates.io/crates/actix-files)
[![Documentation](https://docs.rs/actix-files/badge.svg?version=0.6.2)](https://docs.rs/actix-files/0.6.2)
![Version](https://img.shields.io/badge/rustc-1.59+-ab6000.svg)
![Version](https://img.shields.io/badge/rustc-1.57+-ab6000.svg)
![License](https://img.shields.io/crates/l/actix-files.svg)
<br />
[![dependency status](https://deps.rs/crate/actix-files/0.6.2/status.svg)](https://deps.rs/crate/actix-files/0.6.2)

View File

@@ -1,8 +1,8 @@
use std::{fmt::Write, fs::DirEntry, io, path::Path, path::PathBuf};
use actix_web::{dev::ServiceResponse, HttpRequest, HttpResponse};
use askama_escape::{escape as escape_html_entity, Html};
use percent_encoding::{utf8_percent_encode, CONTROLS};
use v_htmlescape::escape as escape_html_entity;
/// A directory; responds with the generated directory listing.
#[derive(Debug)]
@@ -59,7 +59,7 @@ macro_rules! encode_file_url {
/// ```
macro_rules! encode_file_name {
($entry:ident) => {
escape_html_entity(&$entry.file_name().to_string_lossy())
escape_html_entity(&$entry.file_name().to_string_lossy(), Html)
};
}

View File

@@ -1,7 +1,6 @@
# Changes
## Unreleased - 2022-xx-xx
- Minimum supported Rust version (MSRV) is now 1.59.
## 3.0.0 - 2022-07-24

View File

@@ -4,7 +4,7 @@
[![crates.io](https://img.shields.io/crates/v/actix-http-test?label=latest)](https://crates.io/crates/actix-http-test)
[![Documentation](https://docs.rs/actix-http-test/badge.svg?version=3.0.0)](https://docs.rs/actix-http-test/3.0.0)
![Version](https://img.shields.io/badge/rustc-1.59+-ab6000.svg)
![Version](https://img.shields.io/badge/rustc-1.57+-ab6000.svg)
![MIT or Apache 2.0 licensed](https://img.shields.io/crates/l/actix-http-test)
<br>
[![Dependency Status](https://deps.rs/crate/actix-http-test/3.0.0/status.svg)](https://deps.rs/crate/actix-http-test/3.0.0)

View File

@@ -1,16 +1,10 @@
# Changes
## Unreleased - 2022-xx-xx
## 3.2.2 - 2022-09-11
### Changed
- Minimum supported Rust version (MSRV) is now 1.59 due to transitive `time` dependency.
### Fixed
- Avoid possibility of dispatcher getting stuck while back-pressuring I/O. [#2369]
- Dropping the payload early and causing unclean connections no longer causes erroneous 500 responses. [#2745]
[#2369]: https://github.com/actix/actix-web/pull/2369
[#2745]: https://github.com/actix/actix-web/issues/2745
## 3.2.1 - 2022-07-02
@@ -39,9 +33,9 @@
### Fixed
- Revert broken fix in [#2624] that caused erroneous 500 error responses. Temporarily re-introduces [#2357] bug. [#2779]
[#2624]: https://github.com/actix/actix-web/pull/2624
[#2357]: https://github.com/actix/actix-web/issues/2357
[#2779]: https://github.com/actix/actix-web/pull/2779
[#2624]: https://github.com/actix/actix-web/issues/2624
[#2779]: https://github.com/actix/actix-web/issues/2779
## 3.0.4 - 2022-03-09
@@ -53,14 +47,14 @@
### Fixed
- Allow spaces between header name and colon when parsing responses. [#2684]
[#2684]: https://github.com/actix/actix-web/pull/2684
[#2684]: https://github.com/actix/actix-web/issues/2684
## 3.0.2 - 2022-03-05
### Fixed
- Fix encoding camel-case header names with more than one hyphen. [#2683]
[#2683]: https://github.com/actix/actix-web/pull/2683
[#2683]: https://github.com/actix/actix-web/issues/2683
## 3.0.1 - 2022-03-04

View File

@@ -1,6 +1,6 @@
[package]
name = "actix-http"
version = "3.2.2"
version = "3.2.1"
authors = [
"Nikolay Kim <fafhrd91@gmail.com>",
"Rob Ede <robjtede@icloud.com>",

View File

@@ -3,11 +3,11 @@
> HTTP primitives for the Actix ecosystem.
[![crates.io](https://img.shields.io/crates/v/actix-http?label=latest)](https://crates.io/crates/actix-http)
[![Documentation](https://docs.rs/actix-http/badge.svg?version=3.2.2)](https://docs.rs/actix-http/3.2.2)
![Version](https://img.shields.io/badge/rustc-1.59+-ab6000.svg)
[![Documentation](https://docs.rs/actix-http/badge.svg?version=3.2.1)](https://docs.rs/actix-http/3.2.1)
![Version](https://img.shields.io/badge/rustc-1.57+-ab6000.svg)
![MIT or Apache 2.0 licensed](https://img.shields.io/crates/l/actix-http.svg)
<br />
[![dependency status](https://deps.rs/crate/actix-http/3.2.2/status.svg)](https://deps.rs/crate/actix-http/3.2.2)
[![dependency status](https://deps.rs/crate/actix-http/3.2.1/status.svg)](https://deps.rs/crate/actix-http/3.2.1)
[![Download](https://img.shields.io/crates/d/actix-http.svg)](https://crates.io/crates/actix-http)
[![Chat on Discord](https://img.shields.io/discord/771444961383153695?label=chat&logo=discord)](https://discord.gg/NWpN5mmg3x)

View File

@@ -211,7 +211,6 @@ where
/// Finish service configuration and create a HTTP service for HTTP/2 protocol.
#[cfg(feature = "http2")]
#[cfg_attr(docsrs, doc(cfg(feature = "http2")))]
pub fn h2<F, B>(self, service: F) -> crate::h2::H2Service<T, S, B>
where
F: IntoServiceFactory<S, Request>,

View File

@@ -35,7 +35,7 @@ impl Default for ServiceConfig {
}
impl ServiceConfig {
/// Create instance of `ServiceConfig`.
/// Create instance of `ServiceConfig`
pub fn new(
keep_alive: KeepAlive,
client_request_timeout: Duration,

View File

@@ -294,7 +294,6 @@ impl std::error::Error for PayloadError {
PayloadError::Overflow => None,
PayloadError::UnknownLength => None,
#[cfg(feature = "http2")]
#[cfg_attr(docsrs, doc(cfg(feature = "http2")))]
PayloadError::Http2Payload(err) => Some(err),
PayloadError::Io(err) => Some(err),
}
@@ -352,7 +351,6 @@ pub enum DispatchError {
/// HTTP/2 error.
#[display(fmt = "{}", _0)]
#[cfg(feature = "http2")]
#[cfg_attr(docsrs, doc(cfg(feature = "http2")))]
H2(h2::Error),
/// The first request did not complete within the specified timeout.

View File

@@ -22,7 +22,7 @@ use crate::{
config::ServiceConfig,
error::{DispatchError, ParseError, PayloadError},
service::HttpFlow,
Error, Extensions, OnConnectData, Request, Response, StatusCode,
ConnectionType, Error, Extensions, OnConnectData, Request, Response, StatusCode,
};
use super::{
@@ -185,7 +185,9 @@ pin_project! {
None,
ExpectCall { #[pin] fut: X::Future },
ServiceCall { #[pin] fut: S::Future },
SendResponse { res: Option<Response<B>> },
SendPayload { #[pin] body: B },
SendErrorResponse { res: Option<Response<BoxBody>> },
SendErrorPayload { #[pin] body: BoxBody },
}
}
@@ -216,9 +218,15 @@ where
Self::ServiceCall { .. } => {
f.debug_struct("State::ServiceCall").finish_non_exhaustive()
}
Self::SendResponse { .. } => f
.debug_struct("State::SendResponse")
.finish_non_exhaustive(),
Self::SendPayload { .. } => {
f.debug_struct("State::SendPayload").finish_non_exhaustive()
}
Self::SendErrorResponse { .. } => f
.debug_struct("State::SendErrorResponse")
.finish_non_exhaustive(),
Self::SendErrorPayload { .. } => f
.debug_struct("State::SendErrorPayload")
.finish_non_exhaustive(),
@@ -379,11 +387,8 @@ where
Ok(size)
}
fn send_response(
mut self: Pin<&mut Self>,
res: Response<()>,
body: B,
) -> Result<(), DispatchError> {
fn send_response(mut self: Pin<&mut Self>, res: Response<B>) -> Result<(), DispatchError> {
let (res, body) = res.replace_body(());
let size = self.as_mut().send_response_inner(res, &body)?;
let mut this = self.project();
this.state.set(match size {
@@ -397,11 +402,17 @@ where
Ok(())
}
fn queue_response(self: Pin<&mut Self>, res: Response<B>) {
self.project()
.state
.set(State::SendResponse { res: Some(res) });
}
fn send_error_response(
mut self: Pin<&mut Self>,
res: Response<()>,
body: BoxBody,
res: Response<BoxBody>,
) -> Result<(), DispatchError> {
let (res, body) = res.replace_body(());
let size = self.as_mut().send_response_inner(res, &body)?;
let mut this = self.project();
this.state.set(match size {
@@ -415,6 +426,12 @@ where
Ok(())
}
fn queue_error_response(self: Pin<&mut Self>, res: Response<BoxBody>) {
self.project()
.state
.set(State::SendErrorResponse { res: Some(res) });
}
fn send_continue(self: Pin<&mut Self>) {
self.project()
.write_buf
@@ -449,7 +466,8 @@ where
// send_response would update InnerDispatcher state to SendPayload or None
// (If response body is empty)
// continue loop to poll it
self.as_mut().send_error_response(res, BoxBody::new(()))?;
self.as_mut()
.queue_error_response(res.set_body(BoxBody::new(())));
}
// return with upgrade request and poll it exclusively
@@ -470,15 +488,12 @@ where
match fut.poll(cx) {
// service call resolved. send response.
Poll::Ready(Ok(res)) => {
let (res, body) = res.into().replace_body(());
self.as_mut().send_response(res, body)?;
self.as_mut().queue_response(res.into());
}
// send service call error as response
Poll::Ready(Err(err)) => {
let res: Response<BoxBody> = err.into();
let (res, body) = res.replace_body(());
self.as_mut().send_error_response(res, body)?;
self.as_mut().queue_error_response(err.into());
}
// service call pending and could be waiting for more chunk messages
@@ -486,14 +501,32 @@ where
Poll::Pending => {
// no new message is decoded and no new payload is fed
// nothing to do except waiting for new incoming data from client
if !self.as_mut().poll_request(cx)? {
return Ok(PollResponse::DoNothing);
}
// optimisation disabled so that poll_request is called from only one place
// if !self.as_mut().poll_request(cx)? {
return Ok(PollResponse::DoNothing);
// }
// else loop
}
}
}
StateProj::SendResponse { res } => {
let mut res = res.take().expect("response should be take-able");
if this.flags.contains(Flags::SHUTDOWN) {
trace!("shutdown flag set; assuming dirty read I/O");
// shutdown flags occur when read I/O is not clean so connections should be
// closed to avoid stuck or erroneous errors on next request
res.head_mut().set_connection_type(ConnectionType::Close);
}
self.send_response(res)?;
return Ok(PollResponse::DrainWriteBuf);
}
StateProj::SendPayload { mut body } => {
// keep populate writer buffer until buffer size limit hit,
// get blocked or finished.
@@ -529,6 +562,23 @@ where
return Ok(PollResponse::DrainWriteBuf);
}
StateProj::SendErrorResponse { res } => {
// TODO: de-dupe impl with SendResponse
let mut res = res.take().expect("response should be take-able");
if this.flags.contains(Flags::SHUTDOWN) {
trace!("shutdown flag set; assuming dirty read I/O");
// shutdown flags occur when read I/O is not clean so connections should be
// closed to avoid stuck or erroneous errors on next request
res.head_mut().set_connection_type(ConnectionType::Close);
}
self.send_error_response(res)?;
return Ok(PollResponse::DrainWriteBuf);
}
StateProj::SendErrorPayload { mut body } => {
// TODO: de-dupe impl with SendPayload
@@ -583,9 +633,7 @@ where
// send expect error as response
Poll::Ready(Err(err)) => {
let res: Response<BoxBody> = err.into();
let (res, body) = res.replace_body(());
self.as_mut().send_error_response(res, body)?;
self.as_mut().queue_error_response(err.into());
}
// expect must be solved before progress can be made.
@@ -637,9 +685,8 @@ where
// on success to notify the dispatcher a new state is set and the outer loop
// should be continued
Poll::Ready(Err(err)) => {
let res: Response<BoxBody> = err.into();
let (res, body) = res.replace_body(());
return self.send_error_response(res, body);
self.queue_error_response(err.into());
return Ok(());
}
// future is pending; return Ok(()) to notify that a new state is
@@ -655,8 +702,8 @@ where
// to notify the dispatcher a new state is set and the outer loop
// should be continue.
Poll::Ready(Ok(res)) => {
let (res, body) = res.into().replace_body(());
self.as_mut().send_response(res, body)
self.as_mut().queue_response(res.into());
Ok(())
}
// see the comment on ExpectCall state branch's Pending
@@ -664,9 +711,8 @@ where
// see the comment on ExpectCall state branch's Ready(Err(_))
Poll::Ready(Err(err)) => {
let res: Response<BoxBody> = err.into();
let (res, body) = res.replace_body(());
self.as_mut().send_error_response(res, body)
self.as_mut().queue_error_response(err.into());
Ok(())
}
};
}
@@ -688,15 +734,13 @@ where
cx: &mut Context<'_>,
) -> Result<bool, DispatchError> {
let pipeline_queue_full = self.messages.len() >= MAX_PIPELINED_MESSAGES;
let can_not_read = !self.can_read(cx);
// limit amount of non-processed requests
if pipeline_queue_full || can_not_read {
if pipeline_queue_full {
return Ok(false);
}
let mut this = self.as_mut().project();
let mut updated = false;
// decode from read buf as many full requests as possible
@@ -829,6 +873,72 @@ where
}
}
let can_read = self.can_read(cx);
let mut this = self.as_mut().project();
if !can_read {
// request payload is not readable...
tracing::debug!("cannot read request payload");
if let Some(sender) = &this.payload {
// ...maybe handler does not want to read any more payload...
if let PayloadStatus::Dropped = sender.need_read(cx) {
tracing::debug!(
"handler dropped payload early; attempt to clean connection"
);
// ...in which case poll request payload a few times
loop {
match this.codec.decode(this.read_buf)? {
Some(msg) => {
match msg {
// payload decoded did not yield EOF yet
Message::Chunk(Some(_)) => {
// if non-clean connection, next loop iter will detect empty
// read buffer and close connection
}
// connection is in clean state for next request
Message::Chunk(None) => {
tracing::debug!("connection successfully cleaned");
// reset dispatcher state
let _ = this.payload.take();
this.state.set(State::None);
// break out of payload decode loop
break;
}
// Either whole payload is read and loop is broken or more data
// was expected in which case connection is closed. In both
// situations dispatcher cannot get here.
Message::Item(_) => {
unreachable!("dispatcher is in payload receive state")
}
}
}
// not enough info to decide if connection is going to be clean or not
None => {
tracing::debug!(
"handler did not read whole payload and dispatcher could not \
drain read buf; close connection"
);
this.flags.insert(Flags::SHUTDOWN);
return Ok(updated);
}
}
}
}
} else {
// can_not_read and no request payload
return Ok(false);
}
}
Ok(updated)
}
@@ -844,10 +954,10 @@ where
trace!("timed out on slow request; replying with 408 and closing connection");
let _ = self.as_mut().send_error_response(
Response::with_body(StatusCode::REQUEST_TIMEOUT, ()),
BoxBody::new(()),
);
let mut res =
Response::with_body(StatusCode::REQUEST_TIMEOUT, BoxBody::new(()));
res.head_mut().set_connection_type(ConnectionType::Close);
self.as_mut().send_error_response(res)?;
self.project().flags.insert(Flags::SHUTDOWN);
}
@@ -976,11 +1086,9 @@ where
//
// A Request head too large to parse is only checked on `httparse::Status::Partial`.
match this.payload {
// When dispatcher has a payload the responsibility of wake ups is shifted to
// `h1::payload::Payload` unless the payload is needing a read, in which case it
// might not have access to the waker and could result in the dispatcher
// getting stuck until timeout.
if this.payload.is_none() {
// When dispatcher has a payload the responsibility of wake up it would be shift
// to h1::payload::Payload.
//
// Reason:
// Self wake up when there is payload would waste poll and/or result in
@@ -991,8 +1099,7 @@ where
// read anymore. At this case read_buf could always remain beyond
// MAX_BUFFER_SIZE and self wake up would be busy poll dispatcher and
// waste resources.
Some(ref p) if p.need_read(cx) != PayloadStatus::Read => {}
_ => cx.waker().wake_by_ref(),
cx.waker().wake_by_ref();
}
return Ok(false);
@@ -1126,6 +1233,7 @@ where
}
}
// process request(s) and queue response
inner.as_mut().poll_request(cx)?;
if should_disconnect {

View File

@@ -861,56 +861,26 @@ async fn handler_drop_payload() {
",
));
assert!(h1.as_mut().poll(cx).is_pending());
// polls: manual => manual
assert_eq!(h1.poll_count, 2);
let mut res = BytesMut::from(buf.take_write_buf().as_ref());
stabilize_date_header(&mut res);
let res = &res[..];
// expect response immediately even though request side has not finished reading payload
let exp = http_msg(
r"
HTTP/1.1 200 OK
content-length: 15
date: Thu, 01 Jan 1970 12:34:56 UTC
payload dropped
",
);
assert_eq!(
res,
exp,
"\nexpected response not in write buffer:\n\
response: {:?}\n\
expected: {:?}",
String::from_utf8_lossy(res),
String::from_utf8_lossy(&exp)
);
})
.await;
lazy(|cx| {
assert!(h1.as_mut().poll(cx).is_ready());
// polls: manual => manual => manual
// polls: manual => manual => shutdown
assert_eq!(h1.poll_count, 3);
let mut res = BytesMut::from(buf.take_write_buf().as_ref());
stabilize_date_header(&mut res);
let res = &res[..];
// expect that unrequested error response is sent back since connection could not be cleaned
// expect response immediately even though request side has not finished reading payload
// since write buffer was "too short" we should expect a closed connection hint
let exp = http_msg(
// connection: close
r"
HTTP/1.1 500 Internal Server Error
content-length: 0
HTTP/1.1 200 OK
content-length: 15
connection: close
date: Thu, 01 Jan 1970 12:34:56 UTC
payload dropped
",
);

View File

@@ -134,7 +134,6 @@ mod openssl {
U::InitError: fmt::Debug,
{
/// Create OpenSSL based service.
#[cfg_attr(docsrs, doc(cfg(feature = "openssl")))]
pub fn openssl(
self,
acceptor: SslAcceptor,
@@ -197,7 +196,6 @@ mod rustls {
U::InitError: fmt::Debug,
{
/// Create Rustls based service.
#[cfg_attr(docsrs, doc(cfg(feature = "rustls")))]
pub fn rustls(
self,
config: ServerConfig,

View File

@@ -67,7 +67,7 @@ where
timer
})
.unwrap_or_else(|| Box::pin(sleep(dur))),
in_flight: false,
on_flight: false,
ping_pong: conn.ping_pong().unwrap(),
});
@@ -84,14 +84,9 @@ where
}
struct H2PingPong {
/// Handle to send ping frames from the peer.
ping_pong: PingPong,
/// True when a ping has been sent and is waiting for a reply.
in_flight: bool,
/// Timeout for pong response.
timer: Pin<Box<Sleep>>,
on_flight: bool,
ping_pong: PingPong,
}
impl<T, S, B, X, U> Future for Dispatcher<T, S, B, X, U>
@@ -157,28 +152,26 @@ where
});
}
Poll::Ready(None) => return Poll::Ready(Ok(())),
Poll::Pending => match this.ping_pong.as_mut() {
Some(ping_pong) => loop {
if ping_pong.in_flight {
// When there is an in-flight ping-pong, poll pong and and keep-alive
// timer. On successful pong received, update keep-alive timer to
// determine the next timing of ping pong.
if ping_pong.on_flight {
// When have on flight ping pong. poll pong and and keep alive timer.
// on success pong received update keep alive timer to determine the next timing of
// ping pong.
match ping_pong.ping_pong.poll_pong(cx)? {
Poll::Ready(_) => {
ping_pong.in_flight = false;
ping_pong.on_flight = false;
let dead_line = this.config.keep_alive_deadline().unwrap();
ping_pong.timer.as_mut().reset(dead_line.into());
}
Poll::Pending => {
return ping_pong.timer.as_mut().poll(cx).map(|_| Ok(()));
return ping_pong.timer.as_mut().poll(cx).map(|_| Ok(()))
}
}
} else {
// When there is no in-flight ping-pong, keep-alive timer is used to
// wait for next timing of ping-pong. Therefore, at this point it serves
// as an interval instead.
// When there is no on flight ping pong. keep alive timer is used to wait for next
// timing of ping pong. Therefore at this point it serves as an interval instead.
ready!(ping_pong.timer.as_mut().poll(cx));
ping_pong.ping_pong.send_ping(Ping::opaque())?;
@@ -186,7 +179,7 @@ where
let dead_line = this.config.keep_alive_deadline().unwrap();
ping_pong.timer.as_mut().reset(dead_line.into());
ping_pong.in_flight = true;
ping_pong.on_flight = true;
}
},
None => return Poll::Pending,
@@ -294,13 +287,13 @@ fn prepare_response(
_ => {}
}
match size {
BodySize::None | BodySize::Stream => {}
let _ = match size {
BodySize::None | BodySize::Stream => None,
BodySize::Sized(0) => {
#[allow(clippy::declare_interior_mutable_const)]
const HV_ZERO: HeaderValue = HeaderValue::from_static("0");
res.headers_mut().insert(CONTENT_LENGTH, HV_ZERO);
res.headers_mut().insert(CONTENT_LENGTH, HV_ZERO)
}
BodySize::Sized(len) => {
@@ -309,7 +302,7 @@ fn prepare_response(
res.headers_mut().insert(
CONTENT_LENGTH,
HeaderValue::from_str(buf.format(*len)).unwrap(),
);
)
}
};

View File

@@ -117,7 +117,6 @@ mod openssl {
B: MessageBody + 'static,
{
/// Create OpenSSL based service.
#[cfg_attr(docsrs, doc(cfg(feature = "openssl")))]
pub fn openssl(
self,
acceptor: SslAcceptor,
@@ -165,7 +164,6 @@ mod rustls {
B: MessageBody + 'static,
{
/// Create Rustls based service.
#[cfg_attr(docsrs, doc(cfg(feature = "rustls")))]
pub fn rustls(
self,
mut config: ServerConfig,

View File

@@ -40,7 +40,6 @@ pub mod error;
mod extensions;
pub mod h1;
#[cfg(feature = "http2")]
#[cfg_attr(docsrs, doc(cfg(feature = "http2")))]
pub mod h2;
pub mod header;
mod helpers;
@@ -55,7 +54,6 @@ mod responses;
mod service;
pub mod test;
#[cfg(feature = "ws")]
#[cfg_attr(docsrs, doc(cfg(feature = "ws")))]
pub mod ws;
pub use self::builder::HttpServiceBuilder;
@@ -73,7 +71,6 @@ pub use self::requests::{Request, RequestHead, RequestHeadType};
pub use self::responses::{Response, ResponseBuilder, ResponseHead};
pub use self::service::HttpService;
#[cfg(any(feature = "openssl", feature = "rustls"))]
#[cfg_attr(docsrs, doc(cfg(any(feature = "openssl", feature = "rustls"))))]
pub use self::service::TlsAcceptorConfig;
/// A major HTTP protocol version.

View File

@@ -239,7 +239,6 @@ mod openssl {
U::InitError: fmt::Debug,
{
/// Create OpenSSL based service.
#[cfg_attr(docsrs, doc(cfg(feature = "openssl")))]
pub fn openssl(
self,
acceptor: SslAcceptor,
@@ -254,7 +253,6 @@ mod openssl {
}
/// Create OpenSSL based service with custom TLS acceptor configuration.
#[cfg_attr(docsrs, doc(cfg(feature = "openssl")))]
pub fn openssl_with_config(
self,
acceptor: SslAcceptor,
@@ -334,7 +332,6 @@ mod rustls {
U::InitError: fmt::Debug,
{
/// Create Rustls based service.
#[cfg_attr(docsrs, doc(cfg(feature = "rustls")))]
pub fn rustls(
self,
config: ServerConfig,
@@ -349,7 +346,6 @@ mod rustls {
}
/// Create Rustls based service with custom TLS acceptor configuration.
#[cfg_attr(docsrs, doc(cfg(feature = "rustls")))]
pub fn rustls_with_config(
self,
mut config: ServerConfig,

View File

@@ -1,7 +1,7 @@
# Changes
## Unreleased - 2022-xx-xx
- Minimum supported Rust version (MSRV) is now 1.59 due to transitive `time` dependency.
- Minimum supported Rust version (MSRV) is now 1.57 due to transitive `time` dependency.
## 0.4.0 - 2022-02-25

View File

@@ -28,7 +28,7 @@ twoway = "0.2"
[dev-dependencies]
actix-rt = "2.2"
actix-http = "3"
actix-http = "3.0.0"
futures-util = { version = "0.3.7", default-features = false, features = ["alloc"] }
tokio = { version = "1.8.4", features = ["sync"] }
tokio-stream = "0.1"

View File

@@ -4,7 +4,7 @@
[![crates.io](https://img.shields.io/crates/v/actix-multipart?label=latest)](https://crates.io/crates/actix-multipart)
[![Documentation](https://docs.rs/actix-multipart/badge.svg?version=0.4.0)](https://docs.rs/actix-multipart/0.4.0)
![Version](https://img.shields.io/badge/rustc-1.59+-ab6000.svg)
![Version](https://img.shields.io/badge/rustc-1.57+-ab6000.svg)
![MIT or Apache 2.0 licensed](https://img.shields.io/crates/l/actix-multipart.svg)
<br />
[![dependency status](https://deps.rs/crate/actix-multipart/0.4.0/status.svg)](https://deps.rs/crate/actix-multipart/0.4.0)

View File

@@ -1,7 +1,7 @@
# Changes
## Unreleased - 2022-xx-xx
- Minimum supported Rust version (MSRV) is now 1.59 due to transitive `time` dependency.
- Minimum supported Rust version (MSRV) is now 1.57 due to transitive `time` dependency.
## 0.5.0 - 2022-02-22

View File

@@ -1,7 +1,6 @@
# Changes
## Unreleased - 2022-xx-xx
- Minimum supported Rust version (MSRV) is now 1.59 due to transitive `time` dependency.
## 0.1.0 - 2022-07-24

View File

@@ -4,7 +4,7 @@
[![crates.io](https://img.shields.io/crates/v/actix-web-actors?label=latest)](https://crates.io/crates/actix-web-actors)
[![Documentation](https://docs.rs/actix-web-actors/badge.svg?version=4.1.0)](https://docs.rs/actix-web-actors/4.1.0)
![Version](https://img.shields.io/badge/rustc-1.59+-ab6000.svg)
![Version](https://img.shields.io/badge/rustc-1.57+-ab6000.svg)
![License](https://img.shields.io/crates/l/actix-web-actors.svg)
<br />
[![dependency status](https://deps.rs/crate/actix-web-actors/4.1.0/status.svg)](https://deps.rs/crate/actix-web-actors/4.1.0)

View File

@@ -1,11 +1,8 @@
# Changes
## Unreleased - 2022-xx-xx
## 4.1.0 - 2022-09-11
- Add `#[routes]` macro to support multiple paths for one handler. [#2718]
- Minimum supported Rust version (MSRV) is now 1.59 due to transitive `time` dependency.
- Minimum supported Rust version (MSRV) is now 1.57 due to transitive `time` dependency.
[#2718]: https://github.com/actix/actix-web/pull/2718

View File

@@ -1,6 +1,6 @@
[package]
name = "actix-web-codegen"
version = "4.1.0"
version = "4.0.1"
description = "Routing and runtime macros for Actix Web"
homepage = "https://actix.rs"
repository = "https://github.com/actix/actix-web.git"
@@ -24,8 +24,8 @@ syn = { version = "1", features = ["full", "extra-traits"] }
actix-macros = "0.2.3"
actix-rt = "2.2"
actix-test = "0.1"
actix-utils = "3"
actix-web = "4"
actix-utils = "3.0.0"
actix-web = "4.0.0"
futures-core = { version = "0.3.7", default-features = false, features = ["alloc"] }
trybuild = "1"

View File

@@ -3,11 +3,11 @@
> Routing and runtime macros for Actix Web.
[![crates.io](https://img.shields.io/crates/v/actix-web-codegen?label=latest)](https://crates.io/crates/actix-web-codegen)
[![Documentation](https://docs.rs/actix-web-codegen/badge.svg?version=4.1.0)](https://docs.rs/actix-web-codegen/4.1.0)
![Version](https://img.shields.io/badge/rustc-1.59+-ab6000.svg)
[![Documentation](https://docs.rs/actix-web-codegen/badge.svg?version=4.0.1)](https://docs.rs/actix-web-codegen/4.0.1)
![Version](https://img.shields.io/badge/rustc-1.57+-ab6000.svg)
![License](https://img.shields.io/crates/l/actix-web-codegen.svg)
<br />
[![dependency status](https://deps.rs/crate/actix-web-codegen/4.1.0/status.svg)](https://deps.rs/crate/actix-web-codegen/4.1.0)
[![dependency status](https://deps.rs/crate/actix-web-codegen/4.0.1/status.svg)](https://deps.rs/crate/actix-web-codegen/4.0.1)
[![Download](https://img.shields.io/crates/d/actix-web-codegen.svg)](https://crates.io/crates/actix-web-codegen)
[![Chat on Discord](https://img.shields.io/discord/771444961383153695?label=chat&logo=discord)](https://discord.gg/NWpN5mmg3x)

View File

@@ -1,4 +1,4 @@
#[rustversion::stable(1.59)] // MSRV
#[rustversion::stable(1.57)] // MSRV
#[test]
fn compile_macros() {
let t = trybuild::TestCases::new();

View File

@@ -4,16 +4,10 @@ error: HTTP method defined more than once: `GET`
3 | #[route("/", method="GET", method="GET")]
| ^^^^^
error[E0277]: the trait bound `fn() -> impl std::future::Future<Output = String> {index}: HttpServiceFactory` is not satisfied
--> tests/trybuild/route-duplicate-method-fail.rs:12:55
|
12 | let srv = actix_test::start(|| App::new().service(index));
| ------- ^^^^^ the trait `HttpServiceFactory` is not implemented for `fn() -> impl std::future::Future<Output = String> {index}`
| |
| required by a bound introduced by this call
|
note: required by a bound in `App::<T>::service`
--> $WORKSPACE/actix-web/src/app.rs
|
| F: HttpServiceFactory + 'static,
| ^^^^^^^^^^^^^^^^^^ required by this bound in `App::<T>::service`
error[E0277]: the trait bound `fn() -> impl std::future::Future {index}: HttpServiceFactory` is not satisfied
--> tests/trybuild/route-duplicate-method-fail.rs:12:55
|
12 | let srv = actix_test::start(|| App::new().service(index));
| ------- ^^^^^ the trait `HttpServiceFactory` is not implemented for `fn() -> impl std::future::Future {index}`
| |
| required by a bound introduced by this call

View File

@@ -6,16 +6,10 @@ error: The #[route(..)] macro requires at least one `method` attribute
|
= note: this error originates in the attribute macro `route` (in Nightly builds, run with -Z macro-backtrace for more info)
error[E0277]: the trait bound `fn() -> impl std::future::Future<Output = String> {index}: HttpServiceFactory` is not satisfied
--> tests/trybuild/route-missing-method-fail.rs:12:55
|
12 | let srv = actix_test::start(|| App::new().service(index));
| ------- ^^^^^ the trait `HttpServiceFactory` is not implemented for `fn() -> impl std::future::Future<Output = String> {index}`
| |
| required by a bound introduced by this call
|
note: required by a bound in `App::<T>::service`
--> $WORKSPACE/actix-web/src/app.rs
|
| F: HttpServiceFactory + 'static,
| ^^^^^^^^^^^^^^^^^^ required by this bound in `App::<T>::service`
error[E0277]: the trait bound `fn() -> impl std::future::Future {index}: HttpServiceFactory` is not satisfied
--> tests/trybuild/route-missing-method-fail.rs:12:55
|
12 | let srv = actix_test::start(|| App::new().service(index));
| ------- ^^^^^ the trait `HttpServiceFactory` is not implemented for `fn() -> impl std::future::Future {index}`
| |
| required by a bound introduced by this call

View File

@@ -4,16 +4,10 @@ error: Unexpected HTTP method: `UNEXPECTED`
3 | #[route("/", method="UNEXPECTED")]
| ^^^^^^^^^^^^
error[E0277]: the trait bound `fn() -> impl std::future::Future<Output = String> {index}: HttpServiceFactory` is not satisfied
--> tests/trybuild/route-unexpected-method-fail.rs:12:55
|
12 | let srv = actix_test::start(|| App::new().service(index));
| ------- ^^^^^ the trait `HttpServiceFactory` is not implemented for `fn() -> impl std::future::Future<Output = String> {index}`
| |
| required by a bound introduced by this call
|
note: required by a bound in `App::<T>::service`
--> $WORKSPACE/actix-web/src/app.rs
|
| F: HttpServiceFactory + 'static,
| ^^^^^^^^^^^^^^^^^^ required by this bound in `App::<T>::service`
error[E0277]: the trait bound `fn() -> impl std::future::Future {index}: HttpServiceFactory` is not satisfied
--> tests/trybuild/route-unexpected-method-fail.rs:12:55
|
12 | let srv = actix_test::start(|| App::new().service(index));
| ------- ^^^^^ the trait `HttpServiceFactory` is not implemented for `fn() -> impl std::future::Future {index}`
| |
| required by a bound introduced by this call

View File

@@ -12,16 +12,10 @@ error: Invalid input for macro
4 | #[get]
| ^^^^^^
error[E0277]: the trait bound `fn() -> impl std::future::Future<Output = String> {index}: HttpServiceFactory` is not satisfied
--> tests/trybuild/routes-missing-args-fail.rs:13:55
|
13 | let srv = actix_test::start(|| App::new().service(index));
| ------- ^^^^^ the trait `HttpServiceFactory` is not implemented for `fn() -> impl std::future::Future<Output = String> {index}`
| |
| required by a bound introduced by this call
|
note: required by a bound in `App::<T>::service`
--> $WORKSPACE/actix-web/src/app.rs
|
| F: HttpServiceFactory + 'static,
| ^^^^^^^^^^^^^^^^^^ required by this bound in `App::<T>::service`
error[E0277]: the trait bound `fn() -> impl std::future::Future {index}: HttpServiceFactory` is not satisfied
--> tests/trybuild/routes-missing-args-fail.rs:13:55
|
13 | let srv = actix_test::start(|| App::new().service(index));
| ------- ^^^^^ the trait `HttpServiceFactory` is not implemented for `fn() -> impl std::future::Future {index}`
| |
| required by a bound introduced by this call

View File

@@ -6,16 +6,10 @@ error: The #[routes] macro requires at least one `#[<method>(..)]` attribute.
|
= note: this error originates in the attribute macro `routes` (in Nightly builds, run with -Z macro-backtrace for more info)
error[E0277]: the trait bound `fn() -> impl std::future::Future<Output = String> {index}: HttpServiceFactory` is not satisfied
--> tests/trybuild/routes-missing-method-fail.rs:12:55
|
12 | let srv = actix_test::start(|| App::new().service(index));
| ------- ^^^^^ the trait `HttpServiceFactory` is not implemented for `fn() -> impl std::future::Future<Output = String> {index}`
| |
| required by a bound introduced by this call
|
note: required by a bound in `App::<T>::service`
--> $WORKSPACE/actix-web/src/app.rs
|
| F: HttpServiceFactory + 'static,
| ^^^^^^^^^^^^^^^^^^ required by this bound in `App::<T>::service`
error[E0277]: the trait bound `fn() -> impl std::future::Future {index}: HttpServiceFactory` is not satisfied
--> tests/trybuild/routes-missing-method-fail.rs:12:55
|
12 | let srv = actix_test::start(|| App::new().service(index));
| ------- ^^^^^ the trait `HttpServiceFactory` is not implemented for `fn() -> impl std::future::Future {index}`
| |
| required by a bound introduced by this call

View File

@@ -1,16 +1,13 @@
# Changelog
## Unreleased - 2022-xx-xx
## 4.2.0 - 2022-09-11
### Added
- Add `#[routes]` macro to support multiple paths for one handler. [#2718]
- Add `ServiceRequest::{parts, request}()` getter methods. [#2786]
- Add configuration options for TLS handshake timeout via `HttpServer::{rustls, openssl}_with_config` methods. [#2752]
### Changed
- Minimum supported Rust version (MSRV) is now 1.59 due to transitive `time` dependency.
- Minimum supported Rust version (MSRV) is now 1.57 due to transitive `time` dependency.
[#2718]: https://github.com/actix/actix-web/pull/2718
[#2752]: https://github.com/actix/actix-web/pull/2752

View File

@@ -1,6 +1,6 @@
[package]
name = "actix-web"
version = "4.2.0"
version = "4.1.0"
authors = [
"Nikolay Kim <fafhrd91@gmail.com>",
"Rob Ede <robjtede@icloud.com>",
@@ -73,7 +73,7 @@ actix-tls = { version = "3", default-features = false, optional = true }
actix-http = { version = "3", features = ["http2", "ws"] }
actix-router = "0.5"
actix-web-codegen = { version = "4.1", optional = true }
actix-web-codegen = { version = "4", optional = true }
ahash = "0.7"
bytes = "1"

View File

@@ -6,10 +6,10 @@
<p>
[![crates.io](https://img.shields.io/crates/v/actix-web?label=latest)](https://crates.io/crates/actix-web)
[![Documentation](https://docs.rs/actix-web/badge.svg?version=4.2.0)](https://docs.rs/actix-web/4.2.0)
![MSRV](https://img.shields.io/badge/rustc-1.59+-ab6000.svg)
[![Documentation](https://docs.rs/actix-web/badge.svg?version=4.1.0)](https://docs.rs/actix-web/4.1.0)
![MSRV](https://img.shields.io/badge/rustc-1.57+-ab6000.svg)
![MIT or Apache 2.0 licensed](https://img.shields.io/crates/l/actix-web.svg)
[![Dependency Status](https://deps.rs/crate/actix-web/4.2.0/status.svg)](https://deps.rs/crate/actix-web/4.2.0)
[![Dependency Status](https://deps.rs/crate/actix-web/4.1.0/status.svg)](https://deps.rs/crate/actix-web/4.1.0)
<br />
[![CI](https://github.com/actix/actix-web/actions/workflows/ci.yml/badge.svg)](https://github.com/actix/actix-web/actions/workflows/ci.yml)
[![codecov](https://codecov.io/gh/actix/actix-web/branch/master/graph/badge.svg)](https://codecov.io/gh/actix/actix-web)
@@ -33,7 +33,7 @@
- SSL support using OpenSSL or Rustls
- Middlewares ([Logger, Session, CORS, etc](https://actix.rs/docs/middleware/))
- Integrates with the [`awc` HTTP client](https://docs.rs/awc/)
- Runs on stable Rust 1.59+
- Runs on stable Rust 1.57+
## Documentation

View File

@@ -311,7 +311,6 @@ impl HttpRequest {
/// Load request cookies.
#[cfg(feature = "cookies")]
#[cfg_attr(docsrs, doc(cfg(feature = "cookies")))]
pub fn cookies(&self) -> Result<Ref<'_, Vec<Cookie<'static>>>, CookieParseError> {
use actix_http::header::COOKIE;
@@ -335,7 +334,6 @@ impl HttpRequest {
/// Return request cookie.
#[cfg(feature = "cookies")]
#[cfg_attr(docsrs, doc(cfg(feature = "cookies")))]
pub fn cookie(&self, name: &str) -> Option<Cookie<'static>> {
if let Ok(cookies) = self.cookies() {
for cookie in cookies.iter() {

View File

@@ -40,7 +40,7 @@ type Guards = Vec<Box<dyn Guard>>;
/// use actix_web::{web, App, HttpResponse};
///
/// let app = App::new().service(
/// web::scope("/{project_id}")
/// web::scope("/{project_id}/")
/// .service(web::resource("/path1").to(|| async { "OK" }))
/// .service(web::resource("/path2").route(web::get().to(|| HttpResponse::Ok())))
/// .service(web::resource("/path3").route(web::head().to(HttpResponse::MethodNotAllowed)))

View File

@@ -41,22 +41,17 @@ struct Config {
///
/// Create new HTTP server with application factory.
///
/// # HTTP/2
/// Currently, HTTP/2 is only supported when using TLS (HTTPS). See `bind_rustls` or `bind_openssl`.
///
/// # Examples
/// ```no_run
/// use actix_web::{web, App, HttpResponse, HttpServer};
///
/// #[actix_web::main]
/// #[actix_rt::main]
/// async fn main() -> std::io::Result<()> {
/// HttpServer::new(|| {
/// App::new()
/// .service(web::resource("/").to(|| async { "hello world" }))
/// })
/// .bind(("127.0.0.1", 8080))?
/// .run()
/// .await
/// HttpServer::new(
/// || App::new()
/// .service(web::resource("/").to(|| HttpResponse::Ok())))
/// .bind("127.0.0.1:59090")?
/// .run()
/// .await
/// }
/// ```
pub struct HttpServer<F, I, S, B>
@@ -113,7 +108,32 @@ where
}
}
/// Sets number of workers to start (per bind address).
/// Sets function that will be called once before each connection is handled.
/// It will receive a `&std::any::Any`, which contains underlying connection type and an
/// [Extensions] container so that connection data can be accessed in middleware and handlers.
///
/// # Connection Types
/// - `actix_tls::accept::openssl::TlsStream<actix_web::rt::net::TcpStream>` when using openssl.
/// - `actix_tls::accept::rustls::TlsStream<actix_web::rt::net::TcpStream>` when using rustls.
/// - `actix_web::rt::net::TcpStream` when no encryption is used.
///
/// See the `on_connect` example for additional details.
pub fn on_connect<CB>(self, f: CB) -> HttpServer<F, I, S, B>
where
CB: Fn(&dyn Any, &mut Extensions) + Send + Sync + 'static,
{
HttpServer {
factory: self.factory,
config: self.config,
backlog: self.backlog,
sockets: self.sockets,
builder: self.builder,
on_connect_fn: Some(Arc::new(f)),
_phantom: PhantomData,
}
}
/// Set number of workers to start.
///
/// By default, the number of available physical CPUs is used as the worker count.
pub fn workers(mut self, num: usize) -> Self {
@@ -121,30 +141,23 @@ where
self
}
/// Sets server keep-alive preference.
/// Set the maximum number of pending connections.
///
/// By default keep-alive is set to 5 seconds.
pub fn keep_alive<T: Into<KeepAlive>>(self, val: T) -> Self {
self.config.lock().unwrap().keep_alive = val.into();
self
}
/// Sets the maximum number of pending connections.
/// This refers to the number of clients that can be waiting to be served.
/// Exceeding this number results in the client getting an error when
/// attempting to connect. It should only affect servers under significant
/// load.
///
/// This refers to the number of clients that can be waiting to be served. Exceeding this number
/// results in the client getting an error when attempting to connect. It should only affect
/// servers under significant load.
/// Generally set in the 64-2048 range. Default value is 2048.
///
/// Generally set in the 642048 range. Default value is 2048.
///
/// This method will have no effect if called after a `bind()`.
/// This method should be called before `bind()` method call.
pub fn backlog(mut self, backlog: u32) -> Self {
self.backlog = backlog;
self.builder = self.builder.backlog(backlog);
self
}
/// Sets the per-worker maximum number of concurrent connections.
/// Sets the maximum per-worker number of concurrent connections.
///
/// All socket listeners will stop accepting connections when this limit is reached for
/// each worker.
@@ -155,7 +168,7 @@ where
self
}
/// Sets the per-worker maximum concurrent TLS connection limit.
/// Sets the maximum per-worker concurrent connection establish process.
///
/// All listeners will stop accepting connections when this limit is reached. It can be used to
/// limit the global TLS CPU usage.
@@ -168,20 +181,29 @@ where
self
}
/// Sets max number of threads for each worker's blocking task thread pool.
/// Set max number of threads for each worker's blocking task thread pool.
///
/// One thread pool is set up **per worker**; not shared across workers.
///
/// By default set to 512 divided by the number of workers.
/// By default set to 512 / workers.
pub fn worker_max_blocking_threads(mut self, num: usize) -> Self {
self.builder = self.builder.worker_max_blocking_threads(num);
self
}
/// Sets server client timeout for first request.
/// Set server keep-alive setting.
///
/// Defines a timeout for reading client request head. If a client does not transmit the entire
/// set headers within this time, the request is terminated with a 408 (Request Timeout) error.
/// By default keep alive is set to a 5 seconds.
pub fn keep_alive<T: Into<KeepAlive>>(self, val: T) -> Self {
self.config.lock().unwrap().keep_alive = val.into();
self
}
/// Set server client timeout in milliseconds for first request.
///
/// Defines a timeout for reading client request header. If a client does not transmit
/// the entire set headers within this time, the request is terminated with
/// the 408 (Request Time-out) error.
///
/// To disable timeout set value to 0.
///
@@ -197,10 +219,10 @@ where
self.client_request_timeout(dur)
}
/// Sets server connection shutdown timeout.
/// Set server connection shutdown timeout in milliseconds.
///
/// Defines a timeout for connection shutdown. If a shutdown procedure does not complete within
/// this time, the request is dropped.
/// Defines a timeout for shutdown connection. If a shutdown procedure does not complete
/// within this time, the request is dropped.
///
/// To disable timeout set value to 0.
///
@@ -210,10 +232,10 @@ where
self
}
/// Sets TLS handshake timeout.
/// Set TLS handshake timeout.
///
/// Defines a timeout for TLS handshake. If the TLS handshake does not complete within this
/// time, the connection is closed.
/// Defines a timeout for TLS handshake. If the TLS handshake does not complete
/// within this time, the connection is closed.
///
/// By default handshake timeout is set to 3000 milliseconds.
#[cfg(any(feature = "openssl", feature = "rustls"))]
@@ -234,61 +256,35 @@ where
self.client_disconnect_timeout(Duration::from_millis(dur))
}
/// Sets function that will be called once before each connection is handled.
/// Set server host name.
///
/// It will receive a `&std::any::Any`, which contains underlying connection type and an
/// [Extensions] container so that connection data can be accessed in middleware and handlers.
/// Host name is used by application router as a hostname for url generation.
/// Check [ConnectionInfo](super::dev::ConnectionInfo::host())
/// documentation for more information.
///
/// # Connection Types
/// - `actix_tls::accept::openssl::TlsStream<actix_web::rt::net::TcpStream>` when using OpenSSL.
/// - `actix_tls::accept::rustls::TlsStream<actix_web::rt::net::TcpStream>` when using Rustls.
/// - `actix_web::rt::net::TcpStream` when no encryption is used.
///
/// See the `on_connect` example for additional details.
pub fn on_connect<CB>(self, f: CB) -> HttpServer<F, I, S, B>
where
CB: Fn(&dyn Any, &mut Extensions) + Send + Sync + 'static,
{
HttpServer {
factory: self.factory,
config: self.config,
backlog: self.backlog,
sockets: self.sockets,
builder: self.builder,
on_connect_fn: Some(Arc::new(f)),
_phantom: PhantomData,
}
}
/// Sets server host name.
///
/// Host name is used by application router as a hostname for url generation. Check
/// [`ConnectionInfo`](crate::dev::ConnectionInfo::host()) docs for more info.
///
/// By default, hostname is set to "localhost".
/// By default host name is set to a "localhost" value.
pub fn server_hostname<T: AsRef<str>>(self, val: T) -> Self {
self.config.lock().unwrap().host = Some(val.as_ref().to_owned());
self
}
/// Flags the `System` to exit after server shutdown.
///
/// Does nothing when running under `#[tokio::main]` runtime.
/// Stop Actix `System` after server shutdown.
pub fn system_exit(mut self) -> Self {
self.builder = self.builder.system_exit();
self
}
/// Disables signal handling.
/// Disable signal handling
pub fn disable_signals(mut self) -> Self {
self.builder = self.builder.disable_signals();
self
}
/// Sets timeout for graceful worker shutdown of workers.
/// Timeout for graceful workers shutdown.
///
/// After receiving a stop signal, workers have this much time to finish serving requests.
/// Workers still alive after the timeout are force dropped.
/// After receiving a stop signal, workers have this much time to finish
/// serving requests. Workers still alive after the timeout are force
/// dropped.
///
/// By default shutdown timeout sets to 30 seconds.
pub fn shutdown_timeout(mut self, sec: u64) -> Self {
@@ -296,141 +292,33 @@ where
self
}
/// Returns addresses of bound sockets.
/// Get addresses of bound sockets.
pub fn addrs(&self) -> Vec<net::SocketAddr> {
self.sockets.iter().map(|s| s.addr).collect()
}
/// Returns addresses of bound sockets and the scheme for it.
/// Get addresses of bound sockets and the scheme for it.
///
/// This is useful when the server is bound from different sources with some sockets listening
/// on HTTP and some listening on HTTPS and the user should be presented with an enumeration of
/// which socket requires which protocol.
/// This is useful when the server is bound from different sources
/// with some sockets listening on HTTP and some listening on HTTPS
/// and the user should be presented with an enumeration of which
/// socket requires which protocol.
pub fn addrs_with_scheme(&self) -> Vec<(net::SocketAddr, &str)> {
self.sockets.iter().map(|s| (s.addr, s.scheme)).collect()
}
/// Resolves socket address(es) and binds server to created listener(s).
/// Use listener for accepting incoming connection requests
///
/// # Hostname Resolution
/// When `addr` includes a hostname, it is possible for this method to bind to both the IPv4 and
/// IPv6 addresses that result from a DNS lookup. You can test this by passing `localhost:8080`
/// and noting that the server binds to `127.0.0.1:8080` _and_ `[::1]:8080`. To bind additional
/// addresses, call this method multiple times.
///
/// Note that, if a DNS lookup is required, resolving hostnames is a blocking operation.
///
/// # Typical Usage
/// In general, use `127.0.0.1:<port>` when testing locally and `0.0.0.0:<port>` when deploying
/// (with or without a reverse proxy or load balancer) so that the server is accessible.
///
/// # Errors
/// Returns an `io::Error` if:
/// - `addrs` cannot be resolved into one or more socket addresses;
/// - all the resolved socket addresses are already bound.
///
/// # Example
/// ```
/// # use actix_web::{App, HttpServer};
/// # fn inner() -> std::io::Result<()> {
/// HttpServer::new(|| App::new())
/// .bind(("127.0.0.1", 8080))?
/// .bind("[::1]:9000")?
/// # ; Ok(()) }
/// ```
pub fn bind<A: net::ToSocketAddrs>(mut self, addrs: A) -> io::Result<Self> {
let sockets = self.bind2(addrs)?;
for lst in sockets {
self = self.listen(lst)?;
}
Ok(self)
}
fn bind2<A: net::ToSocketAddrs>(&self, addrs: A) -> io::Result<Vec<net::TcpListener>> {
let mut err = None;
let mut success = false;
let mut sockets = Vec::new();
for addr in addrs.to_socket_addrs()? {
match create_tcp_listener(addr, self.backlog) {
Ok(lst) => {
success = true;
sockets.push(lst);
}
Err(e) => err = Some(e),
}
}
if success {
Ok(sockets)
} else if let Some(e) = err.take() {
Err(e)
} else {
Err(io::Error::new(
io::ErrorKind::Other,
"Can not bind to address.",
))
}
}
/// Resolves socket address(es) and binds server to created listener(s) for TLS connections
/// using Rustls.
///
/// See [`bind()`](Self::bind) for more details on `addrs` argument.
///
/// ALPN protocols "h2" and "http/1.1" are added to any configured ones.
#[cfg(feature = "rustls")]
#[cfg_attr(docsrs, doc(cfg(feature = "rustls")))]
pub fn bind_rustls<A: net::ToSocketAddrs>(
mut self,
addrs: A,
config: RustlsServerConfig,
) -> io::Result<Self> {
let sockets = self.bind2(addrs)?;
for lst in sockets {
self = self.listen_rustls_inner(lst, config.clone())?;
}
Ok(self)
}
/// Resolves socket address(es) and binds server to created listener(s) for TLS connections
/// using OpenSSL.
///
/// See [`bind()`](Self::bind) for more details on `addrs` argument.
///
/// ALPN protocols "h2" and "http/1.1" are added to any configured ones.
#[cfg(feature = "openssl")]
#[cfg_attr(docsrs, doc(cfg(feature = "openssl")))]
pub fn bind_openssl<A>(mut self, addrs: A, builder: SslAcceptorBuilder) -> io::Result<Self>
where
A: net::ToSocketAddrs,
{
let sockets = self.bind2(addrs)?;
let acceptor = openssl_acceptor(builder)?;
for lst in sockets {
self = self.listen_openssl_inner(lst, acceptor.clone())?;
}
Ok(self)
}
/// Binds to existing listener for accepting incoming connection requests.
///
/// No changes are made to `lst`'s configuration. Ensure it is configured properly before
/// passing ownership to `listen()`.
/// HttpServer does not change any configuration for TcpListener,
/// it needs to be configured before passing it to listen() method.
pub fn listen(mut self, lst: net::TcpListener) -> io::Result<Self> {
let cfg = self.config.clone();
let factory = self.factory.clone();
let addr = lst.local_addr().unwrap();
self.sockets.push(Socket {
addr,
scheme: "http",
});
let on_connect_fn = self.on_connect_fn.clone();
self.builder =
@@ -463,13 +351,76 @@ where
Ok(self)
}
/// Binds to existing listener for accepting incoming TLS connection requests using Rustls.
#[cfg(feature = "openssl")]
/// Use listener for accepting incoming tls connection requests
///
/// See [`listen()`](Self::listen) for more details on the `lst` argument.
///
/// ALPN protocols "h2" and "http/1.1" are added to any configured ones.
/// This method sets alpn protocols to "h2" and "http/1.1"
pub fn listen_openssl(
self,
lst: net::TcpListener,
builder: SslAcceptorBuilder,
) -> io::Result<Self> {
self.listen_ssl_inner(lst, openssl_acceptor(builder)?)
}
#[cfg(feature = "openssl")]
fn listen_ssl_inner(
mut self,
lst: net::TcpListener,
acceptor: SslAcceptor,
) -> io::Result<Self> {
let factory = self.factory.clone();
let cfg = self.config.clone();
let addr = lst.local_addr().unwrap();
self.sockets.push(Socket {
addr,
scheme: "https",
});
let on_connect_fn = self.on_connect_fn.clone();
self.builder =
self.builder
.listen(format!("actix-web-service-{}", addr), lst, move || {
let c = cfg.lock().unwrap();
let host = c.host.clone().unwrap_or_else(|| format!("{}", addr));
let svc = HttpService::build()
.keep_alive(c.keep_alive)
.client_request_timeout(c.client_request_timeout)
.client_disconnect_timeout(c.client_disconnect_timeout)
.local_addr(addr);
let svc = if let Some(handler) = on_connect_fn.clone() {
svc.on_connect_ext(move |io: &_, ext: _| (handler)(io as &dyn Any, ext))
} else {
svc
};
let fac = factory()
.into_factory()
.map_err(|err| err.into().error_response());
// false positive lint (?)
#[allow(clippy::significant_drop_in_scrutinee)]
let acceptor_config = match c.tls_handshake_timeout {
Some(dur) => TlsAcceptorConfig::default().handshake_timeout(dur),
None => TlsAcceptorConfig::default(),
};
svc.finish(map_config(fac, move |_| {
AppConfig::new(true, host.clone(), addr)
}))
.openssl_with_config(acceptor.clone(), acceptor_config)
})?;
Ok(self)
}
#[cfg(feature = "rustls")]
#[cfg_attr(docsrs, doc(cfg(feature = "rustls")))]
/// Use listener for accepting incoming tls connection requests
///
/// This method prepends alpn protocols "h2" and "http/1.1" to configured ones
pub fn listen_rustls(
self,
lst: net::TcpListener,
@@ -529,125 +480,82 @@ where
Ok(self)
}
/// Binds to existing listener for accepting incoming TLS connection requests using OpenSSL.
/// The socket address to bind
///
/// See [`listen()`](Self::listen) for more details on the `lst` argument.
///
/// ALPN protocols "h2" and "http/1.1" are added to any configured ones.
#[cfg(feature = "openssl")]
#[cfg_attr(docsrs, doc(cfg(feature = "openssl")))]
pub fn listen_openssl(
self,
lst: net::TcpListener,
builder: SslAcceptorBuilder,
) -> io::Result<Self> {
self.listen_openssl_inner(lst, openssl_acceptor(builder)?)
}
/// To bind multiple addresses this method can be called multiple times.
pub fn bind<A: net::ToSocketAddrs>(mut self, addr: A) -> io::Result<Self> {
let sockets = self.bind2(addr)?;
#[cfg(feature = "openssl")]
fn listen_openssl_inner(
mut self,
lst: net::TcpListener,
acceptor: SslAcceptor,
) -> io::Result<Self> {
let factory = self.factory.clone();
let cfg = self.config.clone();
let addr = lst.local_addr().unwrap();
self.sockets.push(Socket {
addr,
scheme: "https",
});
let on_connect_fn = self.on_connect_fn.clone();
self.builder =
self.builder
.listen(format!("actix-web-service-{}", addr), lst, move || {
let c = cfg.lock().unwrap();
let host = c.host.clone().unwrap_or_else(|| format!("{}", addr));
let svc = HttpService::build()
.keep_alive(c.keep_alive)
.client_request_timeout(c.client_request_timeout)
.client_disconnect_timeout(c.client_disconnect_timeout)
.local_addr(addr);
let svc = if let Some(handler) = on_connect_fn.clone() {
svc.on_connect_ext(move |io: &_, ext: _| (handler)(io as &dyn Any, ext))
} else {
svc
};
let fac = factory()
.into_factory()
.map_err(|err| err.into().error_response());
// false positive lint (?)
#[allow(clippy::significant_drop_in_scrutinee)]
let acceptor_config = match c.tls_handshake_timeout {
Some(dur) => TlsAcceptorConfig::default().handshake_timeout(dur),
None => TlsAcceptorConfig::default(),
};
svc.finish(map_config(fac, move |_| {
AppConfig::new(true, host.clone(), addr)
}))
.openssl_with_config(acceptor.clone(), acceptor_config)
})?;
for lst in sockets {
self = self.listen(lst)?;
}
Ok(self)
}
/// Opens Unix Domain Socket (UDS) from `uds` path and binds server to created listener.
#[cfg(unix)]
pub fn bind_uds<A>(mut self, uds_path: A) -> io::Result<Self>
fn bind2<A: net::ToSocketAddrs>(&self, addr: A) -> io::Result<Vec<net::TcpListener>> {
let mut err = None;
let mut success = false;
let mut sockets = Vec::new();
for addr in addr.to_socket_addrs()? {
match create_tcp_listener(addr, self.backlog) {
Ok(lst) => {
success = true;
sockets.push(lst);
}
Err(e) => err = Some(e),
}
}
if success {
Ok(sockets)
} else if let Some(e) = err.take() {
Err(e)
} else {
Err(io::Error::new(
io::ErrorKind::Other,
"Can not bind to address.",
))
}
}
#[cfg(feature = "openssl")]
/// Start listening for incoming tls connections.
///
/// This method sets alpn protocols to "h2" and "http/1.1"
pub fn bind_openssl<A>(mut self, addr: A, builder: SslAcceptorBuilder) -> io::Result<Self>
where
A: AsRef<std::path::Path>,
A: net::ToSocketAddrs,
{
use actix_http::Protocol;
use actix_rt::net::UnixStream;
use actix_service::{fn_service, ServiceFactoryExt as _};
let sockets = self.bind2(addr)?;
let acceptor = openssl_acceptor(builder)?;
let cfg = self.config.clone();
let factory = self.factory.clone();
let socket_addr =
net::SocketAddr::new(net::IpAddr::V4(net::Ipv4Addr::new(127, 0, 0, 1)), 8080);
self.sockets.push(Socket {
scheme: "http",
addr: socket_addr,
});
self.builder = self.builder.bind_uds(
format!("actix-web-service-{:?}", uds_path.as_ref()),
uds_path,
move || {
let c = cfg.lock().unwrap();
let config = AppConfig::new(
false,
c.host.clone().unwrap_or_else(|| format!("{}", socket_addr)),
socket_addr,
);
let fac = factory()
.into_factory()
.map_err(|err| err.into().error_response());
fn_service(|io: UnixStream| async { Ok((io, Protocol::Http1, None)) }).and_then(
HttpService::build()
.keep_alive(c.keep_alive)
.client_request_timeout(c.client_request_timeout)
.client_disconnect_timeout(c.client_disconnect_timeout)
.finish(map_config(fac, move |_| config.clone())),
)
},
)?;
for lst in sockets {
self = self.listen_ssl_inner(lst, acceptor.clone())?;
}
Ok(self)
}
/// Binds to existing Unix Domain Socket (UDS) listener.
#[cfg(feature = "rustls")]
/// Start listening for incoming tls connections.
///
/// This method prepends alpn protocols "h2" and "http/1.1" to configured ones
pub fn bind_rustls<A: net::ToSocketAddrs>(
mut self,
addr: A,
config: RustlsServerConfig,
) -> io::Result<Self> {
let sockets = self.bind2(addr)?;
for lst in sockets {
self = self.listen_rustls_inner(lst, config.clone())?;
}
Ok(self)
}
#[cfg(unix)]
/// Start listening for unix domain (UDS) connections on existing listener.
pub fn listen_uds(mut self, lst: std::os::unix::net::UnixListener) -> io::Result<Self> {
use actix_http::Protocol;
use actix_rt::net::UnixStream;
@@ -694,6 +602,54 @@ where
})?;
Ok(self)
}
/// Start listening for incoming unix domain connections.
#[cfg(unix)]
pub fn bind_uds<A>(mut self, addr: A) -> io::Result<Self>
where
A: AsRef<std::path::Path>,
{
use actix_http::Protocol;
use actix_rt::net::UnixStream;
use actix_service::{fn_service, ServiceFactoryExt as _};
let cfg = self.config.clone();
let factory = self.factory.clone();
let socket_addr =
net::SocketAddr::new(net::IpAddr::V4(net::Ipv4Addr::new(127, 0, 0, 1)), 8080);
self.sockets.push(Socket {
scheme: "http",
addr: socket_addr,
});
self.builder = self.builder.bind_uds(
format!("actix-web-service-{:?}", addr.as_ref()),
addr,
move || {
let c = cfg.lock().unwrap();
let config = AppConfig::new(
false,
c.host.clone().unwrap_or_else(|| format!("{}", socket_addr)),
socket_addr,
);
let fac = factory()
.into_factory()
.map_err(|err| err.into().error_response());
fn_service(|io: UnixStream| async { Ok((io, Protocol::Http1, None)) }).and_then(
HttpService::build()
.keep_alive(c.keep_alive)
.client_request_timeout(c.client_request_timeout)
.client_disconnect_timeout(c.client_disconnect_timeout)
.finish(map_config(fac, move |_| config.clone())),
)
},
)?;
Ok(self)
}
}
impl<F, I, S, B> HttpServer<F, I, S, B>
@@ -709,16 +665,25 @@ where
{
/// Start listening for incoming connections.
///
/// # Workers
/// This method starts a number of HTTP workers in separate threads. The number of workers in a
/// set is defined by [`workers()`](Self::workers) or, by default, the number of the machine's
/// physical cores. One worker set is created for each socket address to be bound. For example,
/// if workers is set to 4, and there are 2 addresses to bind, then 8 worker threads will be
/// spawned.
/// This method starts number of HTTP workers in separate threads.
/// For each address this method starts separate thread which does
/// `accept()` in a loop.
///
/// # Panics
/// This methods panics if no socket addresses were successfully bound or if no Tokio runtime
/// is set up.
/// This methods panics if no socket address can be bound or an `Actix` system is not yet
/// configured.
///
/// ```no_run
/// use std::io;
/// use actix_web::{web, App, HttpResponse, HttpServer};
///
/// #[actix_rt::main]
/// async fn main() -> io::Result<()> {
/// HttpServer::new(|| App::new().service(web::resource("/").to(|| HttpResponse::Ok())))
/// .bind("127.0.0.1:0")?
/// .run()
/// .await
/// }
/// ```
pub fn run(self) -> Server {
self.builder.run()
}

View File

@@ -2,18 +2,8 @@
## Unreleased - 2022-xx-xx
### Changed
- Minimum supported Rust version (MSRV) is now 1.59 due to transitive `time` dependency.
## 3.0.1 - 2022-08-25
### Changed
- Minimum supported Rust version (MSRV) is now 1.57 due to transitive `time` dependency.
### Fixed
- Fixed handling of redirection requests that begin with `//`. [#2840]
[#2840]: https://github.com/actix/actix-web/pull/2840
## 3.0.0 - 2022-03-07
### Dependencies

View File

@@ -1,6 +1,6 @@
[package]
name = "awc"
version = "3.0.1"
version = "3.0.0"
authors = [
"Nikolay Kim <fafhrd91@gmail.com>",
"fakeshadow <24548779@qq.com>",

View File

@@ -3,9 +3,9 @@
> Async HTTP and WebSocket client library.
[![crates.io](https://img.shields.io/crates/v/awc?label=latest)](https://crates.io/crates/awc)
[![Documentation](https://docs.rs/awc/badge.svg?version=3.0.1)](https://docs.rs/awc/3.0.1)
[![Documentation](https://docs.rs/awc/badge.svg?version=3.0.0)](https://docs.rs/awc/3.0.0)
![MIT or Apache 2.0 licensed](https://img.shields.io/crates/l/awc)
[![Dependency Status](https://deps.rs/crate/awc/3.0.1/status.svg)](https://deps.rs/crate/awc/3.0.1)
[![Dependency Status](https://deps.rs/crate/awc/3.0.0/status.svg)](https://deps.rs/crate/awc/3.0.0)
[![Chat on Discord](https://img.shields.io/discord/771444961383153695?label=chat&logo=discord)](https://discord.gg/NWpN5mmg3x)
## Documentation & Resources

View File

@@ -257,16 +257,6 @@ fn build_next_uri(res: &ClientResponse, prev_uri: &Uri) -> Result<Uri, SendReque
.scheme(prev_uri.scheme().cloned().unwrap())
.authority(prev_uri.authority().cloned().unwrap());
// scheme-relative address
if location.as_bytes().starts_with(b"//") {
let scheme = prev_uri.scheme_str().unwrap();
let mut full_url: Vec<u8> = scheme.as_bytes().to_vec();
full_url.push(b':');
full_url.extend(location.as_bytes());
return Uri::try_from(full_url)
.map_err(|_| SendRequestError::Url(InvalidUrl::MissingScheme));
}
// when scheme or authority is missing treat the location value as path and query
// recover error where location does not have leading slash
let path = if location.as_bytes().starts_with(b"/") {
@@ -598,41 +588,6 @@ mod tests {
assert_eq!(res.status().as_u16(), 200);
}
#[actix_rt::test]
async fn test_double_slash_redirect() {
let client = ClientBuilder::new()
.disable_redirects()
.wrap(Redirect::new().max_redirect_times(10))
.finish();
let srv = actix_test::start(|| {
App::new()
.service(web::resource("/test").route(web::to(|| async {
Ok::<_, Error>(HttpResponse::BadRequest())
})))
.service(
web::resource("/").route(web::to(|req: HttpRequest| async move {
Ok::<_, Error>(
HttpResponse::Found()
.append_header((
"location",
format!(
"//localhost:{}/test",
req.app_config().local_addr().port()
)
.as_str(),
))
.finish(),
)
})),
)
});
let res = client.get(srv.url("/")).send().await.unwrap();
assert_eq!(res.status().as_u16(), 400);
}
#[actix_rt::test]
async fn test_remove_sensitive_headers() {
fn gen_headers() -> header::HeaderMap {

View File

@@ -1 +1 @@
msrv = "1.59"
msrv = "1.57"

View File

@@ -45,8 +45,6 @@ unreleased_for() {
cat "$CHANGE_CHUNK_FILE"
}
files=$(fd --threads=1 --min-depth=2 --absolute-path 'CHANGE\w+.md')
for f in $files; do
unreleased_for $(dirname $f) || true
for f in $(fd --absolute-path 'CHANGE\w+.md'); do
unreleased_for $(dirname $f)
done