2024-01-01 14:58:21 -05:00
|
|
|
|
// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
|
2020-09-18 09:20:55 -04:00
|
|
|
|
|
2021-11-01 00:29:46 -04:00
|
|
|
|
mod fs_fetch_handler;
|
2024-07-17 19:37:31 -04:00
|
|
|
|
mod proxy;
|
2024-07-24 16:20:06 -04:00
|
|
|
|
#[cfg(test)]
|
|
|
|
|
mod tests;
|
2021-11-01 00:29:46 -04:00
|
|
|
|
|
2023-05-01 16:42:05 -04:00
|
|
|
|
use std::borrow::Cow;
|
|
|
|
|
use std::cell::RefCell;
|
|
|
|
|
use std::cmp::min;
|
|
|
|
|
use std::convert::From;
|
|
|
|
|
use std::path::Path;
|
|
|
|
|
use std::path::PathBuf;
|
|
|
|
|
use std::pin::Pin;
|
|
|
|
|
use std::rc::Rc;
|
|
|
|
|
use std::sync::Arc;
|
2023-12-01 10:56:10 -05:00
|
|
|
|
use std::task::Context;
|
|
|
|
|
use std::task::Poll;
|
2023-05-01 16:42:05 -04:00
|
|
|
|
|
2024-07-17 19:37:31 -04:00
|
|
|
|
use deno_core::anyhow::anyhow;
|
2023-08-03 16:27:25 -04:00
|
|
|
|
use deno_core::anyhow::Error;
|
2020-09-18 09:20:55 -04:00
|
|
|
|
use deno_core::error::type_error;
|
|
|
|
|
use deno_core::error::AnyError;
|
2022-10-09 10:49:25 -04:00
|
|
|
|
use deno_core::futures::stream::Peekable;
|
2021-01-10 14:54:29 -05:00
|
|
|
|
use deno_core::futures::Future;
|
2023-08-03 16:27:25 -04:00
|
|
|
|
use deno_core::futures::FutureExt;
|
2021-01-10 14:54:29 -05:00
|
|
|
|
use deno_core::futures::Stream;
|
|
|
|
|
use deno_core::futures::StreamExt;
|
2024-08-08 02:18:33 -04:00
|
|
|
|
use deno_core::futures::TryFutureExt;
|
2023-09-21 10:08:23 -04:00
|
|
|
|
use deno_core::op2;
|
2020-09-18 09:20:55 -04:00
|
|
|
|
use deno_core::url::Url;
|
2020-12-16 11:14:12 -05:00
|
|
|
|
use deno_core::AsyncRefCell;
|
2021-11-09 13:26:17 -05:00
|
|
|
|
use deno_core::AsyncResult;
|
2023-12-01 10:56:10 -05:00
|
|
|
|
use deno_core::BufView;
|
2021-06-26 11:34:24 -04:00
|
|
|
|
use deno_core::ByteString;
|
2020-12-16 11:14:12 -05:00
|
|
|
|
use deno_core::CancelFuture;
|
|
|
|
|
use deno_core::CancelHandle;
|
2021-01-12 02:50:02 -05:00
|
|
|
|
use deno_core::CancelTryFuture;
|
2021-06-06 09:37:17 -04:00
|
|
|
|
use deno_core::Canceled;
|
2023-06-22 17:37:56 -04:00
|
|
|
|
use deno_core::JsBuffer;
|
2020-09-18 09:20:55 -04:00
|
|
|
|
use deno_core::OpState;
|
2020-12-16 11:14:12 -05:00
|
|
|
|
use deno_core::RcRef;
|
|
|
|
|
use deno_core::Resource;
|
2021-03-19 13:25:37 -04:00
|
|
|
|
use deno_core::ResourceId;
|
2021-08-07 08:49:38 -04:00
|
|
|
|
use deno_tls::rustls::RootCertStore;
|
|
|
|
|
use deno_tls::Proxy;
|
2023-05-01 16:42:05 -04:00
|
|
|
|
use deno_tls::RootCertStoreProvider;
|
2024-04-08 17:01:02 -04:00
|
|
|
|
use deno_tls::TlsKey;
|
|
|
|
|
use deno_tls::TlsKeys;
|
refactor(ext/tls): Implement required functionality for later SNI support (#23686)
Precursor to #23236
This implements the SNI features, but uses private symbols to avoid
exposing the functionality at this time. Note that to properly test this
feature, we need to add a way for `connectTls` to specify a hostname.
This is something that should be pushed into that API at a later time as
well.
```ts
Deno.test(
{ permissions: { net: true, read: true } },
async function listenResolver() {
let sniRequests = [];
const listener = Deno.listenTls({
hostname: "localhost",
port: 0,
[resolverSymbol]: (sni: string) => {
sniRequests.push(sni);
return {
cert,
key,
};
},
});
{
const conn = await Deno.connectTls({
hostname: "localhost",
[serverNameSymbol]: "server-1",
port: listener.addr.port,
});
const [_handshake, serverConn] = await Promise.all([
conn.handshake(),
listener.accept(),
]);
conn.close();
serverConn.close();
}
{
const conn = await Deno.connectTls({
hostname: "localhost",
[serverNameSymbol]: "server-2",
port: listener.addr.port,
});
const [_handshake, serverConn] = await Promise.all([
conn.handshake(),
listener.accept(),
]);
conn.close();
serverConn.close();
}
assertEquals(sniRequests, ["server-1", "server-2"]);
listener.close();
},
);
```
---------
Signed-off-by: Matt Mastracci <matthew@mastracci.com>
2024-05-09 12:54:47 -04:00
|
|
|
|
use deno_tls::TlsKeysHolder;
|
2024-07-17 19:37:31 -04:00
|
|
|
|
|
|
|
|
|
use bytes::Bytes;
|
|
|
|
|
use data_url::DataUrl;
|
|
|
|
|
use http::header::HeaderName;
|
|
|
|
|
use http::header::HeaderValue;
|
|
|
|
|
use http::header::ACCEPT;
|
|
|
|
|
use http::header::ACCEPT_ENCODING;
|
2024-07-24 17:22:43 -04:00
|
|
|
|
use http::header::AUTHORIZATION;
|
2024-07-01 20:09:47 -04:00
|
|
|
|
use http::header::CONTENT_LENGTH;
|
2024-07-17 19:37:31 -04:00
|
|
|
|
use http::header::HOST;
|
|
|
|
|
use http::header::PROXY_AUTHORIZATION;
|
|
|
|
|
use http::header::RANGE;
|
|
|
|
|
use http::header::USER_AGENT;
|
2024-08-08 11:47:15 -04:00
|
|
|
|
use http::Extensions;
|
2024-07-17 19:37:31 -04:00
|
|
|
|
use http::Method;
|
2024-07-01 20:09:47 -04:00
|
|
|
|
use http::Uri;
|
2024-07-17 19:37:31 -04:00
|
|
|
|
use http_body_util::BodyExt;
|
|
|
|
|
use hyper::body::Frame;
|
|
|
|
|
use hyper_util::client::legacy::connect::HttpConnector;
|
2024-08-08 11:47:15 -04:00
|
|
|
|
use hyper_util::client::legacy::connect::HttpInfo;
|
2024-07-17 19:37:31 -04:00
|
|
|
|
use hyper_util::rt::TokioExecutor;
|
|
|
|
|
use hyper_util::rt::TokioTimer;
|
2020-09-18 09:20:55 -04:00
|
|
|
|
use serde::Deserialize;
|
2021-04-05 12:40:24 -04:00
|
|
|
|
use serde::Serialize;
|
2024-07-17 19:37:31 -04:00
|
|
|
|
use tower::ServiceExt;
|
|
|
|
|
use tower_http::decompression::Decompression;
|
2020-09-18 09:20:55 -04:00
|
|
|
|
|
2024-07-17 19:37:31 -04:00
|
|
|
|
// Re-export data_url
|
2021-08-16 08:29:54 -04:00
|
|
|
|
pub use data_url;
|
2024-07-24 17:22:43 -04:00
|
|
|
|
pub use proxy::basic_auth;
|
2020-09-18 12:31:30 -04:00
|
|
|
|
|
2021-11-01 00:29:46 -04:00
|
|
|
|
pub use fs_fetch_handler::FsFetchHandler;
|
|
|
|
|
|
2021-11-29 10:29:41 -05:00
|
|
|
|
#[derive(Clone)]
|
2021-11-28 13:07:03 -05:00
|
|
|
|
pub struct Options {
|
|
|
|
|
pub user_agent: String,
|
2023-05-01 16:42:05 -04:00
|
|
|
|
pub root_cert_store_provider: Option<Arc<dyn RootCertStoreProvider>>,
|
2021-11-28 13:07:03 -05:00
|
|
|
|
pub proxy: Option<Proxy>,
|
2024-07-17 19:37:31 -04:00
|
|
|
|
#[allow(clippy::type_complexity)]
|
2023-03-13 06:29:05 -04:00
|
|
|
|
pub request_builder_hook:
|
2024-07-17 19:37:31 -04:00
|
|
|
|
Option<fn(&mut http::Request<ReqBody>) -> Result<(), AnyError>>,
|
2021-11-28 13:07:03 -05:00
|
|
|
|
pub unsafely_ignore_certificate_errors: Option<Vec<String>>,
|
refactor(ext/tls): Implement required functionality for later SNI support (#23686)
Precursor to #23236
This implements the SNI features, but uses private symbols to avoid
exposing the functionality at this time. Note that to properly test this
feature, we need to add a way for `connectTls` to specify a hostname.
This is something that should be pushed into that API at a later time as
well.
```ts
Deno.test(
{ permissions: { net: true, read: true } },
async function listenResolver() {
let sniRequests = [];
const listener = Deno.listenTls({
hostname: "localhost",
port: 0,
[resolverSymbol]: (sni: string) => {
sniRequests.push(sni);
return {
cert,
key,
};
},
});
{
const conn = await Deno.connectTls({
hostname: "localhost",
[serverNameSymbol]: "server-1",
port: listener.addr.port,
});
const [_handshake, serverConn] = await Promise.all([
conn.handshake(),
listener.accept(),
]);
conn.close();
serverConn.close();
}
{
const conn = await Deno.connectTls({
hostname: "localhost",
[serverNameSymbol]: "server-2",
port: listener.addr.port,
});
const [_handshake, serverConn] = await Promise.all([
conn.handshake(),
listener.accept(),
]);
conn.close();
serverConn.close();
}
assertEquals(sniRequests, ["server-1", "server-2"]);
listener.close();
},
);
```
---------
Signed-off-by: Matt Mastracci <matthew@mastracci.com>
2024-05-09 12:54:47 -04:00
|
|
|
|
pub client_cert_chain_and_key: TlsKeys,
|
2021-12-03 08:25:16 -05:00
|
|
|
|
pub file_fetch_handler: Rc<dyn FetchHandler>,
|
2021-11-28 13:07:03 -05:00
|
|
|
|
}
|
|
|
|
|
|
2023-05-01 16:42:05 -04:00
|
|
|
|
impl Options {
|
|
|
|
|
pub fn root_cert_store(&self) -> Result<Option<RootCertStore>, AnyError> {
|
|
|
|
|
Ok(match &self.root_cert_store_provider {
|
|
|
|
|
Some(provider) => Some(provider.get_or_try_init()?.clone()),
|
|
|
|
|
None => None,
|
|
|
|
|
})
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2021-11-28 13:07:03 -05:00
|
|
|
|
impl Default for Options {
|
|
|
|
|
fn default() -> Self {
|
|
|
|
|
Self {
|
|
|
|
|
user_agent: "".to_string(),
|
2023-05-01 16:42:05 -04:00
|
|
|
|
root_cert_store_provider: None,
|
2021-11-28 13:07:03 -05:00
|
|
|
|
proxy: None,
|
|
|
|
|
request_builder_hook: None,
|
|
|
|
|
unsafely_ignore_certificate_errors: None,
|
refactor(ext/tls): Implement required functionality for later SNI support (#23686)
Precursor to #23236
This implements the SNI features, but uses private symbols to avoid
exposing the functionality at this time. Note that to properly test this
feature, we need to add a way for `connectTls` to specify a hostname.
This is something that should be pushed into that API at a later time as
well.
```ts
Deno.test(
{ permissions: { net: true, read: true } },
async function listenResolver() {
let sniRequests = [];
const listener = Deno.listenTls({
hostname: "localhost",
port: 0,
[resolverSymbol]: (sni: string) => {
sniRequests.push(sni);
return {
cert,
key,
};
},
});
{
const conn = await Deno.connectTls({
hostname: "localhost",
[serverNameSymbol]: "server-1",
port: listener.addr.port,
});
const [_handshake, serverConn] = await Promise.all([
conn.handshake(),
listener.accept(),
]);
conn.close();
serverConn.close();
}
{
const conn = await Deno.connectTls({
hostname: "localhost",
[serverNameSymbol]: "server-2",
port: listener.addr.port,
});
const [_handshake, serverConn] = await Promise.all([
conn.handshake(),
listener.accept(),
]);
conn.close();
serverConn.close();
}
assertEquals(sniRequests, ["server-1", "server-2"]);
listener.close();
},
);
```
---------
Signed-off-by: Matt Mastracci <matthew@mastracci.com>
2024-05-09 12:54:47 -04:00
|
|
|
|
client_cert_chain_and_key: TlsKeys::Null,
|
2021-12-03 08:25:16 -05:00
|
|
|
|
file_fetch_handler: Rc::new(DefaultFileFetchHandler),
|
2021-11-28 13:07:03 -05:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2023-03-17 14:22:15 -04:00
|
|
|
|
deno_core::extension!(deno_fetch,
|
|
|
|
|
deps = [ deno_webidl, deno_web, deno_url, deno_console ],
|
|
|
|
|
parameters = [FP: FetchPermissions],
|
|
|
|
|
ops = [
|
|
|
|
|
op_fetch<FP>,
|
|
|
|
|
op_fetch_send,
|
2023-10-31 13:16:27 -04:00
|
|
|
|
op_utf8_to_byte_string,
|
2023-03-17 14:22:15 -04:00
|
|
|
|
op_fetch_custom_client<FP>,
|
|
|
|
|
],
|
|
|
|
|
esm = [
|
|
|
|
|
"20_headers.js",
|
|
|
|
|
"21_formdata.js",
|
|
|
|
|
"22_body.js",
|
|
|
|
|
"22_http_client.js",
|
|
|
|
|
"23_request.js",
|
|
|
|
|
"23_response.js",
|
2023-10-31 13:16:27 -04:00
|
|
|
|
"26_fetch.js",
|
|
|
|
|
"27_eventsource.js"
|
2023-03-17 14:22:15 -04:00
|
|
|
|
],
|
2023-03-17 18:15:27 -04:00
|
|
|
|
options = {
|
2023-03-17 14:22:15 -04:00
|
|
|
|
options: Options,
|
|
|
|
|
},
|
|
|
|
|
state = |state, options| {
|
2023-05-01 16:42:05 -04:00
|
|
|
|
state.put::<Options>(options.options);
|
2023-03-17 14:22:15 -04:00
|
|
|
|
},
|
|
|
|
|
);
|
2020-09-18 09:20:55 -04:00
|
|
|
|
|
2021-11-01 00:29:46 -04:00
|
|
|
|
pub type CancelableResponseFuture =
|
|
|
|
|
Pin<Box<dyn Future<Output = CancelableResponseResult>>>;
|
|
|
|
|
|
2021-11-28 13:07:03 -05:00
|
|
|
|
pub trait FetchHandler: dyn_clone::DynClone {
|
2021-11-01 00:29:46 -04:00
|
|
|
|
// Return the result of the fetch request consisting of a tuple of the
|
|
|
|
|
// cancelable response result, the optional fetch body resource and the
|
|
|
|
|
// optional cancel handle.
|
|
|
|
|
fn fetch_file(
|
2021-12-03 08:25:16 -05:00
|
|
|
|
&self,
|
|
|
|
|
state: &mut OpState,
|
2024-07-17 19:37:31 -04:00
|
|
|
|
url: &Url,
|
2023-08-09 12:47:47 -04:00
|
|
|
|
) -> (CancelableResponseFuture, Option<Rc<CancelHandle>>);
|
2021-11-01 00:29:46 -04:00
|
|
|
|
}
|
|
|
|
|
|
2021-11-28 13:07:03 -05:00
|
|
|
|
dyn_clone::clone_trait_object!(FetchHandler);
|
|
|
|
|
|
2021-11-01 00:29:46 -04:00
|
|
|
|
/// A default implementation which will error for every request.
|
|
|
|
|
#[derive(Clone)]
|
|
|
|
|
pub struct DefaultFileFetchHandler;
|
|
|
|
|
|
|
|
|
|
impl FetchHandler for DefaultFileFetchHandler {
|
|
|
|
|
fn fetch_file(
|
2021-12-03 08:25:16 -05:00
|
|
|
|
&self,
|
|
|
|
|
_state: &mut OpState,
|
2024-07-17 19:37:31 -04:00
|
|
|
|
_url: &Url,
|
2023-08-09 12:47:47 -04:00
|
|
|
|
) -> (CancelableResponseFuture, Option<Rc<CancelHandle>>) {
|
2021-11-01 00:29:46 -04:00
|
|
|
|
let fut = async move {
|
|
|
|
|
Ok(Err(type_error(
|
2024-09-04 03:05:29 -04:00
|
|
|
|
"NetworkError when attempting to fetch resource",
|
2021-11-01 00:29:46 -04:00
|
|
|
|
)))
|
|
|
|
|
};
|
2023-08-09 12:47:47 -04:00
|
|
|
|
(Box::pin(fut), None)
|
2021-11-01 00:29:46 -04:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2022-03-16 20:25:44 -04:00
|
|
|
|
pub fn get_declaration() -> PathBuf {
|
|
|
|
|
PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("lib.deno_fetch.d.ts")
|
|
|
|
|
}
|
2021-04-05 12:40:24 -04:00
|
|
|
|
#[derive(Serialize)]
|
|
|
|
|
#[serde(rename_all = "camelCase")]
|
|
|
|
|
pub struct FetchReturn {
|
2023-05-16 19:20:32 -04:00
|
|
|
|
pub request_rid: ResourceId,
|
|
|
|
|
pub cancel_handle_rid: Option<ResourceId>,
|
2021-04-05 12:40:24 -04:00
|
|
|
|
}
|
|
|
|
|
|
2023-05-01 16:42:05 -04:00
|
|
|
|
pub fn get_or_create_client_from_state(
|
|
|
|
|
state: &mut OpState,
|
2024-07-17 19:37:31 -04:00
|
|
|
|
) -> Result<Client, AnyError> {
|
|
|
|
|
if let Some(client) = state.try_borrow::<Client>() {
|
2023-05-01 16:42:05 -04:00
|
|
|
|
Ok(client.clone())
|
|
|
|
|
} else {
|
|
|
|
|
let options = state.borrow::<Options>();
|
2024-05-05 10:07:21 -04:00
|
|
|
|
let client = create_client_from_options(options)?;
|
2024-07-17 19:37:31 -04:00
|
|
|
|
state.put::<Client>(client.clone());
|
2023-05-01 16:42:05 -04:00
|
|
|
|
Ok(client)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2024-05-05 10:07:21 -04:00
|
|
|
|
pub fn create_client_from_options(
|
|
|
|
|
options: &Options,
|
2024-07-17 19:37:31 -04:00
|
|
|
|
) -> Result<Client, AnyError> {
|
2024-05-05 10:07:21 -04:00
|
|
|
|
create_http_client(
|
|
|
|
|
&options.user_agent,
|
|
|
|
|
CreateHttpClientOptions {
|
|
|
|
|
root_cert_store: options.root_cert_store()?,
|
|
|
|
|
ca_certs: vec![],
|
|
|
|
|
proxy: options.proxy.clone(),
|
|
|
|
|
unsafely_ignore_certificate_errors: options
|
|
|
|
|
.unsafely_ignore_certificate_errors
|
|
|
|
|
.clone(),
|
refactor(ext/tls): Implement required functionality for later SNI support (#23686)
Precursor to #23236
This implements the SNI features, but uses private symbols to avoid
exposing the functionality at this time. Note that to properly test this
feature, we need to add a way for `connectTls` to specify a hostname.
This is something that should be pushed into that API at a later time as
well.
```ts
Deno.test(
{ permissions: { net: true, read: true } },
async function listenResolver() {
let sniRequests = [];
const listener = Deno.listenTls({
hostname: "localhost",
port: 0,
[resolverSymbol]: (sni: string) => {
sniRequests.push(sni);
return {
cert,
key,
};
},
});
{
const conn = await Deno.connectTls({
hostname: "localhost",
[serverNameSymbol]: "server-1",
port: listener.addr.port,
});
const [_handshake, serverConn] = await Promise.all([
conn.handshake(),
listener.accept(),
]);
conn.close();
serverConn.close();
}
{
const conn = await Deno.connectTls({
hostname: "localhost",
[serverNameSymbol]: "server-2",
port: listener.addr.port,
});
const [_handshake, serverConn] = await Promise.all([
conn.handshake(),
listener.accept(),
]);
conn.close();
serverConn.close();
}
assertEquals(sniRequests, ["server-1", "server-2"]);
listener.close();
},
);
```
---------
Signed-off-by: Matt Mastracci <matthew@mastracci.com>
2024-05-09 12:54:47 -04:00
|
|
|
|
client_cert_chain_and_key: options
|
|
|
|
|
.client_cert_chain_and_key
|
|
|
|
|
.clone()
|
|
|
|
|
.try_into()
|
|
|
|
|
.unwrap_or_default(),
|
2024-05-05 10:07:21 -04:00
|
|
|
|
pool_max_idle_per_host: None,
|
|
|
|
|
pool_idle_timeout: None,
|
|
|
|
|
http1: true,
|
|
|
|
|
http2: true,
|
|
|
|
|
},
|
|
|
|
|
)
|
|
|
|
|
}
|
|
|
|
|
|
2023-12-01 10:56:10 -05:00
|
|
|
|
#[allow(clippy::type_complexity)]
|
|
|
|
|
pub struct ResourceToBodyAdapter(
|
|
|
|
|
Rc<dyn Resource>,
|
|
|
|
|
Option<Pin<Box<dyn Future<Output = Result<BufView, Error>>>>>,
|
|
|
|
|
);
|
|
|
|
|
|
|
|
|
|
impl ResourceToBodyAdapter {
|
|
|
|
|
pub fn new(resource: Rc<dyn Resource>) -> Self {
|
|
|
|
|
let future = resource.clone().read(64 * 1024);
|
|
|
|
|
Self(resource, Some(future))
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// SAFETY: we only use this on a single-threaded executor
|
|
|
|
|
unsafe impl Send for ResourceToBodyAdapter {}
|
|
|
|
|
// SAFETY: we only use this on a single-threaded executor
|
|
|
|
|
unsafe impl Sync for ResourceToBodyAdapter {}
|
|
|
|
|
|
|
|
|
|
impl Stream for ResourceToBodyAdapter {
|
2023-12-23 10:58:20 -05:00
|
|
|
|
type Item = Result<Bytes, Error>;
|
2023-12-01 10:56:10 -05:00
|
|
|
|
|
|
|
|
|
fn poll_next(
|
|
|
|
|
self: Pin<&mut Self>,
|
|
|
|
|
cx: &mut Context<'_>,
|
|
|
|
|
) -> Poll<Option<Self::Item>> {
|
|
|
|
|
let this = self.get_mut();
|
|
|
|
|
if let Some(mut fut) = this.1.take() {
|
|
|
|
|
match fut.poll_unpin(cx) {
|
|
|
|
|
Poll::Pending => {
|
|
|
|
|
this.1 = Some(fut);
|
|
|
|
|
Poll::Pending
|
|
|
|
|
}
|
|
|
|
|
Poll::Ready(res) => match res {
|
|
|
|
|
Ok(buf) if buf.is_empty() => Poll::Ready(None),
|
2024-07-17 19:37:31 -04:00
|
|
|
|
Ok(buf) => {
|
2023-12-01 10:56:10 -05:00
|
|
|
|
this.1 = Some(this.0.clone().read(64 * 1024));
|
2024-07-17 19:37:31 -04:00
|
|
|
|
Poll::Ready(Some(Ok(buf.to_vec().into())))
|
2023-12-01 10:56:10 -05:00
|
|
|
|
}
|
2024-07-17 19:37:31 -04:00
|
|
|
|
Err(err) => Poll::Ready(Some(Err(err))),
|
2023-12-01 10:56:10 -05:00
|
|
|
|
},
|
|
|
|
|
}
|
|
|
|
|
} else {
|
|
|
|
|
Poll::Ready(None)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2024-07-17 19:37:31 -04:00
|
|
|
|
impl hyper::body::Body for ResourceToBodyAdapter {
|
|
|
|
|
type Data = Bytes;
|
|
|
|
|
type Error = Error;
|
|
|
|
|
|
|
|
|
|
fn poll_frame(
|
|
|
|
|
self: Pin<&mut Self>,
|
|
|
|
|
cx: &mut Context<'_>,
|
|
|
|
|
) -> Poll<Option<Result<Frame<Self::Data>, Self::Error>>> {
|
|
|
|
|
match self.poll_next(cx) {
|
|
|
|
|
Poll::Ready(Some(res)) => Poll::Ready(Some(res.map(Frame::data))),
|
|
|
|
|
Poll::Ready(None) => Poll::Ready(None),
|
|
|
|
|
Poll::Pending => Poll::Pending,
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2023-12-01 10:56:10 -05:00
|
|
|
|
impl Drop for ResourceToBodyAdapter {
|
|
|
|
|
fn drop(&mut self) {
|
|
|
|
|
self.0.clone().close()
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2024-03-12 13:42:26 -04:00
|
|
|
|
pub trait FetchPermissions {
|
|
|
|
|
fn check_net_url(
|
|
|
|
|
&mut self,
|
2024-09-16 16:39:37 -04:00
|
|
|
|
url: &Url,
|
2024-03-12 13:42:26 -04:00
|
|
|
|
api_name: &str,
|
|
|
|
|
) -> Result<(), AnyError>;
|
2024-09-16 16:39:37 -04:00
|
|
|
|
#[must_use = "the resolved return value to mitigate time-of-check to time-of-use issues"]
|
|
|
|
|
fn check_read<'a>(
|
|
|
|
|
&mut self,
|
|
|
|
|
p: &'a Path,
|
|
|
|
|
api_name: &str,
|
|
|
|
|
) -> Result<Cow<'a, Path>, AnyError>;
|
2024-03-12 13:42:26 -04:00
|
|
|
|
}
|
|
|
|
|
|
2024-06-06 23:37:53 -04:00
|
|
|
|
impl FetchPermissions for deno_permissions::PermissionsContainer {
|
|
|
|
|
#[inline(always)]
|
|
|
|
|
fn check_net_url(
|
|
|
|
|
&mut self,
|
|
|
|
|
url: &Url,
|
|
|
|
|
api_name: &str,
|
|
|
|
|
) -> Result<(), AnyError> {
|
|
|
|
|
deno_permissions::PermissionsContainer::check_net_url(self, url, api_name)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
#[inline(always)]
|
2024-09-16 16:39:37 -04:00
|
|
|
|
fn check_read<'a>(
|
2024-06-06 23:37:53 -04:00
|
|
|
|
&mut self,
|
2024-09-16 16:39:37 -04:00
|
|
|
|
path: &'a Path,
|
2024-06-06 23:37:53 -04:00
|
|
|
|
api_name: &str,
|
2024-09-16 16:39:37 -04:00
|
|
|
|
) -> Result<Cow<'a, Path>, AnyError> {
|
|
|
|
|
deno_permissions::PermissionsContainer::check_read_path(
|
|
|
|
|
self,
|
|
|
|
|
path,
|
|
|
|
|
Some(api_name),
|
|
|
|
|
)
|
2024-06-06 23:37:53 -04:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2023-09-23 08:04:47 -04:00
|
|
|
|
#[op2]
|
|
|
|
|
#[serde]
|
|
|
|
|
#[allow(clippy::too_many_arguments)]
|
2021-11-28 13:07:03 -05:00
|
|
|
|
pub fn op_fetch<FP>(
|
2021-01-10 14:54:29 -05:00
|
|
|
|
state: &mut OpState,
|
2023-09-23 08:04:47 -04:00
|
|
|
|
#[serde] method: ByteString,
|
|
|
|
|
#[string] url: String,
|
|
|
|
|
#[serde] headers: Vec<(ByteString, ByteString)>,
|
|
|
|
|
#[smi] client_rid: Option<u32>,
|
2022-04-23 12:49:06 -04:00
|
|
|
|
has_body: bool,
|
2023-09-23 08:04:47 -04:00
|
|
|
|
#[buffer] data: Option<JsBuffer>,
|
2023-12-01 10:56:10 -05:00
|
|
|
|
#[smi] resource: Option<ResourceId>,
|
2021-04-05 12:40:24 -04:00
|
|
|
|
) -> Result<FetchReturn, AnyError>
|
2020-09-18 09:20:55 -04:00
|
|
|
|
where
|
|
|
|
|
FP: FetchPermissions + 'static,
|
|
|
|
|
{
|
2023-07-28 03:01:06 -04:00
|
|
|
|
let (client, allow_host) = if let Some(rid) = client_rid {
|
2021-08-15 07:29:19 -04:00
|
|
|
|
let r = state.resource_table.get::<HttpClientResource>(rid)?;
|
2023-07-28 03:01:06 -04:00
|
|
|
|
(r.client.clone(), r.allow_host)
|
2020-09-18 09:20:55 -04:00
|
|
|
|
} else {
|
2023-07-28 03:01:06 -04:00
|
|
|
|
(get_or_create_client_from_state(state)?, false)
|
2020-09-18 09:20:55 -04:00
|
|
|
|
};
|
|
|
|
|
|
2022-04-23 12:49:06 -04:00
|
|
|
|
let method = Method::from_bytes(&method)?;
|
2024-07-24 17:22:43 -04:00
|
|
|
|
let mut url = Url::parse(&url)?;
|
2020-09-18 09:20:55 -04:00
|
|
|
|
|
|
|
|
|
// Check scheme before asking for net permission
|
2021-01-07 13:06:08 -05:00
|
|
|
|
let scheme = url.scheme();
|
2023-12-01 10:56:10 -05:00
|
|
|
|
let (request_rid, cancel_handle_rid) = match scheme {
|
2021-11-01 00:29:46 -04:00
|
|
|
|
"file" => {
|
|
|
|
|
let path = url.to_file_path().map_err(|_| {
|
2024-09-04 03:05:29 -04:00
|
|
|
|
type_error("NetworkError when attempting to fetch resource")
|
2021-11-01 00:29:46 -04:00
|
|
|
|
})?;
|
|
|
|
|
let permissions = state.borrow_mut::<FP>();
|
2024-09-16 16:39:37 -04:00
|
|
|
|
let path = permissions.check_read(&path, "fetch()")?;
|
|
|
|
|
let url = match path {
|
|
|
|
|
Cow::Owned(path) => Url::from_file_path(path).unwrap(),
|
|
|
|
|
Cow::Borrowed(_) => url,
|
|
|
|
|
};
|
2021-11-01 00:29:46 -04:00
|
|
|
|
|
|
|
|
|
if method != Method::GET {
|
|
|
|
|
return Err(type_error(format!(
|
2024-09-04 03:05:29 -04:00
|
|
|
|
"Fetching files only supports the GET method: received {method}"
|
2021-11-01 00:29:46 -04:00
|
|
|
|
)));
|
|
|
|
|
}
|
|
|
|
|
|
2021-11-29 10:29:41 -05:00
|
|
|
|
let Options {
|
|
|
|
|
file_fetch_handler, ..
|
|
|
|
|
} = state.borrow_mut::<Options>();
|
2021-12-03 08:25:16 -05:00
|
|
|
|
let file_fetch_handler = file_fetch_handler.clone();
|
2024-07-17 19:37:31 -04:00
|
|
|
|
let (future, maybe_cancel_handle) =
|
|
|
|
|
file_fetch_handler.fetch_file(state, &url);
|
|
|
|
|
let request_rid = state
|
|
|
|
|
.resource_table
|
|
|
|
|
.add(FetchRequestResource { future, url });
|
2021-11-01 00:29:46 -04:00
|
|
|
|
let maybe_cancel_handle_rid = maybe_cancel_handle
|
|
|
|
|
.map(|ch| state.resource_table.add(FetchCancelHandle(ch)));
|
|
|
|
|
|
2023-12-01 10:56:10 -05:00
|
|
|
|
(request_rid, maybe_cancel_handle_rid)
|
2021-11-01 00:29:46 -04:00
|
|
|
|
}
|
2021-04-10 17:38:15 -04:00
|
|
|
|
"http" | "https" => {
|
2021-04-11 22:15:43 -04:00
|
|
|
|
let permissions = state.borrow_mut::<FP>();
|
2022-09-27 16:36:33 -04:00
|
|
|
|
permissions.check_net_url(&url, "fetch()")?;
|
2020-09-18 09:20:55 -04:00
|
|
|
|
|
2024-07-24 17:22:43 -04:00
|
|
|
|
let maybe_authority = extract_authority(&mut url);
|
2024-07-17 19:37:31 -04:00
|
|
|
|
let uri = url
|
|
|
|
|
.as_str()
|
|
|
|
|
.parse::<Uri>()
|
2024-09-04 03:05:29 -04:00
|
|
|
|
.map_err(|_| type_error(format!("Invalid URL {url}")))?;
|
2024-07-13 17:08:23 -04:00
|
|
|
|
|
2024-07-17 19:37:31 -04:00
|
|
|
|
let mut con_len = None;
|
|
|
|
|
let body = if has_body {
|
2023-12-01 10:56:10 -05:00
|
|
|
|
match (data, resource) {
|
|
|
|
|
(Some(data), _) => {
|
2021-04-10 17:38:15 -04:00
|
|
|
|
// If a body is passed, we use it, and don't return a body for streaming.
|
2024-07-17 19:37:31 -04:00
|
|
|
|
con_len = Some(data.len() as u64);
|
|
|
|
|
|
|
|
|
|
http_body_util::Full::new(data.to_vec().into())
|
|
|
|
|
.map_err(|never| match never {})
|
|
|
|
|
.boxed()
|
2021-04-10 17:38:15 -04:00
|
|
|
|
}
|
2023-12-01 10:56:10 -05:00
|
|
|
|
(_, Some(resource)) => {
|
|
|
|
|
let resource = state.resource_table.take_any(resource)?;
|
|
|
|
|
match resource.size_hint() {
|
|
|
|
|
(body_size, Some(n)) if body_size == n && body_size > 0 => {
|
2024-07-17 19:37:31 -04:00
|
|
|
|
con_len = Some(body_size);
|
2023-12-01 10:56:10 -05:00
|
|
|
|
}
|
|
|
|
|
_ => {}
|
|
|
|
|
}
|
2024-07-17 19:37:31 -04:00
|
|
|
|
ReqBody::new(ResourceToBodyAdapter::new(resource))
|
2023-12-01 10:56:10 -05:00
|
|
|
|
}
|
|
|
|
|
(None, None) => unreachable!(),
|
2021-04-10 17:38:15 -04:00
|
|
|
|
}
|
|
|
|
|
} else {
|
2021-11-09 06:10:40 -05:00
|
|
|
|
// POST and PUT requests should always have a 0 length content-length,
|
|
|
|
|
// if there is no body. https://fetch.spec.whatwg.org/#http-network-or-cache-fetch
|
|
|
|
|
if matches!(method, Method::POST | Method::PUT) {
|
2024-07-17 19:37:31 -04:00
|
|
|
|
con_len = Some(0);
|
2021-11-09 06:10:40 -05:00
|
|
|
|
}
|
2024-07-17 19:37:31 -04:00
|
|
|
|
http_body_util::Empty::new()
|
|
|
|
|
.map_err(|never| match never {})
|
|
|
|
|
.boxed()
|
2021-04-10 17:38:15 -04:00
|
|
|
|
};
|
|
|
|
|
|
2024-07-17 19:37:31 -04:00
|
|
|
|
let mut request = http::Request::new(body);
|
|
|
|
|
*request.method_mut() = method.clone();
|
2024-08-08 02:18:33 -04:00
|
|
|
|
*request.uri_mut() = uri.clone();
|
2024-07-17 19:37:31 -04:00
|
|
|
|
|
2024-07-24 17:22:43 -04:00
|
|
|
|
if let Some((username, password)) = maybe_authority {
|
|
|
|
|
request.headers_mut().insert(
|
|
|
|
|
AUTHORIZATION,
|
|
|
|
|
proxy::basic_auth(&username, password.as_deref()),
|
|
|
|
|
);
|
|
|
|
|
}
|
2024-07-17 19:37:31 -04:00
|
|
|
|
if let Some(len) = con_len {
|
|
|
|
|
request.headers_mut().insert(CONTENT_LENGTH, len.into());
|
|
|
|
|
}
|
|
|
|
|
|
2022-04-23 12:49:06 -04:00
|
|
|
|
for (key, value) in headers {
|
2021-09-29 12:42:06 -04:00
|
|
|
|
let name = HeaderName::from_bytes(&key)
|
|
|
|
|
.map_err(|err| type_error(err.to_string()))?;
|
|
|
|
|
let v = HeaderValue::from_bytes(&value)
|
|
|
|
|
.map_err(|err| type_error(err.to_string()))?;
|
2022-10-17 09:39:41 -04:00
|
|
|
|
|
2023-07-28 03:01:06 -04:00
|
|
|
|
if (name != HOST || allow_host) && name != CONTENT_LENGTH {
|
2024-07-17 19:37:31 -04:00
|
|
|
|
request.headers_mut().append(name, v);
|
2021-06-21 23:42:04 -04:00
|
|
|
|
}
|
2021-01-10 14:54:29 -05:00
|
|
|
|
}
|
2021-04-10 17:38:15 -04:00
|
|
|
|
|
2024-07-17 19:37:31 -04:00
|
|
|
|
if request.headers().contains_key(RANGE) {
|
2022-10-17 09:39:41 -04:00
|
|
|
|
// https://fetch.spec.whatwg.org/#http-network-or-cache-fetch step 18
|
|
|
|
|
// If httpRequest’s header list contains `Range`, then append (`Accept-Encoding`, `identity`)
|
2024-07-17 19:37:31 -04:00
|
|
|
|
request
|
|
|
|
|
.headers_mut()
|
2022-10-17 09:39:41 -04:00
|
|
|
|
.insert(ACCEPT_ENCODING, HeaderValue::from_static("identity"));
|
|
|
|
|
}
|
|
|
|
|
|
2021-11-29 10:29:41 -05:00
|
|
|
|
let options = state.borrow::<Options>();
|
|
|
|
|
if let Some(request_builder_hook) = options.request_builder_hook {
|
2024-07-17 19:37:31 -04:00
|
|
|
|
request_builder_hook(&mut request)
|
2023-03-13 06:29:05 -04:00
|
|
|
|
.map_err(|err| type_error(err.to_string()))?;
|
2021-07-27 19:04:08 -04:00
|
|
|
|
}
|
|
|
|
|
|
2021-06-06 09:37:17 -04:00
|
|
|
|
let cancel_handle = CancelHandle::new_rc();
|
|
|
|
|
let cancel_handle_ = cancel_handle.clone();
|
|
|
|
|
|
2024-08-08 02:18:33 -04:00
|
|
|
|
let fut = {
|
|
|
|
|
async move {
|
|
|
|
|
client
|
|
|
|
|
.send(request)
|
|
|
|
|
.map_err(Into::into)
|
|
|
|
|
.or_cancel(cancel_handle_)
|
|
|
|
|
.await
|
|
|
|
|
}
|
|
|
|
|
};
|
2021-04-10 17:38:15 -04:00
|
|
|
|
|
2024-07-17 19:37:31 -04:00
|
|
|
|
let request_rid = state.resource_table.add(FetchRequestResource {
|
|
|
|
|
future: Box::pin(fut),
|
|
|
|
|
url,
|
|
|
|
|
});
|
2021-04-10 17:38:15 -04:00
|
|
|
|
|
2021-06-06 09:37:17 -04:00
|
|
|
|
let cancel_handle_rid =
|
|
|
|
|
state.resource_table.add(FetchCancelHandle(cancel_handle));
|
|
|
|
|
|
2023-12-01 10:56:10 -05:00
|
|
|
|
(request_rid, Some(cancel_handle_rid))
|
2021-01-10 14:54:29 -05:00
|
|
|
|
}
|
2021-04-10 17:38:15 -04:00
|
|
|
|
"data" => {
|
|
|
|
|
let data_url = DataUrl::process(url.as_str())
|
2023-01-27 10:43:16 -05:00
|
|
|
|
.map_err(|e| type_error(format!("{e:?}")))?;
|
2020-09-18 09:20:55 -04:00
|
|
|
|
|
2021-04-10 17:38:15 -04:00
|
|
|
|
let (body, _) = data_url
|
|
|
|
|
.decode_to_vec()
|
2023-01-27 10:43:16 -05:00
|
|
|
|
.map_err(|e| type_error(format!("{e:?}")))?;
|
2024-07-17 19:37:31 -04:00
|
|
|
|
let body = http_body_util::Full::new(body.into())
|
|
|
|
|
.map_err(|never| match never {})
|
|
|
|
|
.boxed();
|
2020-09-18 09:20:55 -04:00
|
|
|
|
|
2024-07-01 20:09:47 -04:00
|
|
|
|
let response = http::Response::builder()
|
|
|
|
|
.status(http::StatusCode::OK)
|
|
|
|
|
.header(http::header::CONTENT_TYPE, data_url.mime_type().to_string())
|
2024-07-17 19:37:31 -04:00
|
|
|
|
.body(body)?;
|
2021-01-10 14:54:29 -05:00
|
|
|
|
|
2024-07-17 19:37:31 -04:00
|
|
|
|
let fut = async move { Ok(Ok(response)) };
|
2021-04-10 17:38:15 -04:00
|
|
|
|
|
2024-07-17 19:37:31 -04:00
|
|
|
|
let request_rid = state.resource_table.add(FetchRequestResource {
|
|
|
|
|
future: Box::pin(fut),
|
|
|
|
|
url,
|
|
|
|
|
});
|
2021-04-11 08:09:10 -04:00
|
|
|
|
|
2023-12-01 10:56:10 -05:00
|
|
|
|
(request_rid, None)
|
2021-04-11 08:09:10 -04:00
|
|
|
|
}
|
|
|
|
|
"blob" => {
|
fix: a `Request` whose URL is a revoked blob URL should still fetch (#11947)
In the spec, a URL record has an associated "blob URL entry", which for
`blob:` URLs is populated during parsing to contain a reference to the
`Blob` object that backs that object URL. It is this blob URL entry that
the `fetch` API uses to resolve an object URL.
Therefore, since the `Request` constructor parses URL inputs, it will
have an associated blob URL entry which will be used when fetching, even
if the object URL has been revoked since the construction of the
`Request` object. (The `Request` constructor takes the URL as a string
and parses it, so the object URL must be live at the time it is called.)
This PR adds a new `blobFromObjectUrl` JS function (backed by a new
`op_blob_from_object_url` op) that, if the URL is a valid object URL,
returns a new `Blob` object whose parts are references to the same Rust
`BlobPart`s used by the original `Blob` object. It uses this function to
add a new `blobUrlEntry` field to inner requests, which will be `null`
or such a `Blob`, and then uses `Blob.prototype.stream()` as the
response's body. As a result of this, the `blob:` URL resolution from
`op_fetch` is now useless, and has been removed.
2021-09-08 05:29:21 -04:00
|
|
|
|
// Blob URL resolution happens in the JS side of fetch. If we got here is
|
|
|
|
|
// because the URL isn't an object URL.
|
|
|
|
|
return Err(type_error("Blob for the given URL not found."));
|
2021-04-10 17:38:15 -04:00
|
|
|
|
}
|
2024-09-04 03:05:29 -04:00
|
|
|
|
_ => {
|
|
|
|
|
return Err(type_error(format!("Url scheme '{scheme}' not supported")))
|
|
|
|
|
}
|
2021-04-10 17:38:15 -04:00
|
|
|
|
};
|
2021-01-10 14:54:29 -05:00
|
|
|
|
|
2021-04-05 12:40:24 -04:00
|
|
|
|
Ok(FetchReturn {
|
|
|
|
|
request_rid,
|
2021-06-06 09:37:17 -04:00
|
|
|
|
cancel_handle_rid,
|
2021-04-05 12:40:24 -04:00
|
|
|
|
})
|
2021-01-10 14:54:29 -05:00
|
|
|
|
}
|
|
|
|
|
|
2023-12-01 10:56:10 -05:00
|
|
|
|
#[derive(Default, Serialize)]
|
2021-03-17 17:33:29 -04:00
|
|
|
|
#[serde(rename_all = "camelCase")]
|
2021-04-05 12:40:24 -04:00
|
|
|
|
pub struct FetchResponse {
|
2023-05-16 19:20:32 -04:00
|
|
|
|
pub status: u16,
|
|
|
|
|
pub status_text: String,
|
|
|
|
|
pub headers: Vec<(ByteString, ByteString)>,
|
|
|
|
|
pub url: String,
|
|
|
|
|
pub response_rid: ResourceId,
|
|
|
|
|
pub content_length: Option<u64>,
|
2023-06-13 08:11:27 -04:00
|
|
|
|
pub remote_addr_ip: Option<String>,
|
|
|
|
|
pub remote_addr_port: Option<u16>,
|
2024-08-08 02:18:33 -04:00
|
|
|
|
/// This field is populated if some error occurred which needs to be
|
|
|
|
|
/// reconstructed in the JS side to set the error _cause_.
|
|
|
|
|
/// In the tuple, the first element is an error message and the second one is
|
|
|
|
|
/// an error cause.
|
|
|
|
|
pub error: Option<(String, String)>,
|
2021-03-17 17:33:29 -04:00
|
|
|
|
}
|
|
|
|
|
|
2023-09-21 10:08:23 -04:00
|
|
|
|
#[op2(async)]
|
|
|
|
|
#[serde]
|
2021-01-10 14:54:29 -05:00
|
|
|
|
pub async fn op_fetch_send(
|
|
|
|
|
state: Rc<RefCell<OpState>>,
|
2023-09-21 10:08:23 -04:00
|
|
|
|
#[smi] rid: ResourceId,
|
2021-04-05 12:40:24 -04:00
|
|
|
|
) -> Result<FetchResponse, AnyError> {
|
2021-01-10 14:54:29 -05:00
|
|
|
|
let request = state
|
|
|
|
|
.borrow_mut()
|
|
|
|
|
.resource_table
|
2021-08-15 07:29:19 -04:00
|
|
|
|
.take::<FetchRequestResource>(rid)?;
|
2021-01-10 14:54:29 -05:00
|
|
|
|
|
|
|
|
|
let request = Rc::try_unwrap(request)
|
|
|
|
|
.ok()
|
|
|
|
|
.expect("multiple op_fetch_send ongoing");
|
|
|
|
|
|
2024-07-17 19:37:31 -04:00
|
|
|
|
let res = match request.future.await {
|
2021-06-06 09:37:17 -04:00
|
|
|
|
Ok(Ok(res)) => res,
|
2023-12-01 10:56:10 -05:00
|
|
|
|
Ok(Err(err)) => {
|
|
|
|
|
// We're going to try and rescue the error cause from a stream and return it from this fetch.
|
2024-07-17 19:37:31 -04:00
|
|
|
|
// If any error in the chain is a hyper body error, return that as a special result we can use to
|
2023-12-01 10:56:10 -05:00
|
|
|
|
// reconstruct an error chain (eg: `new TypeError(..., { cause: new Error(...) })`).
|
|
|
|
|
// TODO(mmastrac): it would be a lot easier if we just passed a v8::Global through here instead
|
|
|
|
|
let mut err_ref: &dyn std::error::Error = err.as_ref();
|
2024-08-08 02:18:33 -04:00
|
|
|
|
while let Some(err_src) = std::error::Error::source(err_ref) {
|
|
|
|
|
if let Some(err_src) = err_src.downcast_ref::<hyper::Error>() {
|
|
|
|
|
if let Some(err_src) = std::error::Error::source(err_src) {
|
2024-07-17 19:37:31 -04:00
|
|
|
|
return Ok(FetchResponse {
|
2024-08-08 02:18:33 -04:00
|
|
|
|
error: Some((err.to_string(), err_src.to_string())),
|
2024-07-17 19:37:31 -04:00
|
|
|
|
..Default::default()
|
|
|
|
|
});
|
2023-12-01 10:56:10 -05:00
|
|
|
|
}
|
|
|
|
|
}
|
2024-08-08 02:18:33 -04:00
|
|
|
|
err_ref = err_src;
|
2023-12-01 10:56:10 -05:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return Err(type_error(err.to_string()));
|
|
|
|
|
}
|
2024-09-04 03:05:29 -04:00
|
|
|
|
Err(_) => return Err(type_error("Request was cancelled")),
|
2020-12-26 08:06:00 -05:00
|
|
|
|
};
|
2020-09-18 09:20:55 -04:00
|
|
|
|
|
|
|
|
|
let status = res.status();
|
2024-07-17 19:37:31 -04:00
|
|
|
|
let url = request.url.into();
|
2020-09-18 09:20:55 -04:00
|
|
|
|
let mut res_headers = Vec::new();
|
|
|
|
|
for (key, val) in res.headers().iter() {
|
2022-04-02 08:37:11 -04:00
|
|
|
|
res_headers.push((key.as_str().into(), val.as_bytes().into()));
|
2020-09-18 09:20:55 -04:00
|
|
|
|
}
|
|
|
|
|
|
2024-07-17 19:37:31 -04:00
|
|
|
|
let content_length = hyper::body::Body::size_hint(res.body()).exact();
|
|
|
|
|
let remote_addr = res
|
|
|
|
|
.extensions()
|
|
|
|
|
.get::<hyper_util::client::legacy::connect::HttpInfo>()
|
|
|
|
|
.map(|info| info.remote_addr());
|
2023-06-13 08:11:27 -04:00
|
|
|
|
let (remote_addr_ip, remote_addr_port) = if let Some(addr) = remote_addr {
|
|
|
|
|
(Some(addr.ip().to_string()), Some(addr.port()))
|
|
|
|
|
} else {
|
|
|
|
|
(None, None)
|
|
|
|
|
};
|
2022-09-26 14:27:50 -04:00
|
|
|
|
|
2023-06-15 09:34:21 -04:00
|
|
|
|
let response_rid = state
|
|
|
|
|
.borrow_mut()
|
|
|
|
|
.resource_table
|
|
|
|
|
.add(FetchResponseResource::new(res, content_length));
|
2020-09-18 09:20:55 -04:00
|
|
|
|
|
2021-04-05 12:40:24 -04:00
|
|
|
|
Ok(FetchResponse {
|
|
|
|
|
status: status.as_u16(),
|
|
|
|
|
status_text: status.canonical_reason().unwrap_or("").to_string(),
|
|
|
|
|
headers: res_headers,
|
|
|
|
|
url,
|
2023-06-13 08:11:27 -04:00
|
|
|
|
response_rid,
|
2022-09-26 14:27:50 -04:00
|
|
|
|
content_length,
|
2023-06-13 08:11:27 -04:00
|
|
|
|
remote_addr_ip,
|
|
|
|
|
remote_addr_port,
|
2023-12-01 10:56:10 -05:00
|
|
|
|
error: None,
|
2021-04-05 12:40:24 -04:00
|
|
|
|
})
|
2021-03-17 17:33:29 -04:00
|
|
|
|
}
|
|
|
|
|
|
2024-07-17 19:37:31 -04:00
|
|
|
|
type CancelableResponseResult =
|
|
|
|
|
Result<Result<http::Response<ResBody>, AnyError>, Canceled>;
|
2021-06-06 09:37:17 -04:00
|
|
|
|
|
2024-07-17 19:37:31 -04:00
|
|
|
|
pub struct FetchRequestResource {
|
|
|
|
|
pub future: Pin<Box<dyn Future<Output = CancelableResponseResult>>>,
|
|
|
|
|
pub url: Url,
|
|
|
|
|
}
|
2021-01-10 14:54:29 -05:00
|
|
|
|
|
|
|
|
|
impl Resource for FetchRequestResource {
|
|
|
|
|
fn name(&self) -> Cow<str> {
|
|
|
|
|
"fetchRequest".into()
|
2020-12-16 11:14:12 -05:00
|
|
|
|
}
|
|
|
|
|
}
|
2020-09-18 09:20:55 -04:00
|
|
|
|
|
2023-05-16 19:20:32 -04:00
|
|
|
|
pub struct FetchCancelHandle(pub Rc<CancelHandle>);
|
2021-06-06 09:37:17 -04:00
|
|
|
|
|
|
|
|
|
impl Resource for FetchCancelHandle {
|
|
|
|
|
fn name(&self) -> Cow<str> {
|
|
|
|
|
"fetchCancelHandle".into()
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
fn close(self: Rc<Self>) {
|
|
|
|
|
self.0.cancel()
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2021-01-10 14:54:29 -05:00
|
|
|
|
type BytesStream =
|
|
|
|
|
Pin<Box<dyn Stream<Item = Result<bytes::Bytes, std::io::Error>> + Unpin>>;
|
|
|
|
|
|
2023-06-15 09:34:21 -04:00
|
|
|
|
pub enum FetchResponseReader {
|
2024-07-17 19:37:31 -04:00
|
|
|
|
Start(http::Response<ResBody>),
|
2023-06-15 09:34:21 -04:00
|
|
|
|
BodyReader(Peekable<BytesStream>),
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
impl Default for FetchResponseReader {
|
|
|
|
|
fn default() -> Self {
|
|
|
|
|
let stream: BytesStream = Box::pin(deno_core::futures::stream::empty());
|
|
|
|
|
Self::BodyReader(stream.peekable())
|
|
|
|
|
}
|
|
|
|
|
}
|
2023-06-13 08:11:27 -04:00
|
|
|
|
#[derive(Debug)]
|
|
|
|
|
pub struct FetchResponseResource {
|
2023-06-15 09:34:21 -04:00
|
|
|
|
pub response_reader: AsyncRefCell<FetchResponseReader>,
|
|
|
|
|
pub cancel: CancelHandle,
|
2023-06-13 08:11:27 -04:00
|
|
|
|
pub size: Option<u64>,
|
|
|
|
|
}
|
|
|
|
|
|
2023-06-15 09:34:21 -04:00
|
|
|
|
impl FetchResponseResource {
|
2024-07-17 19:37:31 -04:00
|
|
|
|
pub fn new(response: http::Response<ResBody>, size: Option<u64>) -> Self {
|
2023-06-15 09:34:21 -04:00
|
|
|
|
Self {
|
|
|
|
|
response_reader: AsyncRefCell::new(FetchResponseReader::Start(response)),
|
|
|
|
|
cancel: CancelHandle::default(),
|
|
|
|
|
size,
|
|
|
|
|
}
|
2023-06-13 08:11:27 -04:00
|
|
|
|
}
|
|
|
|
|
|
2024-07-17 19:37:31 -04:00
|
|
|
|
pub async fn upgrade(self) -> Result<hyper::upgrade::Upgraded, AnyError> {
|
2023-06-15 09:34:21 -04:00
|
|
|
|
let reader = self.response_reader.into_inner();
|
|
|
|
|
match reader {
|
2024-07-17 19:37:31 -04:00
|
|
|
|
FetchResponseReader::Start(resp) => Ok(hyper::upgrade::on(resp).await?),
|
2023-06-15 09:34:21 -04:00
|
|
|
|
_ => unreachable!(),
|
|
|
|
|
}
|
|
|
|
|
}
|
2020-12-16 11:14:12 -05:00
|
|
|
|
}
|
|
|
|
|
|
2023-06-15 09:34:21 -04:00
|
|
|
|
impl Resource for FetchResponseResource {
|
2020-12-16 11:14:12 -05:00
|
|
|
|
fn name(&self) -> Cow<str> {
|
2023-06-15 09:34:21 -04:00
|
|
|
|
"fetchResponse".into()
|
2020-12-16 11:14:12 -05:00
|
|
|
|
}
|
2021-06-06 09:37:17 -04:00
|
|
|
|
|
2022-10-09 10:49:25 -04:00
|
|
|
|
fn read(self: Rc<Self>, limit: usize) -> AsyncResult<BufView> {
|
2021-11-09 13:26:17 -05:00
|
|
|
|
Box::pin(async move {
|
2023-06-15 09:34:21 -04:00
|
|
|
|
let mut reader =
|
|
|
|
|
RcRef::map(&self, |r| &r.response_reader).borrow_mut().await;
|
2022-10-09 10:49:25 -04:00
|
|
|
|
|
2023-06-15 09:34:21 -04:00
|
|
|
|
let body = loop {
|
|
|
|
|
match &mut *reader {
|
|
|
|
|
FetchResponseReader::BodyReader(reader) => break reader,
|
|
|
|
|
FetchResponseReader::Start(_) => {}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
match std::mem::take(&mut *reader) {
|
|
|
|
|
FetchResponseReader::Start(resp) => {
|
2024-07-17 19:37:31 -04:00
|
|
|
|
let stream: BytesStream =
|
|
|
|
|
Box::pin(resp.into_body().into_data_stream().map(|r| {
|
|
|
|
|
r.map_err(|err| {
|
|
|
|
|
std::io::Error::new(std::io::ErrorKind::Other, err)
|
|
|
|
|
})
|
|
|
|
|
}));
|
2023-06-15 09:34:21 -04:00
|
|
|
|
*reader = FetchResponseReader::BodyReader(stream.peekable());
|
|
|
|
|
}
|
|
|
|
|
FetchResponseReader::BodyReader(_) => unreachable!(),
|
|
|
|
|
}
|
|
|
|
|
};
|
2022-10-09 10:49:25 -04:00
|
|
|
|
let fut = async move {
|
2023-06-15 09:34:21 -04:00
|
|
|
|
let mut reader = Pin::new(body);
|
2022-10-09 10:49:25 -04:00
|
|
|
|
loop {
|
|
|
|
|
match reader.as_mut().peek_mut().await {
|
|
|
|
|
Some(Ok(chunk)) if !chunk.is_empty() => {
|
|
|
|
|
let len = min(limit, chunk.len());
|
|
|
|
|
let chunk = chunk.split_to(len);
|
|
|
|
|
break Ok(chunk.into());
|
|
|
|
|
}
|
|
|
|
|
// 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 reader.as_mut().next().await.unwrap() {
|
|
|
|
|
Ok(chunk) => assert!(chunk.is_empty()),
|
2022-10-12 03:23:33 -04:00
|
|
|
|
Err(err) => break Err(type_error(err.to_string())),
|
2022-10-09 10:49:25 -04:00
|
|
|
|
},
|
|
|
|
|
None => break Ok(BufView::empty()),
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
let cancel_handle = RcRef::map(self, |r| &r.cancel);
|
|
|
|
|
fut.try_or_cancel(cancel_handle).await
|
2021-11-09 13:26:17 -05:00
|
|
|
|
})
|
|
|
|
|
}
|
|
|
|
|
|
2022-10-04 09:48:50 -04:00
|
|
|
|
fn size_hint(&self) -> (u64, Option<u64>) {
|
2022-10-24 07:26:41 -04:00
|
|
|
|
(self.size.unwrap_or(0), self.size)
|
2022-10-04 09:48:50 -04:00
|
|
|
|
}
|
|
|
|
|
|
2021-06-06 09:37:17 -04:00
|
|
|
|
fn close(self: Rc<Self>) {
|
|
|
|
|
self.cancel.cancel()
|
|
|
|
|
}
|
2020-09-18 09:20:55 -04:00
|
|
|
|
}
|
|
|
|
|
|
2023-05-16 19:20:32 -04:00
|
|
|
|
pub struct HttpClientResource {
|
|
|
|
|
pub client: Client,
|
2023-07-28 03:01:06 -04:00
|
|
|
|
pub allow_host: bool,
|
2020-09-18 09:20:55 -04:00
|
|
|
|
}
|
|
|
|
|
|
2020-12-16 11:14:12 -05:00
|
|
|
|
impl Resource for HttpClientResource {
|
|
|
|
|
fn name(&self) -> Cow<str> {
|
|
|
|
|
"httpClient".into()
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2020-09-18 09:20:55 -04:00
|
|
|
|
impl HttpClientResource {
|
2023-07-28 03:01:06 -04:00
|
|
|
|
fn new(client: Client, allow_host: bool) -> Self {
|
|
|
|
|
Self { client, allow_host }
|
2020-09-18 09:20:55 -04:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2021-09-30 03:26:15 -04:00
|
|
|
|
#[derive(Deserialize, Debug)]
|
2021-03-17 17:33:29 -04:00
|
|
|
|
#[serde(rename_all = "camelCase")]
|
2023-05-20 21:43:54 -04:00
|
|
|
|
pub struct CreateHttpClientArgs {
|
2021-09-30 03:26:15 -04:00
|
|
|
|
ca_certs: Vec<String>,
|
2021-06-21 23:21:57 -04:00
|
|
|
|
proxy: Option<Proxy>,
|
2023-05-20 21:43:54 -04:00
|
|
|
|
pool_max_idle_per_host: Option<usize>,
|
2023-12-31 07:45:12 -05:00
|
|
|
|
pool_idle_timeout: Option<serde_json::Value>,
|
2023-05-20 21:43:54 -04:00
|
|
|
|
#[serde(default = "default_true")]
|
|
|
|
|
http1: bool,
|
|
|
|
|
#[serde(default = "default_true")]
|
|
|
|
|
http2: bool,
|
2023-07-28 03:01:06 -04:00
|
|
|
|
#[serde(default)]
|
|
|
|
|
allow_host: bool,
|
2023-05-20 21:43:54 -04:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
fn default_true() -> bool {
|
|
|
|
|
true
|
2021-06-21 23:21:57 -04:00
|
|
|
|
}
|
|
|
|
|
|
2023-09-21 10:08:23 -04:00
|
|
|
|
#[op2]
|
|
|
|
|
#[smi]
|
2021-10-31 14:14:22 -04:00
|
|
|
|
pub fn op_fetch_custom_client<FP>(
|
2020-09-18 09:20:55 -04:00
|
|
|
|
state: &mut OpState,
|
2023-09-21 10:08:23 -04:00
|
|
|
|
#[serde] args: CreateHttpClientArgs,
|
refactor(ext/tls): Implement required functionality for later SNI support (#23686)
Precursor to #23236
This implements the SNI features, but uses private symbols to avoid
exposing the functionality at this time. Note that to properly test this
feature, we need to add a way for `connectTls` to specify a hostname.
This is something that should be pushed into that API at a later time as
well.
```ts
Deno.test(
{ permissions: { net: true, read: true } },
async function listenResolver() {
let sniRequests = [];
const listener = Deno.listenTls({
hostname: "localhost",
port: 0,
[resolverSymbol]: (sni: string) => {
sniRequests.push(sni);
return {
cert,
key,
};
},
});
{
const conn = await Deno.connectTls({
hostname: "localhost",
[serverNameSymbol]: "server-1",
port: listener.addr.port,
});
const [_handshake, serverConn] = await Promise.all([
conn.handshake(),
listener.accept(),
]);
conn.close();
serverConn.close();
}
{
const conn = await Deno.connectTls({
hostname: "localhost",
[serverNameSymbol]: "server-2",
port: listener.addr.port,
});
const [_handshake, serverConn] = await Promise.all([
conn.handshake(),
listener.accept(),
]);
conn.close();
serverConn.close();
}
assertEquals(sniRequests, ["server-1", "server-2"]);
listener.close();
},
);
```
---------
Signed-off-by: Matt Mastracci <matthew@mastracci.com>
2024-05-09 12:54:47 -04:00
|
|
|
|
#[cppgc] tls_keys: &TlsKeysHolder,
|
2021-04-05 12:40:24 -04:00
|
|
|
|
) -> Result<ResourceId, AnyError>
|
2020-09-18 09:20:55 -04:00
|
|
|
|
where
|
|
|
|
|
FP: FetchPermissions + 'static,
|
|
|
|
|
{
|
2021-06-21 23:21:57 -04:00
|
|
|
|
if let Some(proxy) = args.proxy.clone() {
|
|
|
|
|
let permissions = state.borrow_mut::<FP>();
|
|
|
|
|
let url = Url::parse(&proxy.url)?;
|
2022-09-27 16:36:33 -04:00
|
|
|
|
permissions.check_net_url(&url, "Deno.createHttpClient()")?;
|
2021-06-21 23:21:57 -04:00
|
|
|
|
}
|
|
|
|
|
|
2021-11-29 10:29:41 -05:00
|
|
|
|
let options = state.borrow::<Options>();
|
2021-09-30 03:26:15 -04:00
|
|
|
|
let ca_certs = args
|
|
|
|
|
.ca_certs
|
|
|
|
|
.into_iter()
|
|
|
|
|
.map(|cert| cert.into_bytes())
|
|
|
|
|
.collect::<Vec<_>>();
|
2021-08-09 10:53:21 -04:00
|
|
|
|
|
2021-03-18 18:54:26 -04:00
|
|
|
|
let client = create_http_client(
|
2023-03-23 18:27:58 -04:00
|
|
|
|
&options.user_agent,
|
2023-05-20 21:43:54 -04:00
|
|
|
|
CreateHttpClientOptions {
|
|
|
|
|
root_cert_store: options.root_cert_store()?,
|
|
|
|
|
ca_certs,
|
|
|
|
|
proxy: args.proxy,
|
|
|
|
|
unsafely_ignore_certificate_errors: options
|
|
|
|
|
.unsafely_ignore_certificate_errors
|
|
|
|
|
.clone(),
|
refactor(ext/tls): Implement required functionality for later SNI support (#23686)
Precursor to #23236
This implements the SNI features, but uses private symbols to avoid
exposing the functionality at this time. Note that to properly test this
feature, we need to add a way for `connectTls` to specify a hostname.
This is something that should be pushed into that API at a later time as
well.
```ts
Deno.test(
{ permissions: { net: true, read: true } },
async function listenResolver() {
let sniRequests = [];
const listener = Deno.listenTls({
hostname: "localhost",
port: 0,
[resolverSymbol]: (sni: string) => {
sniRequests.push(sni);
return {
cert,
key,
};
},
});
{
const conn = await Deno.connectTls({
hostname: "localhost",
[serverNameSymbol]: "server-1",
port: listener.addr.port,
});
const [_handshake, serverConn] = await Promise.all([
conn.handshake(),
listener.accept(),
]);
conn.close();
serverConn.close();
}
{
const conn = await Deno.connectTls({
hostname: "localhost",
[serverNameSymbol]: "server-2",
port: listener.addr.port,
});
const [_handshake, serverConn] = await Promise.all([
conn.handshake(),
listener.accept(),
]);
conn.close();
serverConn.close();
}
assertEquals(sniRequests, ["server-1", "server-2"]);
listener.close();
},
);
```
---------
Signed-off-by: Matt Mastracci <matthew@mastracci.com>
2024-05-09 12:54:47 -04:00
|
|
|
|
client_cert_chain_and_key: tls_keys.take().try_into().unwrap(),
|
2023-05-20 21:43:54 -04:00
|
|
|
|
pool_max_idle_per_host: args.pool_max_idle_per_host,
|
|
|
|
|
pool_idle_timeout: args.pool_idle_timeout.and_then(
|
|
|
|
|
|timeout| match timeout {
|
2023-12-31 07:45:12 -05:00
|
|
|
|
serde_json::Value::Bool(true) => None,
|
|
|
|
|
serde_json::Value::Bool(false) => Some(None),
|
|
|
|
|
serde_json::Value::Number(specify) => {
|
|
|
|
|
Some(Some(specify.as_u64().unwrap_or_default()))
|
|
|
|
|
}
|
|
|
|
|
_ => Some(None),
|
2023-05-20 21:43:54 -04:00
|
|
|
|
},
|
|
|
|
|
),
|
|
|
|
|
http1: args.http1,
|
|
|
|
|
http2: args.http2,
|
|
|
|
|
},
|
2021-08-25 08:25:12 -04:00
|
|
|
|
)?;
|
2020-09-18 09:20:55 -04:00
|
|
|
|
|
2023-07-28 03:01:06 -04:00
|
|
|
|
let rid = state
|
|
|
|
|
.resource_table
|
|
|
|
|
.add(HttpClientResource::new(client, args.allow_host));
|
2021-04-05 12:40:24 -04:00
|
|
|
|
Ok(rid)
|
2020-09-18 09:20:55 -04:00
|
|
|
|
}
|
2021-12-01 11:13:11 -05:00
|
|
|
|
|
2023-05-20 21:43:54 -04:00
|
|
|
|
#[derive(Debug, Clone)]
|
|
|
|
|
pub struct CreateHttpClientOptions {
|
|
|
|
|
pub root_cert_store: Option<RootCertStore>,
|
|
|
|
|
pub ca_certs: Vec<Vec<u8>>,
|
|
|
|
|
pub proxy: Option<Proxy>,
|
|
|
|
|
pub unsafely_ignore_certificate_errors: Option<Vec<String>>,
|
2024-04-08 17:01:02 -04:00
|
|
|
|
pub client_cert_chain_and_key: Option<TlsKey>,
|
2023-05-20 21:43:54 -04:00
|
|
|
|
pub pool_max_idle_per_host: Option<usize>,
|
|
|
|
|
pub pool_idle_timeout: Option<Option<u64>>,
|
|
|
|
|
pub http1: bool,
|
|
|
|
|
pub http2: bool,
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
impl Default for CreateHttpClientOptions {
|
|
|
|
|
fn default() -> Self {
|
|
|
|
|
CreateHttpClientOptions {
|
|
|
|
|
root_cert_store: None,
|
|
|
|
|
ca_certs: vec![],
|
|
|
|
|
proxy: None,
|
|
|
|
|
unsafely_ignore_certificate_errors: None,
|
|
|
|
|
client_cert_chain_and_key: None,
|
|
|
|
|
pool_max_idle_per_host: None,
|
|
|
|
|
pool_idle_timeout: None,
|
|
|
|
|
http1: true,
|
|
|
|
|
http2: true,
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2024-07-17 19:37:31 -04:00
|
|
|
|
/// Create new instance of async Client. This client supports
|
2021-12-01 11:13:11 -05:00
|
|
|
|
/// proxies and doesn't follow redirects.
|
|
|
|
|
pub fn create_http_client(
|
2023-03-23 18:27:58 -04:00
|
|
|
|
user_agent: &str,
|
2023-05-20 21:43:54 -04:00
|
|
|
|
options: CreateHttpClientOptions,
|
2021-12-01 11:13:11 -05:00
|
|
|
|
) -> Result<Client, AnyError> {
|
|
|
|
|
let mut tls_config = deno_tls::create_client_config(
|
2023-05-20 21:43:54 -04:00
|
|
|
|
options.root_cert_store,
|
|
|
|
|
options.ca_certs,
|
|
|
|
|
options.unsafely_ignore_certificate_errors,
|
refactor(ext/tls): Implement required functionality for later SNI support (#23686)
Precursor to #23236
This implements the SNI features, but uses private symbols to avoid
exposing the functionality at this time. Note that to properly test this
feature, we need to add a way for `connectTls` to specify a hostname.
This is something that should be pushed into that API at a later time as
well.
```ts
Deno.test(
{ permissions: { net: true, read: true } },
async function listenResolver() {
let sniRequests = [];
const listener = Deno.listenTls({
hostname: "localhost",
port: 0,
[resolverSymbol]: (sni: string) => {
sniRequests.push(sni);
return {
cert,
key,
};
},
});
{
const conn = await Deno.connectTls({
hostname: "localhost",
[serverNameSymbol]: "server-1",
port: listener.addr.port,
});
const [_handshake, serverConn] = await Promise.all([
conn.handshake(),
listener.accept(),
]);
conn.close();
serverConn.close();
}
{
const conn = await Deno.connectTls({
hostname: "localhost",
[serverNameSymbol]: "server-2",
port: listener.addr.port,
});
const [_handshake, serverConn] = await Promise.all([
conn.handshake(),
listener.accept(),
]);
conn.close();
serverConn.close();
}
assertEquals(sniRequests, ["server-1", "server-2"]);
listener.close();
},
);
```
---------
Signed-off-by: Matt Mastracci <matthew@mastracci.com>
2024-05-09 12:54:47 -04:00
|
|
|
|
options.client_cert_chain_and_key.into(),
|
2023-11-01 17:11:01 -04:00
|
|
|
|
deno_tls::SocketUse::Http,
|
2021-12-01 11:13:11 -05:00
|
|
|
|
)?;
|
|
|
|
|
|
2024-07-24 16:20:06 -04:00
|
|
|
|
// Proxy TLS should not send ALPN
|
|
|
|
|
tls_config.alpn_protocols.clear();
|
|
|
|
|
let proxy_tls_config = Arc::from(tls_config.clone());
|
|
|
|
|
|
2023-05-29 17:05:45 -04:00
|
|
|
|
let mut alpn_protocols = vec![];
|
|
|
|
|
if options.http2 {
|
|
|
|
|
alpn_protocols.push("h2".into());
|
|
|
|
|
}
|
|
|
|
|
if options.http1 {
|
|
|
|
|
alpn_protocols.push("http/1.1".into());
|
|
|
|
|
}
|
|
|
|
|
tls_config.alpn_protocols = alpn_protocols;
|
2024-07-17 19:37:31 -04:00
|
|
|
|
let tls_config = Arc::from(tls_config);
|
|
|
|
|
|
|
|
|
|
let mut http_connector = HttpConnector::new();
|
|
|
|
|
http_connector.enforce_http(false);
|
2021-12-01 11:13:11 -05:00
|
|
|
|
|
2024-09-04 03:05:29 -04:00
|
|
|
|
let user_agent = user_agent.parse::<HeaderValue>().map_err(|_| {
|
|
|
|
|
type_error(format!(
|
|
|
|
|
"Illegal characters in User-Agent: received {user_agent}"
|
|
|
|
|
))
|
|
|
|
|
})?;
|
2021-12-01 11:13:11 -05:00
|
|
|
|
|
2024-07-17 19:37:31 -04:00
|
|
|
|
let mut builder =
|
|
|
|
|
hyper_util::client::legacy::Builder::new(TokioExecutor::new());
|
|
|
|
|
builder.timer(TokioTimer::new());
|
|
|
|
|
builder.pool_timer(TokioTimer::new());
|
|
|
|
|
|
|
|
|
|
let mut proxies = proxy::from_env();
|
2023-05-20 21:43:54 -04:00
|
|
|
|
if let Some(proxy) = options.proxy {
|
2024-07-17 19:37:31 -04:00
|
|
|
|
let mut intercept = proxy::Intercept::all(&proxy.url)
|
|
|
|
|
.ok_or_else(|| type_error("invalid proxy url"))?;
|
2021-12-01 11:13:11 -05:00
|
|
|
|
if let Some(basic_auth) = &proxy.basic_auth {
|
2024-07-17 19:37:31 -04:00
|
|
|
|
intercept.set_auth(&basic_auth.username, &basic_auth.password);
|
2021-12-01 11:13:11 -05:00
|
|
|
|
}
|
2024-07-17 19:37:31 -04:00
|
|
|
|
proxies.prepend(intercept);
|
2021-12-01 11:13:11 -05:00
|
|
|
|
}
|
2024-07-17 19:37:31 -04:00
|
|
|
|
let proxies = Arc::new(proxies);
|
2024-07-24 16:20:06 -04:00
|
|
|
|
let connector = proxy::ProxyConnector {
|
|
|
|
|
http: http_connector,
|
|
|
|
|
proxies: proxies.clone(),
|
|
|
|
|
tls: tls_config,
|
|
|
|
|
tls_proxy: proxy_tls_config,
|
|
|
|
|
user_agent: Some(user_agent.clone()),
|
|
|
|
|
};
|
2021-12-01 11:13:11 -05:00
|
|
|
|
|
2023-05-20 21:43:54 -04:00
|
|
|
|
if let Some(pool_max_idle_per_host) = options.pool_max_idle_per_host {
|
2024-07-17 19:37:31 -04:00
|
|
|
|
builder.pool_max_idle_per_host(pool_max_idle_per_host);
|
2023-05-20 21:43:54 -04:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if let Some(pool_idle_timeout) = options.pool_idle_timeout {
|
2024-07-17 19:37:31 -04:00
|
|
|
|
builder.pool_idle_timeout(
|
2023-05-20 21:43:54 -04:00
|
|
|
|
pool_idle_timeout.map(std::time::Duration::from_millis),
|
|
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
match (options.http1, options.http2) {
|
2024-07-17 19:37:31 -04:00
|
|
|
|
(true, false) => {} // noop, handled by ALPN above
|
|
|
|
|
(false, true) => {
|
|
|
|
|
builder.http2_only(true);
|
|
|
|
|
}
|
2023-05-20 21:43:54 -04:00
|
|
|
|
(true, true) => {}
|
|
|
|
|
(false, false) => {
|
2024-09-04 03:05:29 -04:00
|
|
|
|
return Err(type_error("Cannot create Http Client: either `http1` or `http2` needs to be set to true"))
|
2023-05-20 21:43:54 -04:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2024-07-17 19:37:31 -04:00
|
|
|
|
let pooled_client = builder.build(connector);
|
|
|
|
|
let decompress = Decompression::new(pooled_client).gzip(true).br(true);
|
|
|
|
|
|
|
|
|
|
Ok(Client {
|
|
|
|
|
inner: decompress,
|
|
|
|
|
proxies,
|
|
|
|
|
user_agent,
|
|
|
|
|
})
|
2021-12-01 11:13:11 -05:00
|
|
|
|
}
|
2023-10-31 13:16:27 -04:00
|
|
|
|
|
|
|
|
|
#[op2]
|
|
|
|
|
#[serde]
|
|
|
|
|
pub fn op_utf8_to_byte_string(
|
|
|
|
|
#[string] input: String,
|
|
|
|
|
) -> Result<ByteString, AnyError> {
|
|
|
|
|
Ok(input.into())
|
|
|
|
|
}
|
2024-07-17 19:37:31 -04:00
|
|
|
|
|
|
|
|
|
#[derive(Clone, Debug)]
|
|
|
|
|
pub struct Client {
|
|
|
|
|
inner: Decompression<hyper_util::client::legacy::Client<Connector, ReqBody>>,
|
|
|
|
|
// Used to check whether to include a proxy-authorization header
|
|
|
|
|
proxies: Arc<proxy::Proxies>,
|
|
|
|
|
user_agent: HeaderValue,
|
|
|
|
|
}
|
|
|
|
|
|
2024-07-24 16:20:06 -04:00
|
|
|
|
type Connector = proxy::ProxyConnector<HttpConnector>;
|
2024-07-17 19:37:31 -04:00
|
|
|
|
|
|
|
|
|
// clippy is wrong here
|
|
|
|
|
#[allow(clippy::declare_interior_mutable_const)]
|
|
|
|
|
const STAR_STAR: HeaderValue = HeaderValue::from_static("*/*");
|
|
|
|
|
|
2024-08-08 02:18:33 -04:00
|
|
|
|
#[derive(Debug)]
|
|
|
|
|
pub struct ClientSendError {
|
|
|
|
|
uri: Uri,
|
|
|
|
|
source: hyper_util::client::legacy::Error,
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
impl ClientSendError {
|
|
|
|
|
pub fn is_connect_error(&self) -> bool {
|
|
|
|
|
self.source.is_connect()
|
|
|
|
|
}
|
2024-08-08 11:47:15 -04:00
|
|
|
|
|
|
|
|
|
fn http_info(&self) -> Option<HttpInfo> {
|
|
|
|
|
let mut exts = Extensions::new();
|
|
|
|
|
self.source.connect_info()?.get_extras(&mut exts);
|
|
|
|
|
exts.remove::<HttpInfo>()
|
|
|
|
|
}
|
2024-08-08 02:18:33 -04:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
impl std::fmt::Display for ClientSendError {
|
|
|
|
|
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
|
2024-08-08 11:47:15 -04:00
|
|
|
|
// NOTE: we can use `std::error::Report` instead once it's stabilized.
|
|
|
|
|
let detail = error_reporter::Report::new(&self.source);
|
|
|
|
|
|
|
|
|
|
match self.http_info() {
|
|
|
|
|
Some(http_info) => {
|
|
|
|
|
write!(
|
|
|
|
|
f,
|
|
|
|
|
"error sending request from {src} for {uri} ({dst}): {detail}",
|
|
|
|
|
src = http_info.local_addr(),
|
|
|
|
|
uri = self.uri,
|
|
|
|
|
dst = http_info.remote_addr(),
|
|
|
|
|
detail = detail,
|
|
|
|
|
)
|
|
|
|
|
}
|
|
|
|
|
None => {
|
|
|
|
|
write!(
|
|
|
|
|
f,
|
|
|
|
|
"error sending request for url ({uri}): {detail}",
|
|
|
|
|
uri = self.uri,
|
|
|
|
|
detail = detail,
|
|
|
|
|
)
|
|
|
|
|
}
|
|
|
|
|
}
|
2024-08-08 02:18:33 -04:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
impl std::error::Error for ClientSendError {
|
|
|
|
|
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
|
|
|
|
|
Some(&self.source)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2024-07-17 19:37:31 -04:00
|
|
|
|
impl Client {
|
|
|
|
|
pub async fn send(
|
|
|
|
|
self,
|
|
|
|
|
mut req: http::Request<ReqBody>,
|
2024-08-08 02:18:33 -04:00
|
|
|
|
) -> Result<http::Response<ResBody>, ClientSendError> {
|
2024-07-17 19:37:31 -04:00
|
|
|
|
req
|
|
|
|
|
.headers_mut()
|
|
|
|
|
.entry(USER_AGENT)
|
|
|
|
|
.or_insert_with(|| self.user_agent.clone());
|
|
|
|
|
|
|
|
|
|
req.headers_mut().entry(ACCEPT).or_insert(STAR_STAR);
|
|
|
|
|
|
|
|
|
|
if let Some(auth) = self.proxies.http_forward_auth(req.uri()) {
|
|
|
|
|
req.headers_mut().insert(PROXY_AUTHORIZATION, auth.clone());
|
|
|
|
|
}
|
|
|
|
|
|
2024-08-08 02:18:33 -04:00
|
|
|
|
let uri = req.uri().clone();
|
|
|
|
|
|
|
|
|
|
let resp = self
|
|
|
|
|
.inner
|
|
|
|
|
.oneshot(req)
|
|
|
|
|
.await
|
|
|
|
|
.map_err(|e| ClientSendError { uri, source: e })?;
|
2024-07-17 19:37:31 -04:00
|
|
|
|
Ok(resp.map(|b| b.map_err(|e| anyhow!(e)).boxed()))
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
pub type ReqBody = http_body_util::combinators::BoxBody<Bytes, Error>;
|
|
|
|
|
pub type ResBody = http_body_util::combinators::BoxBody<Bytes, Error>;
|
2024-07-24 17:22:43 -04:00
|
|
|
|
|
|
|
|
|
/// Copied from https://github.com/seanmonstar/reqwest/blob/b9d62a0323d96f11672a61a17bf8849baec00275/src/async_impl/request.rs#L572
|
|
|
|
|
/// Check the request URL for a "username:password" type authority, and if
|
|
|
|
|
/// found, remove it from the URL and return it.
|
|
|
|
|
pub fn extract_authority(url: &mut Url) -> Option<(String, Option<String>)> {
|
|
|
|
|
use percent_encoding::percent_decode;
|
|
|
|
|
|
|
|
|
|
if url.has_authority() {
|
|
|
|
|
let username: String = percent_decode(url.username().as_bytes())
|
|
|
|
|
.decode_utf8()
|
|
|
|
|
.ok()?
|
|
|
|
|
.into();
|
|
|
|
|
let password = url.password().and_then(|pass| {
|
|
|
|
|
percent_decode(pass.as_bytes())
|
|
|
|
|
.decode_utf8()
|
|
|
|
|
.ok()
|
|
|
|
|
.map(String::from)
|
|
|
|
|
});
|
|
|
|
|
if !username.is_empty() || password.is_some() {
|
|
|
|
|
url
|
|
|
|
|
.set_username("")
|
|
|
|
|
.expect("has_authority means set_username shouldn't fail");
|
|
|
|
|
url
|
|
|
|
|
.set_password(None)
|
|
|
|
|
.expect("has_authority means set_password shouldn't fail");
|
|
|
|
|
return Some((username, password));
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
None
|
|
|
|
|
}
|