| 1 | use crate::stdio::serialize_control_frame; |
| 2 | use codewhale_app_server_protocol::runtime::MAX_RUNTIME_IMAGE_BODY_BYTES; |
| 3 | use futures_util::{Sink, Stream}; |
| 4 | use std::io; |
| 5 | use std::pin::Pin; |
| 6 | use std::task::{Context, Poll, ready}; |
| 7 | use std::time::Duration; |
| 8 | use tokio::io::{AsyncRead, AsyncReadExt as _, AsyncWrite, Join, ReadBuf, Take}; |
| 9 | use tokio_tungstenite::WebSocketStream; |
| 10 | use tokio_tungstenite::tungstenite::handshake::server::{ErrorResponse, Request, Response}; |
| 11 | use tokio_tungstenite::tungstenite::protocol::{Message, WebSocketConfig}; |
| 12 | |
| 13 | pub(crate) type LocalWebSocket<R, W> = WebSocketLines<Join<Take<R>, W>>; |
| 14 | |
| 15 | fn configuration() -> WebSocketConfig { |
| 16 | WebSocketConfig::default() |
| 17 | .write_buffer_size(0) |
| 18 | .max_write_buffer_size(MAX_RUNTIME_IMAGE_BODY_BYTES + 128) |
| 19 | .max_message_size(Some(MAX_RUNTIME_IMAGE_BODY_BYTES)) |
| 20 | .max_frame_size(Some(MAX_RUNTIME_IMAGE_BODY_BYTES)) |
| 21 | } |
| 22 | |
| 23 | pub(crate) async fn accept<R, W>(read: R, write: W) -> anyhow::Result<LocalWebSocket<R, W>> |
| 24 | where |
| 25 | R: AsyncRead + Unpin, |
| 26 | W: AsyncWrite + Unpin, |
| 27 | { |
| 28 | let stream = tokio::io::join(read.take(16384), write); |
| 29 | let mut socket = tokio::time::timeout( |
| 30 | Duration::from_secs(5), |
| 31 | tokio_tungstenite::accept_hdr_async_with_config( |
| 32 | stream, |
| 33 | refuse_browser_origin, |
| 34 | Some(configuration()), |
| 35 | ), |
| 36 | ) |
| 37 | .await??; |
| 38 | socket.get_mut().reader_mut().set_limit(u64::MAX); |
| 39 | Ok(WebSocketLines::new(socket)) |
| 40 | } |
| 41 | |
| 42 | #[allow(clippy::result_large_err)] |
| 43 | fn refuse_browser_origin(request: &Request, response: Response) -> Result<Response, ErrorResponse> { |
| 44 | if request.headers().contains_key("origin") { |
| 45 | let mut refusal = tokio_tungstenite::tungstenite::http::Response::new(Some( |
| 46 | "Origin is not accepted on the private owner channel".to_string(), |
| 47 | )); |
| 48 | *refusal.status_mut() = tokio_tungstenite::tungstenite::http::StatusCode::FORBIDDEN; |
| 49 | return Err(refusal); |
| 50 | } |
| 51 | Ok(response) |
| 52 | } |
| 53 | |
| 54 | pub(crate) async fn connect<R, W>(read: R, write: W) -> anyhow::Result<LocalWebSocket<R, W>> |
| 55 | where |
| 56 | R: AsyncRead + Unpin, |
| 57 | W: AsyncWrite + Unpin, |
| 58 | { |
| 59 | let stream = tokio::io::join(read.take(16384), write); |
| 60 | let (mut socket, _) = tokio::time::timeout( |
| 61 | Duration::from_secs(5), |
| 62 | tokio_tungstenite::client_async_with_config( |
| 63 | "ws://localhost/", |
| 64 | stream, |
| 65 | Some(configuration()), |
| 66 | ), |
| 67 | ) |
| 68 | .await??; |
| 69 | socket.get_mut().reader_mut().set_limit(u64::MAX); |
| 70 | Ok(WebSocketLines::new(socket)) |
| 71 | } |
| 72 | |
| 73 | fn peer_gone(error: &tokio_tungstenite::tungstenite::Error) -> bool { |
| 74 | use tokio_tungstenite::tungstenite::Error; |
| 75 | match error { |
| 76 | Error::ConnectionClosed | Error::AlreadyClosed => true, |
| 77 | Error::Io(error) => matches!( |
| 78 | error.kind(), |
| 79 | io::ErrorKind::BrokenPipe |
| 80 | | io::ErrorKind::ConnectionReset |
| 81 | | io::ErrorKind::ConnectionAborted |
| 82 | | io::ErrorKind::UnexpectedEof |
| 83 | ), |
| 84 | _ => false, |
| 85 | } |
| 86 | } |
| 87 | |
| 88 | pub(crate) struct WebSocketLines<S> { |
| 89 | socket: WebSocketStream<S>, |
| 90 | incoming: Vec<u8>, |
| 91 | incoming_offset: usize, |
| 92 | outgoing: Vec<u8>, |
| 93 | flush_control: bool, |
| 94 | closed: bool, |
| 95 | } |
| 96 | |
| 97 | impl<S> WebSocketLines<S> { |
| 98 | fn new(socket: WebSocketStream<S>) -> Self { |
| 99 | Self { |
| 100 | socket, |
| 101 | incoming: Vec::new(), |
| 102 | incoming_offset: 0, |
| 103 | outgoing: Vec::new(), |
| 104 | flush_control: false, |
| 105 | closed: false, |
| 106 | } |
| 107 | } |
| 108 | } |
| 109 | |
| 110 | impl<S: AsyncRead + AsyncWrite + Unpin> AsyncRead for WebSocketLines<S> { |
| 111 | fn poll_read( |
| 112 | self: Pin<&mut Self>, |
| 113 | cx: &mut Context<'_>, |
| 114 | buffer: &mut ReadBuf<'_>, |
| 115 | ) -> Poll<io::Result<()>> { |
| 116 | let this = self.get_mut(); |
| 117 | if buffer.remaining() == 0 { |
| 118 | return Poll::Ready(Ok(())); |
| 119 | } |
| 120 | for _ in 0..32 { |
| 121 | if this.incoming_offset < this.incoming.len() { |
| 122 | let count = buffer |
| 123 | .remaining() |
| 124 | .min(this.incoming.len() - this.incoming_offset); |
| 125 | buffer |
| 126 | .put_slice(&this.incoming[this.incoming_offset..this.incoming_offset + count]); |
| 127 | this.incoming_offset += count; |
| 128 | if this.incoming_offset == this.incoming.len() { |
| 129 | this.incoming.clear(); |
| 130 | this.incoming_offset = 0; |
| 131 | } |
| 132 | return Poll::Ready(Ok(())); |
| 133 | } |
| 134 | if this.flush_control { |
| 135 | match ready!(Pin::new(&mut this.socket).poll_flush(cx)) { |
| 136 | Ok(()) => this.flush_control = false, |
| 137 | Err(error) if peer_gone(&error) => { |
| 138 | this.closed = true; |
| 139 | this.flush_control = false; |
| 140 | return Poll::Ready(Ok(())); |
| 141 | } |
| 142 | Err(error) => return Poll::Ready(Err(io::Error::other(error))), |
| 143 | } |
| 144 | } |
| 145 | if this.closed { |
| 146 | return Poll::Ready(Ok(())); |
| 147 | } |
| 148 | match ready!(Pin::new(&mut this.socket).poll_next(cx)) { |
| 149 | Some(Ok(Message::Text(text))) => { |
| 150 | this.incoming = match serde_json::from_str::<serde_json::Value>(&text) { |
| 151 | Ok(value) => serialize_control_frame(&value)?, |
| 152 | Err(_) if !text.contains(['\r', '\n']) => text.as_bytes().to_vec(), |
| 153 | Err(_) => b"{invalid WebSocket JSON".to_vec(), |
| 154 | }; |
| 155 | this.incoming.reserve_exact(1); |
| 156 | this.incoming.push(b'\n'); |
| 157 | } |
| 158 | Some(Ok(Message::Ping(_))) => this.flush_control = true, |
| 159 | Some(Ok(Message::Close(_))) => { |
| 160 | this.closed = true; |
| 161 | this.flush_control = true; |
| 162 | } |
| 163 | Some(Ok(Message::Binary(_) | Message::Pong(_) | Message::Frame(_))) => {} |
| 164 | Some(Err(tokio_tungstenite::tungstenite::Error::Protocol( |
| 165 | tokio_tungstenite::tungstenite::error::ProtocolError::ResetWithoutClosingHandshake, |
| 166 | ))) => { |
| 167 | this.closed = true; |
| 168 | return Poll::Ready(Ok(())); |
| 169 | } |
| 170 | Some(Err(error)) if peer_gone(&error) => { |
| 171 | this.closed = true; |
| 172 | return Poll::Ready(Ok(())); |
| 173 | } |
| 174 | Some(Err(error)) => return Poll::Ready(Err(io::Error::other(error))), |
| 175 | None => { |
| 176 | this.closed = true; |
| 177 | return Poll::Ready(Ok(())); |
| 178 | } |
| 179 | } |
| 180 | } |
| 181 | cx.waker().wake_by_ref(); |
| 182 | Poll::Pending |
| 183 | } |
| 184 | } |
| 185 | |
| 186 | impl<S: AsyncRead + AsyncWrite + Unpin> AsyncWrite for WebSocketLines<S> { |
| 187 | fn poll_write( |
| 188 | self: Pin<&mut Self>, |
| 189 | cx: &mut Context<'_>, |
| 190 | bytes: &[u8], |
| 191 | ) -> Poll<io::Result<usize>> { |
| 192 | let this = self.get_mut(); |
| 193 | if this.closed { |
| 194 | return Poll::Ready(Err(io::ErrorKind::BrokenPipe.into())); |
| 195 | } |
| 196 | let newline = bytes.iter().position(|byte| *byte == b'\n'); |
| 197 | let count = newline.unwrap_or(bytes.len()); |
| 198 | if count > MAX_RUNTIME_IMAGE_BODY_BYTES.saturating_sub(this.outgoing.len()) { |
| 199 | return Poll::Ready(Err(io::Error::new( |
| 200 | io::ErrorKind::InvalidData, |
| 201 | crate::stdio::FrameRefusal::TooLarge, |
| 202 | ))); |
| 203 | } |
| 204 | if newline.is_some() { |
| 205 | ready!(Pin::new(&mut this.socket).poll_ready(cx)).map_err(io::Error::other)?; |
| 206 | } |
| 207 | this.outgoing.reserve_exact(count); |
| 208 | this.outgoing.extend_from_slice(&bytes[..count]); |
| 209 | if newline.is_some() { |
| 210 | let text = String::from_utf8(std::mem::take(&mut this.outgoing)) |
| 211 | .map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error))?; |
| 212 | Pin::new(&mut this.socket) |
| 213 | .start_send(Message::Text(text.into())) |
| 214 | .map_err(io::Error::other)?; |
| 215 | } |
| 216 | Poll::Ready(Ok(count + usize::from(newline.is_some()))) |
| 217 | } |
| 218 | |
| 219 | fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> { |
| 220 | Pin::new(&mut self.get_mut().socket) |
| 221 | .poll_flush(cx) |
| 222 | .map_err(io::Error::other) |
| 223 | } |
| 224 | |
| 225 | fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> { |
| 226 | let this = self.get_mut(); |
| 227 | if !this.outgoing.is_empty() { |
| 228 | return Poll::Ready(Err(io::Error::new( |
| 229 | io::ErrorKind::InvalidData, |
| 230 | "private WebSocket output ended inside a JSON frame", |
| 231 | ))); |
| 232 | } |
| 233 | Pin::new(&mut this.socket) |
| 234 | .poll_close(cx) |
| 235 | .map_err(io::Error::other) |
| 236 | } |
| 237 | } |
| 238 |