2024-01-01 14:58:21 -05:00
|
|
|
// Copyright 2018-2024 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;
|
2023-08-04 11:28:32 -04:00
|
|
|
use async_compression::Level;
|
2023-10-26 12:39:04 -04:00
|
|
|
use base64::prelude::BASE64_STANDARD;
|
|
|
|
use base64::Engine;
|
2022-03-04 00:04:39 -05:00
|
|
|
use cache_control::CacheControl;
|
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::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;
|
2023-09-14 17:05:18 -04:00
|
|
|
use deno_core::op2;
|
2023-08-23 19:03:05 -04:00
|
|
|
use deno_core::unsync::spawn;
|
2021-04-08 18:34:15 -04:00
|
|
|
use deno_core::AsyncRefCell;
|
2022-10-09 10:49:25 -04:00
|
|
|
use deno_core::AsyncResult;
|
|
|
|
use deno_core::BufView;
|
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;
|
2023-06-22 17:37:56 -04:00
|
|
|
use deno_core::JsBuffer;
|
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;
|
2023-04-22 13:48:21 -04:00
|
|
|
use deno_net::raw::NetworkStream;
|
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;
|
2023-12-21 19:54:28 -05:00
|
|
|
use hyper_util::rt::TokioIo;
|
2023-12-27 11:59:57 -05:00
|
|
|
use hyper_v014::body::Bytes;
|
|
|
|
use hyper_v014::body::HttpBody;
|
|
|
|
use hyper_v014::body::SizeHint;
|
|
|
|
use hyper_v014::header::HeaderName;
|
|
|
|
use hyper_v014::header::HeaderValue;
|
|
|
|
use hyper_v014::server::conn::Http;
|
|
|
|
use hyper_v014::service::Service;
|
|
|
|
use hyper_v014::Body;
|
|
|
|
use hyper_v014::HeaderMap;
|
|
|
|
use hyper_v014::Request;
|
|
|
|
use hyper_v014::Response;
|
2021-04-08 18:34:15 -04:00
|
|
|
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;
|
2023-03-09 21:28:51 -05:00
|
|
|
use std::pin::pin;
|
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;
|
2022-12-20 03:46:45 -05:00
|
|
|
|
2023-04-24 17:24:40 -04:00
|
|
|
use crate::network_buffered_stream::NetworkBufferedStream;
|
2022-12-20 03:46:45 -05:00
|
|
|
use crate::reader_stream::ExternallyAbortableReaderStream;
|
|
|
|
use crate::reader_stream::ShutdownHandle;
|
2021-04-08 18:34:15 -04:00
|
|
|
|
2022-04-24 15:45:56 -04:00
|
|
|
pub mod compressible;
|
2023-12-14 13:43:33 -05:00
|
|
|
mod fly_accept_encoding;
|
2023-04-22 13:48:21 -04:00
|
|
|
mod http_next;
|
2023-04-24 17:24:40 -04:00
|
|
|
mod network_buffered_stream;
|
2022-12-20 03:46:45 -05:00
|
|
|
mod reader_stream;
|
2023-04-22 13:48:21 -04:00
|
|
|
mod request_body;
|
|
|
|
mod request_properties;
|
|
|
|
mod response_body;
|
2023-11-13 09:04:49 -05:00
|
|
|
mod service;
|
2023-04-02 17:27:12 -04:00
|
|
|
mod websocket_upgrade;
|
2022-03-04 00:04:39 -05:00
|
|
|
|
2023-12-14 13:43:33 -05:00
|
|
|
use fly_accept_encoding::Encoding;
|
2024-10-18 18:57:12 -04:00
|
|
|
pub use http_next::HttpNextError;
|
2023-05-10 10:23:26 -04:00
|
|
|
pub use request_properties::DefaultHttpPropertyExtractor;
|
2023-05-10 12:04:01 -04:00
|
|
|
pub use request_properties::HttpConnectionProperties;
|
|
|
|
pub use request_properties::HttpListenProperties;
|
|
|
|
pub use request_properties::HttpPropertyExtractor;
|
|
|
|
pub use request_properties::HttpRequestProperties;
|
2024-10-18 18:57:12 -04:00
|
|
|
pub use service::UpgradeUnavailableError;
|
|
|
|
pub use websocket_upgrade::WebSocketUpgradeError;
|
2023-05-10 10:23:26 -04:00
|
|
|
|
2023-03-17 14:22:15 -04:00
|
|
|
deno_core::extension!(
|
|
|
|
deno_http,
|
|
|
|
deps = [deno_web, deno_net, deno_fetch, deno_websocket],
|
2023-05-10 10:23:26 -04:00
|
|
|
parameters = [ HTTP: HttpPropertyExtractor ],
|
2023-03-17 14:22:15 -04:00
|
|
|
ops = [
|
|
|
|
op_http_accept,
|
|
|
|
op_http_headers,
|
|
|
|
op_http_shutdown,
|
|
|
|
op_http_upgrade_websocket,
|
2023-05-08 17:07:45 -04:00
|
|
|
op_http_websocket_accept_header,
|
|
|
|
op_http_write_headers,
|
|
|
|
op_http_write_resource,
|
|
|
|
op_http_write,
|
2023-11-13 14:17:31 -05:00
|
|
|
http_next::op_http_close_after_finish,
|
2023-05-08 17:07:45 -04:00
|
|
|
http_next::op_http_get_request_header,
|
|
|
|
http_next::op_http_get_request_headers,
|
2024-11-08 08:16:11 -05:00
|
|
|
http_next::op_http_request_on_cancel,
|
2023-05-10 10:23:26 -04:00
|
|
|
http_next::op_http_get_request_method_and_url<HTTP>,
|
2024-11-07 06:42:13 -05:00
|
|
|
http_next::op_http_get_request_cancelled,
|
2023-05-08 17:07:45 -04:00
|
|
|
http_next::op_http_read_request_body,
|
2023-05-10 10:23:26 -04:00
|
|
|
http_next::op_http_serve_on<HTTP>,
|
|
|
|
http_next::op_http_serve<HTTP>,
|
2023-05-08 17:07:45 -04:00
|
|
|
http_next::op_http_set_promise_complete,
|
|
|
|
http_next::op_http_set_response_body_bytes,
|
|
|
|
http_next::op_http_set_response_body_resource,
|
|
|
|
http_next::op_http_set_response_body_text,
|
|
|
|
http_next::op_http_set_response_header,
|
|
|
|
http_next::op_http_set_response_headers,
|
2023-05-18 22:10:25 -04:00
|
|
|
http_next::op_http_set_response_trailers,
|
2023-05-15 19:24:41 -04:00
|
|
|
http_next::op_http_upgrade_websocket_next,
|
2023-05-08 17:07:45 -04:00
|
|
|
http_next::op_http_upgrade_raw,
|
2023-07-07 12:47:08 -04:00
|
|
|
http_next::op_raw_write_vectored,
|
2023-07-18 17:34:26 -04:00
|
|
|
http_next::op_can_write_vectored,
|
2023-05-30 20:02:52 -04:00
|
|
|
http_next::op_http_try_wait,
|
2023-05-08 17:07:45 -04:00
|
|
|
http_next::op_http_wait,
|
2023-09-11 20:06:38 -04:00
|
|
|
http_next::op_http_close,
|
|
|
|
http_next::op_http_cancel,
|
2023-03-17 14:22:15 -04:00
|
|
|
],
|
2024-04-24 14:03:37 -04:00
|
|
|
esm = ["00_serve.ts", "01_http.js", "02_websocket.ts"],
|
2023-03-17 14:22:15 -04:00
|
|
|
);
|
2021-04-08 18:34:15 -04:00
|
|
|
|
2024-10-18 18:57:12 -04:00
|
|
|
#[derive(Debug, thiserror::Error)]
|
|
|
|
pub enum HttpError {
|
|
|
|
#[error(transparent)]
|
|
|
|
Resource(deno_core::error::AnyError),
|
|
|
|
#[error(transparent)]
|
|
|
|
Canceled(#[from] deno_core::Canceled),
|
|
|
|
#[error("{0}")]
|
|
|
|
HyperV014(#[source] Arc<hyper_v014::Error>),
|
|
|
|
#[error("{0}")]
|
|
|
|
InvalidHeaderName(#[from] hyper_v014::header::InvalidHeaderName),
|
|
|
|
#[error("{0}")]
|
|
|
|
InvalidHeaderValue(#[from] hyper_v014::header::InvalidHeaderValue),
|
|
|
|
#[error("{0}")]
|
|
|
|
Http(#[from] hyper_v014::http::Error),
|
|
|
|
#[error("response headers already sent")]
|
|
|
|
ResponseHeadersAlreadySent,
|
|
|
|
#[error("connection closed while sending response")]
|
|
|
|
ConnectionClosedWhileSendingResponse,
|
|
|
|
#[error("already in use")]
|
|
|
|
AlreadyInUse,
|
|
|
|
#[error("{0}")]
|
|
|
|
Io(#[from] std::io::Error),
|
|
|
|
#[error("no response headers")]
|
|
|
|
NoResponseHeaders,
|
|
|
|
#[error("response already completed")]
|
|
|
|
ResponseAlreadyCompleted,
|
|
|
|
#[error("cannot upgrade because request body was used")]
|
|
|
|
UpgradeBodyUsed,
|
|
|
|
#[error(transparent)]
|
|
|
|
Other(deno_core::error::AnyError),
|
|
|
|
}
|
|
|
|
|
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>,
|
2023-12-27 11:59:57 -05:00
|
|
|
closed_fut: Shared<RemoteHandle<Result<(), Arc<hyper_v014::Error>>>>,
|
2021-10-04 21:50:40 -04:00
|
|
|
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 {
|
2023-03-09 21:28:51 -05:00
|
|
|
let conn_fut = pin!(conn_fut);
|
|
|
|
let shutdown_fut = pin!(shutdown_fut);
|
2021-10-04 21:50:40 -04:00
|
|
|
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();
|
2023-05-14 17:40:01 -04:00
|
|
|
spawn(task_fut);
|
2021-10-04 21:50:40 -04:00
|
|
|
|
|
|
|
Self {
|
|
|
|
addr,
|
|
|
|
scheme,
|
|
|
|
acceptors_tx,
|
|
|
|
closed_fut,
|
|
|
|
cancel_handle,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Accepts a new incoming HTTP request.
|
|
|
|
async fn accept(
|
|
|
|
self: &Rc<Self>,
|
2024-04-08 17:02:49 -04:00
|
|
|
) -> Result<
|
|
|
|
Option<(
|
|
|
|
HttpStreamReadResource,
|
|
|
|
HttpStreamWriteResource,
|
|
|
|
String,
|
|
|
|
String,
|
|
|
|
)>,
|
2024-10-18 18:57:12 -04:00
|
|
|
HttpError,
|
2024-04-08 17:02:49 -04:00
|
|
|
> {
|
2021-10-04 21:50:40 -04:00
|
|
|
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()?;
|
2022-07-04 09:11:31 -04:00
|
|
|
let accept_encoding = {
|
2023-12-21 19:54:28 -05:00
|
|
|
let encodings =
|
|
|
|
fly_accept_encoding::encodings_iter_http_02(request.headers())
|
|
|
|
.filter(|r| {
|
|
|
|
matches!(r, Ok((Some(Encoding::Brotli | Encoding::Gzip), _)))
|
|
|
|
});
|
2022-07-04 09:11:31 -04:00
|
|
|
|
|
|
|
fly_accept_encoding::preferred(encodings)
|
|
|
|
.ok()
|
|
|
|
.flatten()
|
|
|
|
.unwrap_or(Encoding::Identity)
|
|
|
|
};
|
|
|
|
|
|
|
|
let method = request.method().to_string();
|
|
|
|
let url = req_url(&request, self.scheme, &self.addr);
|
2024-04-08 17:02:49 -04:00
|
|
|
let read_stream = HttpStreamReadResource::new(self, request);
|
|
|
|
let write_stream =
|
|
|
|
HttpStreamWriteResource::new(self, response_tx, accept_encoding);
|
|
|
|
Some((read_stream, write_stream, method, url))
|
2021-10-04 21:50:40 -04:00
|
|
|
};
|
|
|
|
|
|
|
|
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.
|
2024-10-18 18:57:12 -04:00
|
|
|
async fn closed(&self) -> Result<(), HttpError> {
|
|
|
|
self.closed_fut.clone().map_err(HttpError::HyperV014).await
|
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,
|
2024-10-18 18:57:12 -04:00
|
|
|
) -> ResourceId
|
2021-10-04 21:50:40 -04:00
|
|
|
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());
|
2024-10-18 18:57:12 -04:00
|
|
|
state.resource_table.add(conn)
|
2021-10-04 21:50:40 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
/// 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
|
|
|
}
|
|
|
|
|
2024-04-08 17:02:49 -04:00
|
|
|
pub struct HttpStreamReadResource {
|
|
|
|
_conn: Rc<HttpConnResource>,
|
2022-03-16 09:54:18 -04:00
|
|
|
pub rd: AsyncRefCell<HttpRequestReader>,
|
2021-10-04 21:50:40 -04:00
|
|
|
cancel_handle: CancelHandle,
|
2022-10-04 09:48:50 -04:00
|
|
|
size: SizeHint,
|
2021-04-08 18:34:15 -04:00
|
|
|
}
|
|
|
|
|
2024-04-08 17:02:49 -04:00
|
|
|
pub struct HttpStreamWriteResource {
|
|
|
|
conn: Rc<HttpConnResource>,
|
|
|
|
wr: AsyncRefCell<HttpResponseWriter>,
|
|
|
|
accept_encoding: Encoding,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl HttpStreamReadResource {
|
|
|
|
fn new(conn: &Rc<HttpConnResource>, request: Request<Body>) -> Self {
|
2022-10-04 09:48:50 -04:00
|
|
|
let size = request.body().size_hint();
|
2021-10-04 21:50:40 -04:00
|
|
|
Self {
|
2024-04-08 17:02:49 -04:00
|
|
|
_conn: conn.clone(),
|
2021-10-04 21:50:40 -04:00
|
|
|
rd: HttpRequestReader::Headers(request).into(),
|
2022-10-04 09:48:50 -04:00
|
|
|
size,
|
2021-10-04 21:50:40 -04:00
|
|
|
cancel_handle: CancelHandle::new(),
|
|
|
|
}
|
2021-04-08 18:34:15 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-04-08 17:02:49 -04:00
|
|
|
impl Resource for HttpStreamReadResource {
|
2022-10-09 10:49:25 -04:00
|
|
|
fn name(&self) -> Cow<str> {
|
2024-04-08 17:02:49 -04:00
|
|
|
"httpReadStream".into()
|
2022-10-09 10:49:25 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
fn read(self: Rc<Self>, limit: usize) -> AsyncResult<BufView> {
|
|
|
|
Box::pin(async move {
|
|
|
|
let mut rd = RcRef::map(&self, |r| &r.rd).borrow_mut().await;
|
|
|
|
|
|
|
|
let body = loop {
|
|
|
|
match &mut *rd {
|
|
|
|
HttpRequestReader::Headers(_) => {}
|
|
|
|
HttpRequestReader::Body(_, body) => break body,
|
|
|
|
HttpRequestReader::Closed => return Ok(BufView::empty()),
|
2022-09-30 01:54:12 -04:00
|
|
|
}
|
2022-10-09 10:49:25 -04:00
|
|
|
match take(&mut *rd) {
|
|
|
|
HttpRequestReader::Headers(request) => {
|
|
|
|
let (parts, body) = request.into_parts();
|
|
|
|
*rd = HttpRequestReader::Body(parts.headers, body.peekable());
|
|
|
|
}
|
|
|
|
_ => unreachable!(),
|
|
|
|
};
|
2022-09-30 01:54:12 -04:00
|
|
|
};
|
|
|
|
|
2022-10-09 10:49:25 -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(limit, chunk.len());
|
|
|
|
let buf = chunk.split_to(len);
|
|
|
|
let view = BufView::from(buf);
|
|
|
|
break Ok(view);
|
|
|
|
}
|
|
|
|
// This unwrap is safe because `peek_mut()` returned `Some`, and thus
|
|
|
|
// currently has a peeked value that can be synchronously returned
|
|
|
|
// from `next()`.
|
|
|
|
//
|
|
|
|
// The future returned from `next()` is always ready, so we can
|
|
|
|
// safely call `await` on it without creating a race condition.
|
|
|
|
Some(_) => match body.as_mut().next().await.unwrap() {
|
|
|
|
Ok(chunk) => assert!(chunk.is_empty()),
|
2024-10-18 18:57:12 -04:00
|
|
|
Err(err) => {
|
|
|
|
break Err(HttpError::HyperV014(Arc::new(err)).into())
|
|
|
|
}
|
2022-10-09 10:49:25 -04:00
|
|
|
},
|
|
|
|
None => break Ok(BufView::empty()),
|
2022-09-30 01:54:12 -04:00
|
|
|
}
|
|
|
|
}
|
2022-10-09 10:49:25 -04:00
|
|
|
};
|
2021-06-03 19:32:36 -04:00
|
|
|
|
2022-10-09 10:49:25 -04:00
|
|
|
let cancel_handle = RcRef::map(&self, |r| &r.cancel_handle);
|
|
|
|
fut.try_or_cancel(cancel_handle).await
|
|
|
|
})
|
2022-09-30 01:54:12 -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();
|
|
|
|
}
|
2022-10-04 09:48:50 -04:00
|
|
|
|
|
|
|
fn size_hint(&self) -> (u64, Option<u64>) {
|
|
|
|
(self.size.lower(), self.size.upper())
|
|
|
|
}
|
2021-10-04 21:50:40 -04:00
|
|
|
}
|
|
|
|
|
2024-04-08 17:02:49 -04:00
|
|
|
impl HttpStreamWriteResource {
|
|
|
|
fn new(
|
|
|
|
conn: &Rc<HttpConnResource>,
|
|
|
|
response_tx: oneshot::Sender<Response<Body>>,
|
|
|
|
accept_encoding: Encoding,
|
|
|
|
) -> Self {
|
|
|
|
Self {
|
|
|
|
conn: conn.clone(),
|
|
|
|
wr: HttpResponseWriter::Headers(response_tx).into(),
|
|
|
|
accept_encoding,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Resource for HttpStreamWriteResource {
|
|
|
|
fn name(&self) -> Cow<str> {
|
|
|
|
"httpWriteStream".into()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-10-04 21:50:40 -04:00
|
|
|
/// 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>),
|
2022-07-12 13:31:37 -04:00
|
|
|
Body(HeaderMap<HeaderValue>, Peekable<Body>),
|
2021-10-04 21:50:40 -04:00
|
|
|
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-12-20 03:46:45 -05:00
|
|
|
Body {
|
|
|
|
writer: Pin<Box<dyn tokio::io::AsyncWrite>>,
|
|
|
|
shutdown_handle: ShutdownHandle,
|
|
|
|
},
|
|
|
|
BodyUncompressed(BodyUncompressedSender),
|
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
|
|
|
}
|
|
|
|
|
2023-12-27 11:59:57 -05:00
|
|
|
struct BodyUncompressedSender(Option<hyper_v014::body::Sender>);
|
2022-12-20 03:46:45 -05:00
|
|
|
|
|
|
|
impl BodyUncompressedSender {
|
2023-12-27 11:59:57 -05:00
|
|
|
fn sender(&mut self) -> &mut hyper_v014::body::Sender {
|
2022-12-20 03:46:45 -05:00
|
|
|
// This is safe because we only ever take the sender out of the option
|
|
|
|
// inside of the shutdown method.
|
|
|
|
self.0.as_mut().unwrap()
|
|
|
|
}
|
|
|
|
|
|
|
|
fn shutdown(mut self) {
|
|
|
|
// take the sender out of self so that when self is dropped at the end of
|
|
|
|
// this block, it doesn't get aborted
|
|
|
|
self.0.take();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-12-27 11:59:57 -05:00
|
|
|
impl From<hyper_v014::body::Sender> for BodyUncompressedSender {
|
|
|
|
fn from(sender: hyper_v014::body::Sender) -> Self {
|
2022-12-20 03:46:45 -05:00
|
|
|
BodyUncompressedSender(Some(sender))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Drop for BodyUncompressedSender {
|
|
|
|
fn drop(&mut self) {
|
|
|
|
if let Some(sender) = self.0.take() {
|
|
|
|
sender.abort();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
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(
|
2024-04-08 17:02:49 -04:00
|
|
|
// read_stream_rid:
|
|
|
|
ResourceId,
|
|
|
|
// write_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,
|
|
|
|
// url:
|
|
|
|
String,
|
|
|
|
);
|
|
|
|
|
2023-09-14 17:05:18 -04:00
|
|
|
#[op2(async)]
|
|
|
|
#[serde]
|
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>>,
|
2023-09-14 17:05:18 -04:00
|
|
|
#[smi] rid: ResourceId,
|
2024-10-18 18:57:12 -04:00
|
|
|
) -> Result<Option<NextRequestResponse>, HttpError> {
|
|
|
|
let conn = state
|
|
|
|
.borrow()
|
|
|
|
.resource_table
|
|
|
|
.get::<HttpConnResource>(rid)
|
|
|
|
.map_err(HttpError::Resource)?;
|
2021-04-08 18:34:15 -04:00
|
|
|
|
2022-07-04 09:11:31 -04:00
|
|
|
match conn.accept().await {
|
2024-04-08 17:02:49 -04:00
|
|
|
Ok(Some((read_stream, write_stream, method, url))) => {
|
|
|
|
let read_stream_rid = state
|
|
|
|
.borrow_mut()
|
|
|
|
.resource_table
|
|
|
|
.add_rc(Rc::new(read_stream));
|
|
|
|
let write_stream_rid = state
|
|
|
|
.borrow_mut()
|
|
|
|
.resource_table
|
|
|
|
.add_rc(Rc::new(write_stream));
|
|
|
|
let r =
|
|
|
|
NextRequestResponse(read_stream_rid, write_stream_rid, method, url);
|
2022-07-04 09:11:31 -04:00
|
|
|
Ok(Some(r))
|
|
|
|
}
|
|
|
|
Ok(None) => Ok(None),
|
|
|
|
Err(err) => Err(err),
|
|
|
|
}
|
2021-08-14 07:25:05 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
fn req_url(
|
2023-12-27 11:59:57 -05:00
|
|
|
req: &hyper_v014::Request<hyper_v014::Body>,
|
2021-08-14 07:25:05 -04:00
|
|
|
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
|
|
|
};
|
2023-03-15 17:46:36 -04:00
|
|
|
let path = req
|
|
|
|
.uri()
|
|
|
|
.path_and_query()
|
|
|
|
.map(|p| p.as_str())
|
|
|
|
.unwrap_or("/");
|
2021-10-04 21:50:40 -04:00
|
|
|
[scheme, "://", &host, path].concat()
|
2021-08-14 07:25:05 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
fn req_headers(
|
2022-07-12 13:31:37 -04:00
|
|
|
header_map: &HeaderMap<HeaderValue>,
|
2021-08-14 07:25:05 -04:00
|
|
|
) -> 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![];
|
|
|
|
|
2022-07-12 13:31:37 -04:00
|
|
|
let mut headers = Vec::with_capacity(header_map.len());
|
|
|
|
for (name, value) in header_map.iter() {
|
2023-12-27 11:59:57 -05:00
|
|
|
if name == hyper_v014::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
|
|
|
|
}
|
|
|
|
|
2023-09-14 17:05:18 -04:00
|
|
|
#[op2(async)]
|
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>>,
|
2023-09-14 17:05:18 -04:00
|
|
|
#[smi] rid: u32,
|
|
|
|
#[smi] status: u16,
|
|
|
|
#[serde] headers: Vec<(ByteString, ByteString)>,
|
|
|
|
#[serde] data: Option<StringOrBuffer>,
|
2024-10-18 18:57:12 -04:00
|
|
|
) -> Result<(), HttpError> {
|
2021-10-04 21:50:40 -04:00
|
|
|
let stream = state
|
2021-04-15 18:48:56 -04:00
|
|
|
.borrow_mut()
|
2021-04-08 18:34:15 -04:00
|
|
|
.resource_table
|
2024-10-18 18:57:12 -04:00
|
|
|
.get::<HttpStreamWriteResource>(rid)
|
|
|
|
.map_err(HttpError::Resource)?;
|
2021-04-15 18:48:56 -04:00
|
|
|
|
2022-05-10 16:36:40 -04:00
|
|
|
// Track supported encoding
|
2022-07-04 12:18:09 -04:00
|
|
|
let encoding = stream.accept_encoding;
|
2022-05-10 16:36:40 -04:00
|
|
|
|
2022-05-17 08:40:30 -04:00
|
|
|
let mut builder = Response::builder();
|
|
|
|
// SAFETY: can not fail, since a fresh Builder is non-errored
|
|
|
|
let hmap = unsafe { builder.headers_mut().unwrap_unchecked() };
|
|
|
|
|
|
|
|
// Add headers
|
|
|
|
hmap.reserve(headers.len() + 2);
|
|
|
|
for (k, v) in headers.into_iter() {
|
|
|
|
let v: Vec<u8> = v.into();
|
|
|
|
hmap.append(
|
|
|
|
HeaderName::try_from(k.as_slice())?,
|
|
|
|
HeaderValue::try_from(v)?,
|
|
|
|
);
|
|
|
|
}
|
2022-05-10 16:36:40 -04:00
|
|
|
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.
|
2023-12-27 11:59:57 -05:00
|
|
|
hmap.remove(hyper_v014::header::CONTENT_LENGTH);
|
2022-05-10 16:36:40 -04:00
|
|
|
// Content-Encoding header
|
|
|
|
hmap.insert(
|
2023-12-27 11:59:57 -05:00
|
|
|
hyper_v014::header::CONTENT_ENCODING,
|
2022-05-10 16:36:40 -04:00
|
|
|
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)?;
|
2022-05-17 08:40:30 -04:00
|
|
|
let body = builder.status(status).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,
|
2024-10-18 18:57:12 -04:00
|
|
|
_ => return Err(HttpError::ResponseHeadersAlreadySent),
|
2021-10-04 21:50:40 -04:00
|
|
|
};
|
|
|
|
|
|
|
|
match response_tx.send(body) {
|
|
|
|
Ok(_) => Ok(()),
|
|
|
|
Err(_) => {
|
|
|
|
stream.conn.closed().await?;
|
2024-10-18 18:57:12 -04:00
|
|
|
Err(HttpError::ConnectionClosedWhileSendingResponse)
|
2021-10-04 21:50:40 -04:00
|
|
|
}
|
2021-11-09 06:10:21 -05:00
|
|
|
}
|
2021-04-08 18:34:15 -04:00
|
|
|
}
|
|
|
|
|
2023-09-14 17:05:18 -04:00
|
|
|
#[op2]
|
|
|
|
#[serde]
|
2022-07-03 22:11:52 -04:00
|
|
|
fn op_http_headers(
|
|
|
|
state: &mut OpState,
|
2023-09-14 17:05:18 -04:00
|
|
|
#[smi] rid: u32,
|
2024-10-18 18:57:12 -04:00
|
|
|
) -> Result<Vec<(ByteString, ByteString)>, HttpError> {
|
|
|
|
let stream = state
|
|
|
|
.resource_table
|
|
|
|
.get::<HttpStreamReadResource>(rid)
|
|
|
|
.map_err(HttpError::Resource)?;
|
2022-07-03 22:11:52 -04:00
|
|
|
let rd = RcRef::map(&stream, |r| &r.rd)
|
|
|
|
.try_borrow()
|
2024-10-18 18:57:12 -04:00
|
|
|
.ok_or(HttpError::AlreadyInUse)?;
|
2022-07-03 22:11:52 -04:00
|
|
|
match &*rd {
|
2022-07-12 13:31:37 -04:00
|
|
|
HttpRequestReader::Headers(request) => Ok(req_headers(request.headers())),
|
|
|
|
HttpRequestReader::Body(headers, _) => Ok(req_headers(headers)),
|
2022-07-03 22:11:52 -04:00
|
|
|
_ => unreachable!(),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-05-10 16:36:40 -04:00
|
|
|
fn http_response(
|
|
|
|
data: Option<StringOrBuffer>,
|
|
|
|
compressing: bool,
|
|
|
|
encoding: Encoding,
|
2024-10-18 18:57:12 -04:00
|
|
|
) -> Result<(HttpResponseWriter, hyper_v014::Body), HttpError> {
|
2023-08-04 11:28:32 -04:00
|
|
|
// Gzip, after level 1, doesn't produce significant size difference.
|
|
|
|
// This default matches nginx default gzip compression level (1):
|
|
|
|
// https://nginx.org/en/docs/http/ngx_http_gzip_module.html#gzip_comp_level
|
|
|
|
const GZIP_DEFAULT_COMPRESSION_LEVEL: u8 = 1;
|
|
|
|
|
2022-05-10 16:36:40 -04:00
|
|
|
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 => {
|
2023-08-04 11:28:32 -04:00
|
|
|
let mut writer = GzEncoder::new(
|
|
|
|
Vec::new(),
|
|
|
|
Compression::new(GZIP_DEFAULT_COMPRESSION_LEVEL.into()),
|
|
|
|
);
|
2022-05-10 16:36:40 -04:00
|
|
|
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.
|
2023-12-23 10:58:20 -05:00
|
|
|
Ok((HttpResponseWriter::Closed, data.to_vec().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 {
|
2023-08-04 14:39:39 -04:00
|
|
|
Encoding::Brotli => {
|
|
|
|
Box::pin(BrotliEncoder::with_quality(writer, Level::Fastest))
|
|
|
|
}
|
2023-08-04 11:28:32 -04:00
|
|
|
Encoding::Gzip => Box::pin(GzipEncoder::with_quality(
|
|
|
|
writer,
|
|
|
|
Level::Precise(GZIP_DEFAULT_COMPRESSION_LEVEL.into()),
|
|
|
|
)),
|
2022-05-10 16:36:40 -04:00
|
|
|
_ => unreachable!(), // forbidden by accepts_compression
|
|
|
|
};
|
2022-12-20 03:46:45 -05:00
|
|
|
let (stream, shutdown_handle) =
|
|
|
|
ExternallyAbortableReaderStream::new(reader);
|
2022-05-10 16:36:40 -04:00
|
|
|
Ok((
|
2022-12-20 03:46:45 -05:00
|
|
|
HttpResponseWriter::Body {
|
|
|
|
writer,
|
|
|
|
shutdown_handle,
|
|
|
|
},
|
|
|
|
Body::wrap_stream(stream),
|
2022-05-10 16:36:40 -04:00
|
|
|
))
|
|
|
|
}
|
|
|
|
None => {
|
|
|
|
let (body_tx, body_rx) = Body::channel();
|
2022-12-20 03:46:45 -05:00
|
|
|
Ok((
|
|
|
|
HttpResponseWriter::BodyUncompressed(body_tx.into()),
|
|
|
|
body_rx,
|
|
|
|
))
|
2022-05-10 16:36:40 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// If user provided a ETag header for uncompressed data, we need to
|
|
|
|
// ensure it is a Weak Etag header ("W/").
|
2023-12-27 11:59:57 -05:00
|
|
|
fn weaken_etag(hmap: &mut hyper_v014::HeaderMap) {
|
|
|
|
if let Some(etag) = hmap.get_mut(hyper_v014::header::ETAG) {
|
2022-05-10 16:36:40 -04:00
|
|
|
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.
|
2023-12-27 11:59:57 -05:00
|
|
|
fn ensure_vary_accept_encoding(hmap: &mut hyper_v014::HeaderMap) {
|
|
|
|
if let Some(v) = hmap.get_mut(hyper_v014::header::VARY) {
|
2022-05-10 16:36:40 -04:00
|
|
|
if let Ok(s) = v.to_str() {
|
|
|
|
if !s.to_lowercase().contains("accept-encoding") {
|
2023-01-27 10:43:16 -05:00
|
|
|
*v = format!("Accept-Encoding, {s}").try_into().unwrap()
|
2022-05-10 16:36:40 -04:00
|
|
|
}
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
hmap.insert(
|
2023-12-27 11:59:57 -05:00
|
|
|
hyper_v014::header::VARY,
|
2022-05-10 16:36:40 -04:00
|
|
|
HeaderValue::from_static("Accept-Encoding"),
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
2023-12-27 11:59:57 -05:00
|
|
|
fn should_compress(headers: &hyper_v014::HeaderMap) -> bool {
|
2022-05-10 16:36:40 -04:00
|
|
|
// skip compression if the cache-control header value is set to "no-transform" or not utf8
|
2023-12-27 11:59:57 -05:00
|
|
|
fn cache_control_no_transform(
|
|
|
|
headers: &hyper_v014::HeaderMap,
|
|
|
|
) -> Option<bool> {
|
|
|
|
let v = headers.get(hyper_v014::header::CACHE_CONTROL)?;
|
2022-05-10 16:36:40 -04:00
|
|
|
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
|
2023-12-27 11:59:57 -05:00
|
|
|
let content_range = headers.contains_key(hyper_v014::header::CONTENT_RANGE);
|
2022-05-17 08:02:45 -04:00
|
|
|
// assume body is already compressed if Content-Encoding header present, thus avoid recompressing
|
2023-12-27 11:59:57 -05:00
|
|
|
let is_precompressed =
|
|
|
|
headers.contains_key(hyper_v014::header::CONTENT_ENCODING);
|
2022-05-10 16:36:40 -04:00
|
|
|
|
|
|
|
!content_range
|
2022-05-17 08:02:45 -04:00
|
|
|
&& !is_precompressed
|
2022-05-10 16:36:40 -04:00
|
|
|
&& !cache_control_no_transform(headers).unwrap_or_default()
|
|
|
|
&& headers
|
2023-12-27 11:59:57 -05:00
|
|
|
.get(hyper_v014::header::CONTENT_TYPE)
|
2022-05-10 16:36:40 -04:00
|
|
|
.map(compressible::is_content_compressible)
|
|
|
|
.unwrap_or_default()
|
|
|
|
}
|
|
|
|
|
2023-09-14 17:05:18 -04:00
|
|
|
#[op2(async)]
|
2022-04-22 06:49:08 -04:00
|
|
|
async fn op_http_write_resource(
|
|
|
|
state: Rc<RefCell<OpState>>,
|
2023-09-14 17:05:18 -04:00
|
|
|
#[smi] rid: ResourceId,
|
|
|
|
#[smi] stream: ResourceId,
|
2024-10-18 18:57:12 -04:00
|
|
|
) -> Result<(), HttpError> {
|
2022-04-22 06:49:08 -04:00
|
|
|
let http_stream = state
|
|
|
|
.borrow()
|
|
|
|
.resource_table
|
2024-10-18 18:57:12 -04:00
|
|
|
.get::<HttpStreamWriteResource>(rid)
|
|
|
|
.map_err(HttpError::Resource)?;
|
2022-04-22 06:49:08 -04:00
|
|
|
let mut wr = RcRef::map(&http_stream, |r| &r.wr).borrow_mut().await;
|
2024-10-18 18:57:12 -04:00
|
|
|
let resource = state
|
|
|
|
.borrow()
|
|
|
|
.resource_table
|
|
|
|
.get_any(stream)
|
|
|
|
.map_err(HttpError::Resource)?;
|
2022-04-22 06:49:08 -04:00
|
|
|
loop {
|
2022-04-24 22:43:22 -04:00
|
|
|
match *wr {
|
2022-04-22 06:49:08 -04:00
|
|
|
HttpResponseWriter::Headers(_) => {
|
2024-10-18 18:57:12 -04:00
|
|
|
return Err(HttpError::NoResponseHeaders)
|
2022-04-22 06:49:08 -04:00
|
|
|
}
|
|
|
|
HttpResponseWriter::Closed => {
|
2024-10-18 18:57:12 -04:00
|
|
|
return Err(HttpError::ResponseAlreadyCompleted)
|
2022-04-22 06:49:08 -04:00
|
|
|
}
|
2022-04-24 22:43:22 -04:00
|
|
|
_ => {}
|
2022-04-22 06:49:08 -04:00
|
|
|
};
|
|
|
|
|
2024-10-18 18:57:12 -04:00
|
|
|
let view = resource
|
|
|
|
.clone()
|
|
|
|
.read(64 * 1024)
|
|
|
|
.await
|
|
|
|
.map_err(HttpError::Other)?; // 64KB
|
2022-10-09 10:49:25 -04:00
|
|
|
if view.is_empty() {
|
2022-04-22 06:49:08 -04:00
|
|
|
break;
|
|
|
|
}
|
2022-04-24 22:43:22 -04:00
|
|
|
|
|
|
|
match &mut *wr {
|
2022-12-20 03:46:45 -05:00
|
|
|
HttpResponseWriter::Body { writer, .. } => {
|
|
|
|
let mut result = writer.write_all(&view).await;
|
2022-11-04 13:59:07 -04:00
|
|
|
if result.is_ok() {
|
2022-12-20 03:46:45 -05:00
|
|
|
result = writer.flush().await;
|
2022-11-04 13:59:07 -04:00
|
|
|
}
|
|
|
|
if let Err(err) = result {
|
2022-04-24 22:43:22 -04:00
|
|
|
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) => {
|
2023-12-23 10:58:20 -05:00
|
|
|
let bytes = view.to_vec().into();
|
2022-12-20 03:46:45 -05:00
|
|
|
if let Err(err) = body.sender().send_data(bytes).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(())
|
|
|
|
}
|
|
|
|
|
2023-09-14 17:05:18 -04:00
|
|
|
#[op2(async)]
|
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>>,
|
2023-09-14 17:05:18 -04:00
|
|
|
#[smi] rid: ResourceId,
|
|
|
|
#[buffer] buf: JsBuffer,
|
2024-10-18 18:57:12 -04:00
|
|
|
) -> Result<(), HttpError> {
|
2021-10-04 21:50:40 -04:00
|
|
|
let stream = state
|
2021-04-08 18:34:15 -04:00
|
|
|
.borrow()
|
|
|
|
.resource_table
|
2024-10-18 18:57:12 -04:00
|
|
|
.get::<HttpStreamWriteResource>(rid)
|
|
|
|
.map_err(HttpError::Resource)?;
|
2021-10-04 21:50:40 -04:00
|
|
|
let mut wr = RcRef::map(&stream, |r| &r.wr).borrow_mut().await;
|
|
|
|
|
2022-05-10 16:36:40 -04:00
|
|
|
match &mut *wr {
|
2024-10-18 18:57:12 -04:00
|
|
|
HttpResponseWriter::Headers(_) => Err(HttpError::NoResponseHeaders),
|
|
|
|
HttpResponseWriter::Closed => Err(HttpError::ResponseAlreadyCompleted),
|
2022-12-20 03:46:45 -05:00
|
|
|
HttpResponseWriter::Body { writer, .. } => {
|
|
|
|
let mut result = writer.write_all(&buf).await;
|
2022-05-10 16:36:40 -04:00
|
|
|
if result.is_ok() {
|
2022-12-20 03:46:45 -05:00
|
|
|
result = writer.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;
|
2024-10-18 18:57:12 -04:00
|
|
|
Err(HttpError::ResponseAlreadyCompleted)
|
2022-04-24 22:43:22 -04:00
|
|
|
}
|
|
|
|
}
|
2022-05-10 16:36:40 -04:00
|
|
|
}
|
|
|
|
HttpResponseWriter::BodyUncompressed(body) => {
|
2023-12-23 10:58:20 -05:00
|
|
|
let bytes = Bytes::from(buf.to_vec());
|
2022-12-20 03:46:45 -05:00
|
|
|
match body.sender().send_data(bytes).await {
|
2022-05-10 16:36:40 -04:00
|
|
|
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;
|
2024-10-18 18:57:12 -04:00
|
|
|
Err(HttpError::ResponseAlreadyCompleted)
|
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()`.
|
2023-09-14 17:05:18 -04:00
|
|
|
#[op2(async)]
|
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>>,
|
2023-09-14 17:05:18 -04:00
|
|
|
#[smi] rid: ResourceId,
|
2024-10-18 18:57:12 -04:00
|
|
|
) -> Result<(), HttpError> {
|
2021-10-04 21:50:40 -04:00
|
|
|
let stream = state
|
2021-11-09 06:10:21 -05:00
|
|
|
.borrow()
|
|
|
|
.resource_table
|
2024-10-18 18:57:12 -04:00
|
|
|
.get::<HttpStreamWriteResource>(rid)
|
|
|
|
.map_err(HttpError::Resource)?;
|
2021-10-04 21:50:40 -04:00
|
|
|
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);
|
2022-12-20 03:46:45 -05:00
|
|
|
match wr {
|
|
|
|
HttpResponseWriter::Body {
|
|
|
|
mut writer,
|
|
|
|
shutdown_handle,
|
|
|
|
} => {
|
|
|
|
shutdown_handle.shutdown();
|
|
|
|
match 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?;
|
|
|
|
}
|
2022-04-21 03:07:49 -04:00
|
|
|
}
|
|
|
|
}
|
2022-12-20 03:46:45 -05:00
|
|
|
HttpResponseWriter::BodyUncompressed(body) => {
|
|
|
|
body.shutdown();
|
|
|
|
}
|
|
|
|
_ => {}
|
|
|
|
};
|
2021-10-04 21:50:40 -04:00
|
|
|
Ok(())
|
|
|
|
}
|
2021-11-09 06:10:21 -05:00
|
|
|
|
2023-09-14 17:05:18 -04:00
|
|
|
#[op2]
|
|
|
|
#[string]
|
2024-10-18 18:57:12 -04:00
|
|
|
fn op_http_websocket_accept_header(#[string] key: String) -> String {
|
2021-07-08 07:33:01 -04:00
|
|
|
let digest = ring::digest::digest(
|
|
|
|
&ring::digest::SHA1_FOR_LEGACY_USE_ONLY,
|
2023-01-27 10:43:16 -05:00
|
|
|
format!("{key}258EAFA5-E914-47DA-95CA-C5AB0DC85B11").as_bytes(),
|
2021-07-08 07:33:01 -04:00
|
|
|
);
|
2024-10-18 18:57:12 -04:00
|
|
|
BASE64_STANDARD.encode(digest)
|
2021-07-08 07:33:01 -04:00
|
|
|
}
|
|
|
|
|
2023-09-14 17:05:18 -04:00
|
|
|
#[op2(async)]
|
|
|
|
#[smi]
|
2021-07-08 07:33:01 -04:00
|
|
|
async fn op_http_upgrade_websocket(
|
|
|
|
state: Rc<RefCell<OpState>>,
|
2023-09-14 17:05:18 -04:00
|
|
|
#[smi] rid: ResourceId,
|
2024-10-18 18:57:12 -04:00
|
|
|
) -> Result<ResourceId, HttpError> {
|
2021-10-04 21:50:40 -04:00
|
|
|
let stream = state
|
2021-07-08 07:33:01 -04:00
|
|
|
.borrow_mut()
|
|
|
|
.resource_table
|
2024-10-18 18:57:12 -04:00
|
|
|
.get::<HttpStreamReadResource>(rid)
|
|
|
|
.map_err(HttpError::Resource)?;
|
2021-10-04 21:50:40 -04:00
|
|
|
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,
|
2024-10-18 18:57:12 -04:00
|
|
|
_ => return Err(HttpError::UpgradeBodyUsed),
|
2021-10-04 21:50:40 -04:00
|
|
|
};
|
2021-11-09 06:10:21 -05:00
|
|
|
|
2024-10-18 18:57:12 -04:00
|
|
|
let (transport, bytes) = extract_network_stream(
|
|
|
|
hyper_v014::upgrade::on(request)
|
|
|
|
.await
|
|
|
|
.map_err(|err| HttpError::HyperV014(Arc::new(err)))?,
|
|
|
|
);
|
2024-10-18 15:30:46 -04:00
|
|
|
Ok(ws_create_server_stream(
|
|
|
|
&mut state.borrow_mut(),
|
|
|
|
transport,
|
|
|
|
bytes,
|
|
|
|
))
|
2021-04-08 18:34:15 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
// Needed so hyper can use non Send futures
|
|
|
|
#[derive(Clone)]
|
|
|
|
struct LocalExecutor;
|
|
|
|
|
2023-12-27 11:59:57 -05:00
|
|
|
impl<Fut> hyper_v014::rt::Executor<Fut> for LocalExecutor
|
2021-04-08 18:34:15 -04:00
|
|
|
where
|
|
|
|
Fut: Future + 'static,
|
|
|
|
Fut::Output: 'static,
|
|
|
|
{
|
|
|
|
fn execute(&self, fut: Fut) {
|
2023-08-23 19:03:05 -04:00
|
|
|
deno_core::unsync::spawn(fut);
|
2021-10-04 21:50:40 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-12-27 11:59:57 -05:00
|
|
|
impl<Fut> hyper::rt::Executor<Fut> for LocalExecutor
|
2023-04-22 13:48:21 -04:00
|
|
|
where
|
|
|
|
Fut: Future + 'static,
|
|
|
|
Fut::Output: 'static,
|
|
|
|
{
|
|
|
|
fn execute(&self, fut: Fut) {
|
2023-08-23 19:03:05 -04:00
|
|
|
deno_core::unsync::spawn(fut);
|
2023-04-22 13:48:21 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-10-04 21:50:40 -04:00
|
|
|
/// Filters out the ever-surprising 'shutdown ENOTCONN' errors.
|
|
|
|
fn filter_enotconn(
|
2023-12-27 11:59:57 -05:00
|
|
|
result: Result<(), hyper_v014::Error>,
|
|
|
|
) -> Result<(), hyper_v014::Error> {
|
2021-10-04 21:50:40 -04:00
|
|
|
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()
|
|
|
|
}
|
2023-04-22 13:48:21 -04:00
|
|
|
|
|
|
|
trait CanDowncastUpgrade: Sized {
|
|
|
|
fn downcast<T: AsyncRead + AsyncWrite + Unpin + 'static>(
|
|
|
|
self,
|
|
|
|
) -> Result<(T, Bytes), Self>;
|
|
|
|
}
|
|
|
|
|
2023-12-27 11:59:57 -05:00
|
|
|
impl CanDowncastUpgrade for hyper::upgrade::Upgraded {
|
2023-04-22 13:48:21 -04:00
|
|
|
fn downcast<T: AsyncRead + AsyncWrite + Unpin + 'static>(
|
|
|
|
self,
|
|
|
|
) -> Result<(T, Bytes), Self> {
|
2023-12-27 11:59:57 -05:00
|
|
|
let hyper::upgrade::Parts { io, read_buf, .. } =
|
2023-07-31 09:34:53 -04:00
|
|
|
self.downcast::<TokioIo<T>>()?;
|
|
|
|
Ok((io.into_inner(), read_buf))
|
2023-04-22 13:48:21 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-12-27 11:59:57 -05:00
|
|
|
impl CanDowncastUpgrade for hyper_v014::upgrade::Upgraded {
|
2023-04-22 13:48:21 -04:00
|
|
|
fn downcast<T: AsyncRead + AsyncWrite + Unpin + 'static>(
|
|
|
|
self,
|
|
|
|
) -> Result<(T, Bytes), Self> {
|
2023-12-27 11:59:57 -05:00
|
|
|
let hyper_v014::upgrade::Parts { io, read_buf, .. } = self.downcast()?;
|
2023-04-22 13:48:21 -04:00
|
|
|
Ok((io, read_buf))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-04-24 17:24:40 -04:00
|
|
|
fn maybe_extract_network_stream<
|
|
|
|
T: Into<NetworkStream> + AsyncRead + AsyncWrite + Unpin + 'static,
|
|
|
|
U: CanDowncastUpgrade,
|
|
|
|
>(
|
2023-04-22 13:48:21 -04:00
|
|
|
upgraded: U,
|
2023-04-24 17:24:40 -04:00
|
|
|
) -> Result<(NetworkStream, Bytes), U> {
|
|
|
|
let upgraded = match upgraded.downcast::<T>() {
|
|
|
|
Ok((stream, bytes)) => return Ok((stream.into(), bytes)),
|
2023-04-22 13:48:21 -04:00
|
|
|
Err(x) => x,
|
|
|
|
};
|
2023-04-24 17:24:40 -04:00
|
|
|
|
|
|
|
match upgraded.downcast::<NetworkBufferedStream<T>>() {
|
|
|
|
Ok((stream, upgraded_bytes)) => {
|
|
|
|
// Both the upgrade and the stream might have unread bytes
|
|
|
|
let (io, stream_bytes) = stream.into_inner();
|
|
|
|
let bytes = match (stream_bytes.is_empty(), upgraded_bytes.is_empty()) {
|
|
|
|
(false, false) => Bytes::default(),
|
|
|
|
(true, false) => upgraded_bytes,
|
|
|
|
(false, true) => stream_bytes,
|
|
|
|
(true, true) => {
|
|
|
|
// The upgraded bytes come first as they have already been read
|
|
|
|
let mut v = upgraded_bytes.to_vec();
|
|
|
|
v.append(&mut stream_bytes.to_vec());
|
|
|
|
Bytes::from(v)
|
|
|
|
}
|
|
|
|
};
|
|
|
|
Ok((io.into(), bytes))
|
|
|
|
}
|
|
|
|
Err(x) => Err(x),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn extract_network_stream<U: CanDowncastUpgrade>(
|
|
|
|
upgraded: U,
|
|
|
|
) -> (NetworkStream, Bytes) {
|
|
|
|
let upgraded =
|
|
|
|
match maybe_extract_network_stream::<tokio::net::TcpStream, _>(upgraded) {
|
|
|
|
Ok(res) => return res,
|
|
|
|
Err(x) => x,
|
|
|
|
};
|
|
|
|
let upgraded =
|
|
|
|
match maybe_extract_network_stream::<deno_net::ops_tls::TlsStream, _>(
|
|
|
|
upgraded,
|
|
|
|
) {
|
|
|
|
Ok(res) => return res,
|
|
|
|
Err(x) => x,
|
|
|
|
};
|
2023-04-22 13:48:21 -04:00
|
|
|
#[cfg(unix)]
|
2023-04-24 17:24:40 -04:00
|
|
|
let upgraded =
|
|
|
|
match maybe_extract_network_stream::<tokio::net::UnixStream, _>(upgraded) {
|
|
|
|
Ok(res) => return res,
|
|
|
|
Err(x) => x,
|
|
|
|
};
|
|
|
|
let upgraded =
|
|
|
|
match maybe_extract_network_stream::<NetworkStream, _>(upgraded) {
|
|
|
|
Ok(res) => return res,
|
|
|
|
Err(x) => x,
|
|
|
|
};
|
|
|
|
|
|
|
|
// TODO(mmastrac): HTTP/2 websockets may yield an un-downgradable type
|
2023-04-22 13:48:21 -04:00
|
|
|
drop(upgraded);
|
|
|
|
unreachable!("unexpected stream type");
|
|
|
|
}
|