2023-01-02 16:00:42 -05:00
|
|
|
// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
|
2020-09-05 20:34:02 -04:00
|
|
|
|
2021-06-28 19:43:03 -04:00
|
|
|
use crate::io::TcpStreamResource;
|
|
|
|
use crate::ops::IpAddr;
|
2021-11-26 13:59:53 -05:00
|
|
|
use crate::ops::TlsHandshakeInfo;
|
2019-09-23 14:40:38 -04:00
|
|
|
use crate::resolve_addr::resolve_addr;
|
2020-12-15 07:02:26 -05:00
|
|
|
use crate::resolve_addr::resolve_addr_sync;
|
2021-07-22 06:28:46 -04:00
|
|
|
use crate::DefaultTlsOptions;
|
2021-06-28 19:43:03 -04:00
|
|
|
use crate::NetPermissions;
|
2021-08-10 07:19:45 -04:00
|
|
|
use crate::UnsafelyIgnoreCertificateErrors;
|
2020-09-14 12:48:57 -04:00
|
|
|
use deno_core::error::bad_resource;
|
|
|
|
use deno_core::error::custom_error;
|
2020-12-29 20:19:28 -05:00
|
|
|
use deno_core::error::generic_error;
|
2021-04-26 15:39:55 -04:00
|
|
|
use deno_core::error::invalid_hostname;
|
2021-08-09 09:55:00 -04:00
|
|
|
use deno_core::error::type_error;
|
2020-09-14 12:48:57 -04:00
|
|
|
use deno_core::error::AnyError;
|
2021-05-10 19:49:57 -04:00
|
|
|
use deno_core::futures::future::poll_fn;
|
|
|
|
use deno_core::futures::ready;
|
|
|
|
use deno_core::futures::task::noop_waker_ref;
|
|
|
|
use deno_core::futures::task::AtomicWaker;
|
|
|
|
use deno_core::futures::task::Context;
|
|
|
|
use deno_core::futures::task::Poll;
|
|
|
|
use deno_core::futures::task::RawWaker;
|
|
|
|
use deno_core::futures::task::RawWakerVTable;
|
|
|
|
use deno_core::futures::task::Waker;
|
2022-03-14 13:44:15 -04:00
|
|
|
use deno_core::op;
|
|
|
|
|
2021-07-06 23:48:01 -04:00
|
|
|
use deno_core::parking_lot::Mutex;
|
2023-05-14 17:40:01 -04:00
|
|
|
use deno_core::task::spawn;
|
2020-12-16 11:14:12 -05:00
|
|
|
use deno_core::AsyncRefCell;
|
2021-11-09 13:26:17 -05:00
|
|
|
use deno_core::AsyncResult;
|
2021-11-26 13:59:53 -05:00
|
|
|
use deno_core::ByteString;
|
2020-12-16 11:14:12 -05:00
|
|
|
use deno_core::CancelHandle;
|
|
|
|
use deno_core::CancelTryFuture;
|
2020-09-10 09:57:45 -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::create_client_config;
|
2021-08-25 08:25:12 -04:00
|
|
|
use deno_tls::load_certs;
|
|
|
|
use deno_tls::load_private_keys;
|
2021-08-07 08:49:38 -04:00
|
|
|
use deno_tls::rustls::Certificate;
|
|
|
|
use deno_tls::rustls::ClientConfig;
|
2021-12-06 18:48:11 -05:00
|
|
|
use deno_tls::rustls::ClientConnection;
|
|
|
|
use deno_tls::rustls::Connection;
|
2021-08-07 08:49:38 -04:00
|
|
|
use deno_tls::rustls::PrivateKey;
|
|
|
|
use deno_tls::rustls::ServerConfig;
|
2021-12-06 18:48:11 -05:00
|
|
|
use deno_tls::rustls::ServerConnection;
|
|
|
|
use deno_tls::rustls::ServerName;
|
2021-05-10 19:49:57 -04:00
|
|
|
use io::Error;
|
|
|
|
use io::Read;
|
|
|
|
use io::Write;
|
2020-09-16 12:43:08 -04:00
|
|
|
use serde::Deserialize;
|
2022-03-04 18:43:48 -05:00
|
|
|
use socket2::Domain;
|
|
|
|
use socket2::Socket;
|
|
|
|
use socket2::Type;
|
2020-12-16 11:14:12 -05:00
|
|
|
use std::borrow::Cow;
|
2020-09-10 09:57:45 -04:00
|
|
|
use std::cell::RefCell;
|
2019-09-23 14:40:38 -04:00
|
|
|
use std::convert::From;
|
2021-12-06 18:48:11 -05:00
|
|
|
use std::convert::TryFrom;
|
2019-10-21 14:38:28 -04:00
|
|
|
use std::fs::File;
|
2021-05-10 19:49:57 -04:00
|
|
|
use std::io;
|
2019-10-21 14:38:28 -04:00
|
|
|
use std::io::BufReader;
|
2021-05-10 19:49:57 -04:00
|
|
|
use std::io::ErrorKind;
|
2023-04-22 13:48:21 -04:00
|
|
|
use std::net::SocketAddr;
|
2020-01-20 09:45:44 -05:00
|
|
|
use std::path::Path;
|
2021-05-10 19:49:57 -04:00
|
|
|
use std::pin::Pin;
|
2020-08-18 12:30:13 -04:00
|
|
|
use std::rc::Rc;
|
2019-09-23 14:40:38 -04:00
|
|
|
use std::sync::Arc;
|
2021-05-10 19:49:57 -04:00
|
|
|
use std::sync::Weak;
|
|
|
|
use tokio::io::AsyncRead;
|
2021-10-19 19:30:04 -04:00
|
|
|
use tokio::io::AsyncReadExt;
|
2021-05-10 19:49:57 -04:00
|
|
|
use tokio::io::AsyncWrite;
|
2021-10-19 19:30:04 -04:00
|
|
|
use tokio::io::AsyncWriteExt;
|
2021-05-10 19:49:57 -04:00
|
|
|
use tokio::io::ReadBuf;
|
2019-10-21 14:38:28 -04:00
|
|
|
use tokio::net::TcpListener;
|
2019-09-23 14:40:38 -04:00
|
|
|
use tokio::net::TcpStream;
|
2021-01-12 19:22:33 -05:00
|
|
|
|
2021-05-10 19:49:57 -04:00
|
|
|
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
|
|
|
|
enum Flow {
|
2021-10-19 19:30:04 -04:00
|
|
|
Handshake,
|
2021-05-10 19:49:57 -04:00
|
|
|
Read,
|
|
|
|
Write,
|
|
|
|
}
|
|
|
|
|
|
|
|
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
|
|
|
|
enum State {
|
|
|
|
StreamOpen,
|
|
|
|
StreamClosed,
|
|
|
|
TlsClosing,
|
|
|
|
TlsClosed,
|
|
|
|
TcpClosed,
|
|
|
|
}
|
|
|
|
|
|
|
|
pub struct TlsStream(Option<TlsStreamInner>);
|
|
|
|
|
|
|
|
impl TlsStream {
|
2021-12-06 18:48:11 -05:00
|
|
|
fn new(tcp: TcpStream, mut tls: Connection) -> Self {
|
|
|
|
tls.set_buffer_limit(None);
|
|
|
|
|
2021-05-10 19:49:57 -04:00
|
|
|
let inner = TlsStreamInner {
|
|
|
|
tcp,
|
|
|
|
tls,
|
|
|
|
rd_state: State::StreamOpen,
|
|
|
|
wr_state: State::StreamOpen,
|
|
|
|
};
|
|
|
|
Self(Some(inner))
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn new_client_side(
|
|
|
|
tcp: TcpStream,
|
2021-12-06 18:48:11 -05:00
|
|
|
tls_config: Arc<ClientConfig>,
|
|
|
|
server_name: ServerName,
|
2021-05-10 19:49:57 -04:00
|
|
|
) -> Self {
|
2021-12-06 18:48:11 -05:00
|
|
|
let tls = ClientConnection::new(tls_config, server_name).unwrap();
|
|
|
|
Self::new(tcp, Connection::Client(tls))
|
2021-05-10 19:49:57 -04:00
|
|
|
}
|
|
|
|
|
2023-04-22 13:48:21 -04:00
|
|
|
pub fn new_client_side_from(
|
|
|
|
tcp: TcpStream,
|
|
|
|
connection: ClientConnection,
|
|
|
|
) -> Self {
|
|
|
|
Self::new(tcp, Connection::Client(connection))
|
|
|
|
}
|
|
|
|
|
2021-05-10 19:49:57 -04:00
|
|
|
pub fn new_server_side(
|
|
|
|
tcp: TcpStream,
|
2021-12-06 18:48:11 -05:00
|
|
|
tls_config: Arc<ServerConfig>,
|
2021-05-10 19:49:57 -04:00
|
|
|
) -> Self {
|
2021-12-06 18:48:11 -05:00
|
|
|
let tls = ServerConnection::new(tls_config).unwrap();
|
|
|
|
Self::new(tcp, Connection::Server(tls))
|
2021-05-10 19:49:57 -04:00
|
|
|
}
|
|
|
|
|
2023-04-22 13:48:21 -04:00
|
|
|
pub fn new_server_side_from(
|
|
|
|
tcp: TcpStream,
|
|
|
|
connection: ServerConnection,
|
|
|
|
) -> Self {
|
|
|
|
Self::new(tcp, Connection::Server(connection))
|
|
|
|
}
|
|
|
|
|
2022-03-16 09:54:18 -04:00
|
|
|
pub fn into_split(self) -> (ReadHalf, WriteHalf) {
|
2021-05-10 19:49:57 -04:00
|
|
|
let shared = Shared::new(self);
|
|
|
|
let rd = ReadHalf {
|
|
|
|
shared: shared.clone(),
|
|
|
|
};
|
|
|
|
let wr = WriteHalf { shared };
|
|
|
|
(rd, wr)
|
|
|
|
}
|
|
|
|
|
2023-04-22 13:48:21 -04:00
|
|
|
/// Convenience method to match [`TcpStream`].
|
|
|
|
pub fn peer_addr(&self) -> Result<SocketAddr, io::Error> {
|
|
|
|
self.0.as_ref().unwrap().tcp.peer_addr()
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Convenience method to match [`TcpStream`].
|
|
|
|
pub fn local_addr(&self) -> Result<SocketAddr, io::Error> {
|
|
|
|
self.0.as_ref().unwrap().tcp.local_addr()
|
|
|
|
}
|
|
|
|
|
2021-05-10 19:49:57 -04:00
|
|
|
/// Tokio-rustls compatibility: returns a reference to the underlying TCP
|
2021-12-06 18:48:11 -05:00
|
|
|
/// stream, and a reference to the Rustls `Connection` object.
|
|
|
|
pub fn get_ref(&self) -> (&TcpStream, &Connection) {
|
2021-05-10 19:49:57 -04:00
|
|
|
let inner = self.0.as_ref().unwrap();
|
2021-12-06 18:48:11 -05:00
|
|
|
(&inner.tcp, &inner.tls)
|
2021-05-10 19:49:57 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
fn inner_mut(&mut self) -> &mut TlsStreamInner {
|
|
|
|
self.0.as_mut().unwrap()
|
|
|
|
}
|
2021-10-19 19:30:04 -04:00
|
|
|
|
|
|
|
pub async fn handshake(&mut self) -> io::Result<()> {
|
|
|
|
poll_fn(|cx| self.inner_mut().poll_handshake(cx)).await
|
|
|
|
}
|
|
|
|
|
|
|
|
fn poll_handshake(&mut self, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
|
|
|
|
self.inner_mut().poll_handshake(cx)
|
|
|
|
}
|
2021-11-26 13:59:53 -05:00
|
|
|
|
|
|
|
fn get_alpn_protocol(&mut self) -> Option<ByteString> {
|
2022-04-02 08:37:11 -04:00
|
|
|
self.inner_mut().tls.alpn_protocol().map(|s| s.into())
|
2021-11-26 13:59:53 -05:00
|
|
|
}
|
2021-05-10 19:49:57 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
impl AsyncRead for TlsStream {
|
|
|
|
fn poll_read(
|
|
|
|
mut self: Pin<&mut Self>,
|
|
|
|
cx: &mut Context<'_>,
|
|
|
|
buf: &mut ReadBuf<'_>,
|
|
|
|
) -> Poll<io::Result<()>> {
|
|
|
|
self.inner_mut().poll_read(cx, buf)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl AsyncWrite for TlsStream {
|
|
|
|
fn poll_write(
|
|
|
|
mut self: Pin<&mut Self>,
|
|
|
|
cx: &mut Context<'_>,
|
|
|
|
buf: &[u8],
|
|
|
|
) -> Poll<io::Result<usize>> {
|
|
|
|
self.inner_mut().poll_write(cx, buf)
|
|
|
|
}
|
|
|
|
|
|
|
|
fn poll_flush(
|
|
|
|
mut self: Pin<&mut Self>,
|
|
|
|
cx: &mut Context<'_>,
|
|
|
|
) -> Poll<io::Result<()>> {
|
|
|
|
self.inner_mut().poll_io(cx, Flow::Write)
|
|
|
|
// The underlying TCP stream does not need to be flushed.
|
|
|
|
}
|
|
|
|
|
|
|
|
fn poll_shutdown(
|
|
|
|
mut self: Pin<&mut Self>,
|
|
|
|
cx: &mut Context<'_>,
|
|
|
|
) -> Poll<io::Result<()>> {
|
|
|
|
self.inner_mut().poll_shutdown(cx)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Drop for TlsStream {
|
|
|
|
fn drop(&mut self) {
|
|
|
|
let mut inner = self.0.take().unwrap();
|
|
|
|
|
|
|
|
let mut cx = Context::from_waker(noop_waker_ref());
|
|
|
|
let use_linger_task = inner.poll_close(&mut cx).is_pending();
|
|
|
|
|
|
|
|
if use_linger_task {
|
2023-05-14 17:40:01 -04:00
|
|
|
spawn(poll_fn(move |cx| inner.poll_close(cx)));
|
2021-05-10 19:49:57 -04:00
|
|
|
} else if cfg!(debug_assertions) {
|
2023-05-14 17:40:01 -04:00
|
|
|
spawn(async {}); // Spawn dummy task to detect missing runtime.
|
2021-05-10 19:49:57 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
pub struct TlsStreamInner {
|
2021-12-06 18:48:11 -05:00
|
|
|
tls: Connection,
|
2021-05-10 19:49:57 -04:00
|
|
|
tcp: TcpStream,
|
|
|
|
rd_state: State,
|
|
|
|
wr_state: State,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl TlsStreamInner {
|
|
|
|
fn poll_io(
|
|
|
|
&mut self,
|
|
|
|
cx: &mut Context<'_>,
|
|
|
|
flow: Flow,
|
|
|
|
) -> Poll<io::Result<()>> {
|
|
|
|
loop {
|
|
|
|
let wr_ready = loop {
|
|
|
|
match self.wr_state {
|
|
|
|
_ if self.tls.is_handshaking() && !self.tls.wants_write() => {
|
|
|
|
break true;
|
|
|
|
}
|
|
|
|
_ if self.tls.is_handshaking() => {}
|
|
|
|
State::StreamOpen if !self.tls.wants_write() => break true,
|
|
|
|
State::StreamClosed => {
|
|
|
|
// Rustls will enqueue the 'CloseNotify' alert and send it after
|
2021-12-06 18:48:11 -05:00
|
|
|
// flushing the data that is already in the queue.
|
2021-05-10 19:49:57 -04:00
|
|
|
self.tls.send_close_notify();
|
|
|
|
self.wr_state = State::TlsClosing;
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
State::TlsClosing if !self.tls.wants_write() => {
|
|
|
|
self.wr_state = State::TlsClosed;
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
// If a 'CloseNotify' alert sent by the remote end has been received,
|
|
|
|
// shut down the underlying TCP socket. Otherwise, consider polling
|
|
|
|
// done for the moment.
|
|
|
|
State::TlsClosed if self.rd_state < State::TlsClosed => break true,
|
|
|
|
State::TlsClosed
|
|
|
|
if Pin::new(&mut self.tcp).poll_shutdown(cx)?.is_pending() =>
|
|
|
|
{
|
|
|
|
break false;
|
|
|
|
}
|
|
|
|
State::TlsClosed => {
|
|
|
|
self.wr_state = State::TcpClosed;
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
State::TcpClosed => break true,
|
|
|
|
_ => {}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Write ciphertext to the TCP socket.
|
|
|
|
let mut wrapped_tcp = ImplementWriteTrait(&mut self.tcp);
|
|
|
|
match self.tls.write_tls(&mut wrapped_tcp) {
|
2021-10-19 19:30:04 -04:00
|
|
|
Ok(0) => {} // Wait until the socket has enough buffer space.
|
|
|
|
Ok(_) => continue, // Try to send more more data immediately.
|
|
|
|
Err(err) if err.kind() == ErrorKind::WouldBlock => unreachable!(),
|
2021-05-10 19:49:57 -04:00
|
|
|
Err(err) => return Poll::Ready(Err(err)),
|
|
|
|
}
|
2021-10-19 19:30:04 -04:00
|
|
|
|
|
|
|
// Poll whether there is space in the socket send buffer so we can flush
|
|
|
|
// the remaining outgoing ciphertext.
|
|
|
|
if self.tcp.poll_write_ready(cx)?.is_pending() {
|
|
|
|
break false;
|
|
|
|
}
|
2021-05-10 19:49:57 -04:00
|
|
|
};
|
|
|
|
|
|
|
|
let rd_ready = loop {
|
2021-12-06 18:48:11 -05:00
|
|
|
// Interpret and decrypt unprocessed TLS protocol data.
|
|
|
|
let tls_state = self
|
|
|
|
.tls
|
|
|
|
.process_new_packets()
|
|
|
|
.map_err(|e| Error::new(ErrorKind::InvalidData, e))?;
|
|
|
|
|
2021-05-10 19:49:57 -04:00
|
|
|
match self.rd_state {
|
|
|
|
State::TcpClosed if self.tls.is_handshaking() => {
|
|
|
|
let err = Error::new(ErrorKind::UnexpectedEof, "tls handshake eof");
|
|
|
|
return Poll::Ready(Err(err));
|
|
|
|
}
|
|
|
|
_ if self.tls.is_handshaking() && !self.tls.wants_read() => {
|
|
|
|
break true;
|
|
|
|
}
|
|
|
|
_ if self.tls.is_handshaking() => {}
|
2021-12-06 18:48:11 -05:00
|
|
|
State::StreamOpen if tls_state.plaintext_bytes_to_read() > 0 => {
|
|
|
|
break true;
|
|
|
|
}
|
|
|
|
State::StreamOpen if tls_state.peer_has_closed() => {
|
|
|
|
self.rd_state = State::TlsClosed;
|
|
|
|
continue;
|
|
|
|
}
|
2021-05-10 19:49:57 -04:00
|
|
|
State::StreamOpen => {}
|
2021-12-06 18:48:11 -05:00
|
|
|
State::StreamClosed if tls_state.plaintext_bytes_to_read() > 0 => {
|
2021-05-10 19:49:57 -04:00
|
|
|
// Rustls has more incoming cleartext buffered up, but the TLS
|
|
|
|
// session is closing so this data will never be processed by the
|
|
|
|
// application layer. Just like what would happen if this were a raw
|
|
|
|
// TCP stream, don't gracefully end the TLS session, but abort it.
|
|
|
|
return Poll::Ready(Err(Error::from(ErrorKind::ConnectionReset)));
|
|
|
|
}
|
|
|
|
State::StreamClosed => {}
|
|
|
|
State::TlsClosed if self.wr_state == State::TcpClosed => {
|
2021-12-06 18:48:11 -05:00
|
|
|
// Keep trying to read from the TCP connection until the remote end
|
|
|
|
// closes it gracefully.
|
2021-05-10 19:49:57 -04:00
|
|
|
}
|
2021-12-06 18:48:11 -05:00
|
|
|
State::TlsClosed => break true,
|
|
|
|
State::TcpClosed => break true,
|
|
|
|
_ => unreachable!(),
|
2021-05-10 19:49:57 -04:00
|
|
|
}
|
|
|
|
|
2021-12-06 18:48:11 -05:00
|
|
|
// Try to read more TLS protocol data from the TCP socket.
|
|
|
|
let mut wrapped_tcp = ImplementReadTrait(&mut self.tcp);
|
|
|
|
match self.tls.read_tls(&mut wrapped_tcp) {
|
|
|
|
Ok(0) => {
|
|
|
|
self.rd_state = State::TcpClosed;
|
|
|
|
continue;
|
2021-10-19 19:30:04 -04:00
|
|
|
}
|
2021-12-06 18:48:11 -05:00
|
|
|
Ok(_) => continue,
|
|
|
|
Err(err) if err.kind() == ErrorKind::WouldBlock => {}
|
|
|
|
Err(err) => return Poll::Ready(Err(err)),
|
2021-05-10 19:49:57 -04:00
|
|
|
}
|
|
|
|
|
2021-12-06 18:48:11 -05:00
|
|
|
// Get notified when more ciphertext becomes available to read from the
|
|
|
|
// TCP socket.
|
|
|
|
if self.tcp.poll_read_ready(cx)?.is_pending() {
|
|
|
|
break false;
|
2021-05-10 19:49:57 -04:00
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
if wr_ready {
|
|
|
|
if self.rd_state >= State::TlsClosed
|
|
|
|
&& self.wr_state >= State::TlsClosed
|
|
|
|
&& self.wr_state < State::TcpClosed
|
|
|
|
{
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
if self.tls.wants_write() {
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
let io_ready = match flow {
|
|
|
|
_ if self.tls.is_handshaking() => false,
|
2021-10-19 19:30:04 -04:00
|
|
|
Flow::Handshake => true,
|
2021-05-10 19:49:57 -04:00
|
|
|
Flow::Read => rd_ready,
|
|
|
|
Flow::Write => wr_ready,
|
|
|
|
};
|
|
|
|
return match io_ready {
|
|
|
|
false => Poll::Pending,
|
|
|
|
true => Poll::Ready(Ok(())),
|
|
|
|
};
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-10-19 19:30:04 -04:00
|
|
|
fn poll_handshake(&mut self, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
|
|
|
|
if self.tls.is_handshaking() {
|
|
|
|
ready!(self.poll_io(cx, Flow::Handshake))?;
|
|
|
|
}
|
|
|
|
Poll::Ready(Ok(()))
|
|
|
|
}
|
|
|
|
|
2021-05-10 19:49:57 -04:00
|
|
|
fn poll_read(
|
|
|
|
&mut self,
|
|
|
|
cx: &mut Context<'_>,
|
|
|
|
buf: &mut ReadBuf<'_>,
|
|
|
|
) -> Poll<io::Result<()>> {
|
|
|
|
ready!(self.poll_io(cx, Flow::Read))?;
|
|
|
|
|
|
|
|
if self.rd_state == State::StreamOpen {
|
2022-06-25 18:13:24 -04:00
|
|
|
// TODO(bartlomieju):
|
|
|
|
#[allow(clippy::undocumented_unsafe_blocks)]
|
2021-05-10 19:49:57 -04:00
|
|
|
let buf_slice =
|
|
|
|
unsafe { &mut *(buf.unfilled_mut() as *mut [_] as *mut [u8]) };
|
2021-12-06 18:48:11 -05:00
|
|
|
let bytes_read = self.tls.reader().read(buf_slice)?;
|
2021-05-10 19:49:57 -04:00
|
|
|
assert_ne!(bytes_read, 0);
|
2022-06-25 18:13:24 -04:00
|
|
|
// TODO(bartlomieju):
|
|
|
|
#[allow(clippy::undocumented_unsafe_blocks)]
|
|
|
|
unsafe {
|
|
|
|
buf.assume_init(bytes_read)
|
|
|
|
};
|
2021-05-10 19:49:57 -04:00
|
|
|
buf.advance(bytes_read);
|
|
|
|
}
|
|
|
|
|
|
|
|
Poll::Ready(Ok(()))
|
|
|
|
}
|
|
|
|
|
|
|
|
fn poll_write(
|
|
|
|
&mut self,
|
|
|
|
cx: &mut Context<'_>,
|
|
|
|
buf: &[u8],
|
|
|
|
) -> Poll<io::Result<usize>> {
|
|
|
|
if buf.is_empty() {
|
|
|
|
// Tokio-rustls compatibility: a zero byte write always succeeds.
|
|
|
|
Poll::Ready(Ok(0))
|
|
|
|
} else if self.wr_state == State::StreamOpen {
|
|
|
|
// Flush Rustls' ciphertext send queue.
|
|
|
|
ready!(self.poll_io(cx, Flow::Write))?;
|
|
|
|
|
|
|
|
// Copy data from `buf` to the Rustls cleartext send queue.
|
2021-12-06 18:48:11 -05:00
|
|
|
let bytes_written = self.tls.writer().write(buf)?;
|
2021-05-10 19:49:57 -04:00
|
|
|
assert_ne!(bytes_written, 0);
|
|
|
|
|
|
|
|
// Try to flush as much ciphertext as possible. However, since we just
|
|
|
|
// handed off at least some bytes to rustls, so we can't return
|
|
|
|
// `Poll::Pending()` any more: this would tell the caller that it should
|
|
|
|
// try to send those bytes again.
|
|
|
|
let _ = self.poll_io(cx, Flow::Write)?;
|
|
|
|
|
|
|
|
Poll::Ready(Ok(bytes_written))
|
|
|
|
} else {
|
|
|
|
// Return error if stream has been shut down for writing.
|
|
|
|
Poll::Ready(Err(ErrorKind::BrokenPipe.into()))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn poll_shutdown(&mut self, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
|
|
|
|
if self.wr_state == State::StreamOpen {
|
|
|
|
self.wr_state = State::StreamClosed;
|
|
|
|
}
|
|
|
|
|
|
|
|
ready!(self.poll_io(cx, Flow::Write))?;
|
|
|
|
|
|
|
|
// At minimum, a TLS 'CloseNotify' alert should have been sent.
|
|
|
|
assert!(self.wr_state >= State::TlsClosed);
|
|
|
|
// If we received a TLS 'CloseNotify' alert from the remote end
|
|
|
|
// already, the TCP socket should be shut down at this point.
|
|
|
|
assert!(
|
|
|
|
self.rd_state < State::TlsClosed || self.wr_state == State::TcpClosed
|
|
|
|
);
|
|
|
|
|
|
|
|
Poll::Ready(Ok(()))
|
|
|
|
}
|
|
|
|
|
|
|
|
fn poll_close(&mut self, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
|
|
|
|
if self.rd_state == State::StreamOpen {
|
|
|
|
self.rd_state = State::StreamClosed;
|
|
|
|
}
|
|
|
|
|
2022-05-10 08:27:08 -04:00
|
|
|
// Wait for the handshake to complete.
|
|
|
|
ready!(self.poll_io(cx, Flow::Handshake))?;
|
2021-05-10 19:49:57 -04:00
|
|
|
// Send TLS 'CloseNotify' alert.
|
|
|
|
ready!(self.poll_shutdown(cx))?;
|
|
|
|
// Wait for 'CloseNotify', shut down TCP stream, wait for TCP FIN packet.
|
|
|
|
ready!(self.poll_io(cx, Flow::Read))?;
|
|
|
|
|
|
|
|
assert_eq!(self.rd_state, State::TcpClosed);
|
|
|
|
assert_eq!(self.wr_state, State::TcpClosed);
|
|
|
|
|
|
|
|
Poll::Ready(Ok(()))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
pub struct ReadHalf {
|
|
|
|
shared: Arc<Shared>,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl ReadHalf {
|
|
|
|
pub fn reunite(self, wr: WriteHalf) -> TlsStream {
|
|
|
|
assert!(Arc::ptr_eq(&self.shared, &wr.shared));
|
|
|
|
drop(wr); // Drop `wr`, so only one strong reference to `shared` remains.
|
|
|
|
|
|
|
|
Arc::try_unwrap(self.shared)
|
|
|
|
.unwrap_or_else(|_| panic!("Arc::<Shared>::try_unwrap() failed"))
|
|
|
|
.tls_stream
|
|
|
|
.into_inner()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl AsyncRead for ReadHalf {
|
|
|
|
fn poll_read(
|
|
|
|
self: Pin<&mut Self>,
|
|
|
|
cx: &mut Context<'_>,
|
|
|
|
buf: &mut ReadBuf<'_>,
|
|
|
|
) -> Poll<io::Result<()>> {
|
|
|
|
self
|
|
|
|
.shared
|
|
|
|
.poll_with_shared_waker(cx, Flow::Read, move |tls, cx| {
|
|
|
|
tls.poll_read(cx, buf)
|
|
|
|
})
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
pub struct WriteHalf {
|
|
|
|
shared: Arc<Shared>,
|
|
|
|
}
|
|
|
|
|
2021-10-19 19:30:04 -04:00
|
|
|
impl WriteHalf {
|
|
|
|
pub async fn handshake(&mut self) -> io::Result<()> {
|
|
|
|
poll_fn(|cx| {
|
|
|
|
self
|
|
|
|
.shared
|
|
|
|
.poll_with_shared_waker(cx, Flow::Write, |mut tls, cx| {
|
|
|
|
tls.poll_handshake(cx)
|
|
|
|
})
|
|
|
|
})
|
|
|
|
.await
|
|
|
|
}
|
2021-11-26 13:59:53 -05:00
|
|
|
|
|
|
|
fn get_alpn_protocol(&mut self) -> Option<ByteString> {
|
|
|
|
self.shared.get_alpn_protocol()
|
|
|
|
}
|
2021-10-19 19:30:04 -04:00
|
|
|
}
|
|
|
|
|
2021-05-10 19:49:57 -04:00
|
|
|
impl AsyncWrite for WriteHalf {
|
|
|
|
fn poll_write(
|
|
|
|
self: Pin<&mut Self>,
|
|
|
|
cx: &mut Context<'_>,
|
|
|
|
buf: &[u8],
|
|
|
|
) -> Poll<io::Result<usize>> {
|
|
|
|
self
|
|
|
|
.shared
|
|
|
|
.poll_with_shared_waker(cx, Flow::Write, move |tls, cx| {
|
|
|
|
tls.poll_write(cx, buf)
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
fn poll_flush(
|
|
|
|
self: Pin<&mut Self>,
|
|
|
|
cx: &mut Context<'_>,
|
|
|
|
) -> Poll<io::Result<()>> {
|
|
|
|
self
|
|
|
|
.shared
|
|
|
|
.poll_with_shared_waker(cx, Flow::Write, |tls, cx| tls.poll_flush(cx))
|
|
|
|
}
|
|
|
|
|
|
|
|
fn poll_shutdown(
|
|
|
|
self: Pin<&mut Self>,
|
|
|
|
cx: &mut Context<'_>,
|
|
|
|
) -> Poll<io::Result<()>> {
|
|
|
|
self
|
|
|
|
.shared
|
|
|
|
.poll_with_shared_waker(cx, Flow::Write, |tls, cx| tls.poll_shutdown(cx))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
struct Shared {
|
|
|
|
tls_stream: Mutex<TlsStream>,
|
|
|
|
rd_waker: AtomicWaker,
|
|
|
|
wr_waker: AtomicWaker,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Shared {
|
|
|
|
fn new(tls_stream: TlsStream) -> Arc<Self> {
|
|
|
|
let self_ = Self {
|
|
|
|
tls_stream: Mutex::new(tls_stream),
|
|
|
|
rd_waker: AtomicWaker::new(),
|
|
|
|
wr_waker: AtomicWaker::new(),
|
|
|
|
};
|
|
|
|
Arc::new(self_)
|
|
|
|
}
|
|
|
|
|
|
|
|
fn poll_with_shared_waker<R>(
|
|
|
|
self: &Arc<Self>,
|
|
|
|
cx: &mut Context<'_>,
|
|
|
|
flow: Flow,
|
|
|
|
mut f: impl FnMut(Pin<&mut TlsStream>, &mut Context<'_>) -> R,
|
|
|
|
) -> R {
|
|
|
|
match flow {
|
2021-10-19 19:30:04 -04:00
|
|
|
Flow::Handshake => unreachable!(),
|
2021-05-10 19:49:57 -04:00
|
|
|
Flow::Read => self.rd_waker.register(cx.waker()),
|
|
|
|
Flow::Write => self.wr_waker.register(cx.waker()),
|
|
|
|
}
|
|
|
|
|
|
|
|
let shared_waker = self.new_shared_waker();
|
|
|
|
let mut cx = Context::from_waker(&shared_waker);
|
|
|
|
|
2021-07-06 23:48:01 -04:00
|
|
|
let mut tls_stream = self.tls_stream.lock();
|
2021-05-10 19:49:57 -04:00
|
|
|
f(Pin::new(&mut tls_stream), &mut cx)
|
|
|
|
}
|
|
|
|
|
|
|
|
const SHARED_WAKER_VTABLE: RawWakerVTable = RawWakerVTable::new(
|
|
|
|
Self::clone_shared_waker,
|
|
|
|
Self::wake_shared_waker,
|
|
|
|
Self::wake_shared_waker_by_ref,
|
|
|
|
Self::drop_shared_waker,
|
|
|
|
);
|
|
|
|
|
|
|
|
fn new_shared_waker(self: &Arc<Self>) -> Waker {
|
|
|
|
let self_weak = Arc::downgrade(self);
|
|
|
|
let self_ptr = self_weak.into_raw() as *const ();
|
|
|
|
let raw_waker = RawWaker::new(self_ptr, &Self::SHARED_WAKER_VTABLE);
|
2022-06-25 18:13:24 -04:00
|
|
|
// TODO(bartlomieju):
|
|
|
|
#[allow(clippy::undocumented_unsafe_blocks)]
|
|
|
|
unsafe {
|
|
|
|
Waker::from_raw(raw_waker)
|
|
|
|
}
|
2021-05-10 19:49:57 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
fn clone_shared_waker(self_ptr: *const ()) -> RawWaker {
|
2022-06-25 18:13:24 -04:00
|
|
|
// TODO(bartlomieju):
|
|
|
|
#[allow(clippy::undocumented_unsafe_blocks)]
|
2021-05-10 19:49:57 -04:00
|
|
|
let self_weak = unsafe { Weak::from_raw(self_ptr as *const Self) };
|
|
|
|
let ptr1 = self_weak.clone().into_raw();
|
|
|
|
let ptr2 = self_weak.into_raw();
|
|
|
|
assert!(ptr1 == ptr2);
|
|
|
|
RawWaker::new(self_ptr, &Self::SHARED_WAKER_VTABLE)
|
|
|
|
}
|
|
|
|
|
|
|
|
fn wake_shared_waker(self_ptr: *const ()) {
|
|
|
|
Self::wake_shared_waker_by_ref(self_ptr);
|
|
|
|
Self::drop_shared_waker(self_ptr);
|
|
|
|
}
|
|
|
|
|
|
|
|
fn wake_shared_waker_by_ref(self_ptr: *const ()) {
|
2022-06-25 18:13:24 -04:00
|
|
|
// TODO(bartlomieju):
|
|
|
|
#[allow(clippy::undocumented_unsafe_blocks)]
|
2021-05-10 19:49:57 -04:00
|
|
|
let self_weak = unsafe { Weak::from_raw(self_ptr as *const Self) };
|
|
|
|
if let Some(self_arc) = Weak::upgrade(&self_weak) {
|
|
|
|
self_arc.rd_waker.wake();
|
|
|
|
self_arc.wr_waker.wake();
|
|
|
|
}
|
2021-12-04 08:19:06 -05:00
|
|
|
let _ = self_weak.into_raw();
|
2021-05-10 19:49:57 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
fn drop_shared_waker(self_ptr: *const ()) {
|
2022-06-25 18:13:24 -04:00
|
|
|
// TODO(bartlomieju):
|
|
|
|
#[allow(clippy::undocumented_unsafe_blocks)]
|
2021-05-10 19:49:57 -04:00
|
|
|
let _ = unsafe { Weak::from_raw(self_ptr as *const Self) };
|
|
|
|
}
|
2021-11-26 13:59:53 -05:00
|
|
|
|
|
|
|
fn get_alpn_protocol(self: &Arc<Self>) -> Option<ByteString> {
|
|
|
|
let mut tls_stream = self.tls_stream.lock();
|
|
|
|
tls_stream.get_alpn_protocol()
|
|
|
|
}
|
2021-05-10 19:49:57 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
struct ImplementReadTrait<'a, T>(&'a mut T);
|
|
|
|
|
|
|
|
impl Read for ImplementReadTrait<'_, TcpStream> {
|
|
|
|
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
|
|
|
|
self.0.try_read(buf)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
struct ImplementWriteTrait<'a, T>(&'a mut T);
|
|
|
|
|
|
|
|
impl Write for ImplementWriteTrait<'_, TcpStream> {
|
|
|
|
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
|
2021-10-19 19:30:04 -04:00
|
|
|
match self.0.try_write(buf) {
|
|
|
|
Ok(n) => Ok(n),
|
|
|
|
Err(err) if err.kind() == ErrorKind::WouldBlock => Ok(0),
|
|
|
|
Err(err) => Err(err),
|
|
|
|
}
|
2021-05-10 19:49:57 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
fn flush(&mut self) -> io::Result<()> {
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-10-19 19:30:04 -04:00
|
|
|
#[derive(Debug)]
|
|
|
|
pub struct TlsStreamResource {
|
|
|
|
rd: AsyncRefCell<ReadHalf>,
|
|
|
|
wr: AsyncRefCell<WriteHalf>,
|
2021-11-26 13:59:53 -05:00
|
|
|
// `None` when a TLS handshake hasn't been done.
|
|
|
|
handshake_info: RefCell<Option<TlsHandshakeInfo>>,
|
2021-10-19 19:30:04 -04:00
|
|
|
cancel_handle: CancelHandle, // Only read and handshake ops get canceled.
|
|
|
|
}
|
|
|
|
|
|
|
|
impl TlsStreamResource {
|
|
|
|
pub fn new((rd, wr): (ReadHalf, WriteHalf)) -> Self {
|
|
|
|
Self {
|
|
|
|
rd: rd.into(),
|
|
|
|
wr: wr.into(),
|
2021-11-26 13:59:53 -05:00
|
|
|
handshake_info: RefCell::new(None),
|
2021-10-19 19:30:04 -04:00
|
|
|
cancel_handle: Default::default(),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn into_inner(self) -> (ReadHalf, WriteHalf) {
|
|
|
|
(self.rd.into_inner(), self.wr.into_inner())
|
|
|
|
}
|
|
|
|
|
|
|
|
pub async fn read(
|
2021-11-09 13:26:17 -05:00
|
|
|
self: Rc<Self>,
|
2022-10-09 10:49:25 -04:00
|
|
|
data: &mut [u8],
|
|
|
|
) -> Result<usize, AnyError> {
|
2021-11-09 13:26:17 -05:00
|
|
|
let mut rd = RcRef::map(&self, |r| &r.rd).borrow_mut().await;
|
|
|
|
let cancel_handle = RcRef::map(&self, |r| &r.cancel_handle);
|
2022-10-09 10:49:25 -04:00
|
|
|
let nread = rd.read(data).try_or_cancel(cancel_handle).await?;
|
|
|
|
Ok(nread)
|
2021-10-19 19:30:04 -04:00
|
|
|
}
|
|
|
|
|
2022-10-09 10:49:25 -04:00
|
|
|
pub async fn write(self: Rc<Self>, data: &[u8]) -> Result<usize, AnyError> {
|
2021-10-19 19:30:04 -04:00
|
|
|
self.handshake().await?;
|
|
|
|
let mut wr = RcRef::map(self, |r| &r.wr).borrow_mut().await;
|
2022-10-09 10:49:25 -04:00
|
|
|
let nwritten = wr.write(data).await?;
|
2021-10-19 19:30:04 -04:00
|
|
|
wr.flush().await?;
|
|
|
|
Ok(nwritten)
|
|
|
|
}
|
|
|
|
|
2021-11-09 13:26:17 -05:00
|
|
|
pub async fn shutdown(self: Rc<Self>) -> Result<(), AnyError> {
|
2021-10-19 19:30:04 -04:00
|
|
|
self.handshake().await?;
|
|
|
|
let mut wr = RcRef::map(self, |r| &r.wr).borrow_mut().await;
|
|
|
|
wr.shutdown().await?;
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
2021-11-26 13:59:53 -05:00
|
|
|
pub async fn handshake(
|
|
|
|
self: &Rc<Self>,
|
|
|
|
) -> Result<TlsHandshakeInfo, AnyError> {
|
|
|
|
if let Some(tls_info) = &*self.handshake_info.borrow() {
|
|
|
|
return Ok(tls_info.clone());
|
2021-10-19 19:30:04 -04:00
|
|
|
}
|
2021-11-26 13:59:53 -05:00
|
|
|
|
|
|
|
let mut wr = RcRef::map(self, |r| &r.wr).borrow_mut().await;
|
|
|
|
let cancel_handle = RcRef::map(self, |r| &r.cancel_handle);
|
|
|
|
wr.handshake().try_or_cancel(cancel_handle).await?;
|
|
|
|
|
|
|
|
let alpn_protocol = wr.get_alpn_protocol();
|
|
|
|
let tls_info = TlsHandshakeInfo { alpn_protocol };
|
|
|
|
self.handshake_info.replace(Some(tls_info.clone()));
|
|
|
|
Ok(tls_info)
|
2021-10-19 19:30:04 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Resource for TlsStreamResource {
|
2022-10-09 10:49:25 -04:00
|
|
|
deno_core::impl_readable_byob!();
|
|
|
|
deno_core::impl_writable!();
|
|
|
|
|
2021-10-19 19:30:04 -04:00
|
|
|
fn name(&self) -> Cow<str> {
|
|
|
|
"tlsStream".into()
|
|
|
|
}
|
|
|
|
|
2021-11-09 13:26:17 -05:00
|
|
|
fn shutdown(self: Rc<Self>) -> AsyncResult<()> {
|
|
|
|
Box::pin(self.shutdown())
|
|
|
|
}
|
|
|
|
|
2021-10-19 19:30:04 -04:00
|
|
|
fn close(self: Rc<Self>) {
|
|
|
|
self.cancel_handle.cancel();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-09-23 14:40:38 -04:00
|
|
|
#[derive(Deserialize)]
|
2019-10-21 14:38:28 -04:00
|
|
|
#[serde(rename_all = "camelCase")]
|
2021-03-25 14:17:37 -04:00
|
|
|
pub struct ConnectTlsArgs {
|
2019-10-21 14:38:28 -04:00
|
|
|
cert_file: Option<String>,
|
2021-09-30 03:26:15 -04:00
|
|
|
ca_certs: Vec<String>,
|
2021-08-09 09:55:00 -04:00
|
|
|
cert_chain: Option<String>,
|
|
|
|
private_key: Option<String>,
|
2021-11-26 13:59:53 -05:00
|
|
|
alpn_protocols: Option<Vec<String>>,
|
2019-10-13 10:37:37 -04:00
|
|
|
}
|
2019-09-23 14:40:38 -04:00
|
|
|
|
2020-04-18 11:21:20 -04:00
|
|
|
#[derive(Deserialize)]
|
|
|
|
#[serde(rename_all = "camelCase")]
|
2021-11-08 20:07:12 -05:00
|
|
|
pub struct StartTlsArgs {
|
2021-03-19 13:25:37 -04:00
|
|
|
rid: ResourceId,
|
2021-09-30 03:26:15 -04:00
|
|
|
ca_certs: Vec<String>,
|
2020-04-18 11:21:20 -04:00
|
|
|
hostname: String,
|
2021-11-26 13:59:53 -05:00
|
|
|
alpn_protocols: Option<Vec<String>>,
|
2020-04-18 11:21:20 -04:00
|
|
|
}
|
|
|
|
|
2022-03-14 13:44:15 -04:00
|
|
|
#[op]
|
2021-11-08 20:07:12 -05:00
|
|
|
pub async fn op_tls_start<NP>(
|
2020-09-10 09:57:45 -04:00
|
|
|
state: Rc<RefCell<OpState>>,
|
2021-03-25 14:17:37 -04:00
|
|
|
args: StartTlsArgs,
|
2022-10-25 16:50:55 -04:00
|
|
|
) -> Result<(ResourceId, IpAddr, IpAddr), AnyError>
|
2021-06-28 19:43:03 -04:00
|
|
|
where
|
|
|
|
NP: NetPermissions + 'static,
|
|
|
|
{
|
2021-03-18 20:55:31 -04:00
|
|
|
let rid = args.rid;
|
2021-05-10 19:49:57 -04:00
|
|
|
let hostname = match &*args.hostname {
|
|
|
|
"" => "localhost",
|
|
|
|
n => n,
|
|
|
|
};
|
2021-10-29 11:13:31 -04:00
|
|
|
|
2020-09-10 09:57:45 -04:00
|
|
|
{
|
2021-04-11 22:15:43 -04:00
|
|
|
let mut s = state.borrow_mut();
|
2021-06-28 19:43:03 -04:00
|
|
|
let permissions = s.borrow_mut::<NP>();
|
2022-09-27 16:36:33 -04:00
|
|
|
permissions.check_net(&(hostname, Some(0)), "Deno.startTls()")?;
|
2020-04-28 12:01:13 -04:00
|
|
|
}
|
2020-04-18 11:21:20 -04:00
|
|
|
|
2021-10-29 11:13:31 -04:00
|
|
|
let ca_certs = args
|
2021-09-30 03:26:15 -04:00
|
|
|
.ca_certs
|
|
|
|
.into_iter()
|
|
|
|
.map(|s| s.into_bytes())
|
|
|
|
.collect::<Vec<_>>();
|
|
|
|
|
2021-12-06 18:48:11 -05:00
|
|
|
let hostname_dns =
|
|
|
|
ServerName::try_from(hostname).map_err(|_| invalid_hostname(hostname))?;
|
2021-05-10 19:49:57 -04:00
|
|
|
|
2021-08-10 08:19:42 -04:00
|
|
|
let unsafely_ignore_certificate_errors = state
|
|
|
|
.borrow()
|
2021-09-22 05:12:08 -04:00
|
|
|
.try_borrow::<UnsafelyIgnoreCertificateErrors>()
|
|
|
|
.and_then(|it| it.0.clone());
|
2021-08-10 08:19:42 -04:00
|
|
|
|
2021-08-07 08:49:38 -04:00
|
|
|
let root_cert_store = state
|
|
|
|
.borrow()
|
|
|
|
.borrow::<DefaultTlsOptions>()
|
2023-05-01 16:42:05 -04:00
|
|
|
.root_cert_store()?;
|
2022-10-17 22:28:27 -04:00
|
|
|
|
2020-12-16 11:14:12 -05:00
|
|
|
let resource_rc = state
|
|
|
|
.borrow_mut()
|
|
|
|
.resource_table
|
2021-08-15 07:29:19 -04:00
|
|
|
.take::<TcpStreamResource>(rid)?;
|
2022-10-17 22:28:27 -04:00
|
|
|
// This TCP connection might be used somewhere else. If it's the case, we cannot proceed with the
|
|
|
|
// process of starting a TLS connection on top of this TCP connection, so we just return a bad
|
|
|
|
// resource error. See also: https://github.com/denoland/deno/pull/16242
|
2020-12-16 11:14:12 -05:00
|
|
|
let resource = Rc::try_unwrap(resource_rc)
|
2022-10-17 22:28:27 -04:00
|
|
|
.map_err(|_| bad_resource("TCP stream is currently in use"))?;
|
2020-12-16 11:14:12 -05:00
|
|
|
let (read_half, write_half) = resource.into_inner();
|
|
|
|
let tcp_stream = read_half.reunite(write_half)?;
|
2020-08-28 11:08:24 -04:00
|
|
|
|
2020-12-16 11:14:12 -05:00
|
|
|
let local_addr = tcp_stream.local_addr()?;
|
|
|
|
let remote_addr = tcp_stream.peer_addr()?;
|
2021-05-10 19:49:57 -04:00
|
|
|
|
2021-11-26 13:59:53 -05:00
|
|
|
let mut tls_config = create_client_config(
|
2021-08-10 08:19:42 -04:00
|
|
|
root_cert_store,
|
2021-09-30 03:26:15 -04:00
|
|
|
ca_certs,
|
2021-08-10 08:19:42 -04:00
|
|
|
unsafely_ignore_certificate_errors,
|
2021-12-01 11:13:11 -05:00
|
|
|
None,
|
2021-11-26 13:59:53 -05:00
|
|
|
)?;
|
|
|
|
|
|
|
|
if let Some(alpn_protocols) = args.alpn_protocols {
|
|
|
|
super::check_unstable2(&state, "Deno.startTls#alpnProtocols");
|
|
|
|
tls_config.alpn_protocols =
|
|
|
|
alpn_protocols.into_iter().map(|s| s.into_bytes()).collect();
|
|
|
|
}
|
|
|
|
|
|
|
|
let tls_config = Arc::new(tls_config);
|
|
|
|
|
2021-05-10 19:49:57 -04:00
|
|
|
let tls_stream =
|
2021-12-06 18:48:11 -05:00
|
|
|
TlsStream::new_client_side(tcp_stream, tls_config, hostname_dns);
|
2020-12-16 11:14:12 -05:00
|
|
|
|
|
|
|
let rid = {
|
|
|
|
let mut state_ = state.borrow_mut();
|
|
|
|
state_
|
|
|
|
.resource_table
|
2021-05-10 19:49:57 -04:00
|
|
|
.add(TlsStreamResource::new(tls_stream.into_split()))
|
2020-12-16 11:14:12 -05:00
|
|
|
};
|
2021-05-10 19:49:57 -04:00
|
|
|
|
2022-10-25 16:50:55 -04:00
|
|
|
Ok((rid, IpAddr::from(local_addr), IpAddr::from(remote_addr)))
|
2020-08-28 11:08:24 -04:00
|
|
|
}
|
|
|
|
|
2022-03-14 13:44:15 -04:00
|
|
|
#[op]
|
2022-10-25 16:50:55 -04:00
|
|
|
pub async fn op_net_connect_tls<NP>(
|
2020-09-10 09:57:45 -04:00
|
|
|
state: Rc<RefCell<OpState>>,
|
2022-10-25 16:50:55 -04:00
|
|
|
addr: IpAddr,
|
2021-03-25 14:17:37 -04:00
|
|
|
args: ConnectTlsArgs,
|
2022-10-25 16:50:55 -04:00
|
|
|
) -> Result<(ResourceId, IpAddr, IpAddr), AnyError>
|
2021-06-28 19:43:03 -04:00
|
|
|
where
|
|
|
|
NP: NetPermissions + 'static,
|
|
|
|
{
|
2021-05-10 19:49:57 -04:00
|
|
|
let cert_file = args.cert_file.as_deref();
|
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-09 09:55:00 -04:00
|
|
|
|
|
|
|
if args.cert_chain.is_some() {
|
|
|
|
super::check_unstable2(&state, "ConnectTlsOptions.certChain");
|
|
|
|
}
|
|
|
|
if args.private_key.is_some() {
|
|
|
|
super::check_unstable2(&state, "ConnectTlsOptions.privateKey");
|
|
|
|
}
|
|
|
|
|
2020-09-10 09:57:45 -04:00
|
|
|
{
|
2021-04-11 22:15:43 -04:00
|
|
|
let mut s = state.borrow_mut();
|
2021-06-28 19:43:03 -04:00
|
|
|
let permissions = s.borrow_mut::<NP>();
|
2022-10-25 16:50:55 -04:00
|
|
|
permissions
|
|
|
|
.check_net(&(&addr.hostname, Some(addr.port)), "Deno.connectTls()")?;
|
2021-05-10 19:49:57 -04:00
|
|
|
if let Some(path) = cert_file {
|
2022-09-27 16:36:33 -04:00
|
|
|
permissions.check_read(Path::new(path), "Deno.connectTls()")?;
|
2020-09-10 09:57:45 -04:00
|
|
|
}
|
2020-08-28 11:08:24 -04:00
|
|
|
}
|
|
|
|
|
2021-09-30 03:26:15 -04:00
|
|
|
let mut ca_certs = args
|
|
|
|
.ca_certs
|
|
|
|
.into_iter()
|
|
|
|
.map(|s| s.into_bytes())
|
|
|
|
.collect::<Vec<_>>();
|
|
|
|
|
|
|
|
if let Some(path) = cert_file {
|
|
|
|
let mut buf = Vec::new();
|
|
|
|
File::open(path)?.read_to_end(&mut buf)?;
|
|
|
|
ca_certs.push(buf);
|
2021-08-07 08:49:38 -04:00
|
|
|
};
|
|
|
|
|
|
|
|
let root_cert_store = state
|
|
|
|
.borrow()
|
|
|
|
.borrow::<DefaultTlsOptions>()
|
2023-05-01 16:42:05 -04:00
|
|
|
.root_cert_store()?;
|
2022-10-25 16:50:55 -04:00
|
|
|
let hostname_dns = ServerName::try_from(&*addr.hostname)
|
|
|
|
.map_err(|_| invalid_hostname(&addr.hostname))?;
|
|
|
|
let connect_addr = resolve_addr(&addr.hostname, addr.port)
|
2020-12-29 20:19:28 -05:00
|
|
|
.await?
|
|
|
|
.next()
|
|
|
|
.ok_or_else(|| generic_error("No resolved address found"))?;
|
2021-05-10 19:49:57 -04:00
|
|
|
let tcp_stream = TcpStream::connect(connect_addr).await?;
|
2020-08-28 11:08:24 -04:00
|
|
|
let local_addr = tcp_stream.local_addr()?;
|
|
|
|
let remote_addr = tcp_stream.peer_addr()?;
|
2021-12-06 18:48:11 -05:00
|
|
|
|
|
|
|
let cert_chain_and_key =
|
|
|
|
if args.cert_chain.is_some() || args.private_key.is_some() {
|
|
|
|
let cert_chain = args
|
|
|
|
.cert_chain
|
|
|
|
.ok_or_else(|| type_error("No certificate chain provided"))?;
|
|
|
|
let private_key = args
|
|
|
|
.private_key
|
|
|
|
.ok_or_else(|| type_error("No private key provided"))?;
|
|
|
|
Some((cert_chain, private_key))
|
|
|
|
} else {
|
|
|
|
None
|
|
|
|
};
|
|
|
|
|
2021-08-09 10:53:21 -04:00
|
|
|
let mut tls_config = create_client_config(
|
|
|
|
root_cert_store,
|
2021-09-30 03:26:15 -04:00
|
|
|
ca_certs,
|
2021-08-10 07:19:45 -04:00
|
|
|
unsafely_ignore_certificate_errors,
|
2021-12-06 18:48:11 -05:00
|
|
|
cert_chain_and_key,
|
2021-08-09 10:53:21 -04:00
|
|
|
)?;
|
2021-08-09 09:55:00 -04:00
|
|
|
|
2021-11-26 13:59:53 -05:00
|
|
|
if let Some(alpn_protocols) = args.alpn_protocols {
|
|
|
|
super::check_unstable2(&state, "Deno.connectTls#alpnProtocols");
|
|
|
|
tls_config.alpn_protocols =
|
|
|
|
alpn_protocols.into_iter().map(|s| s.into_bytes()).collect();
|
|
|
|
}
|
|
|
|
|
2021-08-09 09:55:00 -04:00
|
|
|
let tls_config = Arc::new(tls_config);
|
|
|
|
|
2021-05-10 19:49:57 -04:00
|
|
|
let tls_stream =
|
2021-12-06 18:48:11 -05:00
|
|
|
TlsStream::new_client_side(tcp_stream, tls_config, hostname_dns);
|
2021-05-10 19:49:57 -04:00
|
|
|
|
2020-09-10 09:57:45 -04:00
|
|
|
let rid = {
|
|
|
|
let mut state_ = state.borrow_mut();
|
2020-12-16 11:14:12 -05:00
|
|
|
state_
|
|
|
|
.resource_table
|
2021-05-10 19:49:57 -04:00
|
|
|
.add(TlsStreamResource::new(tls_stream.into_split()))
|
2020-09-10 09:57:45 -04:00
|
|
|
};
|
2021-05-10 19:49:57 -04:00
|
|
|
|
2022-10-25 16:50:55 -04:00
|
|
|
Ok((rid, IpAddr::from(local_addr), IpAddr::from(remote_addr)))
|
2019-09-23 14:40:38 -04:00
|
|
|
}
|
2019-10-21 14:38:28 -04:00
|
|
|
|
2021-08-09 09:55:00 -04:00
|
|
|
fn load_certs_from_file(path: &str) -> Result<Vec<Certificate>, AnyError> {
|
|
|
|
let cert_file = File::open(path)?;
|
|
|
|
let reader = &mut BufReader::new(cert_file);
|
|
|
|
load_certs(reader)
|
|
|
|
}
|
|
|
|
|
|
|
|
fn load_private_keys_from_file(
|
|
|
|
path: &str,
|
|
|
|
) -> Result<Vec<PrivateKey>, AnyError> {
|
|
|
|
let key_bytes = std::fs::read(path)?;
|
|
|
|
load_private_keys(&key_bytes)
|
|
|
|
}
|
|
|
|
|
2019-11-07 09:59:02 -05:00
|
|
|
pub struct TlsListenerResource {
|
2023-04-22 13:48:21 -04:00
|
|
|
pub(crate) tcp_listener: AsyncRefCell<TcpListener>,
|
|
|
|
pub(crate) tls_config: Arc<ServerConfig>,
|
2021-05-10 19:49:57 -04:00
|
|
|
cancel_handle: CancelHandle,
|
2019-11-07 09:59:02 -05:00
|
|
|
}
|
|
|
|
|
2020-12-16 11:14:12 -05:00
|
|
|
impl Resource for TlsListenerResource {
|
|
|
|
fn name(&self) -> Cow<str> {
|
|
|
|
"tlsListener".into()
|
2019-11-07 09:59:02 -05:00
|
|
|
}
|
|
|
|
|
2020-12-16 11:14:12 -05:00
|
|
|
fn close(self: Rc<Self>) {
|
2021-05-10 19:49:57 -04:00
|
|
|
self.cancel_handle.cancel();
|
2019-11-07 09:59:02 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-10-21 14:38:28 -04:00
|
|
|
#[derive(Deserialize)]
|
|
|
|
#[serde(rename_all = "camelCase")]
|
2021-03-18 14:42:01 -04:00
|
|
|
pub struct ListenTlsArgs {
|
2022-02-23 23:16:56 -05:00
|
|
|
cert: Option<String>,
|
|
|
|
// TODO(kt3k): Remove this option at v2.0.
|
|
|
|
cert_file: Option<String>,
|
|
|
|
key: Option<String>,
|
|
|
|
// TODO(kt3k): Remove this option at v2.0.
|
|
|
|
key_file: Option<String>,
|
2021-04-10 16:04:44 -04:00
|
|
|
alpn_protocols: Option<Vec<String>>,
|
2022-10-26 15:04:27 -04:00
|
|
|
reuse_port: bool,
|
2019-10-21 14:38:28 -04:00
|
|
|
}
|
|
|
|
|
2022-03-14 13:44:15 -04:00
|
|
|
#[op]
|
2022-10-25 16:50:55 -04:00
|
|
|
pub fn op_net_listen_tls<NP>(
|
2020-09-10 09:57:45 -04:00
|
|
|
state: &mut OpState,
|
2022-10-25 16:50:55 -04:00
|
|
|
addr: IpAddr,
|
2021-03-18 14:42:01 -04:00
|
|
|
args: ListenTlsArgs,
|
2022-10-25 16:50:55 -04:00
|
|
|
) -> Result<(ResourceId, IpAddr), AnyError>
|
2021-06-28 19:43:03 -04:00
|
|
|
where
|
|
|
|
NP: NetPermissions + 'static,
|
|
|
|
{
|
2022-10-26 15:04:27 -04:00
|
|
|
if args.reuse_port {
|
|
|
|
super::check_unstable(state, "Deno.listenTls({ reusePort: true })");
|
|
|
|
}
|
|
|
|
|
2022-02-23 23:16:56 -05:00
|
|
|
let cert_file = args.cert_file.as_deref();
|
|
|
|
let key_file = args.key_file.as_deref();
|
|
|
|
let cert = args.cert.as_deref();
|
|
|
|
let key = args.key.as_deref();
|
2019-10-21 14:38:28 -04:00
|
|
|
|
2020-09-10 09:57:45 -04:00
|
|
|
{
|
2021-06-28 19:43:03 -04:00
|
|
|
let permissions = state.borrow_mut::<NP>();
|
2022-10-25 16:50:55 -04:00
|
|
|
permissions
|
|
|
|
.check_net(&(&addr.hostname, Some(addr.port)), "Deno.listenTls()")?;
|
2022-02-23 23:16:56 -05:00
|
|
|
if let Some(path) = cert_file {
|
2022-09-27 16:36:33 -04:00
|
|
|
permissions.check_read(Path::new(path), "Deno.listenTls()")?;
|
2022-02-23 23:16:56 -05:00
|
|
|
}
|
|
|
|
if let Some(path) = key_file {
|
2022-09-27 16:36:33 -04:00
|
|
|
permissions.check_read(Path::new(path), "Deno.listenTls()")?;
|
2022-02-23 23:16:56 -05:00
|
|
|
}
|
2020-09-10 09:57:45 -04:00
|
|
|
}
|
2021-05-10 19:49:57 -04:00
|
|
|
|
2022-02-23 23:16:56 -05:00
|
|
|
let cert_chain = if cert_file.is_some() && cert.is_some() {
|
|
|
|
return Err(generic_error("Both cert and certFile is specified. You can specify either one of them."));
|
|
|
|
} else if let Some(path) = cert_file {
|
|
|
|
load_certs_from_file(path)?
|
|
|
|
} else if let Some(cert) = cert {
|
|
|
|
load_certs(&mut BufReader::new(cert.as_bytes()))?
|
|
|
|
} else {
|
|
|
|
return Err(generic_error("`cert` is not specified."));
|
|
|
|
};
|
|
|
|
let key_der = if key_file.is_some() && key.is_some() {
|
|
|
|
return Err(generic_error(
|
|
|
|
"Both key and keyFile is specified. You can specify either one of them.",
|
|
|
|
));
|
|
|
|
} else if let Some(path) = key_file {
|
|
|
|
load_private_keys_from_file(path)?.remove(0)
|
|
|
|
} else if let Some(key) = key {
|
|
|
|
load_private_keys(key.as_bytes())?.remove(0)
|
|
|
|
} else {
|
|
|
|
return Err(generic_error("`key` is not specified."));
|
|
|
|
};
|
|
|
|
|
2021-12-06 18:48:11 -05:00
|
|
|
let mut tls_config = ServerConfig::builder()
|
|
|
|
.with_safe_defaults()
|
|
|
|
.with_no_client_auth()
|
2022-02-23 23:16:56 -05:00
|
|
|
.with_single_cert(cert_chain, key_der)
|
2021-12-06 18:48:11 -05:00
|
|
|
.expect("invalid key or certificate");
|
2021-04-10 16:04:44 -04:00
|
|
|
if let Some(alpn_protocols) = args.alpn_protocols {
|
|
|
|
super::check_unstable(state, "Deno.listenTls#alpn_protocols");
|
2021-05-10 19:49:57 -04:00
|
|
|
tls_config.alpn_protocols =
|
2021-04-10 16:04:44 -04:00
|
|
|
alpn_protocols.into_iter().map(|s| s.into_bytes()).collect();
|
|
|
|
}
|
2021-05-10 19:49:57 -04:00
|
|
|
|
2022-10-25 16:50:55 -04:00
|
|
|
let bind_addr = resolve_addr_sync(&addr.hostname, addr.port)?
|
2020-12-29 20:19:28 -05:00
|
|
|
.next()
|
|
|
|
.ok_or_else(|| generic_error("No resolved address found"))?;
|
2022-03-04 18:43:48 -05:00
|
|
|
let domain = if bind_addr.is_ipv4() {
|
|
|
|
Domain::IPV4
|
|
|
|
} else {
|
|
|
|
Domain::IPV6
|
|
|
|
};
|
|
|
|
let socket = Socket::new(domain, Type::STREAM, None)?;
|
|
|
|
#[cfg(not(windows))]
|
|
|
|
socket.set_reuse_address(true)?;
|
2022-10-26 15:04:27 -04:00
|
|
|
if args.reuse_port {
|
|
|
|
#[cfg(target_os = "linux")]
|
|
|
|
socket.set_reuse_port(true)?;
|
|
|
|
}
|
2022-03-04 18:43:48 -05:00
|
|
|
let socket_addr = socket2::SockAddr::from(bind_addr);
|
|
|
|
socket.bind(&socket_addr)?;
|
|
|
|
socket.listen(128)?;
|
|
|
|
socket.set_nonblocking(true)?;
|
|
|
|
let std_listener: std::net::TcpListener = socket.into();
|
2021-05-10 19:49:57 -04:00
|
|
|
let tcp_listener = TcpListener::from_std(std_listener)?;
|
|
|
|
let local_addr = tcp_listener.local_addr()?;
|
|
|
|
|
2019-11-07 09:59:02 -05:00
|
|
|
let tls_listener_resource = TlsListenerResource {
|
2021-05-10 19:49:57 -04:00
|
|
|
tcp_listener: AsyncRefCell::new(tcp_listener),
|
|
|
|
tls_config: Arc::new(tls_config),
|
|
|
|
cancel_handle: Default::default(),
|
2019-11-07 09:59:02 -05:00
|
|
|
};
|
2020-04-21 09:48:44 -04:00
|
|
|
|
2020-12-16 11:14:12 -05:00
|
|
|
let rid = state.resource_table.add(tls_listener_resource);
|
2019-10-21 14:38:28 -04:00
|
|
|
|
2022-10-25 16:50:55 -04:00
|
|
|
Ok((rid, IpAddr::from(local_addr)))
|
2019-10-21 14:38:28 -04:00
|
|
|
}
|
|
|
|
|
2022-03-14 13:44:15 -04:00
|
|
|
#[op]
|
2022-10-25 16:50:55 -04:00
|
|
|
pub async fn op_net_accept_tls(
|
2020-09-10 09:57:45 -04:00
|
|
|
state: Rc<RefCell<OpState>>,
|
2021-04-05 12:40:24 -04:00
|
|
|
rid: ResourceId,
|
2022-10-25 16:50:55 -04:00
|
|
|
) -> Result<(ResourceId, IpAddr, IpAddr), AnyError> {
|
2020-12-16 11:14:12 -05:00
|
|
|
let resource = state
|
|
|
|
.borrow()
|
|
|
|
.resource_table
|
|
|
|
.get::<TlsListenerResource>(rid)
|
2021-08-15 07:29:19 -04:00
|
|
|
.map_err(|_| bad_resource("Listener has been closed"))?;
|
2021-05-10 19:49:57 -04:00
|
|
|
|
|
|
|
let cancel_handle = RcRef::map(&resource, |r| &r.cancel_handle);
|
|
|
|
let tcp_listener = RcRef::map(&resource, |r| &r.tcp_listener)
|
2020-12-16 11:14:12 -05:00
|
|
|
.try_borrow_mut()
|
|
|
|
.ok_or_else(|| custom_error("Busy", "Another accept task is ongoing"))?;
|
2021-05-10 19:49:57 -04:00
|
|
|
|
|
|
|
let (tcp_stream, remote_addr) =
|
|
|
|
match tcp_listener.accept().try_or_cancel(&cancel_handle).await {
|
|
|
|
Ok(tuple) => tuple,
|
|
|
|
Err(err) if err.kind() == ErrorKind::Interrupted => {
|
|
|
|
// FIXME(bartlomieju): compatibility with current JS implementation.
|
|
|
|
return Err(bad_resource("Listener has been closed"));
|
2020-08-28 11:08:24 -04:00
|
|
|
}
|
2021-05-10 19:49:57 -04:00
|
|
|
Err(err) => return Err(err.into()),
|
|
|
|
};
|
|
|
|
|
2020-08-28 11:08:24 -04:00
|
|
|
let local_addr = tcp_stream.local_addr()?;
|
2021-05-10 19:49:57 -04:00
|
|
|
|
2021-12-06 18:48:11 -05:00
|
|
|
let tls_stream =
|
|
|
|
TlsStream::new_server_side(tcp_stream, resource.tls_config.clone());
|
2020-12-16 11:14:12 -05:00
|
|
|
|
2020-08-28 11:08:24 -04:00
|
|
|
let rid = {
|
2020-09-10 09:57:45 -04:00
|
|
|
let mut state_ = state.borrow_mut();
|
2020-12-16 11:14:12 -05:00
|
|
|
state_
|
|
|
|
.resource_table
|
2021-05-10 19:49:57 -04:00
|
|
|
.add(TlsStreamResource::new(tls_stream.into_split()))
|
2020-08-28 11:08:24 -04:00
|
|
|
};
|
2020-12-16 11:14:12 -05:00
|
|
|
|
2022-10-25 16:50:55 -04:00
|
|
|
Ok((rid, IpAddr::from(local_addr), IpAddr::from(remote_addr)))
|
2019-10-21 14:38:28 -04:00
|
|
|
}
|
2021-10-19 19:30:04 -04:00
|
|
|
|
2022-03-14 13:44:15 -04:00
|
|
|
#[op]
|
2021-11-08 20:07:12 -05:00
|
|
|
pub async fn op_tls_handshake(
|
2021-10-19 19:30:04 -04:00
|
|
|
state: Rc<RefCell<OpState>>,
|
|
|
|
rid: ResourceId,
|
2021-11-26 13:59:53 -05:00
|
|
|
) -> Result<TlsHandshakeInfo, AnyError> {
|
2021-10-19 19:30:04 -04:00
|
|
|
let resource = state
|
|
|
|
.borrow()
|
|
|
|
.resource_table
|
|
|
|
.get::<TlsStreamResource>(rid)?;
|
|
|
|
resource.handshake().await
|
|
|
|
}
|