1
0
mirror of https://github.com/fafhrd91/actix-web synced 2024-11-25 00:43:00 +01:00
actix-web/src/server/h1writer.rs

323 lines
10 KiB
Rust
Raw Normal View History

2018-02-26 23:33:56 +01:00
#![cfg_attr(feature = "cargo-clippy", allow(redundant_field_names))]
use bytes::{BufMut, BytesMut};
use futures::{Async, Poll};
2018-04-29 07:55:47 +02:00
use std::io;
2018-04-14 01:02:01 +02:00
use std::rc::Rc;
use tokio_io::AsyncWrite;
2018-06-24 04:54:01 +02:00
use super::encoding::{ContentEncoder, Output};
2018-04-14 01:02:01 +02:00
use super::helpers;
use super::settings::WorkerSettings;
use super::shared::SharedBytes;
use super::{Writer, WriterState, MAX_WRITE_BUFFER_SIZE};
use body::{Binary, Body};
2018-03-29 20:06:44 +02:00
use header::ContentEncoding;
2018-04-29 07:55:47 +02:00
use http::header::{HeaderValue, CONNECTION, CONTENT_LENGTH, DATE};
use http::{Method, Version};
use httprequest::HttpInnerMessage;
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-04-14 01:02:01 +02:00
pub fn new(
2018-05-17 21:20:20 +02:00
stream: T, buf: SharedBytes, settings: Rc<WorkerSettings<H>>,
2018-04-14 01:02:01 +02:00
) -> 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 04:54:01 +02:00
buffer: Output::Buffer(buf),
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
}
pub fn disconnected(&mut self) {
2018-06-24 04:54:01 +02:00
self.buffer = Output::Empty;
}
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-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]
fn set_date(&self, dst: &mut BytesMut) {
2018-06-23 06:13:09 +02:00
self.settings.set_date(dst, 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 04:54:01 +02:00
//self.buffer.get_mut()
unimplemented!()
2018-05-21 05:37:19 +02:00
}
2018-04-14 01:02:01 +02:00
fn start(
2018-05-17 21:20:20 +02:00
&mut self, req: &mut HttpInnerMessage, msg: &mut HttpResponse,
2018-04-14 01:02:01 +02:00
encoding: ContentEncoding,
) -> io::Result<WriterState> {
// prepare task
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
2017-12-09 13:33:40 +01:00
let version = msg.version().unwrap_or_else(|| req.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-01-15 02:00:28 +01:00
let mut buffer = self.buffer.get_mut();
2018-06-24 04:54:01 +02:00
let reason = msg.reason().as_bytes();
2018-03-18 19:05:44 +01:00
let mut is_bin = if let Body::Binary(ref bytes) = body {
buffer.reserve(
2018-05-16 01:41:46 +02:00
256
+ msg.headers().len() * AVERAGE_HEADER_SIZE
+ bytes.len()
2018-04-14 01:02:01 +02:00
+ reason.len(),
);
2018-03-18 19:05:44 +01:00
true
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-03-18 19:05:44 +01:00
false
};
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);
2017-12-16 16:29:15 +01:00
match body {
2018-04-14 01:02:01 +02:00
Body::Empty => if req.method != Method::HEAD {
2018-06-19 19:46:58 +02:00
buffer.extend_from_slice(b"\r\ncontent-length: 0\r\n");
2018-04-14 01:02:01 +02:00
} else {
2018-06-19 19:46:58 +02:00
buffer.extend_from_slice(b"\r\n");
2018-04-14 01:02:01 +02:00
},
Body::Binary(ref bytes) => {
helpers::write_content_length(bytes.len(), &mut buffer)
}
2018-06-19 19:46:58 +02:00
_ => 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() {
if is_bin && key == CONTENT_LENGTH {
is_bin = false;
continue;
}
has_date = has_date || key == DATE;
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;
}
2018-06-24 04:54:01 +02:00
// output encoding
self.buffer = ContentEncoder::for_server(self.buffer.take(), req, msg, encoding);
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) => {
if err.kind() == io::ErrorKind::WriteZero {
self.disconnected();
}
return Err(err);
}
Ok(val) => val,
};
if n < pl.len() {
2018-06-24 04:54:01 +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 04:54:01 +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 04:54:01 +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> {
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) => {
if err.kind() == io::ErrorKind::WriteZero {
self.disconnected();
}
2018-06-23 06:13:09 +02:00
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 {
self.stream.shutdown()
} else {
Ok(Async::Ready(()))
}
}
}