2021-01-11 12:13:41 -05:00
|
|
|
// Copyright 2018-2021 the Deno authors. All rights reserved. MIT license.
|
2021-01-06 10:57:28 -05:00
|
|
|
|
|
|
|
use deno_core::error::bad_resource_id;
|
2021-04-26 15:39:55 -04:00
|
|
|
use deno_core::error::invalid_hostname;
|
2021-04-02 09:47:57 -04:00
|
|
|
use deno_core::error::null_opbuf;
|
2021-01-06 10:57:28 -05:00
|
|
|
use deno_core::error::type_error;
|
|
|
|
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;
|
2021-04-28 12:41:50 -04:00
|
|
|
use deno_core::include_js_files;
|
|
|
|
use deno_core::op_async;
|
|
|
|
use deno_core::op_sync;
|
2021-01-06 10:57:28 -05:00
|
|
|
use deno_core::url;
|
|
|
|
use deno_core::AsyncRefCell;
|
|
|
|
use deno_core::CancelFuture;
|
|
|
|
use deno_core::CancelHandle;
|
2021-04-28 12:41:50 -04:00
|
|
|
use deno_core::Extension;
|
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;
|
2021-03-17 17:33:29 -04:00
|
|
|
use deno_core::ZeroCopyBuf;
|
2021-01-06 10:57:28 -05:00
|
|
|
|
|
|
|
use http::{Method, Request, Uri};
|
|
|
|
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;
|
|
|
|
use std::io::BufReader;
|
|
|
|
use std::io::Cursor;
|
|
|
|
use std::path::PathBuf;
|
|
|
|
use std::rc::Rc;
|
|
|
|
use std::sync::Arc;
|
|
|
|
use tokio::net::TcpStream;
|
|
|
|
use tokio_rustls::{rustls::ClientConfig, TlsConnector};
|
|
|
|
use tokio_tungstenite::tungstenite::{
|
|
|
|
handshake::client::Response, protocol::frame::coding::CloseCode,
|
|
|
|
protocol::CloseFrame, Message,
|
|
|
|
};
|
2021-04-08 12:46:14 -04:00
|
|
|
use tokio_tungstenite::MaybeTlsStream;
|
2021-01-06 10:57:28 -05:00
|
|
|
use tokio_tungstenite::{client_async, WebSocketStream};
|
|
|
|
use webpki::DNSNameRef;
|
|
|
|
|
|
|
|
pub use tokio_tungstenite; // Re-export tokio_tungstenite
|
|
|
|
|
|
|
|
#[derive(Clone)]
|
|
|
|
pub struct WsCaData(pub Vec<u8>);
|
|
|
|
#[derive(Clone)]
|
|
|
|
pub struct WsUserAgent(pub String);
|
|
|
|
|
|
|
|
pub trait WebSocketPermissions {
|
2021-04-11 22:15:43 -04:00
|
|
|
fn check_net_url(&mut self, _url: &url::Url) -> Result<(), AnyError>;
|
2021-01-06 10:57:28 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
/// For use with `op_websocket_*` when the user does not want permissions.
|
|
|
|
pub struct NoWebSocketPermissions;
|
|
|
|
|
|
|
|
impl WebSocketPermissions for NoWebSocketPermissions {
|
2021-04-11 22:15:43 -04:00
|
|
|
fn check_net_url(&mut self, _url: &url::Url) -> Result<(), AnyError> {
|
2021-01-06 10:57:28 -05:00
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-04-08 12:46:14 -04:00
|
|
|
type WsStream = WebSocketStream<MaybeTlsStream<TcpStream>>;
|
2021-01-06 10:57:28 -05:00
|
|
|
struct WsStreamResource {
|
|
|
|
tx: AsyncRefCell<SplitSink<WsStream, Message>>,
|
|
|
|
rx: AsyncRefCell<SplitStream<WsStream>>,
|
|
|
|
// 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.
|
|
|
|
cancel: CancelHandle,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Resource for WsStreamResource {
|
|
|
|
fn name(&self) -> Cow<str> {
|
|
|
|
"webSocketStream".into()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl WsStreamResource {}
|
|
|
|
|
|
|
|
// 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.
|
|
|
|
pub fn op_ws_check_permission<WP>(
|
|
|
|
state: &mut OpState,
|
2021-04-05 12:40:24 -04:00
|
|
|
url: String,
|
2021-05-08 08:37:42 -04:00
|
|
|
_: (),
|
2021-04-05 12:40:24 -04:00
|
|
|
) -> Result<(), 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>()
|
2021-04-05 12:40:24 -04:00
|
|
|
.check_net_url(&url::Url::parse(&url)?)?;
|
2021-01-06 10:57:28 -05:00
|
|
|
|
2021-04-05 12:40:24 -04:00
|
|
|
Ok(())
|
2021-01-06 10:57:28 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
#[derive(Deserialize)]
|
|
|
|
#[serde(rename_all = "camelCase")]
|
2021-03-17 17:33:29 -04:00
|
|
|
pub struct CreateArgs {
|
2021-01-06 10:57:28 -05:00
|
|
|
url: String,
|
|
|
|
protocols: String,
|
|
|
|
}
|
|
|
|
|
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
|
|
|
}
|
|
|
|
|
2021-01-06 10:57:28 -05:00
|
|
|
pub async fn op_ws_create<WP>(
|
|
|
|
state: Rc<RefCell<OpState>>,
|
2021-03-17 17:33:29 -04:00
|
|
|
args: CreateArgs,
|
2021-05-08 08:37:42 -04:00
|
|
|
_: (),
|
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>()
|
2021-01-06 10:57:28 -05:00
|
|
|
.check_net_url(&url::Url::parse(&args.url)?)
|
|
|
|
.expect(
|
|
|
|
"Permission check should have been done in op_ws_check_permission",
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
|
|
|
let ws_ca_data = state.borrow().try_borrow::<WsCaData>().cloned();
|
|
|
|
let user_agent = state.borrow().borrow::<WsUserAgent>().0.clone();
|
|
|
|
let uri: Uri = args.url.parse()?;
|
|
|
|
let mut request = Request::builder().method(Method::GET).uri(&uri);
|
|
|
|
|
|
|
|
request = request.header("User-Agent", user_agent);
|
|
|
|
|
|
|
|
if !args.protocols.is_empty() {
|
|
|
|
request = request.header("Sec-WebSocket-Protocol", args.protocols);
|
|
|
|
}
|
|
|
|
|
|
|
|
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!(),
|
|
|
|
});
|
|
|
|
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") => {
|
|
|
|
let mut config = ClientConfig::new();
|
|
|
|
config
|
|
|
|
.root_store
|
|
|
|
.add_server_trust_anchors(&webpki_roots::TLS_SERVER_ROOTS);
|
|
|
|
|
|
|
|
if let Some(ws_ca_data) = ws_ca_data {
|
|
|
|
let reader = &mut BufReader::new(Cursor::new(ws_ca_data.0));
|
|
|
|
config.root_store.add_pem_file(reader).unwrap();
|
|
|
|
}
|
|
|
|
|
|
|
|
let tls_connector = TlsConnector::from(Arc::new(config));
|
2021-04-26 15:39:55 -04:00
|
|
|
let dnsname = DNSNameRef::try_from_ascii_str(domain)
|
|
|
|
.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!(),
|
|
|
|
};
|
|
|
|
|
|
|
|
let (stream, response): (WsStream, Response) =
|
|
|
|
client_async(request, socket).await.map_err(|err| {
|
|
|
|
type_error(format!(
|
|
|
|
"failed to connect to WebSocket: {}",
|
|
|
|
err.to_string()
|
|
|
|
))
|
|
|
|
})?;
|
|
|
|
|
|
|
|
let (ws_tx, ws_rx) = stream.split();
|
|
|
|
let resource = WsStreamResource {
|
|
|
|
rx: AsyncRefCell::new(ws_rx),
|
|
|
|
tx: AsyncRefCell::new(ws_tx),
|
|
|
|
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)]
|
|
|
|
#[serde(rename_all = "camelCase")]
|
2021-03-17 17:33:29 -04:00
|
|
|
pub struct SendArgs {
|
2021-03-19 13:25:37 -04:00
|
|
|
rid: ResourceId,
|
2021-01-06 10:57:28 -05:00
|
|
|
kind: String,
|
|
|
|
text: Option<String>,
|
|
|
|
}
|
|
|
|
|
|
|
|
pub async fn op_ws_send(
|
|
|
|
state: Rc<RefCell<OpState>>,
|
2021-03-17 17:33:29 -04:00
|
|
|
args: SendArgs,
|
2021-04-02 09:47:57 -04:00
|
|
|
buf: Option<ZeroCopyBuf>,
|
2021-04-05 12:40:24 -04:00
|
|
|
) -> Result<(), AnyError> {
|
2021-01-06 10:57:28 -05:00
|
|
|
let msg = match args.kind.as_str() {
|
|
|
|
"text" => Message::Text(args.text.unwrap()),
|
2021-04-02 09:47:57 -04:00
|
|
|
"binary" => Message::Binary(buf.ok_or_else(null_opbuf)?.to_vec()),
|
2021-01-06 10:57:28 -05:00
|
|
|
"pong" => Message::Pong(vec![]),
|
|
|
|
_ => unreachable!(),
|
|
|
|
};
|
|
|
|
let rid = args.rid;
|
|
|
|
|
|
|
|
let resource = state
|
|
|
|
.borrow_mut()
|
|
|
|
.resource_table
|
|
|
|
.get::<WsStreamResource>(rid)
|
|
|
|
.ok_or_else(bad_resource_id)?;
|
|
|
|
let mut tx = RcRef::map(&resource, |r| &r.tx).borrow_mut().await;
|
|
|
|
tx.send(msg).await?;
|
2021-04-05 12:40:24 -04:00
|
|
|
Ok(())
|
2021-01-06 10:57:28 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
#[derive(Deserialize)]
|
|
|
|
#[serde(rename_all = "camelCase")]
|
2021-03-17 17:33:29 -04:00
|
|
|
pub struct CloseArgs {
|
2021-03-19 13:25:37 -04:00
|
|
|
rid: ResourceId,
|
2021-01-06 10:57:28 -05:00
|
|
|
code: Option<u16>,
|
|
|
|
reason: Option<String>,
|
|
|
|
}
|
|
|
|
|
|
|
|
pub async fn op_ws_close(
|
|
|
|
state: Rc<RefCell<OpState>>,
|
2021-03-17 17:33:29 -04:00
|
|
|
args: CloseArgs,
|
2021-05-08 08:37:42 -04:00
|
|
|
_: (),
|
2021-04-05 12:40:24 -04:00
|
|
|
) -> Result<(), AnyError> {
|
2021-01-06 10:57:28 -05:00
|
|
|
let rid = args.rid;
|
|
|
|
let msg = Message::Close(args.code.map(|c| CloseFrame {
|
|
|
|
code: CloseCode::from(c),
|
|
|
|
reason: match args.reason {
|
|
|
|
Some(reason) => Cow::from(reason),
|
|
|
|
None => Default::default(),
|
|
|
|
},
|
|
|
|
}));
|
|
|
|
|
|
|
|
let resource = state
|
|
|
|
.borrow_mut()
|
|
|
|
.resource_table
|
|
|
|
.get::<WsStreamResource>(rid)
|
|
|
|
.ok_or_else(bad_resource_id)?;
|
|
|
|
let mut tx = RcRef::map(&resource, |r| &r.tx).borrow_mut().await;
|
|
|
|
tx.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,
|
|
|
|
}
|
|
|
|
|
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,
|
2021-05-08 08:37:42 -04:00
|
|
|
_: (),
|
2021-04-19 11:54:56 -04:00
|
|
|
) -> Result<NextEventResponse, AnyError> {
|
2021-01-06 10:57:28 -05:00
|
|
|
let resource = state
|
|
|
|
.borrow_mut()
|
|
|
|
.resource_table
|
2021-04-05 12:40:24 -04:00
|
|
|
.get::<WsStreamResource>(rid)
|
2021-01-06 10:57:28 -05:00
|
|
|
.ok_or_else(bad_resource_id)?;
|
|
|
|
|
|
|
|
let mut rx = RcRef::map(&resource, |r| &r.rx).borrow_mut().await;
|
|
|
|
let cancel = RcRef::map(resource, |r| &r.cancel);
|
|
|
|
let val = rx.next().or_cancel(cancel).await?;
|
|
|
|
let res = match val {
|
2021-04-19 11:54:56 -04:00
|
|
|
Some(Ok(Message::Text(text))) => NextEventResponse::String(text),
|
2021-04-30 11:03:50 -04:00
|
|
|
Some(Ok(Message::Binary(data))) => NextEventResponse::Binary(data.into()),
|
2021-04-19 11:54:56 -04:00
|
|
|
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,
|
2021-05-01 14:52:13 -04:00
|
|
|
Some(Err(e)) => NextEventResponse::Error(e.to_string()),
|
2021-01-06 10:57:28 -05:00
|
|
|
None => {
|
2021-04-05 12:40:24 -04:00
|
|
|
state.borrow_mut().resource_table.close(rid).unwrap();
|
2021-04-19 11:54:56 -04:00
|
|
|
NextEventResponse::Closed
|
2021-01-06 10:57:28 -05:00
|
|
|
}
|
|
|
|
};
|
|
|
|
Ok(res)
|
|
|
|
}
|
|
|
|
|
2021-04-28 12:41:50 -04:00
|
|
|
pub fn init<P: WebSocketPermissions + 'static>(
|
|
|
|
user_agent: String,
|
|
|
|
ca_data: Option<Vec<u8>>,
|
|
|
|
) -> Extension {
|
2021-04-28 18:16:45 -04:00
|
|
|
Extension::builder()
|
|
|
|
.js(include_js_files!(
|
2021-04-30 15:51:48 -04:00
|
|
|
prefix "deno:extensions/websocket",
|
2021-04-28 12:41:50 -04:00
|
|
|
"01_websocket.js",
|
2021-04-28 18:16:45 -04:00
|
|
|
))
|
|
|
|
.ops(vec![
|
2021-04-28 12:41:50 -04:00
|
|
|
(
|
|
|
|
"op_ws_check_permission",
|
|
|
|
op_sync(op_ws_check_permission::<P>),
|
|
|
|
),
|
|
|
|
("op_ws_create", op_async(op_ws_create::<P>)),
|
|
|
|
("op_ws_send", op_async(op_ws_send)),
|
|
|
|
("op_ws_close", op_async(op_ws_close)),
|
|
|
|
("op_ws_next_event", op_async(op_ws_next_event)),
|
2021-04-28 18:16:45 -04:00
|
|
|
])
|
|
|
|
.state(move |state| {
|
2021-04-28 12:41:50 -04:00
|
|
|
state.put::<WsUserAgent>(WsUserAgent(user_agent.clone()));
|
|
|
|
if let Some(ca_data) = ca_data.clone() {
|
|
|
|
state.put::<WsCaData>(WsCaData(ca_data));
|
|
|
|
}
|
|
|
|
Ok(())
|
2021-04-28 18:16:45 -04:00
|
|
|
})
|
|
|
|
.build()
|
2021-01-06 10:57:28 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
pub fn get_declaration() -> PathBuf {
|
|
|
|
PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("lib.deno_websocket.d.ts")
|
|
|
|
}
|