2023-01-02 16:00:42 -05:00
|
|
|
// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
|
2021-01-06 10:57:28 -05:00
|
|
|
|
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;
|
|
|
|
use deno_core::futures::stream::SplitSink;
|
|
|
|
use deno_core::futures::stream::SplitStream;
|
|
|
|
use deno_core::futures::SinkExt;
|
|
|
|
use deno_core::futures::StreamExt;
|
2022-03-14 13:44:15 -04:00
|
|
|
use deno_core::op;
|
|
|
|
|
2021-01-06 10:57:28 -05:00
|
|
|
use deno_core::url;
|
|
|
|
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::CancelFuture;
|
|
|
|
use deno_core::CancelHandle;
|
|
|
|
use deno_core::OpState;
|
|
|
|
use deno_core::RcRef;
|
|
|
|
use deno_core::Resource;
|
2021-03-19 13:25:37 -04:00
|
|
|
use deno_core::ResourceId;
|
2021-03-17 17:33:29 -04:00
|
|
|
use deno_core::ZeroCopyBuf;
|
2021-08-07 08:49:38 -04:00
|
|
|
use deno_tls::create_client_config;
|
2023-03-18 20:34:56 -04:00
|
|
|
use http::HeaderName;
|
2022-01-05 11:41:44 -05:00
|
|
|
use http::HeaderValue;
|
2021-12-06 18:48:11 -05:00
|
|
|
use http::Method;
|
|
|
|
use http::Request;
|
|
|
|
use http::Uri;
|
2021-01-06 10:57:28 -05:00
|
|
|
use serde::Deserialize;
|
2021-04-19 11:54:56 -04:00
|
|
|
use serde::Serialize;
|
2021-01-06 10:57:28 -05:00
|
|
|
use std::borrow::Cow;
|
|
|
|
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;
|
2022-03-16 20:25:44 -04:00
|
|
|
use std::path::PathBuf;
|
2022-08-18 08:05:02 -04:00
|
|
|
use std::pin::Pin;
|
2021-01-06 10:57:28 -05:00
|
|
|
use std::rc::Rc;
|
|
|
|
use std::sync::Arc;
|
2022-08-18 08:05:02 -04:00
|
|
|
use tokio::io::AsyncRead;
|
|
|
|
use tokio::io::AsyncWrite;
|
2021-01-06 10:57:28 -05:00
|
|
|
use tokio::net::TcpStream;
|
2021-08-07 08:49:38 -04:00
|
|
|
use tokio_rustls::rustls::RootCertStore;
|
2021-12-06 18:48:11 -05:00
|
|
|
use tokio_rustls::rustls::ServerName;
|
2021-08-07 08:49:38 -04:00
|
|
|
use tokio_rustls::TlsConnector;
|
2022-08-04 12:29:04 -04:00
|
|
|
use tokio_tungstenite::client_async_with_config;
|
2021-12-06 18:48:11 -05:00
|
|
|
use tokio_tungstenite::tungstenite::handshake::client::Response;
|
|
|
|
use tokio_tungstenite::tungstenite::protocol::frame::coding::CloseCode;
|
|
|
|
use tokio_tungstenite::tungstenite::protocol::CloseFrame;
|
|
|
|
use tokio_tungstenite::tungstenite::protocol::Message;
|
|
|
|
use tokio_tungstenite::tungstenite::protocol::Role;
|
2022-08-04 12:29:04 -04:00
|
|
|
use tokio_tungstenite::tungstenite::protocol::WebSocketConfig;
|
2021-04-08 12:46:14 -04:00
|
|
|
use tokio_tungstenite::MaybeTlsStream;
|
2021-10-04 21:50:40 -04:00
|
|
|
use tokio_tungstenite::WebSocketStream;
|
2021-01-06 10:57:28 -05:00
|
|
|
|
|
|
|
pub use tokio_tungstenite; // Re-export tokio_tungstenite
|
|
|
|
|
|
|
|
#[derive(Clone)]
|
2021-08-07 08:49:38 -04:00
|
|
|
pub struct WsRootStore(pub Option<RootCertStore>);
|
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
|
|
|
|
2022-08-18 08:05:02 -04:00
|
|
|
type ClientWsStream = WebSocketStream<MaybeTlsStream<TcpStream>>;
|
|
|
|
type ServerWsStream = WebSocketStream<Pin<Box<dyn Upgraded>>>;
|
|
|
|
|
2021-07-08 07:33:01 -04:00
|
|
|
pub enum WebSocketStreamType {
|
|
|
|
Client {
|
2022-08-18 08:05:02 -04:00
|
|
|
tx: AsyncRefCell<SplitSink<ClientWsStream, Message>>,
|
|
|
|
rx: AsyncRefCell<SplitStream<ClientWsStream>>,
|
2021-07-08 07:33:01 -04:00
|
|
|
},
|
|
|
|
Server {
|
2022-08-18 08:05:02 -04:00
|
|
|
tx: AsyncRefCell<SplitSink<ServerWsStream, Message>>,
|
|
|
|
rx: AsyncRefCell<SplitStream<ServerWsStream>>,
|
2021-07-08 07:33:01 -04:00
|
|
|
},
|
|
|
|
}
|
|
|
|
|
2022-08-18 08:05:02 -04:00
|
|
|
pub trait Upgraded: AsyncRead + AsyncWrite + Unpin {}
|
|
|
|
|
2021-10-04 21:50:40 -04:00
|
|
|
pub async fn ws_create_server_stream(
|
|
|
|
state: &Rc<RefCell<OpState>>,
|
2022-08-18 08:05:02 -04:00
|
|
|
transport: Pin<Box<dyn Upgraded>>,
|
2021-10-04 21:50:40 -04:00
|
|
|
) -> Result<ResourceId, AnyError> {
|
2022-08-04 12:29:04 -04:00
|
|
|
let ws_stream = WebSocketStream::from_raw_socket(
|
|
|
|
transport,
|
|
|
|
Role::Server,
|
|
|
|
Some(WebSocketConfig {
|
|
|
|
max_message_size: Some(128 << 20),
|
|
|
|
max_frame_size: Some(32 << 20),
|
|
|
|
..Default::default()
|
|
|
|
}),
|
|
|
|
)
|
|
|
|
.await;
|
2021-10-04 21:50:40 -04:00
|
|
|
let (ws_tx, ws_rx) = ws_stream.split();
|
|
|
|
|
|
|
|
let ws_resource = WsStreamResource {
|
|
|
|
stream: WebSocketStreamType::Server {
|
|
|
|
tx: AsyncRefCell::new(ws_tx),
|
|
|
|
rx: AsyncRefCell::new(ws_rx),
|
|
|
|
},
|
|
|
|
cancel: Default::default(),
|
|
|
|
};
|
|
|
|
|
|
|
|
let resource_table = &mut state.borrow_mut().resource_table;
|
|
|
|
let rid = resource_table.add(ws_resource);
|
|
|
|
Ok(rid)
|
|
|
|
}
|
|
|
|
|
2021-07-08 07:33:01 -04:00
|
|
|
pub struct WsStreamResource {
|
|
|
|
pub stream: WebSocketStreamType,
|
2021-01-06 10:57:28 -05:00
|
|
|
// When a `WsStreamResource` resource is closed, all pending 'read' ops are
|
|
|
|
// canceled, while 'write' ops are allowed to complete. Therefore only
|
|
|
|
// 'read' futures are attached to this cancel handle.
|
2021-07-08 07:33:01 -04:00
|
|
|
pub cancel: CancelHandle,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl WsStreamResource {
|
|
|
|
async fn send(self: &Rc<Self>, message: Message) -> Result<(), AnyError> {
|
2021-10-19 12:21:15 -04:00
|
|
|
use tokio_tungstenite::tungstenite::Error;
|
|
|
|
let res = match self.stream {
|
2021-07-08 07:33:01 -04:00
|
|
|
WebSocketStreamType::Client { .. } => {
|
|
|
|
let mut tx = RcRef::map(self, |r| match &r.stream {
|
|
|
|
WebSocketStreamType::Client { tx, .. } => tx,
|
|
|
|
WebSocketStreamType::Server { .. } => unreachable!(),
|
|
|
|
})
|
|
|
|
.borrow_mut()
|
|
|
|
.await;
|
2021-10-19 12:21:15 -04:00
|
|
|
tx.send(message).await
|
2021-07-08 07:33:01 -04:00
|
|
|
}
|
|
|
|
WebSocketStreamType::Server { .. } => {
|
|
|
|
let mut tx = RcRef::map(self, |r| match &r.stream {
|
|
|
|
WebSocketStreamType::Client { .. } => unreachable!(),
|
|
|
|
WebSocketStreamType::Server { tx, .. } => tx,
|
|
|
|
})
|
|
|
|
.borrow_mut()
|
|
|
|
.await;
|
2021-10-19 12:21:15 -04:00
|
|
|
tx.send(message).await
|
2021-07-08 07:33:01 -04:00
|
|
|
}
|
2021-10-19 12:21:15 -04:00
|
|
|
};
|
2021-07-08 07:33:01 -04:00
|
|
|
|
2021-10-19 12:21:15 -04:00
|
|
|
match res {
|
|
|
|
Ok(()) => Ok(()),
|
|
|
|
Err(Error::ConnectionClosed) => Ok(()),
|
2022-05-23 07:21:11 -04:00
|
|
|
Err(tokio_tungstenite::tungstenite::Error::Protocol(
|
|
|
|
tokio_tungstenite::tungstenite::error::ProtocolError::SendAfterClosing,
|
|
|
|
)) => Ok(()),
|
2021-10-19 12:21:15 -04:00
|
|
|
Err(err) => Err(err.into()),
|
|
|
|
}
|
2021-07-08 07:33:01 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
async fn next_message(
|
|
|
|
self: &Rc<Self>,
|
|
|
|
cancel: RcRef<CancelHandle>,
|
|
|
|
) -> Result<
|
|
|
|
Option<Result<Message, tokio_tungstenite::tungstenite::Error>>,
|
|
|
|
AnyError,
|
|
|
|
> {
|
|
|
|
match &self.stream {
|
|
|
|
WebSocketStreamType::Client { .. } => {
|
|
|
|
let mut rx = RcRef::map(self, |r| match &r.stream {
|
|
|
|
WebSocketStreamType::Client { rx, .. } => rx,
|
|
|
|
WebSocketStreamType::Server { .. } => unreachable!(),
|
|
|
|
})
|
|
|
|
.borrow_mut()
|
|
|
|
.await;
|
|
|
|
rx.next().or_cancel(cancel).await.map_err(AnyError::from)
|
|
|
|
}
|
|
|
|
WebSocketStreamType::Server { .. } => {
|
|
|
|
let mut rx = RcRef::map(self, |r| match &r.stream {
|
|
|
|
WebSocketStreamType::Client { .. } => unreachable!(),
|
|
|
|
WebSocketStreamType::Server { rx, .. } => rx,
|
|
|
|
})
|
|
|
|
.borrow_mut()
|
|
|
|
.await;
|
|
|
|
rx.next().or_cancel(cancel).await.map_err(AnyError::from)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2021-01-06 10:57:28 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
impl Resource for WsStreamResource {
|
|
|
|
fn name(&self) -> Cow<str> {
|
|
|
|
"webSocketStream".into()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
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.
|
2022-03-14 13:44:15 -04:00
|
|
|
#[op]
|
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,
|
2022-09-27 16:36:33 -04:00
|
|
|
api_name: String,
|
2021-04-05 12:40:24 -04:00
|
|
|
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
|
|
|
}
|
|
|
|
|
2022-03-14 13:44:15 -04:00
|
|
|
#[op]
|
2021-01-06 10:57:28 -05:00
|
|
|
pub async fn op_ws_create<WP>(
|
|
|
|
state: Rc<RefCell<OpState>>,
|
2022-09-27 16:36:33 -04:00
|
|
|
api_name: String,
|
2022-04-04 05:49:50 -04:00
|
|
|
url: String,
|
|
|
|
protocols: String,
|
|
|
|
cancel_handle: Option<ResourceId>,
|
|
|
|
headers: Option<Vec<(ByteString, ByteString)>>,
|
2021-04-19 11:54:56 -04:00
|
|
|
) -> Result<CreateResponse, AnyError>
|
2021-01-06 10:57:28 -05:00
|
|
|
where
|
|
|
|
WP: WebSocketPermissions + 'static,
|
|
|
|
{
|
|
|
|
{
|
2021-04-11 22:15:43 -04:00
|
|
|
let mut s = state.borrow_mut();
|
|
|
|
s.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
|
|
|
.expect(
|
|
|
|
"Permission check should have been done in op_ws_check_permission",
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
2022-04-04 05:49:50 -04:00
|
|
|
let cancel_resource = if let Some(cancel_rid) = cancel_handle {
|
2021-11-28 06:25:49 -05:00
|
|
|
let r = state
|
|
|
|
.borrow_mut()
|
|
|
|
.resource_table
|
|
|
|
.get::<WsCancelResource>(cancel_rid)?;
|
|
|
|
Some(r)
|
|
|
|
} else {
|
|
|
|
None
|
|
|
|
};
|
|
|
|
|
2021-08-10 07:19:45 -04:00
|
|
|
let unsafely_ignore_certificate_errors = 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());
|
2021-08-07 08:49:38 -04:00
|
|
|
let root_cert_store = state.borrow().borrow::<WsRootStore>().0.clone();
|
2021-01-06 10:57:28 -05:00
|
|
|
let user_agent = state.borrow().borrow::<WsUserAgent>().0.clone();
|
2022-04-04 05:49:50 -04:00
|
|
|
let uri: Uri = url.parse()?;
|
2021-01-06 10:57:28 -05:00
|
|
|
let mut request = Request::builder().method(Method::GET).uri(&uri);
|
|
|
|
|
|
|
|
request = request.header("User-Agent", user_agent);
|
|
|
|
|
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 {
|
|
|
|
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()))?;
|
|
|
|
|
|
|
|
let is_disallowed_header = matches!(
|
|
|
|
name,
|
|
|
|
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
|
|
|
|
);
|
|
|
|
if !is_disallowed_header {
|
|
|
|
request = request.header(name, v);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-01-06 10:57:28 -05:00
|
|
|
let request = request.body(())?;
|
|
|
|
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!(),
|
|
|
|
});
|
2023-01-27 10:43:16 -05:00
|
|
|
let addr = format!("{domain}:{port}");
|
2021-05-01 14:52:13 -04:00
|
|
|
let tcp_socket = TcpStream::connect(addr).await?;
|
2021-01-06 10:57:28 -05:00
|
|
|
|
2021-04-08 12:46:14 -04:00
|
|
|
let socket: MaybeTlsStream<TcpStream> = match uri.scheme_str() {
|
|
|
|
Some("ws") => MaybeTlsStream::Plain(tcp_socket),
|
2021-01-06 10:57:28 -05:00
|
|
|
Some("wss") => {
|
2021-08-09 10:53:21 -04:00
|
|
|
let tls_config = create_client_config(
|
|
|
|
root_cert_store,
|
2021-09-30 03:26:15 -04:00
|
|
|
vec![],
|
2021-08-10 07:19:45 -04:00
|
|
|
unsafely_ignore_certificate_errors,
|
2021-12-01 11:13:11 -05:00
|
|
|
None,
|
2021-08-09 10:53:21 -04:00
|
|
|
)?;
|
2021-08-07 08:49:38 -04:00
|
|
|
let tls_connector = TlsConnector::from(Arc::new(tls_config));
|
2021-12-06 18:48:11 -05:00
|
|
|
let dnsname = ServerName::try_from(domain.as_str())
|
2021-04-26 15:39:55 -04:00
|
|
|
.map_err(|_| invalid_hostname(domain))?;
|
2021-01-06 10:57:28 -05:00
|
|
|
let tls_socket = tls_connector.connect(dnsname, tcp_socket).await?;
|
2021-04-08 12:46:14 -04:00
|
|
|
MaybeTlsStream::Rustls(tls_socket)
|
2021-01-06 10:57:28 -05:00
|
|
|
}
|
|
|
|
_ => unreachable!(),
|
|
|
|
};
|
|
|
|
|
2022-08-04 12:29:04 -04:00
|
|
|
let client = client_async_with_config(
|
|
|
|
request,
|
|
|
|
socket,
|
|
|
|
Some(WebSocketConfig {
|
|
|
|
max_message_size: Some(128 << 20),
|
|
|
|
max_frame_size: Some(32 << 20),
|
|
|
|
..Default::default()
|
|
|
|
}),
|
|
|
|
);
|
2022-08-18 08:05:02 -04:00
|
|
|
let (stream, response): (ClientWsStream, Response) =
|
2021-11-28 06:25:49 -05:00
|
|
|
if let Some(cancel_resource) = cancel_resource {
|
2021-12-16 06:57:26 -05:00
|
|
|
client.or_cancel(cancel_resource.0.to_owned()).await?
|
2021-08-09 18:28:17 -04:00
|
|
|
} else {
|
|
|
|
client.await
|
|
|
|
}
|
|
|
|
.map_err(|err| {
|
|
|
|
DomExceptionNetworkError::new(&format!(
|
2023-01-27 10:43:16 -05:00
|
|
|
"failed to connect to WebSocket: {err}"
|
2021-01-06 10:57:28 -05:00
|
|
|
))
|
|
|
|
})?;
|
|
|
|
|
2022-04-04 05:49:50 -04:00
|
|
|
if let Some(cancel_rid) = cancel_handle {
|
2021-08-15 07:29:19 -04:00
|
|
|
state.borrow_mut().resource_table.close(cancel_rid).ok();
|
2021-08-09 18:28:17 -04:00
|
|
|
}
|
|
|
|
|
2021-01-06 10:57:28 -05:00
|
|
|
let (ws_tx, ws_rx) = stream.split();
|
|
|
|
let resource = WsStreamResource {
|
2021-07-08 07:33:01 -04:00
|
|
|
stream: WebSocketStreamType::Client {
|
|
|
|
rx: AsyncRefCell::new(ws_rx),
|
|
|
|
tx: AsyncRefCell::new(ws_tx),
|
|
|
|
},
|
2021-01-06 10:57:28 -05:00
|
|
|
cancel: Default::default(),
|
|
|
|
};
|
|
|
|
let mut state = state.borrow_mut();
|
|
|
|
let rid = state.resource_table.add(resource);
|
|
|
|
|
|
|
|
let protocol = match response.headers().get("Sec-WebSocket-Protocol") {
|
|
|
|
Some(header) => header.to_str().unwrap(),
|
|
|
|
None => "",
|
|
|
|
};
|
|
|
|
let extensions = response
|
|
|
|
.headers()
|
|
|
|
.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
|
|
|
}
|
|
|
|
|
|
|
|
#[derive(Deserialize)]
|
2021-10-05 16:38:27 -04:00
|
|
|
#[serde(tag = "kind", content = "value", rename_all = "camelCase")]
|
|
|
|
pub enum SendValue {
|
|
|
|
Text(String),
|
|
|
|
Binary(ZeroCopyBuf),
|
|
|
|
Pong,
|
2022-01-06 11:41:16 -05:00
|
|
|
Ping,
|
2021-01-06 10:57:28 -05:00
|
|
|
}
|
|
|
|
|
2022-03-14 13:44:15 -04:00
|
|
|
#[op]
|
2021-01-06 10:57:28 -05:00
|
|
|
pub async fn op_ws_send(
|
|
|
|
state: Rc<RefCell<OpState>>,
|
2021-10-05 16:38:27 -04:00
|
|
|
rid: ResourceId,
|
|
|
|
value: SendValue,
|
2021-04-05 12:40:24 -04:00
|
|
|
) -> Result<(), AnyError> {
|
2021-10-05 16:38:27 -04:00
|
|
|
let msg = match value {
|
|
|
|
SendValue::Text(text) => Message::Text(text),
|
|
|
|
SendValue::Binary(buf) => Message::Binary(buf.to_vec()),
|
|
|
|
SendValue::Pong => Message::Pong(vec![]),
|
2022-01-06 11:41:16 -05:00
|
|
|
SendValue::Ping => Message::Ping(vec![]),
|
2021-01-06 10:57:28 -05:00
|
|
|
};
|
|
|
|
|
|
|
|
let resource = state
|
|
|
|
.borrow_mut()
|
|
|
|
.resource_table
|
2021-10-05 16:38:27 -04:00
|
|
|
.get::<WsStreamResource>(rid)?;
|
2021-07-08 07:33:01 -04:00
|
|
|
resource.send(msg).await?;
|
2021-04-05 12:40:24 -04:00
|
|
|
Ok(())
|
2021-01-06 10:57:28 -05:00
|
|
|
}
|
|
|
|
|
2022-09-06 13:38:37 -04:00
|
|
|
#[op(deferred)]
|
2021-01-06 10:57:28 -05:00
|
|
|
pub async fn op_ws_close(
|
|
|
|
state: Rc<RefCell<OpState>>,
|
2022-04-04 05:49:50 -04:00
|
|
|
rid: ResourceId,
|
|
|
|
code: Option<u16>,
|
|
|
|
reason: Option<String>,
|
2021-04-05 12:40:24 -04:00
|
|
|
) -> Result<(), AnyError> {
|
2022-04-04 05:49:50 -04:00
|
|
|
let rid = rid;
|
|
|
|
let msg = Message::Close(code.map(|c| CloseFrame {
|
2021-01-06 10:57:28 -05:00
|
|
|
code: CloseCode::from(c),
|
2022-04-04 05:49:50 -04:00
|
|
|
reason: match reason {
|
2021-01-06 10:57:28 -05:00
|
|
|
Some(reason) => Cow::from(reason),
|
|
|
|
None => Default::default(),
|
|
|
|
},
|
|
|
|
}));
|
|
|
|
|
|
|
|
let resource = state
|
|
|
|
.borrow_mut()
|
|
|
|
.resource_table
|
2021-08-15 07:29:19 -04:00
|
|
|
.get::<WsStreamResource>(rid)?;
|
2021-07-08 07:33:01 -04:00
|
|
|
resource.send(msg).await?;
|
2021-04-05 12:40:24 -04:00
|
|
|
Ok(())
|
2021-01-06 10:57:28 -05:00
|
|
|
}
|
|
|
|
|
2021-04-19 11:54:56 -04:00
|
|
|
#[derive(Serialize)]
|
2021-04-22 19:31:34 -04:00
|
|
|
#[serde(tag = "kind", content = "value", rename_all = "camelCase")]
|
2021-04-19 11:54:56 -04:00
|
|
|
pub enum NextEventResponse {
|
|
|
|
String(String),
|
2021-04-30 11:03:50 -04:00
|
|
|
Binary(ZeroCopyBuf),
|
2021-04-19 11:54:56 -04:00
|
|
|
Close { code: u16, reason: String },
|
|
|
|
Ping,
|
|
|
|
Pong,
|
2021-05-01 14:52:13 -04:00
|
|
|
Error(String),
|
2021-04-19 11:54:56 -04:00
|
|
|
Closed,
|
|
|
|
}
|
|
|
|
|
2022-11-01 11:06:06 -04:00
|
|
|
#[op]
|
2021-01-06 10:57:28 -05:00
|
|
|
pub async fn op_ws_next_event(
|
|
|
|
state: Rc<RefCell<OpState>>,
|
2021-04-05 12:40:24 -04:00
|
|
|
rid: ResourceId,
|
2022-11-01 11:06:06 -04:00
|
|
|
) -> Result<NextEventResponse, AnyError> {
|
2021-01-06 10:57:28 -05:00
|
|
|
let resource = state
|
|
|
|
.borrow_mut()
|
|
|
|
.resource_table
|
2021-08-15 07:29:19 -04:00
|
|
|
.get::<WsStreamResource>(rid)?;
|
2021-01-06 10:57:28 -05:00
|
|
|
|
2021-07-08 07:33:01 -04:00
|
|
|
let cancel = RcRef::map(&resource, |r| &r.cancel);
|
|
|
|
let val = resource.next_message(cancel).await?;
|
2022-11-01 11:06:06 -04:00
|
|
|
let res = match val {
|
|
|
|
Some(Ok(Message::Text(text))) => NextEventResponse::String(text),
|
|
|
|
Some(Ok(Message::Binary(data))) => NextEventResponse::Binary(data.into()),
|
|
|
|
Some(Ok(Message::Close(Some(frame)))) => NextEventResponse::Close {
|
|
|
|
code: frame.code.into(),
|
|
|
|
reason: frame.reason.to_string(),
|
|
|
|
},
|
|
|
|
Some(Ok(Message::Close(None))) => NextEventResponse::Close {
|
|
|
|
code: 1005,
|
|
|
|
reason: String::new(),
|
|
|
|
},
|
|
|
|
Some(Ok(Message::Ping(_))) => NextEventResponse::Ping,
|
|
|
|
Some(Ok(Message::Pong(_))) => NextEventResponse::Pong,
|
|
|
|
Some(Err(e)) => NextEventResponse::Error(e.to_string()),
|
2021-01-06 10:57:28 -05:00
|
|
|
None => {
|
2022-10-15 05:08:09 -04:00
|
|
|
// No message was received, presumably the socket closed while we waited.
|
|
|
|
// Try close the stream, ignoring any errors, and report closed status to JavaScript.
|
|
|
|
let _ = state.borrow_mut().resource_table.close(rid);
|
2022-11-01 11:06:06 -04:00
|
|
|
NextEventResponse::Closed
|
2021-01-06 10:57:28 -05:00
|
|
|
}
|
|
|
|
};
|
2022-11-01 11:06:06 -04:00
|
|
|
Ok(res)
|
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_send,
|
|
|
|
op_ws_close,
|
|
|
|
op_ws_next_event,
|
|
|
|
],
|
|
|
|
esm = [ "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,
|
|
|
|
root_cert_store: Option<RootCertStore>,
|
|
|
|
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-03-17 18:15:27 -04:00
|
|
|
state.put::<WsRootStore>(WsRootStore(options.root_cert_store));
|
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")
|
|
|
|
}
|