1use crate::info::StreamInfo;
18use crate::{config, resolve, ContinuousResolver, Inlet, Outlet};
19use labstream_wire::{ByteOrder, Codec, Format, PackedSample, Sample, Value};
20use std::collections::HashMap;
21use std::io::{self, Read, Write};
22use std::net::{IpAddr, Ipv4Addr, SocketAddr, TcpListener, TcpStream};
23use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
24use std::sync::{Arc, Mutex};
25use std::thread::JoinHandle;
26use std::time::Duration;
27#[cfg(test)]
28use std::time::Instant;
29
30const WS_GUID: &str = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
31const MAX_WS_FRAME: usize = 8 * 1024 * 1024;
32const DEFAULT_MARKER_STREAM: &str = "BrowserMarkers";
33
34#[derive(Debug, Clone)]
36pub struct WsOptions {
37 pub bind: SocketAddr,
39 pub allowed_peers: Vec<IpAddr>,
42 pub allow_any: bool,
44 pub session_id: Option<String>,
47 pub marker_stream_name: String,
50}
51
52impl Default for WsOptions {
53 fn default() -> Self {
54 WsOptions {
55 bind: SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 8765),
56 allowed_peers: Vec::new(),
57 allow_any: false,
58 session_id: None,
59 marker_stream_name: DEFAULT_MARKER_STREAM.to_string(),
60 }
61 }
62}
63
64impl WsOptions {
65 pub fn is_peer_allowed(&self, ip: IpAddr) -> bool {
67 if self.allow_any || ip.is_loopback() {
68 return true;
69 }
70 self.allowed_peers.contains(&ip)
71 }
72}
73
74struct Shared {
75 opts: WsOptions,
76 session_id: String,
77 resolver: ContinuousResolver,
78 markers: Mutex<HashMap<String, Arc<Outlet>>>,
79 stop: AtomicBool,
80}
81
82impl Shared {
83 fn list_streams(&self) -> Vec<StreamInfo> {
84 self.resolver.results(usize::MAX)
85 }
86
87 fn find_stream(&self, target: &str) -> Option<StreamInfo> {
88 let cached = self.resolver.results(usize::MAX);
89 if let Some(found) = cached
90 .into_iter()
91 .find(|s| s.uid == target || s.name == target)
92 {
93 return Some(found);
94 }
95 let query = format!("session_id='{}'", self.session_id);
96 resolve(&query, usize::MAX, Duration::from_secs(1))
97 .ok()?
98 .into_iter()
99 .find(|s| s.uid == target || s.name == target)
100 }
101
102 fn push_marker(&self, stream_name: &str, value: &str, timestamp: f64) -> io::Result<f64> {
103 let name = if stream_name.is_empty() {
104 self.opts.marker_stream_name.as_str()
105 } else {
106 stream_name
107 };
108 let outlet = {
109 let mut map = self.markers.lock().unwrap();
110 if let Some(o) = map.get(name) {
111 Arc::clone(o)
112 } else {
113 let mut info = StreamInfo::new(name, "Markers", 1, Format::String, 0.0);
114 info.session_id = self.session_id.clone();
115 info.source_id = format!("labstream-ws-marker-{name}");
116 let created = Arc::new(Outlet::new(info)?);
117 map.insert(name.to_string(), Arc::clone(&created));
118 created
119 }
120 };
121 let ts = if timestamp == 0.0 || !timestamp.is_finite() {
122 crate::clock()
123 } else {
124 timestamp
125 };
126 outlet.push(&Sample {
127 timestamp: ts,
128 values: vec![Value::Str(value.as_bytes().to_vec())],
129 });
130 Ok(ts)
131 }
132}
133
134pub struct WsBridge {
136 addr: SocketAddr,
137 shared: Arc<Shared>,
138 accept_thread: Option<JoinHandle<()>>,
139}
140
141impl WsBridge {
142 pub fn start(opts: WsOptions) -> io::Result<WsBridge> {
144 let listener = TcpListener::bind(opts.bind)?;
145 let addr = listener.local_addr()?;
146 listener.set_nonblocking(true)?;
147
148 let session_id = opts
149 .session_id
150 .clone()
151 .unwrap_or_else(|| config::get().session_id.clone());
152 let query = format!("session_id='{session_id}'");
153 let resolver = ContinuousResolver::new(&query, 5.0);
154
155 let shared = Arc::new(Shared {
156 opts,
157 session_id,
158 resolver,
159 markers: Mutex::new(HashMap::new()),
160 stop: AtomicBool::new(false),
161 });
162
163 let sh = Arc::clone(&shared);
164 let accept_thread = std::thread::spawn(move || {
165 while !sh.stop.load(Ordering::Relaxed) {
166 match listener.accept() {
167 Ok((mut stream, peer)) => {
168 let _ = stream.set_nonblocking(false);
169 let _ = stream.set_nodelay(true);
170 if !sh.opts.is_peer_allowed(peer.ip()) {
171 let _ = stream.write_all(
172 b"HTTP/1.1 403 Forbidden\r\nContent-Length: 9\r\nConnection: close\r\n\r\nForbidden",
173 );
174 let _ = stream.flush();
175 continue;
176 }
177 let conn_shared = Arc::clone(&sh);
178 std::thread::spawn(move || {
179 let _ = handle_connection(stream, conn_shared);
180 });
181 }
182 Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
183 std::thread::sleep(Duration::from_millis(20));
184 }
185 Err(_) => break,
186 }
187 }
188 });
189
190 Ok(WsBridge {
191 addr,
192 shared,
193 accept_thread: Some(accept_thread),
194 })
195 }
196
197 pub fn local_addr(&self) -> SocketAddr {
199 self.addr
200 }
201
202 pub fn stop(&mut self) {
204 self.shared.stop.store(true, Ordering::SeqCst);
205 if let Some(h) = self.accept_thread.take() {
206 let _ = h.join();
207 }
208 }
209}
210
211impl Drop for WsBridge {
212 fn drop(&mut self) {
213 self.stop();
214 }
215}
216
217fn handle_connection(mut stream: TcpStream, shared: Arc<Shared>) -> io::Result<()> {
218 let _ = stream.set_read_timeout(Some(Duration::from_secs(5)));
219 let mut buf = Vec::with_capacity(1024);
220 let mut chunk = [0u8; 1024];
221 let header_end = loop {
222 if buf.len() > 16384 {
223 let _ = stream.write_all(b"HTTP/1.1 431 Request Header Fields Too Large\r\n\r\n");
224 return Ok(());
225 }
226 let n = stream.read(&mut chunk)?;
227 if n == 0 {
228 return Ok(());
229 }
230 buf.extend_from_slice(&chunk[..n]);
231 if let Some(pos) = buf.windows(4).position(|w| w == b"\r\n\r\n") {
232 break pos + 4;
233 }
234 };
235
236 let req_text = String::from_utf8_lossy(&buf[..header_end]);
237 let mut lines = req_text.lines();
238 let first = lines.next().unwrap_or("");
239 let mut parts = first.split_whitespace();
240 let method = parts.next().unwrap_or("");
241 let path = parts.next().unwrap_or("/");
242
243 let mut headers: HashMap<String, String> = HashMap::new();
244 for line in lines {
245 if let Some((k, v)) = line.split_once(':') {
246 headers.insert(k.trim().to_ascii_lowercase(), v.trim().to_string());
247 }
248 }
249
250 if method != "GET" {
251 let _ = stream.write_all(b"HTTP/1.1 405 Method Not Allowed\r\nContent-Length: 0\r\n\r\n");
252 return Ok(());
253 }
254
255 let is_upgrade = headers
256 .get("upgrade")
257 .is_some_and(|v| v.eq_ignore_ascii_case("websocket"));
258 if is_upgrade {
259 let Some(key) = headers.get("sec-websocket-key") else {
260 let _ = stream.write_all(b"HTTP/1.1 400 Bad Request\r\nContent-Length: 0\r\n\r\n");
261 return Ok(());
262 };
263 let accept = ws_accept_key(key);
264 let resp = format!(
265 "HTTP/1.1 101 Switching Protocols\r\n\
266 Upgrade: websocket\r\n\
267 Connection: Upgrade\r\n\
268 Sec-WebSocket-Accept: {accept}\r\n\r\n"
269 );
270 stream.write_all(resp.as_bytes())?;
271 stream.flush()?;
272 return run_ws_session(stream, shared);
273 }
274
275 if path == "/streams" {
276 let body = streams_list_json(&shared.list_streams());
277 let resp = format!(
278 "HTTP/1.1 200 OK\r\n\
279 Content-Type: application/json\r\n\
280 Access-Control-Allow-Origin: *\r\n\
281 Content-Length: {}\r\n\
282 Connection: close\r\n\r\n{}",
283 body.len(),
284 body
285 );
286 stream.write_all(resp.as_bytes())?;
287 stream.flush()?;
288 return Ok(());
289 }
290
291 if path == "/" || path == "/index.html" {
292 let body = BUILTIN_HTML;
293 let resp = format!(
294 "HTTP/1.1 200 OK\r\n\
295 Content-Type: text/html; charset=utf-8\r\n\
296 Content-Length: {}\r\n\
297 Connection: close\r\n\r\n{}",
298 body.len(),
299 body
300 );
301 stream.write_all(resp.as_bytes())?;
302 stream.flush()?;
303 return Ok(());
304 }
305
306 let _ = stream.write_all(b"HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\n\r\n");
307 Ok(())
308}
309
310struct SubHandle {
311 stop: Arc<AtomicBool>,
312 worker: Option<JoinHandle<()>>,
313}
314
315impl Drop for SubHandle {
316 fn drop(&mut self) {
317 self.stop.store(true, Ordering::SeqCst);
318 if let Some(h) = self.worker.take() {
319 let _ = h.join();
320 }
321 }
322}
323
324fn run_ws_session(mut reader: TcpStream, shared: Arc<Shared>) -> io::Result<()> {
325 let writer = Arc::new(Mutex::new(reader.try_clone()?));
326 let _ = reader.set_read_timeout(Some(Duration::from_millis(100)));
327 let next_sub_id = AtomicU32::new(1);
328 let mut subs: HashMap<u32, SubHandle> = HashMap::new();
329
330 while !shared.stop.load(Ordering::Relaxed) {
331 let frame = match read_ws_frame(&mut reader, &writer) {
332 Ok(Some(f)) => f,
333 Ok(None) => break,
334 Err(ref e)
335 if e.kind() == io::ErrorKind::WouldBlock || e.kind() == io::ErrorKind::TimedOut =>
336 {
337 continue;
338 }
339 Err(_) => break,
340 };
341 if frame.opcode != 0x1 {
342 continue;
343 }
344 let Ok(text) = std::str::from_utf8(&frame.payload) else {
345 continue;
346 };
347 let fields = parse_flat_json(text);
348 let op = fields.get("op").map(String::as_str).unwrap_or("");
349 match op {
350 "list" => {
351 let json = streams_list_json(&shared.list_streams());
352 send_ws_text(&writer, &json)?;
353 }
354 "subscribe" => {
355 let target = fields.get("stream").map(String::as_str).unwrap_or("");
356 let postprocess: u32 = fields
357 .get("postprocess")
358 .and_then(|s| s.parse().ok())
359 .unwrap_or(0);
360 let Some(info) = shared.find_stream(target) else {
361 let msg = format!(
362 "{{\"op\":\"error\",\"message\":\"stream not found: {}\"}}",
363 json_escape(target)
364 );
365 send_ws_text(&writer, &msg)?;
366 continue;
367 };
368 let mut inlet = match Inlet::open_recovering(&info, Duration::from_secs(3), 4096) {
369 Ok(i) => i,
370 Err(e) => {
371 let msg = format!(
372 "{{\"op\":\"error\",\"message\":\"{}\"}}",
373 json_escape(&e.to_string())
374 );
375 send_ws_text(&writer, &msg)?;
376 continue;
377 }
378 };
379 inlet.set_postprocessing(postprocess);
380 let sub_id = next_sub_id.fetch_add(1, Ordering::Relaxed);
381 let info_json = stream_info_json(&info);
382 let ack = format!(
383 "{{\"op\":\"subscribed\",\"id\":{sub_id},\"info\":{info_json},\
384 \"format\":{},\"channel_count\":{},\"nominal_srate\":{},\"byte_order\":\"le\"}}",
385 info.format as u8, info.channel_count, info.nominal_srate
386 );
387 send_ws_text(&writer, &ack)?;
388
389 let sub_stop = Arc::new(AtomicBool::new(false));
390 let sub_stop_w = Arc::clone(&sub_stop);
391 let bridge_stop = Arc::clone(&shared);
392 let w = Arc::clone(&writer);
393 let fmt = info.format;
394 let chs = info.channel_count as usize;
395 let worker = std::thread::spawn(move || {
396 let codec = Codec::new(fmt, chs, ByteOrder::Little);
397 let mut batch: Vec<PackedSample> = Vec::with_capacity(256);
398 let mut frame_buf: Vec<u8> = Vec::with_capacity(4096);
399 while !sub_stop_w.load(Ordering::Relaxed)
400 && !bridge_stop.stop.load(Ordering::Relaxed)
401 {
402 for upd in inlet.pull_metadata() {
404 let msg = format!(
405 "{{\"op\":\"meta\",\"id\":{sub_id},\"seq\":{},\"timestamp\":{:.9},\"key\":\"{}\",\"value\":\"{}\"}}",
406 upd.seq,
407 upd.timestamp,
408 json_escape(&upd.key),
409 json_escape(&upd.value)
410 );
411 if send_ws_text(&w, &msg).is_err() {
412 return;
413 }
414 }
415
416 batch.clear();
417 match inlet.pull_chunk_packed(&mut batch, 256, Duration::from_millis(20)) {
418 Ok(0) => {
419 if inlet.is_finished() {
420 break;
421 }
422 }
423 Ok(n) => {
424 frame_buf.clear();
425 frame_buf.extend_from_slice(&sub_id.to_le_bytes());
426 frame_buf.extend_from_slice(&(n as u32).to_le_bytes());
427 for s in &batch {
428 if codec
429 .encode_packed_at(s, s.timestamp, &mut frame_buf)
430 .is_err()
431 {
432 return;
433 }
434 }
435 if send_ws_binary(&w, &frame_buf).is_err() {
436 return;
437 }
438 }
439 Err(_) => break,
440 }
441 }
442 });
443 subs.insert(
444 sub_id,
445 SubHandle {
446 stop: sub_stop,
447 worker: Some(worker),
448 },
449 );
450 }
451 "unsubscribe" => {
452 if let Some(id) = fields.get("id").and_then(|s| s.parse::<u32>().ok()) {
453 subs.remove(&id);
454 let ack = format!("{{\"op\":\"unsubscribed\",\"id\":{id}}}");
455 send_ws_text(&writer, &ack)?;
456 }
457 }
458 "marker" => {
459 let stream_name = fields.get("stream").map(String::as_str).unwrap_or("");
460 let value = fields.get("value").map(String::as_str).unwrap_or("");
461 let ts: f64 = fields
462 .get("timestamp")
463 .and_then(|s| s.parse().ok())
464 .unwrap_or(0.0);
465 match shared.push_marker(stream_name, value, ts) {
466 Ok(actual_ts) => {
467 let used = if stream_name.is_empty() {
468 shared.opts.marker_stream_name.as_str()
469 } else {
470 stream_name
471 };
472 let ack = format!(
473 "{{\"op\":\"marker_ok\",\"stream\":\"{}\",\"timestamp\":{actual_ts:.9}}}",
474 json_escape(used)
475 );
476 send_ws_text(&writer, &ack)?;
477 }
478 Err(e) => {
479 let msg = format!(
480 "{{\"op\":\"error\",\"message\":\"{}\"}}",
481 json_escape(&e.to_string())
482 );
483 send_ws_text(&writer, &msg)?;
484 }
485 }
486 }
487 _ => {
488 let msg = format!(
489 "{{\"op\":\"error\",\"message\":\"unknown op: {}\"}}",
490 json_escape(op)
491 );
492 send_ws_text(&writer, &msg)?;
493 }
494 }
495 }
496
497 drop(subs);
499 Ok(())
500}
501
502fn send_ws_text(writer: &Mutex<TcpStream>, text: &str) -> io::Result<()> {
503 let mut w = writer.lock().unwrap();
504 write_ws_frame(&mut *w, 0x1, text.as_bytes())
505}
506
507fn send_ws_binary(writer: &Mutex<TcpStream>, payload: &[u8]) -> io::Result<()> {
508 let mut w = writer.lock().unwrap();
509 write_ws_frame(&mut *w, 0x2, payload)
510}
511
512struct WsFrame {
514 opcode: u8,
515 payload: Vec<u8>,
516}
517
518fn write_ws_frame<W: Write>(out: &mut W, opcode: u8, payload: &[u8]) -> io::Result<()> {
519 let mut header = Vec::with_capacity(10);
520 header.push(0x80 | (opcode & 0x0F));
521 let len = payload.len();
522 if len < 126 {
523 header.push(len as u8);
524 } else if len <= 0xFFFF {
525 header.push(126);
526 header.extend_from_slice(&(len as u16).to_be_bytes());
527 } else {
528 header.push(127);
529 header.extend_from_slice(&(len as u64).to_be_bytes());
530 }
531 out.write_all(&header)?;
532 out.write_all(payload)?;
533 out.flush()
534}
535
536fn read_ws_frame(reader: &mut TcpStream, writer: &Mutex<TcpStream>) -> io::Result<Option<WsFrame>> {
537 let mut msg_opcode: Option<u8> = None;
538 let mut msg_payload = Vec::new();
539 loop {
540 let mut h = [0u8; 2];
541 reader.read_exact(&mut h)?;
542 let fin = (h[0] & 0x80) != 0;
543 let opcode = h[0] & 0x0F;
544 let masked = (h[1] & 0x80) != 0;
545 let mut len = (h[1] & 0x7F) as u64;
546 if len == 126 {
547 let mut ext = [0u8; 2];
548 reader.read_exact(&mut ext)?;
549 len = u16::from_be_bytes(ext) as u64;
550 } else if len == 127 {
551 let mut ext = [0u8; 8];
552 reader.read_exact(&mut ext)?;
553 len = u64::from_be_bytes(ext);
554 }
555 if len as usize > MAX_WS_FRAME || msg_payload.len() + len as usize > MAX_WS_FRAME {
556 return Err(io::Error::new(
557 io::ErrorKind::InvalidData,
558 "WebSocket frame too large",
559 ));
560 }
561 let mask_key = if masked {
562 let mut m = [0u8; 4];
563 reader.read_exact(&mut m)?;
564 Some(m)
565 } else {
566 None
567 };
568 let mut data = vec![0u8; len as usize];
569 if !data.is_empty() {
570 reader.read_exact(&mut data)?;
571 }
572 if let Some(m) = mask_key {
573 for (i, b) in data.iter_mut().enumerate() {
574 *b ^= m[i & 3];
575 }
576 }
577 match opcode {
578 0x8 => {
579 let _ = write_ws_frame(&mut *writer.lock().unwrap(), 0x8, &[]);
581 return Ok(None);
582 }
583 0x9 => {
584 let _ = write_ws_frame(&mut *writer.lock().unwrap(), 0xA, &data);
586 continue;
587 }
588 0xA => continue, 0x0 => {
590 msg_payload.extend_from_slice(&data);
591 if fin {
592 return Ok(Some(WsFrame {
593 opcode: msg_opcode.unwrap_or(0x1),
594 payload: msg_payload,
595 }));
596 }
597 }
598 other => {
599 msg_opcode = Some(other);
600 msg_payload.extend_from_slice(&data);
601 if fin {
602 return Ok(Some(WsFrame {
603 opcode: other,
604 payload: msg_payload,
605 }));
606 }
607 }
608 }
609 }
610}
611
612fn stream_info_json(s: &StreamInfo) -> String {
613 format!(
614 "{{\"uid\":\"{}\",\"name\":\"{}\",\"type\":\"{}\",\"channel_count\":{},\"format\":{},\"nominal_srate\":{},\"source_id\":\"{}\",\"hostname\":\"{}\"}}",
615 json_escape(&s.uid),
616 json_escape(&s.name),
617 json_escape(&s.stream_type),
618 s.channel_count,
619 s.format as u8,
620 s.nominal_srate,
621 json_escape(&s.source_id),
622 json_escape(&s.hostname),
623 )
624}
625
626fn streams_list_json(streams: &[StreamInfo]) -> String {
627 let mut out = String::from("{\"op\":\"streams\",\"streams\":[");
628 for (i, s) in streams.iter().enumerate() {
629 if i > 0 {
630 out.push(',');
631 }
632 out.push_str(&stream_info_json(s));
633 }
634 out.push_str("]}");
635 out
636}
637
638fn json_escape(s: &str) -> String {
639 let mut out = String::with_capacity(s.len());
640 for ch in s.chars() {
641 match ch {
642 '"' => out.push_str("\\\""),
643 '\\' => out.push_str("\\\\"),
644 '\n' => out.push_str("\\n"),
645 '\r' => out.push_str("\\r"),
646 '\t' => out.push_str("\\t"),
647 c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)),
648 c => out.push(c),
649 }
650 }
651 out
652}
653
654fn parse_flat_json(input: &str) -> HashMap<String, String> {
656 let mut map = HashMap::new();
657 let bytes = input.as_bytes();
658 let mut i = 0;
659 let skip_ws = |idx: &mut usize| {
660 while *idx < bytes.len() && bytes[*idx].is_ascii_whitespace() {
661 *idx += 1;
662 }
663 };
664 let parse_str = |idx: &mut usize| -> Option<String> {
665 skip_ws(idx);
666 if *idx >= bytes.len() || bytes[*idx] != b'"' {
667 return None;
668 }
669 *idx += 1;
670 let mut s = String::new();
671 while *idx < bytes.len() {
672 let b = bytes[*idx];
673 *idx += 1;
674 if b == b'"' {
675 return Some(s);
676 }
677 if b == b'\\' && *idx < bytes.len() {
678 let esc = bytes[*idx];
679 *idx += 1;
680 match esc {
681 b'"' => s.push('"'),
682 b'\\' => s.push('\\'),
683 b'/' => s.push('/'),
684 b'n' => s.push('\n'),
685 b'r' => s.push('\r'),
686 b't' => s.push('\t'),
687 _ => s.push(esc as char),
688 }
689 } else {
690 s.push(b as char);
691 }
692 }
693 None
694 };
695
696 skip_ws(&mut i);
697 if i >= bytes.len() || bytes[i] != b'{' {
698 return map;
699 }
700 i += 1;
701 loop {
702 skip_ws(&mut i);
703 if i >= bytes.len() || bytes[i] == b'}' {
704 break;
705 }
706 let Some(key) = parse_str(&mut i) else {
707 break;
708 };
709 skip_ws(&mut i);
710 if i >= bytes.len() || bytes[i] != b':' {
711 break;
712 }
713 i += 1;
714 skip_ws(&mut i);
715 if i >= bytes.len() {
716 break;
717 }
718 let val = if bytes[i] == b'"' {
719 match parse_str(&mut i) {
720 Some(v) => v,
721 None => break,
722 }
723 } else {
724 let start = i;
725 while i < bytes.len() && !matches!(bytes[i], b',' | b'}' | b' ' | b'\t' | b'\r' | b'\n')
726 {
727 i += 1;
728 }
729 String::from_utf8_lossy(&bytes[start..i]).to_string()
730 };
731 map.insert(key, val);
732 skip_ws(&mut i);
733 if i < bytes.len() && bytes[i] == b',' {
734 i += 1;
735 } else {
736 break;
737 }
738 }
739 map
740}
741
742pub(crate) fn ws_accept_key(key: &str) -> String {
744 let mut input = Vec::with_capacity(key.len() + WS_GUID.len());
745 input.extend_from_slice(key.trim().as_bytes());
746 input.extend_from_slice(WS_GUID.as_bytes());
747 let digest = sha1(&input);
748 base64_encode(&digest)
749}
750
751fn sha1(data: &[u8]) -> [u8; 20] {
753 let mut h0: u32 = 0x6745_2301;
754 let mut h1: u32 = 0xEFCD_AB89;
755 let mut h2: u32 = 0x98BA_DCFE;
756 let mut h3: u32 = 0x1032_5476;
757 let mut h4: u32 = 0xC3D2_E1F0;
758
759 let bit_len = (data.len() as u64).wrapping_mul(8);
760 let mut msg = data.to_vec();
761 msg.push(0x80);
762 while (msg.len() % 64) != 56 {
763 msg.push(0);
764 }
765 msg.extend_from_slice(&bit_len.to_be_bytes());
766
767 let mut w = [0u32; 80];
768 for chunk in msg.chunks_exact(64) {
769 for (i, word) in chunk.chunks_exact(4).enumerate() {
770 w[i] = u32::from_be_bytes([word[0], word[1], word[2], word[3]]);
771 }
772 for i in 16..80 {
773 w[i] = (w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16]).rotate_left(1);
774 }
775 let (mut a, mut b, mut c, mut d, mut e) = (h0, h1, h2, h3, h4);
776 for (i, &wi) in w.iter().enumerate() {
777 let (f, k) = match i {
778 0..=19 => ((b & c) | ((!b) & d), 0x5A82_7999u32),
779 20..=39 => (b ^ c ^ d, 0x6ED9_EBA1u32),
780 40..=59 => ((b & c) | (b & d) | (c & d), 0x8F1B_BCDC),
781 _ => (b ^ c ^ d, 0xCA62_C1D6),
782 };
783 let temp = a
784 .rotate_left(5)
785 .wrapping_add(f)
786 .wrapping_add(e)
787 .wrapping_add(k)
788 .wrapping_add(wi);
789 e = d;
790 d = c;
791 c = b.rotate_left(30);
792 b = a;
793 a = temp;
794 }
795 h0 = h0.wrapping_add(a);
796 h1 = h1.wrapping_add(b);
797 h2 = h2.wrapping_add(c);
798 h3 = h3.wrapping_add(d);
799 h4 = h4.wrapping_add(e);
800 }
801
802 let mut out = [0u8; 20];
803 out[0..4].copy_from_slice(&h0.to_be_bytes());
804 out[4..8].copy_from_slice(&h1.to_be_bytes());
805 out[8..12].copy_from_slice(&h2.to_be_bytes());
806 out[12..16].copy_from_slice(&h3.to_be_bytes());
807 out[16..20].copy_from_slice(&h4.to_be_bytes());
808 out
809}
810
811fn base64_encode(bytes: &[u8]) -> String {
812 const TABLE: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
813 let mut out = String::with_capacity(bytes.len().div_ceil(3) * 4);
814 for chunk in bytes.chunks(3) {
815 let b0 = chunk[0] as u32;
816 let b1 = if chunk.len() > 1 { chunk[1] as u32 } else { 0 };
817 let b2 = if chunk.len() > 2 { chunk[2] as u32 } else { 0 };
818 let n = (b0 << 16) | (b1 << 8) | b2;
819 out.push(TABLE[((n >> 18) & 63) as usize] as char);
820 out.push(TABLE[((n >> 12) & 63) as usize] as char);
821 out.push(if chunk.len() > 1 {
822 TABLE[((n >> 6) & 63) as usize] as char
823 } else {
824 '='
825 });
826 out.push(if chunk.len() > 2 {
827 TABLE[(n & 63) as usize] as char
828 } else {
829 '='
830 });
831 }
832 out
833}
834
835const BUILTIN_HTML: &str = r#"<!doctype html>
837<html lang="en"><head><meta charset="utf-8"><title>labstream WebSocket bridge</title></head>
838<body style="font-family:system-ui,sans-serif;max-width:720px;margin:2rem auto">
839<h1>labstream WebSocket bridge</h1>
840<p>Connect to <code>ws://<host>/ws</code> or load <code>web/index.html</code> with <code>labstream_wasm.wasm</code>.</p>
841<p><a href="/streams">GET /streams</a></p>
842</body></html>
843"#;
844
845#[cfg(test)]
847fn wait_until(timeout: Duration, mut pred: impl FnMut() -> bool) -> bool {
848 let end = Instant::now() + timeout;
849 while Instant::now() < end {
850 if pred() {
851 return true;
852 }
853 std::thread::sleep(Duration::from_millis(15));
854 }
855 pred()
856}
857
858#[cfg(test)]
859mod tests {
860 use super::*;
861
862 #[test]
863 fn rfc6455_accept_key_matches_spec_vector() {
864 assert_eq!(
865 ws_accept_key("dGhlIHNhbXBsZSBub25jZQ=="),
866 "s3pPLMBiTxaQ9kYGzzhZRbK+xOo="
867 );
868 }
869
870 #[test]
871 fn default_policy_allows_only_loopback() {
872 let opts = WsOptions::default();
873 assert!(opts.is_peer_allowed(IpAddr::V4(Ipv4Addr::LOCALHOST)));
874 assert!(opts.is_peer_allowed(IpAddr::V6(std::net::Ipv6Addr::LOCALHOST)));
875 assert!(!opts.is_peer_allowed(IpAddr::V4(Ipv4Addr::new(192, 168, 1, 10))));
876
877 let mut custom = opts.clone();
878 custom
879 .allowed_peers
880 .push(IpAddr::V4(Ipv4Addr::new(192, 168, 1, 10)));
881 assert!(custom.is_peer_allowed(IpAddr::V4(Ipv4Addr::new(192, 168, 1, 10))));
882 assert!(!custom.is_peer_allowed(IpAddr::V4(Ipv4Addr::new(10, 0, 0, 5))));
883 }
884
885 fn ws_client_connect(addr: SocketAddr) -> TcpStream {
886 let mut s = TcpStream::connect(addr).expect("connect");
887 let req = format!(
888 "GET /ws HTTP/1.1\r\nHost: {addr}\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n\
889 Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\nSec-WebSocket-Version: 13\r\n\r\n"
890 );
891 s.write_all(req.as_bytes()).unwrap();
892 let mut resp = Vec::new();
893 let mut b = [0u8; 1];
894 while !resp.ends_with(b"\r\n\r\n") {
895 s.read_exact(&mut b).unwrap();
896 resp.push(b[0]);
897 }
898 let text = String::from_utf8_lossy(&resp);
899 assert!(text.contains("101 Switching Protocols"), "got: {text}");
900 assert!(text.contains("s3pPLMBiTxaQ9kYGzzhZRbK+xOo="));
901 s
902 }
903
904 fn ws_client_send_text(s: &mut TcpStream, text: &str) {
905 let payload = text.as_bytes();
906 let mask = [0x12u8, 0x34, 0x56, 0x78];
907 let mut out = vec![0x81u8];
908 if payload.len() < 126 {
909 out.push(0x80 | payload.len() as u8);
910 } else {
911 out.push(0x80 | 126);
912 out.extend_from_slice(&(payload.len() as u16).to_be_bytes());
913 }
914 out.extend_from_slice(&mask);
915 for (i, &b) in payload.iter().enumerate() {
916 out.push(b ^ mask[i & 3]);
917 }
918 s.write_all(&out).unwrap();
919 s.flush().unwrap();
920 }
921
922 fn ws_client_read_frame(s: &mut TcpStream) -> (u8, Vec<u8>) {
923 let mut h = [0u8; 2];
924 s.read_exact(&mut h).unwrap();
925 let opcode = h[0] & 0x0F;
926 let mut len = (h[1] & 0x7F) as usize;
927 if len == 126 {
928 let mut ext = [0u8; 2];
929 s.read_exact(&mut ext).unwrap();
930 len = u16::from_be_bytes(ext) as usize;
931 } else if len == 127 {
932 let mut ext = [0u8; 8];
933 s.read_exact(&mut ext).unwrap();
934 len = u64::from_be_bytes(ext) as usize;
935 }
936 let mut data = vec![0u8; len];
937 s.read_exact(&mut data).unwrap();
938 (opcode, data)
939 }
940
941 #[test]
942 fn ws_bridge_streams_exact_samples_and_publishes_markers() {
943 let session = format!("ws-test-{}", std::process::id());
944 let mut info = StreamInfo::new("WsEeg", "EEG", 8, Format::Float32, 512.0);
945 info.session_id = session.clone();
946 info.source_id = "ws-eeg-01".to_string();
947 let outlet = Outlet::new(info).expect("outlet");
948
949 let mut bridge = WsBridge::start(WsOptions {
950 bind: SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 0),
951 session_id: Some(session.clone()),
952 marker_stream_name: "WsMarkers".to_string(),
953 ..WsOptions::default()
954 })
955 .expect("ws bridge");
956
957 let mut ws = ws_client_connect(bridge.local_addr());
958 let _ = ws.set_read_timeout(Some(Duration::from_secs(3)));
959
960 assert!(wait_until(Duration::from_secs(3), || {
962 ws_client_send_text(&mut ws, r#"{"op":"list"}"#);
963 let (op, body) = ws_client_read_frame(&mut ws);
964 op == 1 && String::from_utf8_lossy(&body).contains("WsEeg")
965 }));
966
967 ws_client_send_text(&mut ws, r#"{"op":"subscribe","stream":"WsEeg"}"#);
968 let (op, ack) = ws_client_read_frame(&mut ws);
969 assert_eq!(op, 1);
970 let ack_text = String::from_utf8(ack).unwrap();
971 assert!(
972 ack_text.contains("\"op\":\"subscribed\""),
973 "ack: {ack_text}"
974 );
975
976 let mut native =
978 Inlet::open_with_buffer(outlet.info(), Duration::from_secs(2), 4096).unwrap();
979 assert!(wait_until(Duration::from_secs(2), || outlet
980 .consumer_count()
981 >= 2));
982
983 let sample_vals: Vec<f32> = (0..8).map(|c| c as f32 * 1.25 - 3.5).collect();
984 outlet.push_chunk_f32(&sample_vals, 42.125);
985
986 let mut nat_vals = Vec::new();
987 let mut nat_ts = Vec::new();
988 assert!(wait_until(Duration::from_secs(2), || {
989 let _ = native.pull_chunk_f32(&mut nat_vals, &mut nat_ts, 1, Duration::from_millis(50));
990 !nat_ts.is_empty()
991 }));
992
993 let (bin_op, bin) = ws_client_read_frame(&mut ws);
994 assert_eq!(bin_op, 2, "expected binary sample frame");
995 let stream_id = u32::from_le_bytes(bin[0..4].try_into().unwrap());
996 let count = u32::from_le_bytes(bin[4..8].try_into().unwrap());
997 assert_eq!(stream_id, 1);
998 assert_eq!(count, 1);
999
1000 let codec = Codec::new(Format::Float32, 8, ByteOrder::Little);
1001 let (decoded, _) = codec.decode(&bin[8..]).unwrap();
1002 assert_eq!(decoded.timestamp.to_bits(), nat_ts[0].to_bits());
1003 for (c, v) in decoded.values.iter().enumerate() {
1004 match v {
1005 Value::F32(x) => assert_eq!(x.to_bits(), nat_vals[c].to_bits()),
1006 other => panic!("unexpected {other:?}"),
1007 }
1008 }
1009
1010 ws_client_send_text(
1012 &mut ws,
1013 r#"{"op":"marker","stream":"WsMarkers","value":"stimulus_on","timestamp":99.5}"#,
1014 );
1015 let (op, m_ack) = ws_client_read_frame(&mut ws);
1016 assert_eq!(op, 1);
1017 assert!(String::from_utf8_lossy(&m_ack).contains("marker_ok"));
1018
1019 let found = resolve(
1020 &format!("name='WsMarkers' and session_id='{session}'"),
1021 1,
1022 Duration::from_secs(2),
1023 )
1024 .unwrap();
1025 assert_eq!(found.len(), 1);
1026 let mut m_inlet = Inlet::open(&found[0], Duration::from_secs(2)).unwrap();
1027 ws_client_send_text(
1029 &mut ws,
1030 r#"{"op":"marker","stream":"WsMarkers","value":"response_1","timestamp":100.25}"#,
1031 );
1032 let _ = ws_client_read_frame(&mut ws);
1033 let marker_sample = m_inlet
1034 .pull(Duration::from_secs(2))
1035 .unwrap()
1036 .expect("marker sample");
1037 assert_eq!(marker_sample.timestamp.to_bits(), 100.25f64.to_bits());
1038 assert_eq!(marker_sample.values[0], Value::Str(b"response_1".to_vec()));
1039
1040 bridge.stop();
1041 }
1042}