1
0
mirror of https://github.com/actix/actix-extras.git synced 2024-11-24 16:02:59 +01:00
actix-extras/src/server/h1writer.rs

346 lines
11 KiB
Rust
Raw Normal View History

2018-07-12 06:35:09 +02:00
// #![cfg_attr(feature = "cargo-clippy", allow(redundant_field_names))]
use std::io::{self, Write};
use std::rc::Rc;
2018-02-26 23:33:56 +01:00
use bytes::{BufMut, BytesMut};
use futures::{Async, Poll};
2018-04-14 01:02:01 +02:00
use tokio_io::AsyncWrite;
2018-04-14 01:02:01 +02:00
use super::helpers;
2018-06-25 06:58:04 +02:00
use super::output::{Output, ResponseInfo, ResponseLength};
2018-04-14 01:02:01 +02:00
use super::settings::WorkerSettings;
2018-06-25 06:58:04 +02:00
use super::Request;
2018-04-14 01:02:01 +02:00
use super::{Writer, WriterState, MAX_WRITE_BUFFER_SIZE};
use body::{Binary, Body};
2018-03-29 20:06:44 +02:00
use header::ContentEncoding;
2018-06-25 06:58:04 +02:00
use http::header::{
HeaderValue, CONNECTION, CONTENT_ENCODING, CONTENT_LENGTH, DATE, TRANSFER_ENCODING,
};
2018-04-29 07:55:47 +02:00
use http::{Method, Version};
use httpresponse::HttpResponse;
const AVERAGE_HEADER_SIZE: usize = 30; // totally scientific
bitflags! {
struct Flags: u8 {
const STARTED = 0b0000_0001;
const UPGRADE = 0b0000_0010;
const KEEPALIVE = 0b0000_0100;
const DISCONNECTED = 0b0000_1000;
}
}
2018-03-18 19:05:44 +01:00
pub(crate) struct H1Writer<T: AsyncWrite, H: 'static> {
flags: Flags,
2017-12-14 01:44:35 +01:00
stream: T,
2017-11-10 21:29:54 +01:00
written: u64,
headers_size: u32,
2018-06-24 04:54:01 +02:00
buffer: Output,
2018-03-09 19:00:15 +01:00
buffer_capacity: usize,
2018-03-18 19:05:44 +01:00
settings: Rc<WorkerSettings<H>>,
}
2018-03-18 19:05:44 +01:00
impl<T: AsyncWrite, H: 'static> H1Writer<T, H> {
2018-06-24 06:30:58 +02:00
pub fn new(stream: T, settings: Rc<WorkerSettings<H>>) -> H1Writer<T, H> {
H1Writer {
2018-05-21 05:37:19 +02:00
flags: Flags::KEEPALIVE,
2017-11-10 21:29:54 +01:00
written: 0,
headers_size: 0,
2018-06-24 06:30:58 +02:00
buffer: Output::Buffer(settings.get_bytes()),
2018-03-09 19:00:15 +01:00
buffer_capacity: 0,
2018-02-26 23:33:56 +01:00
stream,
2018-03-18 19:05:44 +01:00
settings,
}
}
pub fn get_mut(&mut self) -> &mut T {
2017-12-14 01:44:35 +01:00
&mut self.stream
}
2017-12-14 01:44:35 +01:00
pub fn reset(&mut self) {
self.written = 0;
2018-05-21 05:37:19 +02:00
self.flags = Flags::KEEPALIVE;
2017-12-14 01:44:35 +01:00
}
2018-09-01 02:24:13 +02:00
pub fn disconnected(&mut self) {
self.flags.insert(Flags::DISCONNECTED);
}
pub fn keepalive(&self) -> bool {
self.flags.contains(Flags::KEEPALIVE) && !self.flags.contains(Flags::UPGRADE)
}
fn write_data(stream: &mut T, data: &[u8]) -> io::Result<usize> {
let mut written = 0;
while written < data.len() {
match stream.write(&data[written..]) {
2018-01-15 04:28:34 +01:00
Ok(0) => {
2018-04-14 01:02:01 +02:00
return Err(io::Error::new(io::ErrorKind::WriteZero, ""));
}
Ok(n) => {
written += n;
2018-04-14 01:02:01 +02:00
}
2017-12-14 01:44:35 +01:00
Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
2018-03-10 19:42:46 +01:00
return Ok(written)
}
2017-12-14 01:44:35 +01:00
Err(err) => return Err(err),
}
}
2018-03-10 19:42:46 +01:00
Ok(written)
}
}
2018-06-24 06:30:58 +02:00
impl<T: AsyncWrite, H: 'static> Drop for H1Writer<T, H> {
fn drop(&mut self) {
if let Some(bytes) = self.buffer.take_option() {
self.settings.release_bytes(bytes);
}
}
}
2018-03-18 19:05:44 +01:00
impl<T: AsyncWrite, H: 'static> Writer for H1Writer<T, H> {
2018-01-12 01:22:27 +01:00
#[inline]
2017-11-10 21:29:54 +01:00
fn written(&self) -> u64 {
2018-01-02 23:53:51 +01:00
self.written
2017-11-10 21:29:54 +01:00
}
2018-05-21 05:37:19 +02:00
#[inline]
2018-06-25 06:58:04 +02:00
fn set_date(&mut self) {
self.settings.set_date(self.buffer.as_mut(), true)
2018-05-21 05:37:19 +02:00
}
#[inline]
2018-06-19 03:44:01 +02:00
fn buffer(&mut self) -> &mut BytesMut {
2018-06-24 06:30:58 +02:00
self.buffer.as_mut()
2018-05-21 05:37:19 +02:00
}
2018-04-14 01:02:01 +02:00
fn start(
2018-06-25 06:58:04 +02:00
&mut self, req: &Request, msg: &mut HttpResponse, encoding: ContentEncoding,
2018-04-14 01:02:01 +02:00
) -> io::Result<WriterState> {
// prepare task
2018-06-25 06:58:04 +02:00
let mut info = ResponseInfo::new(req.inner.method == Method::HEAD);
self.buffer.for_server(&mut info, &req.inner, msg, encoding);
if msg.keep_alive().unwrap_or_else(|| req.keep_alive()) {
2018-05-21 05:37:19 +02:00
self.flags = Flags::STARTED | Flags::KEEPALIVE;
2018-02-10 09:05:20 +01:00
} else {
2018-05-21 05:37:19 +02:00
self.flags = Flags::STARTED;
}
// Connection upgrade
2018-06-25 06:58:04 +02:00
let version = msg.version().unwrap_or_else(|| req.inner.version);
if msg.upgrade() {
2018-02-10 09:05:20 +01:00
self.flags.insert(Flags::UPGRADE);
2018-04-29 18:09:08 +02:00
msg.headers_mut()
.insert(CONNECTION, HeaderValue::from_static("upgrade"));
}
// keep-alive
else if self.flags.contains(Flags::KEEPALIVE) {
if version < Version::HTTP_11 {
2018-04-14 01:02:01 +02:00
msg.headers_mut()
.insert(CONNECTION, HeaderValue::from_static("keep-alive"));
}
} else if version >= Version::HTTP_11 {
2018-04-29 18:09:08 +02:00
msg.headers_mut()
.insert(CONNECTION, HeaderValue::from_static("close"));
}
2017-12-16 16:29:15 +01:00
let body = msg.replace_body(Body::Empty);
// render message
2017-11-09 01:44:23 +01:00
{
2018-06-24 04:54:01 +02:00
// output buffer
2018-06-24 06:30:58 +02:00
let mut buffer = self.buffer.as_mut();
2018-06-24 04:54:01 +02:00
let reason = msg.reason().as_bytes();
2018-07-04 17:01:27 +02:00
if let Body::Binary(ref bytes) = body {
2018-03-18 19:05:44 +01:00
buffer.reserve(
2018-08-23 18:48:01 +02:00
256 + msg.headers().len() * AVERAGE_HEADER_SIZE
2018-05-16 01:41:46 +02:00
+ bytes.len()
2018-04-14 01:02:01 +02:00
+ reason.len(),
);
2017-11-09 01:44:23 +01:00
} else {
buffer.reserve(
2018-04-14 01:02:01 +02:00
256 + msg.headers().len() * AVERAGE_HEADER_SIZE + reason.len(),
);
2018-07-04 17:01:27 +02:00
}
2017-12-25 22:40:06 +01:00
// status line
helpers::write_status_line(version, msg.status().as_u16(), &mut buffer);
2018-06-19 19:46:58 +02:00
buffer.extend_from_slice(reason);
2018-06-25 06:58:04 +02:00
// content length
match info.length {
ResponseLength::Chunked => {
buffer.extend_from_slice(b"\r\ntransfer-encoding: chunked\r\n")
}
ResponseLength::Zero => {
buffer.extend_from_slice(b"\r\ncontent-length: 0\r\n")
}
ResponseLength::Length(len) => {
helpers::write_content_length(len, &mut buffer)
}
ResponseLength::Length64(len) => {
buffer.extend_from_slice(b"\r\ncontent-length: ");
2018-07-12 06:35:09 +02:00
write!(buffer.writer(), "{}", len)?;
2018-06-19 19:46:58 +02:00
buffer.extend_from_slice(b"\r\n");
2018-04-14 01:02:01 +02:00
}
2018-06-25 06:58:04 +02:00
ResponseLength::None => buffer.extend_from_slice(b"\r\n"),
}
if let Some(ce) = info.content_encoding {
buffer.extend_from_slice(b"content-encoding: ");
buffer.extend_from_slice(ce.as_ref());
buffer.extend_from_slice(b"\r\n");
2017-12-16 16:29:15 +01:00
}
2017-12-25 22:40:06 +01:00
// write headers
2018-02-20 02:21:04 +01:00
let mut pos = 0;
2018-03-18 19:05:44 +01:00
let mut has_date = false;
2018-02-20 02:21:04 +01:00
let mut remaining = buffer.remaining_mut();
2018-06-19 03:44:01 +02:00
unsafe {
let mut buf = &mut *(buffer.bytes_mut() as *mut [u8]);
for (key, value) in msg.headers() {
2018-06-25 06:58:04 +02:00
match *key {
TRANSFER_ENCODING => continue,
CONTENT_ENCODING => if encoding != ContentEncoding::Identity {
continue;
},
2018-06-25 06:58:04 +02:00
CONTENT_LENGTH => match info.length {
ResponseLength::None => (),
_ => continue,
},
2018-07-05 09:16:16 +02:00
DATE => {
has_date = true;
}
2018-06-25 06:58:04 +02:00
_ => (),
2018-06-19 03:44:01 +02:00
}
2018-07-05 09:16:16 +02:00
2018-06-19 03:44:01 +02:00
let v = value.as_ref();
let k = key.as_str().as_bytes();
let len = k.len() + v.len() + 4;
if len > remaining {
buffer.advance_mut(pos);
pos = 0;
buffer.reserve(len);
remaining = buffer.remaining_mut();
buf = &mut *(buffer.bytes_mut() as *mut _);
}
buf[pos..pos + k.len()].copy_from_slice(k);
pos += k.len();
buf[pos..pos + 2].copy_from_slice(b": ");
pos += 2;
buf[pos..pos + v.len()].copy_from_slice(v);
pos += v.len();
buf[pos..pos + 2].copy_from_slice(b"\r\n");
pos += 2;
remaining -= len;
2018-03-18 19:05:44 +01:00
}
2018-06-19 03:44:01 +02:00
buffer.advance_mut(pos);
2017-12-25 22:40:06 +01:00
}
// optimized date header, set_date writes \r\n
2018-03-18 19:05:44 +01:00
if !has_date {
2018-06-23 06:13:09 +02:00
self.settings.set_date(&mut buffer, true);
2017-12-25 22:40:06 +01:00
} else {
// msg eof
2018-06-19 19:46:58 +02:00
buffer.extend_from_slice(b"\r\n");
2017-11-09 01:44:23 +01:00
}
self.headers_size = buffer.len() as u32;
}
2017-12-16 16:29:15 +01:00
if let Body::Binary(bytes) = body {
2018-01-02 23:53:51 +01:00
self.written = bytes.len() as u64;
2018-06-24 04:54:01 +02:00
self.buffer.write(bytes.as_ref())?;
2017-12-16 16:29:15 +01:00
} else {
2018-03-09 19:00:15 +01:00
// capacity, makes sense only for streaming or actor
self.buffer_capacity = msg.write_buffer_capacity();
2017-12-16 16:29:15 +01:00
msg.replace_body(body);
2017-11-09 01:44:23 +01:00
}
Ok(WriterState::Done)
}
2018-06-19 03:44:01 +02:00
fn write(&mut self, payload: &Binary) -> io::Result<WriterState> {
2018-01-02 23:53:51 +01:00
self.written += payload.len() as u64;
if !self.flags.contains(Flags::DISCONNECTED) {
if self.flags.contains(Flags::STARTED) {
2018-02-10 09:05:20 +01:00
// shortcut for upgraded connection
if self.flags.contains(Flags::UPGRADE) {
if self.buffer.is_empty() {
2018-03-19 17:30:58 +01:00
let pl: &[u8] = payload.as_ref();
let n = match Self::write_data(&mut self.stream, pl) {
Err(err) => {
2018-09-01 02:24:13 +02:00
self.disconnected();
return Err(err);
}
Ok(val) => val,
};
if n < pl.len() {
2018-06-24 06:30:58 +02:00
self.buffer.write(&pl[n..])?;
2018-03-10 19:42:46 +01:00
return Ok(WriterState::Done);
2018-02-10 09:05:20 +01:00
}
} else {
2018-06-24 06:30:58 +02:00
self.buffer.write(payload.as_ref())?;
2018-02-10 09:05:20 +01:00
}
} else {
// TODO: add warning, write after EOF
2018-06-24 04:54:01 +02:00
self.buffer.write(payload.as_ref())?;
2018-02-10 09:05:20 +01:00
}
} else {
2018-03-19 21:12:36 +01:00
// could be response to EXCEPT header
2018-06-24 06:30:58 +02:00
self.buffer.write(payload.as_ref())?;
}
}
if self.buffer.len() > self.buffer_capacity {
Ok(WriterState::Pause)
} else {
Ok(WriterState::Done)
}
}
2018-01-14 22:50:38 +01:00
fn write_eof(&mut self) -> io::Result<WriterState> {
2018-06-24 04:54:01 +02:00
if !self.buffer.write_eof()? {
2018-04-14 01:02:01 +02:00
Err(io::Error::new(
io::ErrorKind::Other,
"Last payload item, but eof is not reached",
))
2018-01-15 02:00:28 +01:00
} else if self.buffer.len() > MAX_WRITE_BUFFER_SIZE {
Ok(WriterState::Pause)
} else {
Ok(WriterState::Done)
}
}
2018-01-12 01:22:27 +01:00
#[inline]
fn poll_completed(&mut self, shutdown: bool) -> Poll<(), io::Error> {
2018-09-01 02:24:13 +02:00
if self.flags.contains(Flags::DISCONNECTED) {
return Err(io::Error::new(io::ErrorKind::Other, "disconnected"));
}
if !self.buffer.is_empty() {
let written = {
2018-06-24 04:54:01 +02:00
match Self::write_data(&mut self.stream, self.buffer.as_ref().as_ref()) {
Err(err) => {
2018-09-01 02:24:13 +02:00
self.disconnected();
return Err(err);
}
Ok(val) => val,
}
};
2018-03-10 19:42:46 +01:00
let _ = self.buffer.split_to(written);
2018-05-16 01:41:46 +02:00
if shutdown && !self.buffer.is_empty()
|| (self.buffer.len() > self.buffer_capacity)
{
2018-04-14 01:02:01 +02:00
return Ok(Async::NotReady);
}
}
if shutdown {
2018-08-08 18:12:32 +02:00
self.stream.poll_flush()?;
self.stream.shutdown()
} else {
2018-09-01 02:24:13 +02:00
Ok(self.stream.poll_flush()?)
}
}
}