2020-09-05 10:39:25 -04:00
|
|
|
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
|
|
|
|
|
2020-09-19 19:17:35 -04:00
|
|
|
use crate::permissions::Permissions;
|
2020-09-05 10:39:25 -04:00
|
|
|
use core::task::Poll;
|
2020-09-14 12:48:57 -04:00
|
|
|
use deno_core::error::bad_resource_id;
|
|
|
|
use deno_core::error::type_error;
|
|
|
|
use deno_core::error::AnyError;
|
2020-09-21 12:36:37 -04:00
|
|
|
use deno_core::futures::future::poll_fn;
|
|
|
|
use deno_core::futures::StreamExt;
|
|
|
|
use deno_core::futures::{ready, SinkExt};
|
|
|
|
use deno_core::serde_json::json;
|
|
|
|
use deno_core::serde_json::Value;
|
2020-09-16 14:28:07 -04:00
|
|
|
use deno_core::url;
|
2020-09-05 20:34:02 -04:00
|
|
|
use deno_core::BufVec;
|
2020-09-10 09:57:45 -04:00
|
|
|
use deno_core::OpState;
|
2020-11-25 09:17:46 -05:00
|
|
|
use deno_core::{serde_json, ZeroCopyBuf};
|
2020-09-05 10:39:25 -04:00
|
|
|
use http::{Method, Request, Uri};
|
2020-09-16 12:43:08 -04:00
|
|
|
use serde::Deserialize;
|
2020-09-05 10:39:25 -04:00
|
|
|
use std::borrow::Cow;
|
2020-09-10 09:57:45 -04:00
|
|
|
use std::cell::RefCell;
|
2020-09-05 10:39:25 -04:00
|
|
|
use std::fs::File;
|
|
|
|
use std::io::BufReader;
|
|
|
|
use std::rc::Rc;
|
|
|
|
use std::sync::Arc;
|
|
|
|
use tokio::net::TcpStream;
|
|
|
|
use tokio_rustls::{rustls::ClientConfig, TlsConnector};
|
|
|
|
use tokio_tungstenite::stream::Stream as StreamSwitcher;
|
2020-09-14 12:48:57 -04:00
|
|
|
use tokio_tungstenite::tungstenite::Error as TungsteniteError;
|
2020-09-05 10:39:25 -04:00
|
|
|
use tokio_tungstenite::tungstenite::{
|
|
|
|
handshake::client::Response, protocol::frame::coding::CloseCode,
|
2020-09-14 12:48:57 -04:00
|
|
|
protocol::CloseFrame, Message,
|
2020-09-05 10:39:25 -04:00
|
|
|
};
|
|
|
|
use tokio_tungstenite::{client_async, WebSocketStream};
|
|
|
|
use webpki::DNSNameRef;
|
|
|
|
|
2020-12-11 12:49:26 -05:00
|
|
|
#[derive(Clone)]
|
|
|
|
struct WsCaFile(String);
|
2020-12-11 18:36:18 -05:00
|
|
|
#[derive(Clone)]
|
|
|
|
struct WsUserAgent(String);
|
2020-12-11 12:49:26 -05:00
|
|
|
|
2020-12-11 18:36:18 -05:00
|
|
|
pub fn init(
|
|
|
|
rt: &mut deno_core::JsRuntime,
|
|
|
|
maybe_ca_file: Option<&str>,
|
|
|
|
user_agent: String,
|
|
|
|
) {
|
2020-12-11 12:49:26 -05:00
|
|
|
{
|
|
|
|
let op_state = rt.op_state();
|
|
|
|
let mut state = op_state.borrow_mut();
|
|
|
|
if let Some(ca_file) = maybe_ca_file {
|
|
|
|
state.put::<WsCaFile>(WsCaFile(ca_file.to_string()));
|
|
|
|
}
|
2020-12-11 18:36:18 -05:00
|
|
|
state.put::<WsUserAgent>(WsUserAgent(user_agent));
|
2020-12-11 12:49:26 -05:00
|
|
|
}
|
2020-11-25 09:17:46 -05:00
|
|
|
super::reg_json_sync(rt, "op_ws_check_permission", op_ws_check_permission);
|
2020-09-10 09:57:45 -04:00
|
|
|
super::reg_json_async(rt, "op_ws_create", op_ws_create);
|
|
|
|
super::reg_json_async(rt, "op_ws_send", op_ws_send);
|
|
|
|
super::reg_json_async(rt, "op_ws_close", op_ws_close);
|
|
|
|
super::reg_json_async(rt, "op_ws_next_event", op_ws_next_event);
|
2020-09-05 10:39:25 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
type MaybeTlsStream =
|
|
|
|
StreamSwitcher<TcpStream, tokio_rustls::client::TlsStream<TcpStream>>;
|
|
|
|
|
|
|
|
type WsStream = WebSocketStream<MaybeTlsStream>;
|
|
|
|
|
2020-11-25 09:17:46 -05:00
|
|
|
#[derive(Deserialize)]
|
|
|
|
#[serde(rename_all = "camelCase")]
|
|
|
|
struct CheckPermissionArgs {
|
|
|
|
url: String,
|
|
|
|
}
|
|
|
|
|
|
|
|
// This op is needed because creating a WS instance in JavaScript is a sync
|
|
|
|
// operation and should throw error when permissions are not fullfiled,
|
|
|
|
// but actual op that connects WS is async.
|
|
|
|
pub fn op_ws_check_permission(
|
|
|
|
state: &mut OpState,
|
|
|
|
args: Value,
|
|
|
|
_zero_copy: &mut [ZeroCopyBuf],
|
|
|
|
) -> Result<Value, AnyError> {
|
|
|
|
let args: CheckPermissionArgs = serde_json::from_value(args)?;
|
|
|
|
|
|
|
|
state
|
|
|
|
.borrow::<Permissions>()
|
|
|
|
.check_net_url(&url::Url::parse(&args.url)?)?;
|
|
|
|
|
|
|
|
Ok(json!({}))
|
|
|
|
}
|
|
|
|
|
2020-09-05 10:39:25 -04:00
|
|
|
#[derive(Deserialize)]
|
|
|
|
#[serde(rename_all = "camelCase")]
|
|
|
|
struct CreateArgs {
|
|
|
|
url: String,
|
|
|
|
protocols: String,
|
|
|
|
}
|
|
|
|
|
2020-09-05 20:34:02 -04:00
|
|
|
pub async fn op_ws_create(
|
2020-09-10 09:57:45 -04:00
|
|
|
state: Rc<RefCell<OpState>>,
|
2020-09-05 10:39:25 -04:00
|
|
|
args: Value,
|
2020-09-05 20:34:02 -04:00
|
|
|
_bufs: BufVec,
|
2020-09-14 12:48:57 -04:00
|
|
|
) -> Result<Value, AnyError> {
|
2020-09-05 10:39:25 -04:00
|
|
|
let args: CreateArgs = serde_json::from_value(args)?;
|
2020-11-25 09:17:46 -05:00
|
|
|
|
2020-09-19 19:17:35 -04:00
|
|
|
{
|
|
|
|
let s = state.borrow();
|
|
|
|
s.borrow::<Permissions>()
|
2020-11-25 09:17:46 -05:00
|
|
|
.check_net_url(&url::Url::parse(&args.url)?)
|
|
|
|
.expect(
|
|
|
|
"Permission check should have been done in op_ws_check_permission",
|
|
|
|
);
|
2020-09-19 19:17:35 -04:00
|
|
|
}
|
2020-11-25 09:17:46 -05:00
|
|
|
|
2020-12-11 12:49:26 -05:00
|
|
|
let maybe_ca_file = state.borrow().try_borrow::<WsCaFile>().cloned();
|
2020-12-11 18:36:18 -05:00
|
|
|
let user_agent = state.borrow().borrow::<WsUserAgent>().0.clone();
|
2020-09-13 05:52:20 -04:00
|
|
|
let uri: Uri = args.url.parse()?;
|
2020-10-22 11:09:44 -04:00
|
|
|
let mut request = Request::builder().method(Method::GET).uri(&uri);
|
|
|
|
|
2020-12-11 18:36:18 -05:00
|
|
|
request = request.header("User-Agent", user_agent);
|
2020-11-26 07:58:50 -05:00
|
|
|
|
2020-10-22 11:09:44 -04:00
|
|
|
if !args.protocols.is_empty() {
|
|
|
|
request = request.header("Sec-WebSocket-Protocol", args.protocols);
|
|
|
|
}
|
|
|
|
|
|
|
|
let request = request.body(())?;
|
2020-09-05 20:34:02 -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 try_socket = TcpStream::connect(addr).await;
|
2020-09-14 12:48:57 -04:00
|
|
|
let tcp_socket = match try_socket.map_err(TungsteniteError::Io) {
|
2020-09-05 20:34:02 -04:00
|
|
|
Ok(socket) => socket,
|
|
|
|
Err(_) => return Ok(json!({"success": false})),
|
|
|
|
};
|
2020-09-05 10:39:25 -04:00
|
|
|
|
2020-09-05 20:34:02 -04:00
|
|
|
let socket: MaybeTlsStream = match uri.scheme_str() {
|
|
|
|
Some("ws") => StreamSwitcher::Plain(tcp_socket),
|
|
|
|
Some("wss") => {
|
|
|
|
let mut config = ClientConfig::new();
|
|
|
|
config
|
|
|
|
.root_store
|
|
|
|
.add_server_trust_anchors(&webpki_roots::TLS_SERVER_ROOTS);
|
2020-09-05 10:39:25 -04:00
|
|
|
|
2020-12-11 12:49:26 -05:00
|
|
|
if let Some(ws_ca_file) = maybe_ca_file {
|
|
|
|
let key_file = File::open(ws_ca_file.0)?;
|
2020-09-05 20:34:02 -04:00
|
|
|
let reader = &mut BufReader::new(key_file);
|
|
|
|
config.root_store.add_pem_file(reader).unwrap();
|
2020-09-05 10:39:25 -04:00
|
|
|
}
|
|
|
|
|
2020-09-05 20:34:02 -04:00
|
|
|
let tls_connector = TlsConnector::from(Arc::new(config));
|
|
|
|
let dnsname =
|
|
|
|
DNSNameRef::try_from_ascii_str(&domain).expect("Invalid DNS lookup");
|
|
|
|
let tls_socket = tls_connector.connect(dnsname, tcp_socket).await?;
|
|
|
|
StreamSwitcher::Tls(tls_socket)
|
|
|
|
}
|
|
|
|
_ => unreachable!(),
|
|
|
|
};
|
|
|
|
|
|
|
|
let (stream, response): (WsStream, Response) =
|
2020-09-13 05:52:20 -04:00
|
|
|
client_async(request, socket).await.map_err(|err| {
|
2020-09-14 12:48:57 -04:00
|
|
|
type_error(format!(
|
2020-09-13 05:52:20 -04:00
|
|
|
"failed to connect to WebSocket: {}",
|
|
|
|
err.to_string()
|
|
|
|
))
|
|
|
|
})?;
|
2020-09-05 10:39:25 -04:00
|
|
|
|
2020-09-10 09:57:45 -04:00
|
|
|
let mut state = state.borrow_mut();
|
2020-09-05 20:34:02 -04:00
|
|
|
let rid = state
|
|
|
|
.resource_table
|
|
|
|
.add("webSocketStream", Box::new(stream));
|
2020-09-05 10:39:25 -04:00
|
|
|
|
2020-09-05 20:34:02 -04:00
|
|
|
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>();
|
|
|
|
Ok(json!({
|
2020-09-05 10:39:25 -04:00
|
|
|
"success": true,
|
|
|
|
"rid": rid,
|
|
|
|
"protocol": protocol,
|
|
|
|
"extensions": extensions
|
2020-09-05 20:34:02 -04:00
|
|
|
}))
|
2020-09-05 10:39:25 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
#[derive(Deserialize)]
|
|
|
|
#[serde(rename_all = "camelCase")]
|
|
|
|
struct SendArgs {
|
|
|
|
rid: u32,
|
|
|
|
text: Option<String>,
|
|
|
|
}
|
|
|
|
|
2020-09-05 20:34:02 -04:00
|
|
|
pub async fn op_ws_send(
|
2020-09-10 09:57:45 -04:00
|
|
|
state: Rc<RefCell<OpState>>,
|
2020-09-05 10:39:25 -04:00
|
|
|
args: Value,
|
2020-09-05 20:34:02 -04:00
|
|
|
bufs: BufVec,
|
2020-09-14 12:48:57 -04:00
|
|
|
) -> Result<Value, AnyError> {
|
2020-09-05 10:39:25 -04:00
|
|
|
let args: SendArgs = serde_json::from_value(args)?;
|
|
|
|
|
|
|
|
let mut maybe_msg = Some(match args.text {
|
|
|
|
Some(text) => Message::Text(text),
|
2020-09-05 20:34:02 -04:00
|
|
|
None => Message::Binary(bufs[0].to_vec()),
|
2020-09-05 10:39:25 -04:00
|
|
|
});
|
|
|
|
let rid = args.rid;
|
|
|
|
|
2020-09-05 20:34:02 -04:00
|
|
|
poll_fn(move |cx| {
|
2020-09-10 09:57:45 -04:00
|
|
|
let mut state = state.borrow_mut();
|
|
|
|
let stream = state
|
|
|
|
.resource_table
|
2020-09-05 10:39:25 -04:00
|
|
|
.get_mut::<WsStream>(rid)
|
2020-09-14 12:48:57 -04:00
|
|
|
.ok_or_else(bad_resource_id)?;
|
2020-09-05 10:39:25 -04:00
|
|
|
|
|
|
|
// TODO(ry) Handle errors below instead of unwrap.
|
2020-09-14 12:48:57 -04:00
|
|
|
// Need to map `TungsteniteError` to `AnyError`.
|
2020-09-05 10:39:25 -04:00
|
|
|
ready!(stream.poll_ready_unpin(cx)).unwrap();
|
|
|
|
if let Some(msg) = maybe_msg.take() {
|
|
|
|
stream.start_send_unpin(msg).unwrap();
|
|
|
|
}
|
|
|
|
ready!(stream.poll_flush_unpin(cx)).unwrap();
|
|
|
|
|
|
|
|
Poll::Ready(Ok(json!({})))
|
2020-09-05 20:34:02 -04:00
|
|
|
})
|
|
|
|
.await
|
2020-09-05 10:39:25 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
#[derive(Deserialize)]
|
|
|
|
#[serde(rename_all = "camelCase")]
|
|
|
|
struct CloseArgs {
|
|
|
|
rid: u32,
|
|
|
|
code: Option<u16>,
|
|
|
|
reason: Option<String>,
|
|
|
|
}
|
|
|
|
|
2020-09-05 20:34:02 -04:00
|
|
|
pub async fn op_ws_close(
|
2020-09-10 09:57:45 -04:00
|
|
|
state: Rc<RefCell<OpState>>,
|
2020-09-05 10:39:25 -04:00
|
|
|
args: Value,
|
2020-09-05 20:34:02 -04:00
|
|
|
_bufs: BufVec,
|
2020-09-14 12:48:57 -04:00
|
|
|
) -> Result<Value, AnyError> {
|
2020-09-05 10:39:25 -04:00
|
|
|
let args: CloseArgs = serde_json::from_value(args)?;
|
|
|
|
let rid = args.rid;
|
|
|
|
let mut maybe_msg = Some(Message::Close(args.code.map(|c| CloseFrame {
|
|
|
|
code: CloseCode::from(c),
|
|
|
|
reason: match args.reason {
|
|
|
|
Some(reason) => Cow::from(reason),
|
|
|
|
None => Default::default(),
|
|
|
|
},
|
|
|
|
})));
|
|
|
|
|
2020-09-05 20:34:02 -04:00
|
|
|
poll_fn(move |cx| {
|
2020-09-10 09:57:45 -04:00
|
|
|
let mut state = state.borrow_mut();
|
|
|
|
let stream = state
|
|
|
|
.resource_table
|
2020-09-05 10:39:25 -04:00
|
|
|
.get_mut::<WsStream>(rid)
|
2020-09-14 12:48:57 -04:00
|
|
|
.ok_or_else(bad_resource_id)?;
|
2020-09-05 10:39:25 -04:00
|
|
|
|
|
|
|
// TODO(ry) Handle errors below instead of unwrap.
|
2020-09-14 12:48:57 -04:00
|
|
|
// Need to map `TungsteniteError` to `AnyError`.
|
2020-09-05 10:39:25 -04:00
|
|
|
ready!(stream.poll_ready_unpin(cx)).unwrap();
|
|
|
|
if let Some(msg) = maybe_msg.take() {
|
|
|
|
stream.start_send_unpin(msg).unwrap();
|
|
|
|
}
|
|
|
|
ready!(stream.poll_flush_unpin(cx)).unwrap();
|
|
|
|
ready!(stream.poll_close_unpin(cx)).unwrap();
|
|
|
|
|
|
|
|
Poll::Ready(Ok(json!({})))
|
2020-09-05 20:34:02 -04:00
|
|
|
})
|
|
|
|
.await
|
2020-09-05 10:39:25 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
#[derive(Deserialize)]
|
|
|
|
#[serde(rename_all = "camelCase")]
|
|
|
|
struct NextEventArgs {
|
|
|
|
rid: u32,
|
|
|
|
}
|
|
|
|
|
2020-09-05 20:34:02 -04:00
|
|
|
pub async fn op_ws_next_event(
|
2020-09-10 09:57:45 -04:00
|
|
|
state: Rc<RefCell<OpState>>,
|
2020-09-05 10:39:25 -04:00
|
|
|
args: Value,
|
2020-09-05 20:34:02 -04:00
|
|
|
_bufs: BufVec,
|
2020-09-14 12:48:57 -04:00
|
|
|
) -> Result<Value, AnyError> {
|
2020-09-05 10:39:25 -04:00
|
|
|
let args: NextEventArgs = serde_json::from_value(args)?;
|
2020-09-05 20:34:02 -04:00
|
|
|
poll_fn(move |cx| {
|
2020-09-10 09:57:45 -04:00
|
|
|
let mut state = state.borrow_mut();
|
|
|
|
let stream = state
|
|
|
|
.resource_table
|
2020-09-05 10:39:25 -04:00
|
|
|
.get_mut::<WsStream>(args.rid)
|
2020-09-14 12:48:57 -04:00
|
|
|
.ok_or_else(bad_resource_id)?;
|
2020-09-05 20:34:02 -04:00
|
|
|
stream
|
|
|
|
.poll_next_unpin(cx)
|
|
|
|
.map(|val| {
|
|
|
|
match val {
|
|
|
|
Some(Ok(Message::Text(text))) => json!({
|
|
|
|
"type": "string",
|
|
|
|
"data": text
|
|
|
|
}),
|
|
|
|
Some(Ok(Message::Binary(data))) => {
|
|
|
|
// TODO(ry): don't use json to send binary data.
|
|
|
|
json!({
|
|
|
|
"type": "binary",
|
|
|
|
"data": data
|
|
|
|
})
|
|
|
|
}
|
|
|
|
Some(Ok(Message::Close(Some(frame)))) => json!({
|
|
|
|
"type": "close",
|
|
|
|
"code": u16::from(frame.code),
|
|
|
|
"reason": frame.reason.as_ref()
|
|
|
|
}),
|
|
|
|
Some(Ok(Message::Close(None))) => json!({ "type": "close" }),
|
|
|
|
Some(Ok(Message::Ping(_))) => json!({"type": "ping"}),
|
|
|
|
Some(Ok(Message::Pong(_))) => json!({"type": "pong"}),
|
|
|
|
Some(Err(_)) => json!({"type": "error"}),
|
|
|
|
None => {
|
2020-09-10 09:57:45 -04:00
|
|
|
state.resource_table.close(args.rid).unwrap();
|
2020-09-05 20:34:02 -04:00
|
|
|
json!({"type": "closed"})
|
2020-09-05 10:39:25 -04:00
|
|
|
}
|
|
|
|
}
|
2020-09-05 20:34:02 -04:00
|
|
|
})
|
|
|
|
.map(Ok)
|
|
|
|
})
|
|
|
|
.await
|
2020-09-05 10:39:25 -04:00
|
|
|
}
|