2022-01-07 22:09:52 -05:00
|
|
|
// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license.
|
2021-04-08 18:34:15 -04:00
|
|
|
|
2022-04-21 03:07:49 -04:00
|
|
|
use async_compression::tokio::write::BrotliEncoder;
|
|
|
|
use async_compression::tokio::write::GzipEncoder;
|
2022-03-04 00:04:39 -05:00
|
|
|
use cache_control::CacheControl;
|
2021-10-04 21:50:40 -04:00
|
|
|
use deno_core::error::custom_error;
|
2021-04-08 18:34:15 -04:00
|
|
|
use deno_core::error::AnyError;
|
2021-10-04 21:50:40 -04:00
|
|
|
use deno_core::futures::channel::mpsc;
|
|
|
|
use deno_core::futures::channel::oneshot;
|
|
|
|
use deno_core::futures::future::pending;
|
|
|
|
use deno_core::futures::future::select;
|
|
|
|
use deno_core::futures::future::Either;
|
|
|
|
use deno_core::futures::future::Pending;
|
|
|
|
use deno_core::futures::future::RemoteHandle;
|
|
|
|
use deno_core::futures::future::Shared;
|
|
|
|
use deno_core::futures::never::Never;
|
|
|
|
use deno_core::futures::pin_mut;
|
|
|
|
use deno_core::futures::ready;
|
|
|
|
use deno_core::futures::stream::Peekable;
|
2021-04-08 18:34:15 -04:00
|
|
|
use deno_core::futures::FutureExt;
|
|
|
|
use deno_core::futures::StreamExt;
|
2021-10-04 21:50:40 -04:00
|
|
|
use deno_core::futures::TryFutureExt;
|
2021-07-12 06:44:49 -04:00
|
|
|
use deno_core::include_js_files;
|
2022-03-14 13:44:15 -04:00
|
|
|
use deno_core::op;
|
2021-04-08 18:34:15 -04:00
|
|
|
use deno_core::AsyncRefCell;
|
2021-06-26 20:29:01 -04:00
|
|
|
use deno_core::ByteString;
|
2021-10-04 21:50:40 -04:00
|
|
|
use deno_core::CancelFuture;
|
2021-04-08 18:34:15 -04:00
|
|
|
use deno_core::CancelHandle;
|
|
|
|
use deno_core::CancelTryFuture;
|
2021-07-12 06:44:49 -04:00
|
|
|
use deno_core::Extension;
|
2021-04-08 18:34:15 -04:00
|
|
|
use deno_core::OpState;
|
|
|
|
use deno_core::RcRef;
|
|
|
|
use deno_core::Resource;
|
|
|
|
use deno_core::ResourceId;
|
2021-10-26 16:00:01 -04:00
|
|
|
use deno_core::StringOrBuffer;
|
2021-04-08 18:34:15 -04:00
|
|
|
use deno_core::ZeroCopyBuf;
|
2021-10-04 21:50:40 -04:00
|
|
|
use deno_websocket::ws_create_server_stream;
|
2022-03-04 00:04:39 -05:00
|
|
|
use flate2::write::GzEncoder;
|
|
|
|
use flate2::Compression;
|
|
|
|
use fly_accept_encoding::Encoding;
|
2022-04-24 08:28:46 -04:00
|
|
|
use hyper::body::Bytes;
|
2022-05-10 16:36:40 -04:00
|
|
|
use hyper::header::HeaderName;
|
|
|
|
use hyper::header::HeaderValue;
|
2021-04-08 18:34:15 -04:00
|
|
|
use hyper::server::conn::Http;
|
2021-10-04 21:50:40 -04:00
|
|
|
use hyper::service::Service;
|
2021-04-08 18:34:15 -04:00
|
|
|
use hyper::Body;
|
|
|
|
use hyper::Request;
|
|
|
|
use hyper::Response;
|
|
|
|
use serde::Serialize;
|
|
|
|
use std::borrow::Cow;
|
|
|
|
use std::cell::RefCell;
|
2021-10-04 21:50:40 -04:00
|
|
|
use std::cmp::min;
|
|
|
|
use std::error::Error;
|
2021-04-08 18:34:15 -04:00
|
|
|
use std::future::Future;
|
2021-10-04 21:50:40 -04:00
|
|
|
use std::io;
|
2022-03-04 00:04:39 -05:00
|
|
|
use std::io::Write;
|
2021-10-04 21:50:40 -04:00
|
|
|
use std::mem::replace;
|
|
|
|
use std::mem::take;
|
2021-04-08 18:34:15 -04:00
|
|
|
use std::pin::Pin;
|
|
|
|
use std::rc::Rc;
|
2021-10-04 21:50:40 -04:00
|
|
|
use std::sync::Arc;
|
2021-04-08 18:34:15 -04:00
|
|
|
use std::task::Context;
|
|
|
|
use std::task::Poll;
|
2021-07-12 06:44:49 -04:00
|
|
|
use tokio::io::AsyncRead;
|
|
|
|
use tokio::io::AsyncWrite;
|
2022-04-21 03:07:49 -04:00
|
|
|
use tokio::io::AsyncWriteExt;
|
2021-10-04 21:50:40 -04:00
|
|
|
use tokio::task::spawn_local;
|
2022-04-21 03:07:49 -04:00
|
|
|
use tokio_util::io::ReaderStream;
|
2021-04-08 18:34:15 -04:00
|
|
|
|
2022-04-24 15:45:56 -04:00
|
|
|
pub mod compressible;
|
2022-03-04 00:04:39 -05:00
|
|
|
|
2021-07-12 06:44:49 -04:00
|
|
|
pub fn init() -> Extension {
|
|
|
|
Extension::builder()
|
|
|
|
.js(include_js_files!(
|
2021-08-11 06:27:05 -04:00
|
|
|
prefix "deno:ext/http",
|
2021-07-12 06:44:49 -04:00
|
|
|
"01_http.js",
|
|
|
|
))
|
|
|
|
.ops(vec![
|
2022-03-14 13:44:15 -04:00
|
|
|
op_http_accept::decl(),
|
|
|
|
op_http_read::decl(),
|
|
|
|
op_http_write_headers::decl(),
|
|
|
|
op_http_write::decl(),
|
2022-04-22 06:49:08 -04:00
|
|
|
op_http_write_resource::decl(),
|
2022-03-14 13:44:15 -04:00
|
|
|
op_http_shutdown::decl(),
|
|
|
|
op_http_websocket_accept_header::decl(),
|
|
|
|
op_http_upgrade_websocket::decl(),
|
2021-07-12 06:44:49 -04:00
|
|
|
])
|
|
|
|
.build()
|
2021-04-08 18:34:15 -04:00
|
|
|
}
|
|
|
|
|
2022-02-15 18:16:12 -05:00
|
|
|
pub enum HttpSocketAddr {
|
|
|
|
IpSocket(std::net::SocketAddr),
|
|
|
|
#[cfg(unix)]
|
|
|
|
UnixSocket(tokio::net::unix::SocketAddr),
|
|
|
|
}
|
|
|
|
|
|
|
|
impl From<std::net::SocketAddr> for HttpSocketAddr {
|
|
|
|
fn from(addr: std::net::SocketAddr) -> Self {
|
|
|
|
Self::IpSocket(addr)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[cfg(unix)]
|
|
|
|
impl From<tokio::net::unix::SocketAddr> for HttpSocketAddr {
|
|
|
|
fn from(addr: tokio::net::unix::SocketAddr) -> Self {
|
|
|
|
Self::UnixSocket(addr)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-10-04 21:50:40 -04:00
|
|
|
struct HttpConnResource {
|
2022-02-15 18:16:12 -05:00
|
|
|
addr: HttpSocketAddr,
|
2021-10-04 21:50:40 -04:00
|
|
|
scheme: &'static str,
|
|
|
|
acceptors_tx: mpsc::UnboundedSender<HttpAcceptor>,
|
|
|
|
closed_fut: Shared<RemoteHandle<Result<(), Arc<hyper::Error>>>>,
|
|
|
|
cancel_handle: Rc<CancelHandle>, // Closes gracefully and cancels accept ops.
|
2021-04-08 18:34:15 -04:00
|
|
|
}
|
|
|
|
|
2021-10-04 21:50:40 -04:00
|
|
|
impl HttpConnResource {
|
2022-02-15 18:16:12 -05:00
|
|
|
fn new<S>(io: S, scheme: &'static str, addr: HttpSocketAddr) -> Self
|
2021-10-04 21:50:40 -04:00
|
|
|
where
|
|
|
|
S: AsyncRead + AsyncWrite + Unpin + Send + 'static,
|
|
|
|
{
|
|
|
|
let (acceptors_tx, acceptors_rx) = mpsc::unbounded::<HttpAcceptor>();
|
|
|
|
let service = HttpService::new(acceptors_rx);
|
|
|
|
|
|
|
|
let conn_fut = Http::new()
|
|
|
|
.with_executor(LocalExecutor)
|
|
|
|
.serve_connection(io, service)
|
|
|
|
.with_upgrades();
|
|
|
|
|
|
|
|
// When the cancel handle is used, the connection shuts down gracefully.
|
|
|
|
// No new HTTP streams will be accepted, but existing streams will be able
|
|
|
|
// to continue operating and eventually shut down cleanly.
|
|
|
|
let cancel_handle = CancelHandle::new_rc();
|
|
|
|
let shutdown_fut = never().or_cancel(&cancel_handle).fuse();
|
|
|
|
|
|
|
|
// A local task that polls the hyper connection future to completion.
|
|
|
|
let task_fut = async move {
|
|
|
|
pin_mut!(shutdown_fut);
|
|
|
|
pin_mut!(conn_fut);
|
|
|
|
let result = match select(conn_fut, shutdown_fut).await {
|
|
|
|
Either::Left((result, _)) => result,
|
|
|
|
Either::Right((_, mut conn_fut)) => {
|
|
|
|
conn_fut.as_mut().graceful_shutdown();
|
|
|
|
conn_fut.await
|
|
|
|
}
|
|
|
|
};
|
|
|
|
filter_enotconn(result).map_err(Arc::from)
|
|
|
|
};
|
|
|
|
let (task_fut, closed_fut) = task_fut.remote_handle();
|
|
|
|
let closed_fut = closed_fut.shared();
|
|
|
|
spawn_local(task_fut);
|
|
|
|
|
|
|
|
Self {
|
|
|
|
addr,
|
|
|
|
scheme,
|
|
|
|
acceptors_tx,
|
|
|
|
closed_fut,
|
|
|
|
cancel_handle,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Accepts a new incoming HTTP request.
|
|
|
|
async fn accept(
|
|
|
|
self: &Rc<Self>,
|
|
|
|
) -> Result<Option<HttpStreamResource>, AnyError> {
|
|
|
|
let fut = async {
|
|
|
|
let (request_tx, request_rx) = oneshot::channel();
|
|
|
|
let (response_tx, response_rx) = oneshot::channel();
|
|
|
|
|
|
|
|
let acceptor = HttpAcceptor::new(request_tx, response_rx);
|
|
|
|
self.acceptors_tx.unbounded_send(acceptor).ok()?;
|
|
|
|
|
|
|
|
let request = request_rx.await.ok()?;
|
|
|
|
let stream = HttpStreamResource::new(self, request, response_tx);
|
|
|
|
Some(stream)
|
|
|
|
};
|
|
|
|
|
|
|
|
async {
|
|
|
|
match fut.await {
|
|
|
|
Some(stream) => Ok(Some(stream)),
|
|
|
|
// Return the connection error, if any.
|
|
|
|
None => self.closed().map_ok(|_| None).await,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
.try_or_cancel(&self.cancel_handle)
|
|
|
|
.await
|
|
|
|
}
|
|
|
|
|
|
|
|
/// A future that completes when this HTTP connection is closed or errors.
|
|
|
|
async fn closed(&self) -> Result<(), AnyError> {
|
|
|
|
self.closed_fut.clone().map_err(AnyError::from).await
|
|
|
|
}
|
|
|
|
|
|
|
|
fn scheme(&self) -> &'static str {
|
|
|
|
self.scheme
|
|
|
|
}
|
|
|
|
|
2022-02-15 18:16:12 -05:00
|
|
|
fn addr(&self) -> &HttpSocketAddr {
|
|
|
|
&self.addr
|
2021-10-04 21:50:40 -04:00
|
|
|
}
|
2021-04-08 18:34:15 -04:00
|
|
|
}
|
|
|
|
|
2021-10-04 21:50:40 -04:00
|
|
|
impl Resource for HttpConnResource {
|
|
|
|
fn name(&self) -> Cow<str> {
|
|
|
|
"httpConn".into()
|
|
|
|
}
|
|
|
|
|
|
|
|
fn close(self: Rc<Self>) {
|
|
|
|
self.cancel_handle.cancel();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Creates a new HttpConn resource which uses `io` as its transport.
|
2022-02-15 18:16:12 -05:00
|
|
|
pub fn http_create_conn_resource<S, A>(
|
2021-10-04 21:50:40 -04:00
|
|
|
state: &mut OpState,
|
|
|
|
io: S,
|
2022-02-15 18:16:12 -05:00
|
|
|
addr: A,
|
2021-10-04 21:50:40 -04:00
|
|
|
scheme: &'static str,
|
|
|
|
) -> Result<ResourceId, AnyError>
|
|
|
|
where
|
|
|
|
S: AsyncRead + AsyncWrite + Unpin + Send + 'static,
|
2022-02-15 18:16:12 -05:00
|
|
|
A: Into<HttpSocketAddr>,
|
2021-10-04 21:50:40 -04:00
|
|
|
{
|
2022-02-15 18:16:12 -05:00
|
|
|
let conn = HttpConnResource::new(io, scheme, addr.into());
|
2021-10-04 21:50:40 -04:00
|
|
|
let rid = state.resource_table.add(conn);
|
|
|
|
Ok(rid)
|
|
|
|
}
|
|
|
|
|
|
|
|
/// An object that implements the `hyper::Service` trait, through which Hyper
|
|
|
|
/// delivers incoming HTTP requests.
|
|
|
|
struct HttpService {
|
|
|
|
acceptors_rx: Peekable<mpsc::UnboundedReceiver<HttpAcceptor>>,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl HttpService {
|
|
|
|
fn new(acceptors_rx: mpsc::UnboundedReceiver<HttpAcceptor>) -> Self {
|
|
|
|
let acceptors_rx = acceptors_rx.peekable();
|
|
|
|
Self { acceptors_rx }
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Service<Request<Body>> for HttpService {
|
2021-04-08 18:34:15 -04:00
|
|
|
type Response = Response<Body>;
|
2021-10-04 21:50:40 -04:00
|
|
|
type Error = oneshot::Canceled;
|
|
|
|
type Future = oneshot::Receiver<Response<Body>>;
|
2021-04-08 18:34:15 -04:00
|
|
|
|
|
|
|
fn poll_ready(
|
|
|
|
&mut self,
|
2021-10-04 21:50:40 -04:00
|
|
|
cx: &mut Context<'_>,
|
2021-04-08 18:34:15 -04:00
|
|
|
) -> Poll<Result<(), Self::Error>> {
|
2021-10-04 21:50:40 -04:00
|
|
|
let acceptors_rx = Pin::new(&mut self.acceptors_rx);
|
|
|
|
let result = ready!(acceptors_rx.poll_peek(cx))
|
|
|
|
.map(|_| ())
|
|
|
|
.ok_or(oneshot::Canceled);
|
|
|
|
Poll::Ready(result)
|
2021-04-08 18:34:15 -04:00
|
|
|
}
|
|
|
|
|
2021-10-04 21:50:40 -04:00
|
|
|
fn call(&mut self, request: Request<Body>) -> Self::Future {
|
|
|
|
let acceptor = self.acceptors_rx.next().now_or_never().flatten().unwrap();
|
|
|
|
acceptor.call(request)
|
2021-04-08 18:34:15 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-10-04 21:50:40 -04:00
|
|
|
/// A pair of one-shot channels which first transfer a HTTP request from the
|
|
|
|
/// Hyper service to the HttpConn resource, and then take the Response back to
|
|
|
|
/// the service.
|
|
|
|
struct HttpAcceptor {
|
|
|
|
request_tx: oneshot::Sender<Request<Body>>,
|
|
|
|
response_rx: oneshot::Receiver<Response<Body>>,
|
|
|
|
}
|
2021-10-04 21:50:40 -04:00
|
|
|
|
2021-10-04 21:50:40 -04:00
|
|
|
impl HttpAcceptor {
|
|
|
|
fn new(
|
|
|
|
request_tx: oneshot::Sender<Request<Body>>,
|
|
|
|
response_rx: oneshot::Receiver<Response<Body>>,
|
|
|
|
) -> Self {
|
|
|
|
Self {
|
|
|
|
request_tx,
|
|
|
|
response_rx,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn call(self, request: Request<Body>) -> oneshot::Receiver<Response<Body>> {
|
|
|
|
let Self {
|
|
|
|
request_tx,
|
|
|
|
response_rx,
|
|
|
|
} = self;
|
|
|
|
request_tx
|
|
|
|
.send(request)
|
|
|
|
.map(|_| response_rx)
|
|
|
|
.unwrap_or_else(|_| oneshot::channel().1) // Make new canceled receiver.
|
|
|
|
}
|
2021-04-08 18:34:15 -04:00
|
|
|
}
|
|
|
|
|
2021-10-04 21:50:40 -04:00
|
|
|
/// A resource representing a single HTTP request/response stream.
|
2022-03-16 09:54:18 -04:00
|
|
|
pub struct HttpStreamResource {
|
2021-10-04 21:50:40 -04:00
|
|
|
conn: Rc<HttpConnResource>,
|
2022-03-16 09:54:18 -04:00
|
|
|
pub rd: AsyncRefCell<HttpRequestReader>,
|
2021-10-04 21:50:40 -04:00
|
|
|
wr: AsyncRefCell<HttpResponseWriter>,
|
2022-03-04 00:04:39 -05:00
|
|
|
accept_encoding: RefCell<Encoding>,
|
2021-10-04 21:50:40 -04:00
|
|
|
cancel_handle: CancelHandle,
|
2021-04-08 18:34:15 -04:00
|
|
|
}
|
|
|
|
|
2021-10-04 21:50:40 -04:00
|
|
|
impl HttpStreamResource {
|
|
|
|
fn new(
|
|
|
|
conn: &Rc<HttpConnResource>,
|
|
|
|
request: Request<Body>,
|
|
|
|
response_tx: oneshot::Sender<Response<Body>>,
|
|
|
|
) -> Self {
|
|
|
|
Self {
|
|
|
|
conn: conn.clone(),
|
|
|
|
rd: HttpRequestReader::Headers(request).into(),
|
|
|
|
wr: HttpResponseWriter::Headers(response_tx).into(),
|
2022-03-04 00:04:39 -05:00
|
|
|
accept_encoding: RefCell::new(Encoding::Identity),
|
2021-10-04 21:50:40 -04:00
|
|
|
cancel_handle: CancelHandle::new(),
|
|
|
|
}
|
2021-04-08 18:34:15 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-10-04 21:50:40 -04:00
|
|
|
impl Resource for HttpStreamResource {
|
2021-04-08 18:34:15 -04:00
|
|
|
fn name(&self) -> Cow<str> {
|
2021-10-04 21:50:40 -04:00
|
|
|
"httpStream".into()
|
2021-04-08 18:34:15 -04:00
|
|
|
}
|
2021-06-03 19:32:36 -04:00
|
|
|
|
|
|
|
fn close(self: Rc<Self>) {
|
2021-10-04 21:50:40 -04:00
|
|
|
self.cancel_handle.cancel();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// The read half of an HTTP stream.
|
2022-03-16 09:54:18 -04:00
|
|
|
pub enum HttpRequestReader {
|
2021-10-04 21:50:40 -04:00
|
|
|
Headers(Request<Body>),
|
|
|
|
Body(Peekable<Body>),
|
|
|
|
Closed,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Default for HttpRequestReader {
|
|
|
|
fn default() -> Self {
|
|
|
|
Self::Closed
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// The write half of an HTTP stream.
|
|
|
|
enum HttpResponseWriter {
|
|
|
|
Headers(oneshot::Sender<Response<Body>>),
|
2022-04-21 03:07:49 -04:00
|
|
|
Body(Pin<Box<dyn tokio::io::AsyncWrite>>),
|
2022-04-24 22:43:22 -04:00
|
|
|
BodyUncompressed(hyper::body::Sender),
|
2021-10-04 21:50:40 -04:00
|
|
|
Closed,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Default for HttpResponseWriter {
|
|
|
|
fn default() -> Self {
|
|
|
|
Self::Closed
|
2021-06-03 19:32:36 -04:00
|
|
|
}
|
2021-04-08 18:34:15 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
// We use a tuple instead of struct to avoid serialization overhead of the keys.
|
|
|
|
#[derive(Serialize)]
|
|
|
|
#[serde(rename_all = "camelCase")]
|
|
|
|
struct NextRequestResponse(
|
2021-10-04 21:50:40 -04:00
|
|
|
// stream_rid:
|
2021-04-08 18:34:15 -04:00
|
|
|
ResourceId,
|
|
|
|
// method:
|
2021-06-26 20:29:01 -04:00
|
|
|
// This is a String rather than a ByteString because reqwest will only return
|
|
|
|
// the method as a str which is guaranteed to be ASCII-only.
|
2021-04-08 18:34:15 -04:00
|
|
|
String,
|
|
|
|
// headers:
|
2021-06-26 20:29:01 -04:00
|
|
|
Vec<(ByteString, ByteString)>,
|
2021-04-08 18:34:15 -04:00
|
|
|
// url:
|
|
|
|
String,
|
|
|
|
);
|
|
|
|
|
2022-03-14 13:44:15 -04:00
|
|
|
#[op]
|
2021-10-04 21:50:40 -04:00
|
|
|
async fn op_http_accept(
|
2021-04-08 18:34:15 -04:00
|
|
|
state: Rc<RefCell<OpState>>,
|
2021-10-04 21:50:40 -04:00
|
|
|
rid: ResourceId,
|
2021-04-08 18:34:15 -04:00
|
|
|
) -> Result<Option<NextRequestResponse>, AnyError> {
|
2021-10-04 21:50:40 -04:00
|
|
|
let conn = state.borrow().resource_table.get::<HttpConnResource>(rid)?;
|
2021-04-08 18:34:15 -04:00
|
|
|
|
2021-10-04 21:50:40 -04:00
|
|
|
let stream = match conn.accept().await {
|
|
|
|
Ok(Some(stream)) => Rc::new(stream),
|
|
|
|
Ok(None) => return Ok(None),
|
|
|
|
Err(err) => return Err(err),
|
|
|
|
};
|
2021-04-08 18:34:15 -04:00
|
|
|
|
2021-10-04 21:50:40 -04:00
|
|
|
let rd = RcRef::map(&stream, |r| &r.rd).borrow().await;
|
|
|
|
let request = match &*rd {
|
|
|
|
HttpRequestReader::Headers(request) => request,
|
|
|
|
_ => unreachable!(),
|
2021-08-14 07:25:05 -04:00
|
|
|
};
|
|
|
|
|
2022-03-04 00:04:39 -05:00
|
|
|
{
|
|
|
|
let mut accept_encoding = stream.accept_encoding.borrow_mut();
|
2022-05-13 08:10:05 -04:00
|
|
|
|
|
|
|
// curl --compressed sends "Accept-Encoding: deflate, gzip".
|
|
|
|
// fly_accept_encoding::parse() returns Encoding::Deflate.
|
|
|
|
// Deno does not support Encoding::Deflate.
|
|
|
|
// So, Deno used no compression, although gzip was possible.
|
|
|
|
// This patch makes Deno use gzip instead in this case.
|
|
|
|
*accept_encoding = Encoding::Identity;
|
|
|
|
let mut max_qval = 0.0;
|
|
|
|
if let Ok(encodings) = fly_accept_encoding::encodings(request.headers()) {
|
|
|
|
for (encoding, qval) in encodings {
|
|
|
|
if let Some(enc @ (Encoding::Brotli | Encoding::Gzip)) = encoding {
|
|
|
|
// this logic came from fly_accept_encoding.
|
|
|
|
if (qval - 1.0f32).abs() < 0.01 {
|
|
|
|
*accept_encoding = enc;
|
|
|
|
break;
|
|
|
|
} else if qval > max_qval {
|
|
|
|
*accept_encoding = enc;
|
|
|
|
max_qval = qval;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2022-03-04 00:04:39 -05:00
|
|
|
}
|
|
|
|
|
2021-10-04 21:50:40 -04:00
|
|
|
let method = request.method().to_string();
|
|
|
|
let headers = req_headers(request);
|
|
|
|
let url = req_url(request, conn.scheme(), conn.addr());
|
|
|
|
|
|
|
|
let stream_rid = state.borrow_mut().resource_table.add_rc(stream);
|
|
|
|
|
|
|
|
let r = NextRequestResponse(stream_rid, method, headers, url);
|
|
|
|
Ok(Some(r))
|
2021-08-14 07:25:05 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
fn req_url(
|
|
|
|
req: &hyper::Request<hyper::Body>,
|
|
|
|
scheme: &'static str,
|
2022-02-15 18:16:12 -05:00
|
|
|
addr: &HttpSocketAddr,
|
2021-10-04 21:50:40 -04:00
|
|
|
) -> String {
|
2022-02-15 18:16:12 -05:00
|
|
|
let host: Cow<str> = match addr {
|
|
|
|
HttpSocketAddr::IpSocket(addr) => {
|
|
|
|
if let Some(auth) = req.uri().authority() {
|
|
|
|
match addr.port() {
|
|
|
|
443 if scheme == "https" => Cow::Borrowed(auth.host()),
|
|
|
|
80 if scheme == "http" => Cow::Borrowed(auth.host()),
|
|
|
|
_ => Cow::Borrowed(auth.as_str()), // Includes port number.
|
|
|
|
}
|
|
|
|
} else if let Some(host) = req.uri().host() {
|
|
|
|
Cow::Borrowed(host)
|
|
|
|
} else if let Some(host) = req.headers().get("HOST") {
|
|
|
|
match host.to_str() {
|
|
|
|
Ok(host) => Cow::Borrowed(host),
|
|
|
|
Err(_) => Cow::Owned(
|
|
|
|
host
|
|
|
|
.as_bytes()
|
|
|
|
.iter()
|
|
|
|
.cloned()
|
|
|
|
.map(char::from)
|
|
|
|
.collect::<String>(),
|
|
|
|
),
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
Cow::Owned(addr.to_string())
|
|
|
|
}
|
2021-10-04 21:50:40 -04:00
|
|
|
}
|
2022-02-15 18:16:12 -05:00
|
|
|
// There is no standard way for unix domain socket URLs
|
|
|
|
// nginx and nodejs request use http://unix:[socket_path]:/ but it is not a valid URL
|
|
|
|
// httpie uses http+unix://[percent_encoding_of_path]/ which we follow
|
|
|
|
#[cfg(unix)]
|
|
|
|
HttpSocketAddr::UnixSocket(addr) => Cow::Owned(
|
2022-02-16 13:14:19 -05:00
|
|
|
percent_encoding::percent_encode(
|
2022-02-15 18:16:12 -05:00
|
|
|
addr
|
|
|
|
.as_pathname()
|
|
|
|
.and_then(|x| x.to_str())
|
|
|
|
.unwrap_or_default()
|
|
|
|
.as_bytes(),
|
|
|
|
percent_encoding::NON_ALPHANUMERIC,
|
|
|
|
)
|
|
|
|
.to_string(),
|
|
|
|
),
|
2021-08-14 07:25:05 -04:00
|
|
|
};
|
|
|
|
let path = req.uri().path_and_query().map_or("/", |p| p.as_str());
|
2021-10-04 21:50:40 -04:00
|
|
|
[scheme, "://", &host, path].concat()
|
2021-08-14 07:25:05 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
fn req_headers(
|
|
|
|
req: &hyper::Request<hyper::Body>,
|
|
|
|
) -> Vec<(ByteString, ByteString)> {
|
|
|
|
// We treat cookies specially, because we don't want them to get them
|
|
|
|
// mangled by the `Headers` object in JS. What we do is take all cookie
|
2021-10-17 07:04:44 -04:00
|
|
|
// headers and concat them into a single cookie header, separated by
|
2021-08-14 07:25:05 -04:00
|
|
|
// semicolons.
|
2021-08-14 08:35:58 -04:00
|
|
|
let cookie_sep = "; ".as_bytes();
|
2021-08-14 07:25:05 -04:00
|
|
|
let mut cookies = vec![];
|
|
|
|
|
|
|
|
let mut headers = Vec::with_capacity(req.headers().len());
|
|
|
|
for (name, value) in req.headers().iter() {
|
|
|
|
if name == hyper::header::COOKIE {
|
2021-08-14 08:35:58 -04:00
|
|
|
cookies.push(value.as_bytes());
|
2021-08-14 07:25:05 -04:00
|
|
|
} else {
|
|
|
|
let name: &[u8] = name.as_ref();
|
|
|
|
let value = value.as_bytes();
|
2022-04-02 08:37:11 -04:00
|
|
|
headers.push((name.into(), value.into()));
|
2021-08-14 07:25:05 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if !cookies.is_empty() {
|
2022-04-02 08:37:11 -04:00
|
|
|
headers.push(("cookie".into(), cookies.join(cookie_sep).into()));
|
2021-08-14 07:25:05 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
headers
|
|
|
|
}
|
|
|
|
|
2022-03-14 13:44:15 -04:00
|
|
|
#[op]
|
2021-10-04 21:50:40 -04:00
|
|
|
async fn op_http_write_headers(
|
2021-04-15 18:48:56 -04:00
|
|
|
state: Rc<RefCell<OpState>>,
|
2022-04-04 05:49:35 -04:00
|
|
|
rid: u32,
|
|
|
|
status: u16,
|
|
|
|
headers: Vec<(ByteString, ByteString)>,
|
2021-10-26 16:00:01 -04:00
|
|
|
data: Option<StringOrBuffer>,
|
2021-10-04 21:50:40 -04:00
|
|
|
) -> Result<(), AnyError> {
|
|
|
|
let stream = state
|
2021-04-15 18:48:56 -04:00
|
|
|
.borrow_mut()
|
2021-04-08 18:34:15 -04:00
|
|
|
.resource_table
|
2021-10-04 21:50:40 -04:00
|
|
|
.get::<HttpStreamResource>(rid)?;
|
2021-04-15 18:48:56 -04:00
|
|
|
|
2021-04-08 18:34:15 -04:00
|
|
|
let mut builder = Response::builder().status(status);
|
|
|
|
|
2022-05-10 16:36:40 -04:00
|
|
|
// Add headers
|
|
|
|
let header_count = headers.len();
|
|
|
|
let headers = headers.into_iter().filter_map(|(k, v)| {
|
|
|
|
let v: Vec<u8> = v.into();
|
|
|
|
Some((
|
|
|
|
HeaderName::try_from(k.as_slice()).ok()?,
|
|
|
|
HeaderValue::try_from(v).ok()?,
|
|
|
|
))
|
|
|
|
});
|
|
|
|
// Track supported encoding
|
|
|
|
let encoding = *stream.accept_encoding.borrow();
|
|
|
|
|
|
|
|
let hmap = builder.headers_mut().unwrap();
|
|
|
|
hmap.reserve(header_count + 2);
|
|
|
|
hmap.extend(headers);
|
|
|
|
ensure_vary_accept_encoding(hmap);
|
|
|
|
|
|
|
|
let accepts_compression =
|
|
|
|
matches!(encoding, Encoding::Brotli | Encoding::Gzip);
|
|
|
|
let compressing = accepts_compression
|
2022-04-21 03:07:49 -04:00
|
|
|
&& (matches!(data, Some(ref data) if data.len() > 20) || data.is_none())
|
2022-05-10 16:36:40 -04:00
|
|
|
&& should_compress(hmap);
|
|
|
|
|
|
|
|
if compressing {
|
|
|
|
weaken_etag(hmap);
|
2022-04-21 03:07:49 -04:00
|
|
|
// Drop 'content-length' header. Hyper will update it using compressed body.
|
2022-05-10 16:36:40 -04:00
|
|
|
hmap.remove(hyper::header::CONTENT_LENGTH);
|
|
|
|
// Content-Encoding header
|
|
|
|
hmap.insert(
|
|
|
|
hyper::header::CONTENT_ENCODING,
|
|
|
|
HeaderValue::from_static(match encoding {
|
|
|
|
Encoding::Brotli => "br",
|
|
|
|
Encoding::Gzip => "gzip",
|
|
|
|
_ => unreachable!(), // Forbidden by accepts_compression
|
|
|
|
}),
|
|
|
|
);
|
2022-04-21 03:07:49 -04:00
|
|
|
}
|
2022-03-04 00:04:39 -05:00
|
|
|
|
2022-05-10 16:36:40 -04:00
|
|
|
let (new_wr, body) = http_response(data, compressing, encoding)?;
|
|
|
|
let body = builder.body(body)?;
|
2021-11-09 06:10:21 -05:00
|
|
|
|
2021-10-04 21:50:40 -04:00
|
|
|
let mut old_wr = RcRef::map(&stream, |r| &r.wr).borrow_mut().await;
|
|
|
|
let response_tx = match replace(&mut *old_wr, new_wr) {
|
|
|
|
HttpResponseWriter::Headers(response_tx) => response_tx,
|
|
|
|
_ => return Err(http_error("response headers already sent")),
|
|
|
|
};
|
|
|
|
|
|
|
|
match response_tx.send(body) {
|
|
|
|
Ok(_) => Ok(()),
|
|
|
|
Err(_) => {
|
|
|
|
stream.conn.closed().await?;
|
|
|
|
Err(http_error("connection closed while sending response"))
|
|
|
|
}
|
2021-11-09 06:10:21 -05:00
|
|
|
}
|
2021-04-08 18:34:15 -04:00
|
|
|
}
|
|
|
|
|
2022-05-10 16:36:40 -04:00
|
|
|
fn http_response(
|
|
|
|
data: Option<StringOrBuffer>,
|
|
|
|
compressing: bool,
|
|
|
|
encoding: Encoding,
|
|
|
|
) -> Result<(HttpResponseWriter, hyper::Body), AnyError> {
|
|
|
|
match data {
|
|
|
|
Some(data) if compressing => match encoding {
|
|
|
|
Encoding::Brotli => {
|
|
|
|
// quality level 6 is based on google's nginx default value for
|
|
|
|
// on-the-fly compression
|
|
|
|
// https://github.com/google/ngx_brotli#brotli_comp_level
|
|
|
|
// lgwin 22 is equivalent to brotli window size of (2**22)-16 bytes
|
|
|
|
// (~4MB)
|
|
|
|
let mut writer = brotli::CompressorWriter::new(Vec::new(), 4096, 6, 22);
|
|
|
|
writer.write_all(&data)?;
|
|
|
|
Ok((HttpResponseWriter::Closed, writer.into_inner().into()))
|
|
|
|
}
|
|
|
|
Encoding::Gzip => {
|
|
|
|
// Gzip, after level 1, doesn't produce significant size difference.
|
|
|
|
// Probably the reason why nginx's default gzip compression level is
|
|
|
|
// 1.
|
|
|
|
// https://nginx.org/en/docs/http/ngx_http_gzip_module.html#gzip_comp_level
|
|
|
|
let mut writer = GzEncoder::new(Vec::new(), Compression::new(1));
|
|
|
|
writer.write_all(&data)?;
|
|
|
|
Ok((HttpResponseWriter::Closed, writer.finish()?.into()))
|
|
|
|
}
|
|
|
|
_ => unreachable!(), // forbidden by accepts_compression
|
|
|
|
},
|
|
|
|
Some(data) => {
|
|
|
|
// If a buffer was passed, but isn't compressible, we use it to
|
|
|
|
// construct a response body.
|
2022-05-13 06:53:13 -04:00
|
|
|
Ok((HttpResponseWriter::Closed, Bytes::from(data).into()))
|
2022-05-10 16:36:40 -04:00
|
|
|
}
|
|
|
|
None if compressing => {
|
|
|
|
// Create a one way pipe that implements tokio's async io traits. To do
|
|
|
|
// this we create a [tokio::io::DuplexStream], but then throw away one
|
|
|
|
// of the directions to create a one way pipe.
|
|
|
|
let (a, b) = tokio::io::duplex(64 * 1024);
|
|
|
|
let (reader, _) = tokio::io::split(a);
|
|
|
|
let (_, writer) = tokio::io::split(b);
|
|
|
|
let writer: Pin<Box<dyn tokio::io::AsyncWrite>> = match encoding {
|
|
|
|
Encoding::Brotli => Box::pin(BrotliEncoder::new(writer)),
|
|
|
|
Encoding::Gzip => Box::pin(GzipEncoder::new(writer)),
|
|
|
|
_ => unreachable!(), // forbidden by accepts_compression
|
|
|
|
};
|
|
|
|
Ok((
|
|
|
|
HttpResponseWriter::Body(writer),
|
|
|
|
Body::wrap_stream(ReaderStream::new(reader)),
|
|
|
|
))
|
|
|
|
}
|
|
|
|
None => {
|
|
|
|
let (body_tx, body_rx) = Body::channel();
|
|
|
|
Ok((HttpResponseWriter::BodyUncompressed(body_tx), body_rx))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// If user provided a ETag header for uncompressed data, we need to
|
|
|
|
// ensure it is a Weak Etag header ("W/").
|
|
|
|
fn weaken_etag(hmap: &mut hyper::HeaderMap) {
|
|
|
|
if let Some(etag) = hmap.get_mut(hyper::header::ETAG) {
|
|
|
|
if !etag.as_bytes().starts_with(b"W/") {
|
|
|
|
let mut v = Vec::with_capacity(etag.as_bytes().len() + 2);
|
|
|
|
v.extend(b"W/");
|
|
|
|
v.extend(etag.as_bytes());
|
|
|
|
*etag = v.try_into().unwrap();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Set Vary: Accept-Encoding header for direct body response.
|
|
|
|
// Note: we set the header irrespective of whether or not we compress the data
|
|
|
|
// to make sure cache services do not serve uncompressed data to clients that
|
|
|
|
// support compression.
|
|
|
|
fn ensure_vary_accept_encoding(hmap: &mut hyper::HeaderMap) {
|
|
|
|
if let Some(v) = hmap.get_mut(hyper::header::VARY) {
|
|
|
|
if let Ok(s) = v.to_str() {
|
|
|
|
if !s.to_lowercase().contains("accept-encoding") {
|
|
|
|
*v = format!("Accept-Encoding, {}", s).try_into().unwrap()
|
|
|
|
}
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
hmap.insert(
|
|
|
|
hyper::header::VARY,
|
|
|
|
HeaderValue::from_static("Accept-Encoding"),
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
|
|
|
fn should_compress(headers: &hyper::HeaderMap) -> bool {
|
|
|
|
// skip compression if the cache-control header value is set to "no-transform" or not utf8
|
|
|
|
fn cache_control_no_transform(headers: &hyper::HeaderMap) -> Option<bool> {
|
|
|
|
let v = headers.get(hyper::header::CACHE_CONTROL)?;
|
|
|
|
let s = match std::str::from_utf8(v.as_bytes()) {
|
|
|
|
Ok(s) => s,
|
|
|
|
Err(_) => return Some(true),
|
|
|
|
};
|
|
|
|
let c = CacheControl::from_value(s)?;
|
|
|
|
Some(c.no_transform)
|
|
|
|
}
|
|
|
|
// we skip compression if the `content-range` header value is set, as it
|
|
|
|
// indicates the contents of the body were negotiated based directly
|
|
|
|
// with the user code and we can't compress the response
|
|
|
|
let content_range = headers.contains_key(hyper::header::CONTENT_RANGE);
|
|
|
|
|
|
|
|
!content_range
|
|
|
|
&& !cache_control_no_transform(headers).unwrap_or_default()
|
|
|
|
&& headers
|
|
|
|
.get(hyper::header::CONTENT_TYPE)
|
|
|
|
.map(compressible::is_content_compressible)
|
|
|
|
.unwrap_or_default()
|
|
|
|
}
|
|
|
|
|
2022-04-22 06:49:08 -04:00
|
|
|
#[op]
|
|
|
|
async fn op_http_write_resource(
|
|
|
|
state: Rc<RefCell<OpState>>,
|
|
|
|
rid: ResourceId,
|
|
|
|
stream: ResourceId,
|
|
|
|
) -> Result<(), AnyError> {
|
|
|
|
let http_stream = state
|
|
|
|
.borrow()
|
|
|
|
.resource_table
|
|
|
|
.get::<HttpStreamResource>(rid)?;
|
|
|
|
let mut wr = RcRef::map(&http_stream, |r| &r.wr).borrow_mut().await;
|
|
|
|
let resource = state.borrow().resource_table.get_any(stream)?;
|
|
|
|
loop {
|
2022-04-24 22:43:22 -04:00
|
|
|
match *wr {
|
2022-04-22 06:49:08 -04:00
|
|
|
HttpResponseWriter::Headers(_) => {
|
|
|
|
return Err(http_error("no response headers"))
|
|
|
|
}
|
|
|
|
HttpResponseWriter::Closed => {
|
|
|
|
return Err(http_error("response already completed"))
|
|
|
|
}
|
2022-04-24 22:43:22 -04:00
|
|
|
_ => {}
|
2022-04-22 06:49:08 -04:00
|
|
|
};
|
|
|
|
|
|
|
|
let vec = vec![0u8; 64 * 1024]; // 64KB
|
|
|
|
let buf = ZeroCopyBuf::new_temp(vec);
|
|
|
|
let (nread, buf) = resource.clone().read_return(buf).await?;
|
|
|
|
if nread == 0 {
|
|
|
|
break;
|
|
|
|
}
|
2022-04-24 22:43:22 -04:00
|
|
|
|
|
|
|
match &mut *wr {
|
|
|
|
HttpResponseWriter::Body(body) => {
|
|
|
|
if let Err(err) = body.write_all(&buf[..nread]).await {
|
|
|
|
assert_eq!(err.kind(), std::io::ErrorKind::BrokenPipe);
|
|
|
|
// Don't return "broken pipe", that's an implementation detail.
|
|
|
|
// Pull up the failure associated with the transport connection instead.
|
|
|
|
http_stream.conn.closed().await?;
|
|
|
|
// If there was no connection error, drop body_tx.
|
|
|
|
*wr = HttpResponseWriter::Closed;
|
|
|
|
}
|
2022-04-22 06:49:08 -04:00
|
|
|
}
|
2022-04-24 22:43:22 -04:00
|
|
|
HttpResponseWriter::BodyUncompressed(body) => {
|
2022-04-25 13:20:29 -04:00
|
|
|
let mut buf = buf.to_temp();
|
|
|
|
buf.truncate(nread);
|
|
|
|
if let Err(err) = body.send_data(Bytes::from(buf)).await {
|
2022-04-24 22:43:22 -04:00
|
|
|
assert!(err.is_closed());
|
|
|
|
// Pull up the failure associated with the transport connection instead.
|
|
|
|
http_stream.conn.closed().await?;
|
|
|
|
// If there was no connection error, drop body_tx.
|
|
|
|
*wr = HttpResponseWriter::Closed;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
_ => unreachable!(),
|
|
|
|
};
|
2022-04-22 06:49:08 -04:00
|
|
|
}
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
2022-03-14 13:44:15 -04:00
|
|
|
#[op]
|
2021-10-04 21:50:40 -04:00
|
|
|
async fn op_http_write(
|
2021-04-08 18:34:15 -04:00
|
|
|
state: Rc<RefCell<OpState>>,
|
|
|
|
rid: ResourceId,
|
2021-10-04 21:50:40 -04:00
|
|
|
buf: ZeroCopyBuf,
|
2021-04-08 18:34:15 -04:00
|
|
|
) -> Result<(), AnyError> {
|
2021-10-04 21:50:40 -04:00
|
|
|
let stream = state
|
2021-04-08 18:34:15 -04:00
|
|
|
.borrow()
|
|
|
|
.resource_table
|
2021-10-04 21:50:40 -04:00
|
|
|
.get::<HttpStreamResource>(rid)?;
|
|
|
|
let mut wr = RcRef::map(&stream, |r| &r.wr).borrow_mut().await;
|
|
|
|
|
2022-05-10 16:36:40 -04:00
|
|
|
match &mut *wr {
|
|
|
|
HttpResponseWriter::Headers(_) => Err(http_error("no response headers")),
|
|
|
|
HttpResponseWriter::Closed => Err(http_error("response already completed")),
|
|
|
|
HttpResponseWriter::Body(body) => {
|
|
|
|
let mut result = body.write_all(&buf).await;
|
|
|
|
if result.is_ok() {
|
|
|
|
result = body.flush().await;
|
2021-10-04 21:50:40 -04:00
|
|
|
}
|
2022-05-10 16:36:40 -04:00
|
|
|
match result {
|
|
|
|
Ok(_) => Ok(()),
|
|
|
|
Err(err) => {
|
|
|
|
assert_eq!(err.kind(), std::io::ErrorKind::BrokenPipe);
|
|
|
|
// Don't return "broken pipe", that's an implementation detail.
|
|
|
|
// Pull up the failure associated with the transport connection instead.
|
|
|
|
stream.conn.closed().await?;
|
|
|
|
// If there was no connection error, drop body_tx.
|
|
|
|
*wr = HttpResponseWriter::Closed;
|
|
|
|
Err(http_error("response already completed"))
|
2022-04-24 22:43:22 -04:00
|
|
|
}
|
|
|
|
}
|
2022-05-10 16:36:40 -04:00
|
|
|
}
|
|
|
|
HttpResponseWriter::BodyUncompressed(body) => {
|
2022-05-13 06:53:13 -04:00
|
|
|
let bytes = Bytes::from(buf);
|
2022-05-10 16:36:40 -04:00
|
|
|
match body.send_data(bytes).await {
|
|
|
|
Ok(_) => Ok(()),
|
|
|
|
Err(err) => {
|
|
|
|
assert!(err.is_closed());
|
|
|
|
// Pull up the failure associated with the transport connection instead.
|
|
|
|
stream.conn.closed().await?;
|
|
|
|
// If there was no connection error, drop body_tx.
|
|
|
|
*wr = HttpResponseWriter::Closed;
|
|
|
|
Err(http_error("response already completed"))
|
2022-04-24 22:43:22 -04:00
|
|
|
}
|
2021-10-04 21:50:40 -04:00
|
|
|
}
|
2021-11-09 06:10:21 -05:00
|
|
|
}
|
2021-10-04 21:50:40 -04:00
|
|
|
}
|
2021-11-09 06:10:21 -05:00
|
|
|
}
|
|
|
|
|
2021-10-04 21:50:40 -04:00
|
|
|
/// Gracefully closes the write half of the HTTP stream. Note that this does not
|
|
|
|
/// remove the HTTP stream resource from the resource table; it still has to be
|
|
|
|
/// closed with `Deno.core.close()`.
|
2022-03-14 13:44:15 -04:00
|
|
|
#[op]
|
2021-10-04 21:50:40 -04:00
|
|
|
async fn op_http_shutdown(
|
2021-11-09 06:10:21 -05:00
|
|
|
state: Rc<RefCell<OpState>>,
|
|
|
|
rid: ResourceId,
|
|
|
|
) -> Result<(), AnyError> {
|
2021-10-04 21:50:40 -04:00
|
|
|
let stream = state
|
2021-11-09 06:10:21 -05:00
|
|
|
.borrow()
|
|
|
|
.resource_table
|
2021-10-04 21:50:40 -04:00
|
|
|
.get::<HttpStreamResource>(rid)?;
|
|
|
|
let mut wr = RcRef::map(&stream, |r| &r.wr).borrow_mut().await;
|
2022-04-21 03:07:49 -04:00
|
|
|
let wr = take(&mut *wr);
|
|
|
|
if let HttpResponseWriter::Body(mut body_writer) = wr {
|
|
|
|
match body_writer.shutdown().await {
|
|
|
|
Ok(_) => {}
|
|
|
|
Err(err) => {
|
|
|
|
assert_eq!(err.kind(), std::io::ErrorKind::BrokenPipe);
|
|
|
|
// Don't return "broken pipe", that's an implementation detail.
|
|
|
|
// Pull up the failure associated with the transport connection instead.
|
|
|
|
stream.conn.closed().await?;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2021-10-04 21:50:40 -04:00
|
|
|
Ok(())
|
|
|
|
}
|
2021-11-09 06:10:21 -05:00
|
|
|
|
2022-03-14 13:44:15 -04:00
|
|
|
#[op]
|
2021-10-04 21:50:40 -04:00
|
|
|
async fn op_http_read(
|
|
|
|
state: Rc<RefCell<OpState>>,
|
|
|
|
rid: ResourceId,
|
|
|
|
mut buf: ZeroCopyBuf,
|
|
|
|
) -> Result<usize, AnyError> {
|
|
|
|
let stream = state
|
|
|
|
.borrow_mut()
|
2021-11-09 06:10:21 -05:00
|
|
|
.resource_table
|
2021-10-04 21:50:40 -04:00
|
|
|
.get::<HttpStreamResource>(rid)?;
|
|
|
|
let mut rd = RcRef::map(&stream, |r| &r.rd).borrow_mut().await;
|
|
|
|
|
|
|
|
let body = loop {
|
|
|
|
match &mut *rd {
|
|
|
|
HttpRequestReader::Headers(_) => {}
|
|
|
|
HttpRequestReader::Body(body) => break body,
|
|
|
|
HttpRequestReader::Closed => return Ok(0),
|
2021-11-09 06:10:21 -05:00
|
|
|
}
|
2021-10-04 21:50:40 -04:00
|
|
|
match take(&mut *rd) {
|
|
|
|
HttpRequestReader::Headers(request) => {
|
|
|
|
let body = request.into_body().peekable();
|
|
|
|
*rd = HttpRequestReader::Body(body);
|
|
|
|
}
|
|
|
|
_ => unreachable!(),
|
|
|
|
};
|
|
|
|
};
|
2021-11-09 06:10:21 -05:00
|
|
|
|
2021-10-04 21:50:40 -04:00
|
|
|
let fut = async {
|
|
|
|
let mut body = Pin::new(body);
|
|
|
|
loop {
|
|
|
|
match body.as_mut().peek_mut().await {
|
|
|
|
Some(Ok(chunk)) if !chunk.is_empty() => {
|
|
|
|
let len = min(buf.len(), chunk.len());
|
|
|
|
buf[..len].copy_from_slice(&chunk.split_to(len));
|
|
|
|
break Ok(len);
|
|
|
|
}
|
|
|
|
Some(_) => match body.as_mut().next().await.unwrap() {
|
|
|
|
Ok(chunk) => assert!(chunk.is_empty()),
|
|
|
|
Err(err) => break Err(AnyError::from(err)),
|
|
|
|
},
|
|
|
|
None => break Ok(0),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
};
|
2021-11-09 06:10:21 -05:00
|
|
|
|
2021-10-04 21:50:40 -04:00
|
|
|
let cancel_handle = RcRef::map(&stream, |r| &r.cancel_handle);
|
|
|
|
fut.try_or_cancel(cancel_handle).await
|
2021-04-08 18:34:15 -04:00
|
|
|
}
|
|
|
|
|
2022-03-14 13:44:15 -04:00
|
|
|
#[op]
|
2022-03-15 19:33:46 -04:00
|
|
|
fn op_http_websocket_accept_header(key: String) -> Result<String, AnyError> {
|
2021-07-08 07:33:01 -04:00
|
|
|
let digest = ring::digest::digest(
|
|
|
|
&ring::digest::SHA1_FOR_LEGACY_USE_ONLY,
|
|
|
|
format!("{}258EAFA5-E914-47DA-95CA-C5AB0DC85B11", key).as_bytes(),
|
|
|
|
);
|
|
|
|
Ok(base64::encode(digest))
|
|
|
|
}
|
|
|
|
|
2022-03-14 13:44:15 -04:00
|
|
|
#[op]
|
2021-07-08 07:33:01 -04:00
|
|
|
async fn op_http_upgrade_websocket(
|
|
|
|
state: Rc<RefCell<OpState>>,
|
|
|
|
rid: ResourceId,
|
|
|
|
) -> Result<ResourceId, AnyError> {
|
2021-10-04 21:50:40 -04:00
|
|
|
let stream = state
|
2021-07-08 07:33:01 -04:00
|
|
|
.borrow_mut()
|
|
|
|
.resource_table
|
2021-10-04 21:50:40 -04:00
|
|
|
.get::<HttpStreamResource>(rid)?;
|
|
|
|
let mut rd = RcRef::map(&stream, |r| &r.rd).borrow_mut().await;
|
2021-11-09 06:10:21 -05:00
|
|
|
|
2021-10-04 21:50:40 -04:00
|
|
|
let request = match &mut *rd {
|
|
|
|
HttpRequestReader::Headers(request) => request,
|
|
|
|
_ => {
|
|
|
|
return Err(http_error("cannot upgrade because request body was used"))
|
|
|
|
}
|
|
|
|
};
|
2021-11-09 06:10:21 -05:00
|
|
|
|
2021-10-04 21:50:40 -04:00
|
|
|
let transport = hyper::upgrade::on(request).await?;
|
|
|
|
let ws_rid = ws_create_server_stream(&state, transport).await?;
|
|
|
|
Ok(ws_rid)
|
2021-04-08 18:34:15 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
// Needed so hyper can use non Send futures
|
|
|
|
#[derive(Clone)]
|
|
|
|
struct LocalExecutor;
|
|
|
|
|
|
|
|
impl<Fut> hyper::rt::Executor<Fut> for LocalExecutor
|
|
|
|
where
|
|
|
|
Fut: Future + 'static,
|
|
|
|
Fut::Output: 'static,
|
|
|
|
{
|
|
|
|
fn execute(&self, fut: Fut) {
|
2021-10-04 21:50:40 -04:00
|
|
|
spawn_local(fut);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn http_error(message: &'static str) -> AnyError {
|
|
|
|
custom_error("Http", message)
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Filters out the ever-surprising 'shutdown ENOTCONN' errors.
|
|
|
|
fn filter_enotconn(
|
|
|
|
result: Result<(), hyper::Error>,
|
|
|
|
) -> Result<(), hyper::Error> {
|
|
|
|
if result
|
|
|
|
.as_ref()
|
|
|
|
.err()
|
|
|
|
.and_then(|err| err.source())
|
|
|
|
.and_then(|err| err.downcast_ref::<io::Error>())
|
|
|
|
.filter(|err| err.kind() == io::ErrorKind::NotConnected)
|
|
|
|
.is_some()
|
|
|
|
{
|
|
|
|
Ok(())
|
|
|
|
} else {
|
|
|
|
result
|
2021-04-08 18:34:15 -04:00
|
|
|
}
|
|
|
|
}
|
2021-10-04 21:50:40 -04:00
|
|
|
|
|
|
|
/// Create a future that is forever pending.
|
|
|
|
fn never() -> Pending<Never> {
|
|
|
|
pending()
|
|
|
|
}
|