1use std::future::Future;
14use std::io;
15use std::pin::Pin;
16use std::sync::{Arc, OnceLock};
17use std::time::Duration;
18
19use base64::Engine;
20use base64::engine::general_purpose::STANDARD as BASE64;
21use sha1::{Digest, Sha1};
22use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt};
23use tokio::time::Instant;
24
25use crate::config::Config;
26use crate::error::Error;
27use crate::version::{VERSION, user_agent};
28
29pub trait WsIo: AsyncRead + AsyncWrite + Unpin + Send + 'static {}
31
32impl<T: AsyncRead + AsyncWrite + Unpin + Send + 'static> WsIo for T {}
33
34pub type WsConnectFuture = Pin<Box<dyn Future<Output = std::io::Result<Box<dyn WsIo>>> + Send>>;
36
37pub trait WsConnector: Send + Sync + 'static {
43 fn connect(&self, host: &str, port: u16) -> WsConnectFuture;
45}
46
47pub(crate) enum DialOutcome {
48 Open(Box<WsConn>),
49 Refused { status: u16, body: Option<String> },
50 Failed(Error),
51}
52
53const MAX_HEAD: usize = 64 * 1024;
54const MAX_REFUSAL_BODY: usize = 64 * 1024;
55const REFUSAL_BODY_TIMEOUT: Duration = Duration::from_secs(5);
58const WS_GUID: &str = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
59
60fn tls_config() -> std::result::Result<Arc<rustls::ClientConfig>, String> {
61 static CONFIG: OnceLock<std::result::Result<Arc<rustls::ClientConfig>, String>> =
62 OnceLock::new();
63 CONFIG
64 .get_or_init(|| {
65 let provider = rustls::crypto::CryptoProvider::get_default()
66 .cloned()
67 .unwrap_or_else(|| Arc::new(rustls::crypto::aws_lc_rs::default_provider()));
68 let verifier = rustls_platform_verifier::Verifier::new(provider.clone())
69 .map_err(|e| format!("could not load the system trust store: {e}"))?;
70 let builder = rustls::ClientConfig::builder_with_provider(provider)
71 .with_safe_default_protocol_versions()
72 .map_err(|e| format!("could not set up TLS: {e}"))?;
73 Ok(Arc::new(
74 builder
75 .dangerous()
76 .with_custom_certificate_verifier(Arc::new(verifier))
77 .with_no_client_auth(),
78 ))
79 })
80 .clone()
81}
82
83struct Target {
84 tls: bool,
85 host: String,
86 port: u16,
87 host_header: String,
88 path: String,
89}
90
91fn parse_url(url: &str) -> Option<Target> {
92 let parsed = reqwest::Url::parse(url).ok()?;
93 let tls = match parsed.scheme() {
94 "wss" => true,
95 "ws" => false,
96 _ => return None,
97 };
98 let host = parsed.host_str()?.trim_matches(['[', ']']).to_owned();
99 let port = parsed.port_or_known_default()?;
100 let host_header = match parsed.port() {
101 Some(p) => format!("{}:{p}", parsed.host_str()?),
102 None => parsed.host_str()?.to_owned(),
103 };
104 let mut path = parsed.path().to_owned();
105 if path.is_empty() {
106 path.push('/');
107 }
108 if let Some(q) = parsed.query() {
109 path.push('?');
110 path.push_str(q);
111 }
112 Some(Target {
113 tls,
114 host,
115 port,
116 host_header,
117 path,
118 })
119}
120
121fn header_safe(value: &str) -> bool {
122 value.bytes().all(|b| (0x20..=0x7e).contains(&b))
123}
124
125fn random_bytes<const N: usize>() -> [u8; N] {
126 let mut out = [0u8; N];
128 for chunk in out.chunks_mut(16) {
129 let id = uuid::Uuid::new_v4();
130 chunk.copy_from_slice(&id.as_bytes()[..chunk.len()]);
131 }
132 out
133}
134
135fn generate_key() -> String {
136 BASE64.encode(random_bytes::<16>())
137}
138
139fn accept_key(key: &str) -> String {
140 let mut sha = Sha1::new();
141 sha.update(key.as_bytes());
142 sha.update(WS_GUID.as_bytes());
143 BASE64.encode(sha.finalize())
144}
145
146async fn open_io(cfg: &Config, target: &Target) -> std::io::Result<Box<dyn WsIo>> {
147 let io: Box<dyn WsIo> = match &cfg.ws_connector {
148 Some(c) => c.connect(&target.host, target.port).await?,
149 None => {
150 let stream =
151 tokio::net::TcpStream::connect((target.host.as_str(), target.port)).await?;
152 let _ = stream.set_nodelay(true);
153 Box::new(stream)
154 }
155 };
156 if !target.tls {
157 return Ok(io);
158 }
159 let config = tls_config().map_err(io::Error::other)?;
160 let name = rustls::pki_types::ServerName::try_from(target.host.clone())
161 .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidInput, e))?;
162 let tls = tokio_rustls::TlsConnector::from(config)
163 .connect(name, io)
164 .await?;
165 Ok(Box::new(tls))
166}
167
168struct Head {
169 status: u16,
170 headers: Vec<(String, String)>,
171}
172
173impl Head {
174 fn header(&self, name: &str) -> Option<&str> {
175 self.headers
176 .iter()
177 .find(|(k, _)| k.eq_ignore_ascii_case(name))
178 .map(|(_, v)| v.as_str())
179 }
180}
181
182async fn read_head(io: &mut Box<dyn WsIo>) -> std::io::Result<Head> {
183 let bad = |m: &str| std::io::Error::new(std::io::ErrorKind::InvalidData, m.to_owned());
184 let mut buf = Vec::with_capacity(512);
185 let mut byte = [0u8; 1];
186 while !buf.ends_with(b"\r\n\r\n") {
188 if io.read(&mut byte).await? == 0 {
189 return Err(bad("the connection closed during the handshake"));
190 }
191 buf.push(byte[0]);
192 if buf.len() > MAX_HEAD {
193 return Err(bad("the handshake response head is too large"));
194 }
195 }
196 let text = String::from_utf8_lossy(&buf);
197 let mut lines = text.split("\r\n");
198 let status_line = lines.next().unwrap_or_default();
199 let mut parts = status_line.split(' ');
200 if !parts.next().unwrap_or_default().starts_with("HTTP/1.") {
201 return Err(bad("the handshake response is not HTTP/1.x"));
202 }
203 let status = parts
204 .next()
205 .and_then(|s| s.parse::<u16>().ok())
206 .ok_or_else(|| bad("the handshake response has no status"))?;
207 let headers = lines
208 .filter(|l| !l.is_empty())
209 .filter_map(|l| l.split_once(':'))
210 .map(|(k, v)| (k.trim().to_owned(), v.trim().to_owned()))
211 .collect();
212 Ok(Head { status, headers })
213}
214
215async fn read_byte(io: &mut Box<dyn WsIo>, deadline: Instant) -> Option<u8> {
218 let mut byte = [0u8; 1];
219 match tokio::time::timeout_at(deadline, io.read(&mut byte)).await {
220 Ok(Ok(1)) => Some(byte[0]),
221 _ => None,
222 }
223}
224
225async fn read_exactly(
227 io: &mut Box<dyn WsIo>,
228 body: &mut Vec<u8>,
229 mut want: usize,
230 deadline: Instant,
231) -> bool {
232 let mut chunk = [0u8; 4096];
233 while want > 0 {
234 let n = want.min(chunk.len());
235 match tokio::time::timeout_at(deadline, io.read(&mut chunk[..n])).await {
236 Ok(Ok(0)) | Ok(Err(_)) | Err(_) => return false,
237 Ok(Ok(got)) => {
238 body.extend_from_slice(&chunk[..got]);
239 want -= got;
240 }
241 }
242 }
243 true
244}
245
246async fn read_chunked(io: &mut Box<dyn WsIo>, body: &mut Vec<u8>, deadline: Instant) {
248 loop {
249 let mut line = Vec::new();
250 while !line.ends_with(b"\r\n") {
251 let Some(b) = read_byte(io, deadline).await else {
252 return;
253 };
254 line.push(b);
255 if line.len() > 1024 {
256 return;
257 }
258 }
259 let text = String::from_utf8_lossy(&line);
260 let size = text.trim().split(';').next().unwrap_or_default().trim();
261 let Ok(size) = usize::from_str_radix(size, 16) else {
262 return;
263 };
264 if size == 0 || body.len() + size > MAX_REFUSAL_BODY {
265 return;
266 }
267 if !read_exactly(io, body, size, deadline).await {
268 return;
269 }
270 for _ in 0..2 {
272 if read_byte(io, deadline).await.is_none() {
273 return;
274 }
275 }
276 }
277}
278
279async fn read_body(io: &mut Box<dyn WsIo>, head: &Head) -> Option<String> {
283 let deadline = Instant::now() + REFUSAL_BODY_TIMEOUT;
284 let mut body = Vec::new();
285 let chunked = head
286 .header("transfer-encoding")
287 .is_some_and(|v| v.to_ascii_lowercase().contains("chunked"));
288 let length = head
289 .header("content-length")
290 .and_then(|v| v.parse::<usize>().ok());
291 if chunked {
292 read_chunked(io, &mut body, deadline).await;
293 } else if let Some(len) = length {
294 if !read_exactly(io, &mut body, len.min(MAX_REFUSAL_BODY), deadline).await {
295 return None;
296 }
297 } else {
298 let mut chunk = [0u8; 4096];
299 while body.len() < MAX_REFUSAL_BODY {
300 match tokio::time::timeout_at(deadline, io.read(&mut chunk)).await {
301 Ok(Ok(n)) if n > 0 => body.extend_from_slice(&chunk[..n]),
302 Ok(Ok(_)) | Ok(Err(_)) => break,
303 Err(_) => return None,
304 }
305 }
306 }
307 let text = String::from_utf8_lossy(&body).into_owned();
308 if text.trim().is_empty() {
309 None
310 } else {
311 Some(text)
312 }
313}
314
315enum Handshake {
316 Open(Box<WsConn>),
317 Refused(u16, Head, Box<dyn WsIo>),
318 Failed(Error),
319}
320
321async fn handshake(cfg: &Config, target: &Target, takeover: bool) -> Handshake {
322 let mut io = match open_io(cfg, target).await {
323 Ok(io) => io,
324 Err(e) => {
325 return Handshake::Failed(Error::network(
326 "could not connect to the stream endpoint",
327 Some(Box::new(e)),
328 ));
329 }
330 };
331 let key = generate_key();
332 let mut request = format!(
334 "GET {} HTTP/1.1\r\nhost: {}\r\nconnection: Upgrade\r\nupgrade: websocket\r\n\
335 sec-websocket-version: 13\r\nsec-websocket-key: {key}\r\nuser-agent: {}\r\n\
336 x-client-version: {VERSION}\r\nx-api-key: {}\r\n",
337 target.path,
338 target.host_header,
339 user_agent(),
340 cfg.api_key(),
341 );
342 if takeover {
343 request.push_str("x-takeover: true\r\n");
344 }
345 request.push_str("\r\n");
346 let sent = async {
347 io.write_all(request.as_bytes()).await?;
348 io.flush().await
349 };
350 if let Err(e) = sent.await {
351 return Handshake::Failed(Error::network(
352 "the stream handshake failed",
353 Some(Box::new(e)),
354 ));
355 }
356 drop(request);
357 let head = match read_head(&mut io).await {
358 Ok(h) => h,
359 Err(e) => {
360 return Handshake::Failed(Error::network(
361 "the stream handshake failed",
362 Some(Box::new(e)),
363 ));
364 }
365 };
366 if head.status != 101 {
367 return Handshake::Refused(head.status, head, io);
368 }
369 let upgrade_ok = head
370 .header("upgrade")
371 .is_some_and(|v| v.eq_ignore_ascii_case("websocket"))
372 && head.header("sec-websocket-accept") == Some(accept_key(&key).as_str());
373 if !upgrade_ok {
374 return Handshake::Failed(Error::network(
375 "the stream handshake failed: the server did not confirm the WebSocket upgrade",
376 None,
377 ));
378 }
379 Handshake::Open(Box::new(WsConn::new(io, cfg.max_message_bytes)))
380}
381
382pub(crate) async fn dial(cfg: &Config, url: &str, takeover: bool) -> DialOutcome {
385 let Some(target) = parse_url(url) else {
386 return DialOutcome::Failed(Error::validation(
387 "wss_url is not a ws:// or wss:// URL",
388 Some("wss_url"),
389 ));
390 };
391 if !header_safe(cfg.api_key()) {
392 return DialOutcome::Failed(Error::validation(
393 "api_key is not a valid header value",
394 Some("api_key"),
395 ));
396 }
397 match tokio::time::timeout(cfg.connect_timeout, handshake(cfg, &target, takeover)).await {
398 Ok(Handshake::Open(conn)) => DialOutcome::Open(conn),
399 Ok(Handshake::Refused(status, head, mut io)) => {
400 let body = read_body(&mut io, &head).await;
402 DialOutcome::Refused { status, body }
403 }
404 Ok(Handshake::Failed(err)) => DialOutcome::Failed(err),
405 Err(_) => DialOutcome::Failed(Error::timeout(
406 format!(
407 "the stream dial did not finish within connect_timeout ({:?})",
408 cfg.connect_timeout
409 ),
410 None,
411 )),
412 }
413}
414
415#[derive(Debug)]
417pub(crate) enum WsMessage {
418 Text(String),
419 Binary,
420 Ping(Vec<u8>),
421 Pong,
422 Close(Option<u16>),
424}
425
426const OP_CONTINUATION: u8 = 0x0;
427const OP_TEXT: u8 = 0x1;
428const OP_BINARY: u8 = 0x2;
429const OP_CLOSE: u8 = 0x8;
430const OP_PING: u8 = 0x9;
431const OP_PONG: u8 = 0xA;
432
433fn protocol_error(message: &str) -> io::Error {
434 io::Error::new(io::ErrorKind::InvalidData, message.to_owned())
435}
436
437pub(crate) struct WsConn {
439 io: Box<dyn WsIo>,
440 buf: Vec<u8>,
442 partial: Option<(u8, Vec<u8>)>,
444 max_message: usize,
445 done: bool,
446}
447
448impl WsConn {
449 fn new(io: Box<dyn WsIo>, max_message: usize) -> Self {
450 WsConn {
451 io,
452 buf: Vec::new(),
453 partial: None,
454 max_message,
455 done: false,
456 }
457 }
458
459 pub(crate) async fn next(&mut self) -> Option<io::Result<WsMessage>> {
462 if self.done {
463 return None;
464 }
465 loop {
466 match self.parse() {
467 Ok(Some(msg)) => {
468 if matches!(msg, WsMessage::Close(_)) {
469 self.done = true;
470 }
471 return Some(Ok(msg));
472 }
473 Ok(None) => {}
474 Err(e) => {
475 self.done = true;
476 return Some(Err(e));
477 }
478 }
479 self.buf.reserve(8192);
480 match self.io.read_buf(&mut self.buf).await {
481 Ok(0) => {
482 self.done = true;
483 return None;
484 }
485 Ok(_) => {}
486 Err(e) => {
487 self.done = true;
488 return Some(Err(e));
489 }
490 }
491 }
492 }
493
494 fn parse(&mut self) -> io::Result<Option<WsMessage>> {
496 loop {
497 let Some((fin, opcode, start, len)) = self.frame_header()? else {
498 return Ok(None);
499 };
500 if self.buf.len() < start + len {
501 return Ok(None);
502 }
503 let payload: Vec<u8> = self.buf[start..start + len].to_vec();
504 self.buf.drain(..start + len);
505 match opcode {
506 OP_CLOSE => {
507 let code =
508 (payload.len() >= 2).then(|| u16::from_be_bytes([payload[0], payload[1]]));
509 return Ok(Some(WsMessage::Close(code)));
510 }
511 OP_PING => return Ok(Some(WsMessage::Ping(payload))),
512 OP_PONG => return Ok(Some(WsMessage::Pong)),
513 OP_TEXT | OP_BINARY => {
514 if self.partial.is_some() {
515 return Err(protocol_error(
516 "a new message started inside a fragmented one",
517 ));
518 }
519 if fin {
520 return finish(opcode, payload).map(Some);
521 }
522 self.partial = Some((opcode, payload));
523 }
524 OP_CONTINUATION => {
525 let Some((first, mut data)) = self.partial.take() else {
526 return Err(protocol_error("a continuation frame without a message"));
527 };
528 if data.len() + payload.len() > self.max_message {
529 return Err(protocol_error(
530 "the stream message is larger than max_message_bytes",
531 ));
532 }
533 data.extend_from_slice(&payload);
534 if fin {
535 return finish(first, data).map(Some);
536 }
537 self.partial = Some((first, data));
538 }
539 _ => return Err(protocol_error("unknown WebSocket opcode")),
540 }
541 }
542 }
543
544 fn frame_header(&self) -> io::Result<Option<(bool, u8, usize, usize)>> {
546 let b = &self.buf;
547 if b.len() < 2 {
548 return Ok(None);
549 }
550 let fin = b[0] & 0x80 != 0;
551 if b[0] & 0x70 != 0 {
552 return Err(protocol_error("reserved WebSocket bits are set"));
553 }
554 let opcode = b[0] & 0x0f;
555 if b[1] & 0x80 != 0 {
556 return Err(protocol_error("the server sent a masked frame"));
557 }
558 let (len, start) = match b[1] & 0x7f {
559 126 => {
560 if b.len() < 4 {
561 return Ok(None);
562 }
563 (u64::from(u16::from_be_bytes([b[2], b[3]])), 4)
564 }
565 127 => {
566 if b.len() < 10 {
567 return Ok(None);
568 }
569 let mut n = [0u8; 8];
570 n.copy_from_slice(&b[2..10]);
571 (u64::from_be_bytes(n), 10)
572 }
573 n => (u64::from(n), 2),
574 };
575 if opcode >= 0x8 && (!fin || len > 125) {
576 return Err(protocol_error("invalid WebSocket control frame"));
577 }
578 let partial = self.partial.as_ref().map_or(0, |(_, d)| d.len());
579 if opcode < 0x8 && len > (self.max_message - partial.min(self.max_message)) as u64 {
580 return Err(protocol_error(
581 "the stream message is larger than max_message_bytes",
582 ));
583 }
584 Ok(Some((fin, opcode, start, len as usize)))
585 }
586
587 async fn send(&mut self, opcode: u8, payload: &[u8]) -> io::Result<()> {
588 let mut frame = Vec::with_capacity(payload.len() + 14);
589 frame.push(0x80 | opcode);
590 match payload.len() {
591 n if n < 126 => frame.push(0x80 | n as u8),
592 n if n <= usize::from(u16::MAX) => {
593 frame.push(0x80 | 126);
594 frame.extend_from_slice(&(n as u16).to_be_bytes());
595 }
596 n => {
597 frame.push(0x80 | 127);
598 frame.extend_from_slice(&(n as u64).to_be_bytes());
599 }
600 }
601 let mask = random_bytes::<4>();
602 frame.extend_from_slice(&mask);
603 frame.extend(payload.iter().enumerate().map(|(i, b)| b ^ mask[i % 4]));
604 self.io.write_all(&frame).await?;
605 self.io.flush().await
606 }
607
608 pub(crate) async fn send_text(&mut self, text: &str) -> io::Result<()> {
609 self.send(OP_TEXT, text.as_bytes()).await
610 }
611
612 pub(crate) async fn send_pong(&mut self, payload: &[u8]) -> io::Result<()> {
613 self.send(OP_PONG, payload).await
614 }
615
616 pub(crate) async fn send_close(&mut self, code: u16) -> io::Result<()> {
617 self.send(OP_CLOSE, &code.to_be_bytes()).await
618 }
619}
620
621fn finish(opcode: u8, data: Vec<u8>) -> io::Result<WsMessage> {
622 if opcode == OP_BINARY {
623 return Ok(WsMessage::Binary);
624 }
625 String::from_utf8(data)
626 .map(WsMessage::Text)
627 .map_err(|_| protocol_error("a text frame is not valid UTF-8"))
628}
629
630#[cfg(test)]
631mod tests {
632 use super::*;
633
634 #[test]
635 fn accept_key_matches_rfc_6455() {
636 assert_eq!(
637 accept_key("dGhlIHNhbXBsZSBub25jZQ=="),
638 "s3pPLMBiTxaQ9kYGzzhZRbK+xOo="
639 );
640 assert_eq!(generate_key().len(), 24);
641 }
642
643 fn conn(bytes: &[u8], max: usize) -> WsConn {
644 let mut c = WsConn::new(Box::new(tokio::io::empty()), max);
645 c.buf.extend_from_slice(bytes);
646 c
647 }
648
649 #[test]
650 fn parses_fragments_controls_and_limits() {
651 let mut bytes = vec![
653 0x01, 3, b'H', b'e', b'l', 0x89, 1, b'p', 0x80, 2, b'l', b'o',
654 ];
655 bytes.extend_from_slice(&[0x88, 2, 0x03, 0xe8]);
656 let mut c = conn(&bytes, 1024);
657 assert!(matches!(c.parse().unwrap(), Some(WsMessage::Ping(p)) if p == b"p"));
658 assert!(matches!(c.parse().unwrap(), Some(WsMessage::Text(t)) if t == "Hello"));
659 assert!(matches!(
660 c.parse().unwrap(),
661 Some(WsMessage::Close(Some(1000)))
662 ));
663 assert!(c.parse().unwrap().is_none());
664
665 let text = "x".repeat(300);
667 let mut bytes = vec![0x81, 126, 0x01, 0x2c];
668 bytes.extend_from_slice(text.as_bytes());
669 let mut c = conn(&bytes[..100], 1024);
670 assert!(c.parse().unwrap().is_none());
671 c.buf.extend_from_slice(&bytes[100..]);
672 assert!(matches!(c.parse().unwrap(), Some(WsMessage::Text(t)) if t == text));
673
674 assert!(conn(&bytes, 100).parse().is_err(), "over max_message_bytes");
675 assert!(
676 conn(&[0x81, 0x81, 0, 0, 0, 0, b'x'], 100).parse().is_err(),
677 "masked"
678 );
679 assert!(
680 conn(&[0x80, 1, b'x'], 100).parse().is_err(),
681 "stray continuation"
682 );
683 assert!(conn(&[0x81, 1, 0xff], 100).parse().is_err(), "bad UTF-8");
684 }
685}