2023-01-02 16:00:42 -05:00
|
|
|
// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
|
2023-04-22 13:48:21 -04:00
|
|
|
use crate::stream::WebSocketStream;
|
|
|
|
use bytes::Bytes;
|
2023-11-01 17:11:01 -04:00
|
|
|
use deno_core::anyhow::bail;
|
2021-04-26 15:39:55 -04:00
|
|
|
use deno_core::error::invalid_hostname;
|
2022-01-05 11:41:44 -05:00
|
|
|
use deno_core::error::type_error;
|
2021-01-06 10:57:28 -05:00
|
|
|
use deno_core::error::AnyError;
|
2023-11-01 17:11:01 -04:00
|
|
|
use deno_core::futures::TryFutureExt;
|
2023-10-04 17:43:58 -04:00
|
|
|
use deno_core::op2;
|
2023-11-01 17:11:01 -04:00
|
|
|
use deno_core::unsync::spawn;
|
2021-01-06 10:57:28 -05:00
|
|
|
use deno_core::url;
|
2023-06-13 13:16:17 -04:00
|
|
|
use deno_core::AsyncMutFuture;
|
2021-01-06 10:57:28 -05:00
|
|
|
use deno_core::AsyncRefCell;
|
2022-01-05 11:41:44 -05:00
|
|
|
use deno_core::ByteString;
|
2021-01-06 10:57:28 -05:00
|
|
|
use deno_core::CancelHandle;
|
2023-11-01 17:11:01 -04:00
|
|
|
use deno_core::CancelTryFuture;
|
2023-06-22 17:37:56 -04:00
|
|
|
use deno_core::JsBuffer;
|
2021-01-06 10:57:28 -05:00
|
|
|
use deno_core::OpState;
|
|
|
|
use deno_core::RcRef;
|
|
|
|
use deno_core::Resource;
|
2021-03-19 13:25:37 -04:00
|
|
|
use deno_core::ResourceId;
|
2023-06-22 17:37:56 -04:00
|
|
|
use deno_core::ToJsBuffer;
|
2023-04-22 13:48:21 -04:00
|
|
|
use deno_net::raw::NetworkStream;
|
2021-08-07 08:49:38 -04:00
|
|
|
use deno_tls::create_client_config;
|
2023-11-01 17:11:01 -04:00
|
|
|
use deno_tls::rustls::ClientConfig;
|
2023-05-01 16:42:05 -04:00
|
|
|
use deno_tls::RootCertStoreProvider;
|
2023-11-01 17:11:01 -04:00
|
|
|
use deno_tls::SocketUse;
|
2023-12-27 08:38:44 -05:00
|
|
|
use http::header::CONNECTION;
|
|
|
|
use http::header::UPGRADE;
|
|
|
|
use http::HeaderName;
|
|
|
|
use http::HeaderValue;
|
|
|
|
use http::Method;
|
|
|
|
use http::Request;
|
|
|
|
use http::StatusCode;
|
|
|
|
use http::Uri;
|
2023-06-08 06:55:33 -04:00
|
|
|
use once_cell::sync::Lazy;
|
2023-10-31 11:34:45 -04:00
|
|
|
use rustls_tokio_stream::rustls::RootCertStore;
|
|
|
|
use rustls_tokio_stream::rustls::ServerName;
|
|
|
|
use rustls_tokio_stream::TlsStream;
|
2021-04-19 11:54:56 -04:00
|
|
|
use serde::Serialize;
|
2021-01-06 10:57:28 -05:00
|
|
|
use std::borrow::Cow;
|
2023-04-20 12:24:22 -04:00
|
|
|
use std::cell::Cell;
|
2021-01-06 10:57:28 -05:00
|
|
|
use std::cell::RefCell;
|
2021-12-06 18:48:11 -05:00
|
|
|
use std::convert::TryFrom;
|
2021-08-09 18:28:17 -04:00
|
|
|
use std::fmt;
|
2023-04-21 02:55:02 -04:00
|
|
|
use std::future::Future;
|
2023-10-31 11:34:45 -04:00
|
|
|
use std::num::NonZeroUsize;
|
2022-03-16 20:25:44 -04:00
|
|
|
use std::path::PathBuf;
|
2021-01-06 10:57:28 -05:00
|
|
|
use std::rc::Rc;
|
|
|
|
use std::sync::Arc;
|
2023-04-23 16:07:37 -04:00
|
|
|
use tokio::io::AsyncRead;
|
|
|
|
use tokio::io::AsyncWrite;
|
2023-10-30 13:49:19 -04:00
|
|
|
use tokio::io::ReadHalf;
|
|
|
|
use tokio::io::WriteHalf;
|
2021-01-06 10:57:28 -05:00
|
|
|
use tokio::net::TcpStream;
|
|
|
|
|
2023-12-26 15:53:28 -05:00
|
|
|
use fastwebsockets::CloseCode;
|
|
|
|
use fastwebsockets::FragmentCollectorRead;
|
|
|
|
use fastwebsockets::Frame;
|
|
|
|
use fastwebsockets::OpCode;
|
|
|
|
use fastwebsockets::Role;
|
|
|
|
use fastwebsockets::WebSocket;
|
|
|
|
use fastwebsockets::WebSocketWrite;
|
2023-10-30 13:49:19 -04:00
|
|
|
|
2023-04-22 13:48:21 -04:00
|
|
|
mod stream;
|
2023-04-06 09:14:31 -04:00
|
|
|
|
2023-06-08 06:55:33 -04:00
|
|
|
static USE_WRITEV: Lazy<bool> = Lazy::new(|| {
|
|
|
|
let enable = std::env::var("DENO_USE_WRITEV").ok();
|
|
|
|
|
|
|
|
if let Some(val) = enable {
|
|
|
|
return !val.is_empty();
|
|
|
|
}
|
|
|
|
|
|
|
|
false
|
|
|
|
});
|
|
|
|
|
2021-01-06 10:57:28 -05:00
|
|
|
#[derive(Clone)]
|
2023-05-01 16:42:05 -04:00
|
|
|
pub struct WsRootStoreProvider(Option<Arc<dyn RootCertStoreProvider>>);
|
|
|
|
|
|
|
|
impl WsRootStoreProvider {
|
|
|
|
pub fn get_or_try_init(&self) -> Result<Option<RootCertStore>, AnyError> {
|
|
|
|
Ok(match &self.0 {
|
|
|
|
Some(provider) => Some(provider.get_or_try_init()?.clone()),
|
|
|
|
None => None,
|
|
|
|
})
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-01-06 10:57:28 -05:00
|
|
|
#[derive(Clone)]
|
|
|
|
pub struct WsUserAgent(pub String);
|
|
|
|
|
|
|
|
pub trait WebSocketPermissions {
|
2022-09-27 16:36:33 -04:00
|
|
|
fn check_net_url(
|
|
|
|
&mut self,
|
|
|
|
_url: &url::Url,
|
|
|
|
_api_name: &str,
|
|
|
|
) -> Result<(), AnyError>;
|
2021-01-06 10:57:28 -05:00
|
|
|
}
|
|
|
|
|
2021-08-10 07:19:45 -04:00
|
|
|
/// `UnsafelyIgnoreCertificateErrors` is a wrapper struct so it can be placed inside `GothamState`;
|
2021-08-09 10:53:21 -04:00
|
|
|
/// using type alias for a `Option<Vec<String>>` could work, but there's a high chance
|
|
|
|
/// that there might be another type alias pointing to a `Option<Vec<String>>`, which
|
|
|
|
/// would override previously used alias.
|
2021-08-10 07:19:45 -04:00
|
|
|
pub struct UnsafelyIgnoreCertificateErrors(Option<Vec<String>>);
|
2021-08-09 10:53:21 -04:00
|
|
|
|
2021-08-09 18:28:17 -04:00
|
|
|
pub struct WsCancelResource(Rc<CancelHandle>);
|
|
|
|
|
|
|
|
impl Resource for WsCancelResource {
|
|
|
|
fn name(&self) -> Cow<str> {
|
|
|
|
"webSocketCancel".into()
|
|
|
|
}
|
|
|
|
|
|
|
|
fn close(self: Rc<Self>) {
|
|
|
|
self.0.cancel()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-01-06 10:57:28 -05:00
|
|
|
// This op is needed because creating a WS instance in JavaScript is a sync
|
2021-01-10 14:05:24 -05:00
|
|
|
// operation and should throw error when permissions are not fulfilled,
|
2021-01-06 10:57:28 -05:00
|
|
|
// but actual op that connects WS is async.
|
2023-10-04 17:43:58 -04:00
|
|
|
#[op2]
|
|
|
|
#[smi]
|
2021-08-09 18:28:17 -04:00
|
|
|
pub fn op_ws_check_permission_and_cancel_handle<WP>(
|
2021-01-06 10:57:28 -05:00
|
|
|
state: &mut OpState,
|
2023-10-04 17:43:58 -04:00
|
|
|
#[string] api_name: String,
|
|
|
|
#[string] url: String,
|
2021-08-09 18:28:17 -04:00
|
|
|
cancel_handle: bool,
|
|
|
|
) -> Result<Option<ResourceId>, AnyError>
|
2021-01-06 10:57:28 -05:00
|
|
|
where
|
|
|
|
WP: WebSocketPermissions + 'static,
|
|
|
|
{
|
|
|
|
state
|
2021-04-11 22:15:43 -04:00
|
|
|
.borrow_mut::<WP>()
|
2022-09-27 16:36:33 -04:00
|
|
|
.check_net_url(&url::Url::parse(&url)?, &api_name)?;
|
2021-01-06 10:57:28 -05:00
|
|
|
|
2021-08-09 18:28:17 -04:00
|
|
|
if cancel_handle {
|
|
|
|
let rid = state
|
|
|
|
.resource_table
|
|
|
|
.add(WsCancelResource(CancelHandle::new_rc()));
|
|
|
|
Ok(Some(rid))
|
|
|
|
} else {
|
|
|
|
Ok(None)
|
|
|
|
}
|
2021-01-06 10:57:28 -05:00
|
|
|
}
|
|
|
|
|
2021-04-19 11:54:56 -04:00
|
|
|
#[derive(Serialize)]
|
|
|
|
#[serde(rename_all = "camelCase")]
|
|
|
|
pub struct CreateResponse {
|
2021-05-01 14:52:13 -04:00
|
|
|
rid: ResourceId,
|
|
|
|
protocol: String,
|
|
|
|
extensions: String,
|
2021-04-19 11:54:56 -04:00
|
|
|
}
|
|
|
|
|
2023-11-01 17:11:01 -04:00
|
|
|
async fn handshake_websocket(
|
|
|
|
state: &Rc<RefCell<OpState>>,
|
|
|
|
uri: &Uri,
|
|
|
|
protocols: &str,
|
|
|
|
headers: Option<Vec<(ByteString, ByteString)>>,
|
2023-12-27 08:38:44 -05:00
|
|
|
) -> Result<(WebSocket<WebSocketStream>, http::HeaderMap), AnyError> {
|
2023-11-01 17:11:01 -04:00
|
|
|
let mut request = Request::builder().method(Method::GET).uri(
|
|
|
|
uri
|
|
|
|
.path_and_query()
|
|
|
|
.ok_or(type_error("Missing path in url".to_string()))?
|
|
|
|
.as_str(),
|
|
|
|
);
|
|
|
|
|
|
|
|
let authority = uri.authority().unwrap().as_str();
|
|
|
|
let host = authority
|
|
|
|
.find('@')
|
|
|
|
.map(|idx| authority.split_at(idx + 1).1)
|
|
|
|
.unwrap_or_else(|| authority);
|
|
|
|
request = request
|
|
|
|
.header("Host", host)
|
|
|
|
.header(UPGRADE, "websocket")
|
|
|
|
.header(CONNECTION, "Upgrade")
|
|
|
|
.header(
|
|
|
|
"Sec-WebSocket-Key",
|
2023-12-26 15:53:28 -05:00
|
|
|
fastwebsockets::handshake::generate_key(),
|
2023-11-01 17:11:01 -04:00
|
|
|
);
|
|
|
|
|
|
|
|
let user_agent = state.borrow().borrow::<WsUserAgent>().0.clone();
|
|
|
|
request =
|
|
|
|
populate_common_request_headers(request, &user_agent, protocols, &headers)?;
|
|
|
|
|
2023-12-26 05:20:49 -05:00
|
|
|
let request = request.body(http_body_util::Empty::new())?;
|
2023-11-01 17:11:01 -04:00
|
|
|
let domain = &uri.host().unwrap().to_string();
|
|
|
|
let port = &uri.port_u16().unwrap_or(match uri.scheme_str() {
|
|
|
|
Some("wss") => 443,
|
|
|
|
Some("ws") => 80,
|
|
|
|
_ => unreachable!(),
|
|
|
|
});
|
|
|
|
let addr = format!("{domain}:{port}");
|
|
|
|
|
|
|
|
let res = match uri.scheme_str() {
|
|
|
|
Some("ws") => handshake_http1_ws(request, &addr).await?,
|
|
|
|
Some("wss") => {
|
|
|
|
match handshake_http1_wss(state, request, domain, &addr).await {
|
|
|
|
Ok(res) => res,
|
|
|
|
Err(_) => {
|
|
|
|
handshake_http2_wss(
|
|
|
|
state,
|
|
|
|
uri,
|
|
|
|
authority,
|
|
|
|
&user_agent,
|
|
|
|
protocols,
|
|
|
|
domain,
|
|
|
|
&headers,
|
|
|
|
&addr,
|
|
|
|
)
|
|
|
|
.await?
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
_ => unreachable!(),
|
|
|
|
};
|
|
|
|
Ok(res)
|
|
|
|
}
|
|
|
|
|
|
|
|
async fn handshake_http1_ws(
|
2023-12-26 05:20:49 -05:00
|
|
|
request: Request<http_body_util::Empty<Bytes>>,
|
2023-11-01 17:11:01 -04:00
|
|
|
addr: &String,
|
2023-12-27 08:38:44 -05:00
|
|
|
) -> Result<(WebSocket<WebSocketStream>, http::HeaderMap), AnyError> {
|
2023-11-01 17:11:01 -04:00
|
|
|
let tcp_socket = TcpStream::connect(addr).await?;
|
|
|
|
handshake_connection(request, tcp_socket).await
|
|
|
|
}
|
2023-04-23 16:07:37 -04:00
|
|
|
|
2023-11-01 17:11:01 -04:00
|
|
|
async fn handshake_http1_wss(
|
|
|
|
state: &Rc<RefCell<OpState>>,
|
2023-12-26 05:20:49 -05:00
|
|
|
request: Request<http_body_util::Empty<Bytes>>,
|
2023-11-01 17:11:01 -04:00
|
|
|
domain: &str,
|
|
|
|
addr: &str,
|
2023-12-27 08:38:44 -05:00
|
|
|
) -> Result<(WebSocket<WebSocketStream>, http::HeaderMap), AnyError> {
|
2023-11-01 17:11:01 -04:00
|
|
|
let tcp_socket = TcpStream::connect(addr).await?;
|
|
|
|
let tls_config = create_ws_client_config(state, SocketUse::Http1Only)?;
|
|
|
|
let dnsname =
|
|
|
|
ServerName::try_from(domain).map_err(|_| invalid_hostname(domain))?;
|
|
|
|
let mut tls_connector = TlsStream::new_client_side(
|
|
|
|
tcp_socket,
|
|
|
|
tls_config.into(),
|
|
|
|
dnsname,
|
|
|
|
NonZeroUsize::new(65536),
|
|
|
|
);
|
|
|
|
// If we can bail on an http/1.1 ALPN mismatch here, we can avoid doing extra work
|
|
|
|
tls_connector.handshake().await?;
|
|
|
|
handshake_connection(request, tls_connector).await
|
|
|
|
}
|
|
|
|
|
|
|
|
#[allow(clippy::too_many_arguments)]
|
|
|
|
async fn handshake_http2_wss(
|
|
|
|
state: &Rc<RefCell<OpState>>,
|
|
|
|
uri: &Uri,
|
|
|
|
authority: &str,
|
|
|
|
user_agent: &str,
|
|
|
|
protocols: &str,
|
|
|
|
domain: &str,
|
|
|
|
headers: &Option<Vec<(ByteString, ByteString)>>,
|
|
|
|
addr: &str,
|
2023-12-27 08:38:44 -05:00
|
|
|
) -> Result<(WebSocket<WebSocketStream>, http::HeaderMap), AnyError> {
|
2023-11-01 17:11:01 -04:00
|
|
|
let tcp_socket = TcpStream::connect(addr).await?;
|
|
|
|
let tls_config = create_ws_client_config(state, SocketUse::Http2Only)?;
|
|
|
|
let dnsname =
|
|
|
|
ServerName::try_from(domain).map_err(|_| invalid_hostname(domain))?;
|
|
|
|
// We need to better expose the underlying errors here
|
|
|
|
let mut tls_connector =
|
|
|
|
TlsStream::new_client_side(tcp_socket, tls_config.into(), dnsname, None);
|
|
|
|
let handshake = tls_connector.handshake().await?;
|
|
|
|
if handshake.alpn.is_none() {
|
|
|
|
bail!("Didn't receive h2 alpn, aborting connection");
|
|
|
|
}
|
2023-12-27 08:38:44 -05:00
|
|
|
let h2 = h2::client::Builder::new();
|
2023-11-01 17:11:01 -04:00
|
|
|
let (mut send, conn) = h2.handshake::<_, Bytes>(tls_connector).await?;
|
|
|
|
spawn(conn);
|
|
|
|
let mut request = Request::builder();
|
|
|
|
request = request.method(Method::CONNECT);
|
|
|
|
let uri = Uri::builder()
|
|
|
|
.authority(authority)
|
|
|
|
.path_and_query(uri.path_and_query().unwrap().as_str())
|
|
|
|
.scheme("https")
|
|
|
|
.build()?;
|
|
|
|
request = request.uri(uri);
|
|
|
|
request =
|
|
|
|
populate_common_request_headers(request, user_agent, protocols, headers)?;
|
2023-12-27 08:38:44 -05:00
|
|
|
request = request.extension(h2::ext::Protocol::from("websocket"));
|
2023-11-01 17:11:01 -04:00
|
|
|
let (resp, send) = send.send_request(request.body(())?, false)?;
|
|
|
|
let resp = resp.await?;
|
|
|
|
if resp.status() != StatusCode::OK {
|
|
|
|
bail!("Invalid status code: {}", resp.status());
|
2023-04-23 16:07:37 -04:00
|
|
|
}
|
2023-12-27 08:38:44 -05:00
|
|
|
let (http::response::Parts { headers, .. }, recv) = resp.into_parts();
|
2023-11-01 17:11:01 -04:00
|
|
|
let mut stream = WebSocket::after_handshake(
|
|
|
|
WebSocketStream::new(stream::WsStreamKind::H2(send, recv), None),
|
|
|
|
Role::Client,
|
|
|
|
);
|
|
|
|
// We currently don't support vectored writes in the H2 streams
|
|
|
|
stream.set_writev(false);
|
|
|
|
// TODO(mmastrac): we should be able to use a zero masking key over HTTPS
|
|
|
|
// stream.set_auto_apply_mask(false);
|
|
|
|
Ok((stream, headers))
|
|
|
|
}
|
|
|
|
|
|
|
|
async fn handshake_connection<
|
|
|
|
S: AsyncRead + AsyncWrite + Send + Unpin + 'static,
|
|
|
|
>(
|
2023-12-26 05:20:49 -05:00
|
|
|
request: Request<http_body_util::Empty<Bytes>>,
|
2023-11-01 17:11:01 -04:00
|
|
|
socket: S,
|
2023-12-27 08:38:44 -05:00
|
|
|
) -> Result<(WebSocket<WebSocketStream>, http::HeaderMap), AnyError> {
|
2023-11-01 17:11:01 -04:00
|
|
|
let (upgraded, response) =
|
2023-12-26 15:53:28 -05:00
|
|
|
fastwebsockets::handshake::client(&LocalExecutor, request, socket).await?;
|
2023-04-23 16:07:37 -04:00
|
|
|
|
|
|
|
let upgraded = upgraded.into_inner();
|
|
|
|
let stream =
|
|
|
|
WebSocketStream::new(stream::WsStreamKind::Upgraded(upgraded), None);
|
|
|
|
let stream = WebSocket::after_handshake(stream, Role::Client);
|
|
|
|
|
2023-11-01 17:11:01 -04:00
|
|
|
Ok((stream, response.into_parts().0.headers))
|
2023-04-23 16:07:37 -04:00
|
|
|
}
|
|
|
|
|
2023-11-01 17:11:01 -04:00
|
|
|
pub fn create_ws_client_config(
|
|
|
|
state: &Rc<RefCell<OpState>>,
|
|
|
|
socket_use: SocketUse,
|
|
|
|
) -> Result<ClientConfig, AnyError> {
|
|
|
|
let unsafely_ignore_certificate_errors: Option<Vec<String>> = state
|
2021-08-09 10:53:21 -04:00
|
|
|
.borrow()
|
2021-09-22 05:12:08 -04:00
|
|
|
.try_borrow::<UnsafelyIgnoreCertificateErrors>()
|
|
|
|
.and_then(|it| it.0.clone());
|
2023-05-01 16:42:05 -04:00
|
|
|
let root_cert_store = state
|
|
|
|
.borrow()
|
|
|
|
.borrow::<WsRootStoreProvider>()
|
|
|
|
.get_or_try_init()?;
|
2021-01-06 10:57:28 -05:00
|
|
|
|
2023-11-01 17:11:01 -04:00
|
|
|
create_client_config(
|
|
|
|
root_cert_store,
|
|
|
|
vec![],
|
|
|
|
unsafely_ignore_certificate_errors,
|
|
|
|
None,
|
|
|
|
socket_use,
|
|
|
|
)
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Headers common to both http/1.1 and h2 requests.
|
|
|
|
fn populate_common_request_headers(
|
2023-12-27 08:38:44 -05:00
|
|
|
mut request: http::request::Builder,
|
2023-11-01 17:11:01 -04:00
|
|
|
user_agent: &str,
|
|
|
|
protocols: &str,
|
|
|
|
headers: &Option<Vec<(ByteString, ByteString)>>,
|
2023-12-27 08:38:44 -05:00
|
|
|
) -> Result<http::request::Builder, AnyError> {
|
2023-04-20 12:24:22 -04:00
|
|
|
request = request
|
|
|
|
.header("User-Agent", user_agent)
|
|
|
|
.header("Sec-WebSocket-Version", "13");
|
2021-01-06 10:57:28 -05:00
|
|
|
|
2022-04-04 05:49:50 -04:00
|
|
|
if !protocols.is_empty() {
|
|
|
|
request = request.header("Sec-WebSocket-Protocol", protocols);
|
2021-01-06 10:57:28 -05:00
|
|
|
}
|
|
|
|
|
2022-04-04 05:49:50 -04:00
|
|
|
if let Some(headers) = headers {
|
2022-01-05 11:41:44 -05:00
|
|
|
for (key, value) in headers {
|
2023-11-01 17:11:01 -04:00
|
|
|
let name = HeaderName::from_bytes(key)
|
2022-01-05 11:41:44 -05:00
|
|
|
.map_err(|err| type_error(err.to_string()))?;
|
2023-11-01 17:11:01 -04:00
|
|
|
let v = HeaderValue::from_bytes(value)
|
2022-01-05 11:41:44 -05:00
|
|
|
.map_err(|err| type_error(err.to_string()))?;
|
|
|
|
|
|
|
|
let is_disallowed_header = matches!(
|
|
|
|
name,
|
2023-12-27 08:38:44 -05:00
|
|
|
http::header::HOST
|
|
|
|
| http::header::SEC_WEBSOCKET_ACCEPT
|
|
|
|
| http::header::SEC_WEBSOCKET_EXTENSIONS
|
|
|
|
| http::header::SEC_WEBSOCKET_KEY
|
|
|
|
| http::header::SEC_WEBSOCKET_PROTOCOL
|
|
|
|
| http::header::SEC_WEBSOCKET_VERSION
|
|
|
|
| http::header::UPGRADE
|
|
|
|
| http::header::CONNECTION
|
2022-01-05 11:41:44 -05:00
|
|
|
);
|
|
|
|
if !is_disallowed_header {
|
|
|
|
request = request.header(name, v);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2023-11-01 17:11:01 -04:00
|
|
|
Ok(request)
|
|
|
|
}
|
2022-01-05 11:41:44 -05:00
|
|
|
|
2023-11-01 17:11:01 -04:00
|
|
|
#[op2(async)]
|
|
|
|
#[serde]
|
|
|
|
pub async fn op_ws_create<WP>(
|
|
|
|
state: Rc<RefCell<OpState>>,
|
|
|
|
#[string] api_name: String,
|
|
|
|
#[string] url: String,
|
|
|
|
#[string] protocols: String,
|
|
|
|
#[smi] cancel_handle: Option<ResourceId>,
|
|
|
|
#[serde] headers: Option<Vec<(ByteString, ByteString)>>,
|
|
|
|
) -> Result<CreateResponse, AnyError>
|
|
|
|
where
|
|
|
|
WP: WebSocketPermissions + 'static,
|
|
|
|
{
|
|
|
|
{
|
|
|
|
let mut s = state.borrow_mut();
|
|
|
|
s.borrow_mut::<WP>()
|
|
|
|
.check_net_url(&url::Url::parse(&url)?, &api_name)
|
|
|
|
.expect(
|
|
|
|
"Permission check should have been done in op_ws_check_permission",
|
2023-10-31 11:34:45 -04:00
|
|
|
);
|
2023-11-01 17:11:01 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
let cancel_resource = if let Some(cancel_rid) = cancel_handle {
|
|
|
|
let r = state
|
|
|
|
.borrow_mut()
|
|
|
|
.resource_table
|
|
|
|
.get::<WsCancelResource>(cancel_rid)?;
|
|
|
|
Some(r.0.clone())
|
|
|
|
} else {
|
|
|
|
None
|
2021-01-06 10:57:28 -05:00
|
|
|
};
|
|
|
|
|
2023-11-01 17:11:01 -04:00
|
|
|
let uri: Uri = url.parse()?;
|
|
|
|
|
|
|
|
let handshake = handshake_websocket(&state, &uri, &protocols, headers)
|
|
|
|
.map_err(|err| {
|
|
|
|
AnyError::from(DomExceptionNetworkError::new(&format!(
|
|
|
|
"failed to connect to WebSocket: {err}"
|
|
|
|
)))
|
|
|
|
});
|
|
|
|
let (stream, response) = match cancel_resource {
|
|
|
|
Some(rc) => handshake.try_or_cancel(rc).await,
|
|
|
|
None => handshake.await,
|
|
|
|
}?;
|
|
|
|
|
2022-04-04 05:49:50 -04:00
|
|
|
if let Some(cancel_rid) = cancel_handle {
|
2023-09-13 18:01:31 -04:00
|
|
|
if let Ok(res) = state.borrow_mut().resource_table.take_any(cancel_rid) {
|
|
|
|
res.close();
|
|
|
|
}
|
2021-08-09 18:28:17 -04:00
|
|
|
}
|
|
|
|
|
2021-01-06 10:57:28 -05:00
|
|
|
let mut state = state.borrow_mut();
|
2023-06-08 11:32:08 -04:00
|
|
|
let rid = state.resource_table.add(ServerWebSocket::new(stream));
|
2021-01-06 10:57:28 -05:00
|
|
|
|
2023-11-01 17:11:01 -04:00
|
|
|
let protocol = match response.get("Sec-WebSocket-Protocol") {
|
2021-01-06 10:57:28 -05:00
|
|
|
Some(header) => header.to_str().unwrap(),
|
|
|
|
None => "",
|
|
|
|
};
|
|
|
|
let extensions = response
|
|
|
|
.get_all("Sec-WebSocket-Extensions")
|
|
|
|
.iter()
|
|
|
|
.map(|header| header.to_str().unwrap())
|
|
|
|
.collect::<String>();
|
2021-04-19 11:54:56 -04:00
|
|
|
Ok(CreateResponse {
|
2021-05-01 14:52:13 -04:00
|
|
|
rid,
|
|
|
|
protocol: protocol.to_string(),
|
|
|
|
extensions,
|
2021-04-19 11:54:56 -04:00
|
|
|
})
|
2021-01-06 10:57:28 -05:00
|
|
|
}
|
|
|
|
|
2023-04-20 12:24:22 -04:00
|
|
|
#[repr(u16)]
|
|
|
|
pub enum MessageKind {
|
|
|
|
Text = 0,
|
|
|
|
Binary = 1,
|
|
|
|
Pong = 2,
|
2023-04-26 06:07:38 -04:00
|
|
|
Error = 3,
|
2023-06-08 11:32:08 -04:00
|
|
|
ClosedDefault = 1005,
|
2023-04-20 12:24:22 -04:00
|
|
|
}
|
|
|
|
|
2023-06-08 11:32:08 -04:00
|
|
|
/// To avoid locks, we keep as much as we can inside of [`Cell`]s.
|
2023-04-20 12:24:22 -04:00
|
|
|
pub struct ServerWebSocket {
|
2023-06-06 09:58:18 -04:00
|
|
|
buffered: Cell<usize>,
|
2023-06-08 11:32:08 -04:00
|
|
|
error: Cell<Option<String>>,
|
|
|
|
errored: Cell<bool>,
|
2023-06-06 09:58:18 -04:00
|
|
|
closed: Cell<bool>,
|
2023-06-08 11:32:08 -04:00
|
|
|
buffer: Cell<Option<Vec<u8>>>,
|
2023-06-08 14:29:26 -04:00
|
|
|
string: Cell<Option<String>>,
|
2023-10-30 13:49:19 -04:00
|
|
|
ws_read: AsyncRefCell<FragmentCollectorRead<ReadHalf<WebSocketStream>>>,
|
|
|
|
ws_write: AsyncRefCell<WebSocketWrite<WriteHalf<WebSocketStream>>>,
|
2023-04-20 12:24:22 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
impl ServerWebSocket {
|
2023-06-08 11:32:08 -04:00
|
|
|
fn new(ws: WebSocket<WebSocketStream>) -> Self {
|
2023-10-30 13:49:19 -04:00
|
|
|
let (ws_read, ws_write) = ws.split(tokio::io::split);
|
2023-06-08 11:32:08 -04:00
|
|
|
Self {
|
|
|
|
buffered: Cell::new(0),
|
|
|
|
error: Cell::new(None),
|
|
|
|
errored: Cell::new(false),
|
|
|
|
closed: Cell::new(false),
|
|
|
|
buffer: Cell::new(None),
|
2023-06-08 14:29:26 -04:00
|
|
|
string: Cell::new(None),
|
2023-10-30 13:49:19 -04:00
|
|
|
ws_read: AsyncRefCell::new(FragmentCollectorRead::new(ws_read)),
|
|
|
|
ws_write: AsyncRefCell::new(ws_write),
|
2023-06-08 11:32:08 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn set_error(&self, error: Option<String>) {
|
|
|
|
if let Some(error) = error {
|
|
|
|
self.error.set(Some(error));
|
|
|
|
self.errored.set(true);
|
|
|
|
} else {
|
|
|
|
self.error.set(None);
|
|
|
|
self.errored.set(false);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-06-13 13:16:17 -04:00
|
|
|
/// Reserve a lock, but don't wait on it. This gets us our place in line.
|
2023-10-30 13:49:19 -04:00
|
|
|
fn reserve_lock(
|
|
|
|
self: &Rc<Self>,
|
|
|
|
) -> AsyncMutFuture<WebSocketWrite<WriteHalf<WebSocketStream>>> {
|
|
|
|
RcRef::map(self, |r| &r.ws_write).borrow_mut()
|
2023-06-13 13:16:17 -04:00
|
|
|
}
|
|
|
|
|
2023-04-20 12:24:22 -04:00
|
|
|
#[inline]
|
2023-10-30 13:49:19 -04:00
|
|
|
async fn write_frame(
|
2023-06-06 09:58:18 -04:00
|
|
|
self: &Rc<Self>,
|
2023-10-30 13:49:19 -04:00
|
|
|
lock: AsyncMutFuture<WebSocketWrite<WriteHalf<WebSocketStream>>>,
|
2023-08-10 00:29:06 -04:00
|
|
|
frame: Frame<'_>,
|
2023-04-20 12:24:22 -04:00
|
|
|
) -> Result<(), AnyError> {
|
2023-10-30 13:49:19 -04:00
|
|
|
let mut ws = lock.await;
|
|
|
|
if ws.is_closed() {
|
|
|
|
return Ok(());
|
|
|
|
}
|
2023-04-20 12:24:22 -04:00
|
|
|
ws.write_frame(frame)
|
|
|
|
.await
|
|
|
|
.map_err(|err| type_error(err.to_string()))?;
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Resource for ServerWebSocket {
|
|
|
|
fn name(&self) -> Cow<str> {
|
|
|
|
"serverWebSocket".into()
|
|
|
|
}
|
|
|
|
}
|
2023-04-22 13:48:21 -04:00
|
|
|
|
|
|
|
pub fn ws_create_server_stream(
|
|
|
|
state: &mut OpState,
|
|
|
|
transport: NetworkStream,
|
|
|
|
read_buf: Bytes,
|
2023-04-20 12:24:22 -04:00
|
|
|
) -> Result<ResourceId, AnyError> {
|
2023-04-22 13:48:21 -04:00
|
|
|
let mut ws = WebSocket::after_handshake(
|
|
|
|
WebSocketStream::new(
|
|
|
|
stream::WsStreamKind::Network(transport),
|
|
|
|
Some(read_buf),
|
|
|
|
),
|
|
|
|
Role::Server,
|
|
|
|
);
|
2023-06-08 06:55:33 -04:00
|
|
|
ws.set_writev(*USE_WRITEV);
|
2023-04-20 12:24:22 -04:00
|
|
|
ws.set_auto_close(true);
|
|
|
|
ws.set_auto_pong(true);
|
2023-10-30 13:49:19 -04:00
|
|
|
|
2023-06-08 11:32:08 -04:00
|
|
|
let rid = state.resource_table.add(ServerWebSocket::new(ws));
|
2023-04-20 12:24:22 -04:00
|
|
|
Ok(rid)
|
2021-01-06 10:57:28 -05:00
|
|
|
}
|
|
|
|
|
2023-10-04 17:43:58 -04:00
|
|
|
fn send_binary(state: &mut OpState, rid: ResourceId, data: &[u8]) {
|
2023-06-06 09:58:18 -04:00
|
|
|
let resource = state.resource_table.get::<ServerWebSocket>(rid).unwrap();
|
|
|
|
let data = data.to_vec();
|
|
|
|
let len = data.len();
|
|
|
|
resource.buffered.set(resource.buffered.get() + len);
|
2023-06-13 13:16:17 -04:00
|
|
|
let lock = resource.reserve_lock();
|
2023-08-23 19:03:05 -04:00
|
|
|
deno_core::unsync::spawn(async move {
|
2023-06-06 09:58:18 -04:00
|
|
|
if let Err(err) = resource
|
2023-08-10 00:29:06 -04:00
|
|
|
.write_frame(lock, Frame::new(true, OpCode::Binary, None, data.into()))
|
2023-06-06 09:58:18 -04:00
|
|
|
.await
|
|
|
|
{
|
2023-06-08 11:32:08 -04:00
|
|
|
resource.set_error(Some(err.to_string()));
|
2023-06-06 09:58:18 -04:00
|
|
|
} else {
|
|
|
|
resource.buffered.set(resource.buffered.get() - len);
|
|
|
|
}
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2023-10-04 17:43:58 -04:00
|
|
|
#[op2(fast)]
|
|
|
|
pub fn op_ws_send_binary(
|
|
|
|
state: &mut OpState,
|
|
|
|
#[smi] rid: ResourceId,
|
|
|
|
#[anybuffer] data: &[u8],
|
|
|
|
) {
|
|
|
|
send_binary(state, rid, data)
|
|
|
|
}
|
|
|
|
|
|
|
|
#[op2(fast)]
|
|
|
|
pub fn op_ws_send_binary_ab(
|
|
|
|
state: &mut OpState,
|
|
|
|
#[smi] rid: ResourceId,
|
|
|
|
#[arraybuffer] data: &[u8],
|
|
|
|
) {
|
|
|
|
send_binary(state, rid, data)
|
|
|
|
}
|
|
|
|
|
|
|
|
#[op2(fast)]
|
|
|
|
pub fn op_ws_send_text(
|
|
|
|
state: &mut OpState,
|
|
|
|
#[smi] rid: ResourceId,
|
|
|
|
#[string] data: String,
|
|
|
|
) {
|
2023-06-06 09:58:18 -04:00
|
|
|
let resource = state.resource_table.get::<ServerWebSocket>(rid).unwrap();
|
|
|
|
let len = data.len();
|
|
|
|
resource.buffered.set(resource.buffered.get() + len);
|
2023-06-13 13:16:17 -04:00
|
|
|
let lock = resource.reserve_lock();
|
2023-08-23 19:03:05 -04:00
|
|
|
deno_core::unsync::spawn(async move {
|
2023-06-06 09:58:18 -04:00
|
|
|
if let Err(err) = resource
|
2023-06-13 13:16:17 -04:00
|
|
|
.write_frame(
|
|
|
|
lock,
|
2023-08-10 00:29:06 -04:00
|
|
|
Frame::new(true, OpCode::Text, None, data.into_bytes().into()),
|
2023-06-13 13:16:17 -04:00
|
|
|
)
|
2023-06-06 09:58:18 -04:00
|
|
|
.await
|
|
|
|
{
|
2023-06-08 11:32:08 -04:00
|
|
|
resource.set_error(Some(err.to_string()));
|
2023-06-06 09:58:18 -04:00
|
|
|
} else {
|
|
|
|
resource.buffered.set(resource.buffered.get() - len);
|
|
|
|
}
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Async version of send. Does not update buffered amount as we rely on the socket itself for backpressure.
|
2023-10-25 07:43:38 -04:00
|
|
|
#[op2(async)]
|
2023-06-06 09:58:18 -04:00
|
|
|
pub async fn op_ws_send_binary_async(
|
2023-03-30 12:30:19 -04:00
|
|
|
state: Rc<RefCell<OpState>>,
|
2023-10-25 07:43:38 -04:00
|
|
|
#[smi] rid: ResourceId,
|
|
|
|
#[buffer] data: JsBuffer,
|
2023-03-30 12:30:19 -04:00
|
|
|
) -> Result<(), AnyError> {
|
|
|
|
let resource = state
|
|
|
|
.borrow_mut()
|
|
|
|
.resource_table
|
2023-04-20 12:24:22 -04:00
|
|
|
.get::<ServerWebSocket>(rid)?;
|
2023-06-06 09:58:18 -04:00
|
|
|
let data = data.to_vec();
|
2023-06-13 13:16:17 -04:00
|
|
|
let lock = resource.reserve_lock();
|
2023-04-20 12:24:22 -04:00
|
|
|
resource
|
2023-08-10 00:29:06 -04:00
|
|
|
.write_frame(lock, Frame::new(true, OpCode::Binary, None, data.into()))
|
2023-04-20 12:24:22 -04:00
|
|
|
.await
|
2023-03-30 12:30:19 -04:00
|
|
|
}
|
|
|
|
|
2023-06-06 09:58:18 -04:00
|
|
|
/// Async version of send. Does not update buffered amount as we rely on the socket itself for backpressure.
|
2023-10-25 07:43:38 -04:00
|
|
|
#[op2(async)]
|
2023-06-06 09:58:18 -04:00
|
|
|
pub async fn op_ws_send_text_async(
|
2023-03-30 11:52:12 -04:00
|
|
|
state: Rc<RefCell<OpState>>,
|
2023-10-25 07:43:38 -04:00
|
|
|
#[smi] rid: ResourceId,
|
|
|
|
#[string] data: String,
|
2023-03-30 11:52:12 -04:00
|
|
|
) -> Result<(), AnyError> {
|
|
|
|
let resource = state
|
|
|
|
.borrow_mut()
|
|
|
|
.resource_table
|
2023-04-20 12:24:22 -04:00
|
|
|
.get::<ServerWebSocket>(rid)?;
|
2023-06-13 13:16:17 -04:00
|
|
|
let lock = resource.reserve_lock();
|
2023-04-20 12:24:22 -04:00
|
|
|
resource
|
2023-06-13 13:16:17 -04:00
|
|
|
.write_frame(
|
|
|
|
lock,
|
2023-08-10 00:29:06 -04:00
|
|
|
Frame::new(true, OpCode::Text, None, data.into_bytes().into()),
|
2023-06-13 13:16:17 -04:00
|
|
|
)
|
2023-04-20 12:24:22 -04:00
|
|
|
.await
|
2023-03-30 11:52:12 -04:00
|
|
|
}
|
|
|
|
|
2023-08-10 00:29:06 -04:00
|
|
|
const EMPTY_PAYLOAD: &[u8] = &[];
|
|
|
|
|
2023-10-04 17:43:58 -04:00
|
|
|
#[op2(fast)]
|
|
|
|
#[smi]
|
|
|
|
pub fn op_ws_get_buffered_amount(
|
|
|
|
state: &mut OpState,
|
|
|
|
#[smi] rid: ResourceId,
|
|
|
|
) -> u32 {
|
2023-06-06 09:58:18 -04:00
|
|
|
state
|
|
|
|
.resource_table
|
|
|
|
.get::<ServerWebSocket>(rid)
|
|
|
|
.unwrap()
|
|
|
|
.buffered
|
|
|
|
.get() as u32
|
|
|
|
}
|
|
|
|
|
2023-10-04 17:43:58 -04:00
|
|
|
#[op2(async)]
|
2023-04-25 07:53:06 -04:00
|
|
|
pub async fn op_ws_send_pong(
|
|
|
|
state: Rc<RefCell<OpState>>,
|
2023-10-04 17:43:58 -04:00
|
|
|
#[smi] rid: ResourceId,
|
2023-04-25 07:53:06 -04:00
|
|
|
) -> Result<(), AnyError> {
|
2021-01-06 10:57:28 -05:00
|
|
|
let resource = state
|
|
|
|
.borrow_mut()
|
|
|
|
.resource_table
|
2023-04-20 12:24:22 -04:00
|
|
|
.get::<ServerWebSocket>(rid)?;
|
2023-06-13 13:16:17 -04:00
|
|
|
let lock = resource.reserve_lock();
|
2023-08-10 00:29:06 -04:00
|
|
|
resource
|
|
|
|
.write_frame(lock, Frame::pong(EMPTY_PAYLOAD.into()))
|
|
|
|
.await
|
2021-01-06 10:57:28 -05:00
|
|
|
}
|
|
|
|
|
2023-10-04 17:43:58 -04:00
|
|
|
#[op2(async)]
|
2023-04-28 10:48:00 -04:00
|
|
|
pub async fn op_ws_send_ping(
|
|
|
|
state: Rc<RefCell<OpState>>,
|
2023-10-04 17:43:58 -04:00
|
|
|
#[smi] rid: ResourceId,
|
2023-04-28 10:48:00 -04:00
|
|
|
) -> Result<(), AnyError> {
|
|
|
|
let resource = state
|
|
|
|
.borrow_mut()
|
|
|
|
.resource_table
|
|
|
|
.get::<ServerWebSocket>(rid)?;
|
2023-06-13 13:16:17 -04:00
|
|
|
let lock = resource.reserve_lock();
|
2023-04-28 10:48:00 -04:00
|
|
|
resource
|
2023-08-10 00:29:06 -04:00
|
|
|
.write_frame(
|
|
|
|
lock,
|
|
|
|
Frame::new(true, OpCode::Ping, None, EMPTY_PAYLOAD.into()),
|
|
|
|
)
|
2023-04-28 10:48:00 -04:00
|
|
|
.await
|
|
|
|
}
|
|
|
|
|
2023-10-04 17:43:58 -04:00
|
|
|
#[op2(async(lazy))]
|
2021-01-06 10:57:28 -05:00
|
|
|
pub async fn op_ws_close(
|
|
|
|
state: Rc<RefCell<OpState>>,
|
2023-10-04 17:43:58 -04:00
|
|
|
#[smi] rid: ResourceId,
|
|
|
|
#[smi] code: Option<u16>,
|
|
|
|
#[string] reason: Option<String>,
|
2021-04-05 12:40:24 -04:00
|
|
|
) -> Result<(), AnyError> {
|
2021-01-06 10:57:28 -05:00
|
|
|
let resource = state
|
|
|
|
.borrow_mut()
|
|
|
|
.resource_table
|
2023-04-20 12:24:22 -04:00
|
|
|
.get::<ServerWebSocket>(rid)?;
|
|
|
|
let frame = reason
|
|
|
|
.map(|reason| Frame::close(code.unwrap_or(1005), reason.as_bytes()))
|
2023-08-10 00:29:06 -04:00
|
|
|
.unwrap_or_else(|| Frame::close_raw(vec![].into()));
|
2023-04-20 12:24:22 -04:00
|
|
|
|
2023-06-06 09:58:18 -04:00
|
|
|
resource.closed.set(true);
|
2023-06-13 13:16:17 -04:00
|
|
|
let lock = resource.reserve_lock();
|
|
|
|
resource.write_frame(lock, frame).await?;
|
2021-04-05 12:40:24 -04:00
|
|
|
Ok(())
|
2021-01-06 10:57:28 -05:00
|
|
|
}
|
|
|
|
|
2023-10-04 17:43:58 -04:00
|
|
|
#[op2]
|
|
|
|
#[serde]
|
|
|
|
pub fn op_ws_get_buffer(
|
|
|
|
state: &mut OpState,
|
|
|
|
#[smi] rid: ResourceId,
|
2023-12-11 01:52:54 -05:00
|
|
|
) -> Result<ToJsBuffer, AnyError> {
|
|
|
|
let resource = state.resource_table.get::<ServerWebSocket>(rid)?;
|
|
|
|
Ok(resource.buffer.take().unwrap().into())
|
2023-06-08 11:32:08 -04:00
|
|
|
}
|
|
|
|
|
2023-10-04 17:43:58 -04:00
|
|
|
#[op2]
|
|
|
|
#[string]
|
2023-06-08 11:32:08 -04:00
|
|
|
pub fn op_ws_get_buffer_as_string(
|
|
|
|
state: &mut OpState,
|
2023-10-04 17:43:58 -04:00
|
|
|
#[smi] rid: ResourceId,
|
2023-12-11 01:52:54 -05:00
|
|
|
) -> Result<String, AnyError> {
|
|
|
|
let resource = state.resource_table.get::<ServerWebSocket>(rid)?;
|
|
|
|
Ok(resource.string.take().unwrap())
|
2023-06-08 11:32:08 -04:00
|
|
|
}
|
|
|
|
|
2023-10-04 17:43:58 -04:00
|
|
|
#[op2]
|
|
|
|
#[string]
|
|
|
|
pub fn op_ws_get_error(state: &mut OpState, #[smi] rid: ResourceId) -> String {
|
2023-06-08 11:32:08 -04:00
|
|
|
let Ok(resource) = state.resource_table.get::<ServerWebSocket>(rid) else {
|
|
|
|
return "Bad resource".into();
|
|
|
|
};
|
|
|
|
resource.errored.set(false);
|
|
|
|
resource.error.take().unwrap_or_default()
|
|
|
|
}
|
|
|
|
|
2023-10-25 07:43:38 -04:00
|
|
|
#[op2(async)]
|
2021-01-06 10:57:28 -05:00
|
|
|
pub async fn op_ws_next_event(
|
|
|
|
state: Rc<RefCell<OpState>>,
|
2023-10-25 07:43:38 -04:00
|
|
|
#[smi] rid: ResourceId,
|
2023-06-08 11:32:08 -04:00
|
|
|
) -> u16 {
|
|
|
|
let Ok(resource) = state
|
2021-01-06 10:57:28 -05:00
|
|
|
.borrow_mut()
|
|
|
|
.resource_table
|
2023-08-27 00:04:12 -04:00
|
|
|
.get::<ServerWebSocket>(rid)
|
|
|
|
else {
|
2023-06-08 11:32:08 -04:00
|
|
|
// op_ws_get_error will correctly handle a bad resource
|
|
|
|
return MessageKind::Error as u16;
|
|
|
|
};
|
2021-01-06 10:57:28 -05:00
|
|
|
|
2023-06-08 11:32:08 -04:00
|
|
|
// If there's a pending error, this always returns error
|
|
|
|
if resource.errored.get() {
|
|
|
|
return MessageKind::Error as u16;
|
2023-06-06 09:58:18 -04:00
|
|
|
}
|
|
|
|
|
2023-10-30 13:49:19 -04:00
|
|
|
let mut ws = RcRef::map(&resource, |r| &r.ws_read).borrow_mut().await;
|
|
|
|
let writer = RcRef::map(&resource, |r| &r.ws_write);
|
|
|
|
let mut sender = move |frame| {
|
|
|
|
let writer = writer.clone();
|
|
|
|
async move { writer.borrow_mut().await.write_frame(frame).await }
|
|
|
|
};
|
2023-04-26 06:07:38 -04:00
|
|
|
loop {
|
2023-10-30 13:49:19 -04:00
|
|
|
let res = ws.read_frame(&mut sender).await;
|
|
|
|
let val = match res {
|
2023-04-26 06:07:38 -04:00
|
|
|
Ok(val) => val,
|
|
|
|
Err(err) => {
|
|
|
|
// No message was received, socket closed while we waited.
|
2023-06-29 09:24:01 -04:00
|
|
|
// Report closed status to JavaScript.
|
2023-04-26 06:07:38 -04:00
|
|
|
if resource.closed.get() {
|
2023-06-08 11:32:08 -04:00
|
|
|
return MessageKind::ClosedDefault as u16;
|
2023-04-26 06:07:38 -04:00
|
|
|
}
|
|
|
|
|
2023-06-08 11:32:08 -04:00
|
|
|
resource.set_error(Some(err.to_string()));
|
|
|
|
return MessageKind::Error as u16;
|
2023-04-20 12:24:22 -04:00
|
|
|
}
|
2023-04-26 06:07:38 -04:00
|
|
|
};
|
|
|
|
|
2023-06-08 11:32:08 -04:00
|
|
|
break match val.opcode {
|
2023-08-10 00:29:06 -04:00
|
|
|
OpCode::Text => match String::from_utf8(val.payload.to_vec()) {
|
2023-06-08 14:29:26 -04:00
|
|
|
Ok(s) => {
|
|
|
|
resource.string.set(Some(s));
|
|
|
|
MessageKind::Text as u16
|
|
|
|
}
|
|
|
|
Err(_) => {
|
|
|
|
resource.set_error(Some("Invalid string data".into()));
|
|
|
|
MessageKind::Error as u16
|
|
|
|
}
|
|
|
|
},
|
2023-06-08 11:32:08 -04:00
|
|
|
OpCode::Binary => {
|
2023-08-10 00:29:06 -04:00
|
|
|
resource.buffer.set(Some(val.payload.to_vec()));
|
2023-06-08 11:32:08 -04:00
|
|
|
MessageKind::Binary as u16
|
|
|
|
}
|
2023-04-26 06:07:38 -04:00
|
|
|
OpCode::Close => {
|
2023-06-08 11:32:08 -04:00
|
|
|
// Close reason is returned through error
|
2023-04-26 06:07:38 -04:00
|
|
|
if val.payload.len() < 2 {
|
2023-06-08 11:32:08 -04:00
|
|
|
resource.set_error(None);
|
|
|
|
MessageKind::ClosedDefault as u16
|
|
|
|
} else {
|
|
|
|
let close_code = CloseCode::from(u16::from_be_bytes([
|
|
|
|
val.payload[0],
|
|
|
|
val.payload[1],
|
|
|
|
]));
|
|
|
|
let reason = String::from_utf8(val.payload[2..].to_vec()).ok();
|
|
|
|
resource.set_error(reason);
|
|
|
|
close_code.into()
|
2023-04-26 06:07:38 -04:00
|
|
|
}
|
2023-04-20 12:24:22 -04:00
|
|
|
}
|
2023-06-08 11:32:08 -04:00
|
|
|
OpCode::Pong => MessageKind::Pong as u16,
|
2023-04-26 06:07:38 -04:00
|
|
|
OpCode::Continuation | OpCode::Ping => {
|
|
|
|
continue;
|
|
|
|
}
|
2023-06-08 11:32:08 -04:00
|
|
|
};
|
2023-04-26 06:07:38 -04:00
|
|
|
}
|
2021-01-06 10:57:28 -05:00
|
|
|
}
|
|
|
|
|
2023-03-17 14:22:15 -04:00
|
|
|
deno_core::extension!(deno_websocket,
|
|
|
|
deps = [ deno_url, deno_webidl ],
|
|
|
|
parameters = [P: WebSocketPermissions],
|
|
|
|
ops = [
|
|
|
|
op_ws_check_permission_and_cancel_handle<P>,
|
|
|
|
op_ws_create<P>,
|
|
|
|
op_ws_close,
|
|
|
|
op_ws_next_event,
|
2023-06-08 11:32:08 -04:00
|
|
|
op_ws_get_buffer,
|
|
|
|
op_ws_get_buffer_as_string,
|
|
|
|
op_ws_get_error,
|
2023-03-30 12:30:19 -04:00
|
|
|
op_ws_send_binary,
|
2023-10-04 17:43:58 -04:00
|
|
|
op_ws_send_binary_ab,
|
2023-03-30 11:52:12 -04:00
|
|
|
op_ws_send_text,
|
2023-06-06 09:58:18 -04:00
|
|
|
op_ws_send_binary_async,
|
|
|
|
op_ws_send_text_async,
|
2023-04-28 10:48:00 -04:00
|
|
|
op_ws_send_ping,
|
2023-04-25 07:53:06 -04:00
|
|
|
op_ws_send_pong,
|
2023-06-06 09:58:18 -04:00
|
|
|
op_ws_get_buffered_amount,
|
2023-03-17 14:22:15 -04:00
|
|
|
],
|
2023-12-24 08:04:32 -05:00
|
|
|
esm = [ "00_ops.js", "01_websocket.js", "02_websocketstream.js" ],
|
2023-03-17 18:15:27 -04:00
|
|
|
options = {
|
2023-03-17 14:22:15 -04:00
|
|
|
user_agent: String,
|
2023-05-01 16:42:05 -04:00
|
|
|
root_cert_store_provider: Option<Arc<dyn RootCertStoreProvider>>,
|
2023-03-17 14:22:15 -04:00
|
|
|
unsafely_ignore_certificate_errors: Option<Vec<String>>
|
|
|
|
},
|
2023-03-17 18:15:27 -04:00
|
|
|
state = |state, options| {
|
|
|
|
state.put::<WsUserAgent>(WsUserAgent(options.user_agent));
|
2023-03-17 14:22:15 -04:00
|
|
|
state.put(UnsafelyIgnoreCertificateErrors(
|
2023-03-17 18:15:27 -04:00
|
|
|
options.unsafely_ignore_certificate_errors,
|
2023-03-17 14:22:15 -04:00
|
|
|
));
|
2023-05-01 16:42:05 -04:00
|
|
|
state.put::<WsRootStoreProvider>(WsRootStoreProvider(options.root_cert_store_provider));
|
2023-03-17 14:22:15 -04:00
|
|
|
},
|
|
|
|
);
|
2021-01-06 10:57:28 -05:00
|
|
|
|
2022-03-16 20:25:44 -04:00
|
|
|
pub fn get_declaration() -> PathBuf {
|
|
|
|
PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("lib.deno_websocket.d.ts")
|
|
|
|
}
|
|
|
|
|
2021-08-09 18:28:17 -04:00
|
|
|
#[derive(Debug)]
|
|
|
|
pub struct DomExceptionNetworkError {
|
|
|
|
pub msg: String,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl DomExceptionNetworkError {
|
|
|
|
pub fn new(msg: &str) -> Self {
|
|
|
|
DomExceptionNetworkError {
|
|
|
|
msg: msg.to_string(),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl fmt::Display for DomExceptionNetworkError {
|
|
|
|
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
|
|
|
f.pad(&self.msg)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl std::error::Error for DomExceptionNetworkError {}
|
|
|
|
|
|
|
|
pub fn get_network_error_class_name(e: &AnyError) -> Option<&'static str> {
|
|
|
|
e.downcast_ref::<DomExceptionNetworkError>()
|
|
|
|
.map(|_| "DOMExceptionNetworkError")
|
|
|
|
}
|
2023-04-21 02:55:02 -04:00
|
|
|
|
|
|
|
// Needed so hyper can use non Send futures
|
|
|
|
#[derive(Clone)]
|
|
|
|
struct LocalExecutor;
|
|
|
|
|
2023-12-26 05:20:49 -05:00
|
|
|
impl<Fut> hyper1::rt::Executor<Fut> for LocalExecutor
|
2023-04-21 02:55:02 -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-21 02:55:02 -04:00
|
|
|
}
|
|
|
|
}
|