1use crate::config::{self, FallbackDiscovery};
8use crate::info::StreamInfo;
9use crate::inlet::{probe_peers_tcp, QueryWave};
10use crate::netif::{self, Ipv4Interface};
11use labstream_proto::discovery;
12use std::net::{IpAddr, Ipv4Addr, SocketAddr, UdpSocket};
13use std::time::{Duration, Instant};
14
15#[derive(Debug, Clone)]
17pub struct Options {
18 pub peers: Vec<String>,
20 pub timeout: Duration,
22}
23
24impl Default for Options {
25 fn default() -> Self {
26 Options {
27 peers: Vec::new(),
28 timeout: Duration::from_millis(1200),
29 }
30 }
31}
32
33#[derive(Debug, Clone, Copy, PartialEq, Eq)]
35pub enum Status {
36 Ok,
38 Warn,
40 Fail,
42}
43
44impl Status {
45 pub fn as_str(self) -> &'static str {
47 match self {
48 Status::Ok => "ok",
49 Status::Warn => "warn",
50 Status::Fail => "fail",
51 }
52 }
53}
54
55#[derive(Debug, Clone, PartialEq, Eq)]
57pub struct Check {
58 pub name: String,
60 pub status: Status,
62 pub summary: String,
64 pub cause: Option<String>,
66 pub fix: Option<String>,
68}
69
70#[derive(Debug, Clone, PartialEq, Eq)]
72pub struct FoundStream {
73 pub name: String,
75 pub stream_type: String,
77 pub hostname: String,
79 pub address: String,
81 pub data_port: u16,
83 pub via: String,
85}
86
87#[derive(Debug, Clone)]
89pub struct Report {
90 pub config_source: String,
92 pub session_id: String,
94 pub features: Vec<String>,
96 pub fallback_discovery: FallbackDiscovery,
98 pub known_peers: Vec<String>,
100 pub multicast_port: u16,
102 pub base_port: u16,
104 pub port_range: u16,
106 pub interfaces: Vec<Ipv4Interface>,
108 pub streams: Vec<FoundStream>,
110 pub checks: Vec<Check>,
112}
113
114impl Report {
115 pub fn has_failures(&self) -> bool {
117 self.checks.iter().any(|c| c.status == Status::Fail)
118 }
119
120 pub fn format_text(&self) -> String {
122 let mut out = String::new();
123 out.push_str("labstream doctor\n");
124 out.push_str(&format!(" config: {}\n", self.config_source));
125 out.push_str(&format!(" session: {}\n", self.session_id));
126 out.push_str(&format!(" features: {{{}}}\n", self.features.join(", ")));
127 out.push_str(&format!(
128 " fallback: {}\n",
129 self.fallback_discovery.as_str()
130 ));
131 out.push_str(&format!(
132 " ports: multicast {}, unicast {}..{}\n",
133 self.multicast_port,
134 self.base_port,
135 self.base_port + self.port_range
136 ));
137 if !self.known_peers.is_empty() {
138 out.push_str(&format!(" peers: {}\n", self.known_peers.join(", ")));
139 }
140 out.push_str("\nInterfaces:\n");
141 if self.interfaces.is_empty() {
142 out.push_str(" (none detected)\n");
143 } else {
144 for iface in &self.interfaces {
145 let mut flags = Vec::new();
146 if iface.is_up {
147 flags.push("UP");
148 }
149 if iface.is_loopback {
150 flags.push("LOOPBACK");
151 }
152 if iface.supports_multicast {
153 flags.push("MULTICAST");
154 }
155 let bcast = iface
156 .broadcast
157 .map(|b| format!(" bcast {b}"))
158 .unwrap_or_default();
159 out.push_str(&format!(
160 " {:<12} {}/{}{} [{}]\n",
161 iface.name,
162 iface.addr,
163 iface.prefix_len,
164 bcast,
165 flags.join(",")
166 ));
167 }
168 }
169 out.push_str("\nChecks:\n");
170 for c in &self.checks {
171 let tag = match c.status {
172 Status::Ok => "OK ",
173 Status::Warn => "WARN",
174 Status::Fail => "FAIL",
175 };
176 out.push_str(&format!(" [{tag}] {}: {}\n", c.name, c.summary));
177 if let Some(cause) = &c.cause {
178 out.push_str(&format!(" cause: {cause}\n"));
179 }
180 if let Some(fix) = &c.fix {
181 out.push_str(&format!(" fix: {fix}\n"));
182 }
183 }
184 if !self.streams.is_empty() {
185 out.push_str("\nStreams found:\n");
186 for s in &self.streams {
187 out.push_str(&format!(
188 " {} ({}) on {} ({}:{}) via {}\n",
189 s.name, s.stream_type, s.hostname, s.address, s.data_port, s.via
190 ));
191 }
192 }
193 out
194 }
195
196 pub fn to_json(&self) -> String {
198 let mut s = String::new();
199 s.push('{');
200 push_kv_str(&mut s, "config_source", &self.config_source, true);
201 push_kv_str(&mut s, "session_id", &self.session_id, false);
202 s.push_str(",\"features\":[");
203 for (i, f) in self.features.iter().enumerate() {
204 if i > 0 {
205 s.push(',');
206 }
207 push_json_str(&mut s, f);
208 }
209 s.push(']');
210 push_kv_str(
211 &mut s,
212 "fallback_discovery",
213 self.fallback_discovery.as_str(),
214 false,
215 );
216 s.push_str(",\"known_peers\":[");
217 for (i, p) in self.known_peers.iter().enumerate() {
218 if i > 0 {
219 s.push(',');
220 }
221 push_json_str(&mut s, p);
222 }
223 s.push(']');
224 s.push_str(&format!(
225 ",\"multicast_port\":{},\"base_port\":{},\"port_range\":{}",
226 self.multicast_port, self.base_port, self.port_range
227 ));
228 s.push_str(",\"interfaces\":[");
229 for (i, iface) in self.interfaces.iter().enumerate() {
230 if i > 0 {
231 s.push(',');
232 }
233 s.push('{');
234 push_kv_str(&mut s, "name", &iface.name, true);
235 push_kv_str(&mut s, "addr", &iface.addr.to_string(), false);
236 s.push_str(&format!(",\"prefix_len\":{}", iface.prefix_len));
237 match iface.broadcast {
238 Some(b) => push_kv_str(&mut s, "broadcast", &b.to_string(), false),
239 None => s.push_str(",\"broadcast\":null"),
240 }
241 s.push_str(&format!(
242 ",\"ifindex\":{},\"is_up\":{},\"is_loopback\":{},\"supports_multicast\":{}}}",
243 iface.ifindex, iface.is_up, iface.is_loopback, iface.supports_multicast
244 ));
245 }
246 s.push(']');
247 s.push_str(",\"streams\":[");
248 for (i, st) in self.streams.iter().enumerate() {
249 if i > 0 {
250 s.push(',');
251 }
252 s.push('{');
253 push_kv_str(&mut s, "name", &st.name, true);
254 push_kv_str(&mut s, "type", &st.stream_type, false);
255 push_kv_str(&mut s, "hostname", &st.hostname, false);
256 push_kv_str(&mut s, "address", &st.address, false);
257 s.push_str(&format!(",\"data_port\":{}", st.data_port));
258 push_kv_str(&mut s, "via", &st.via, false);
259 s.push('}');
260 }
261 s.push(']');
262 s.push_str(",\"checks\":[");
263 for (i, c) in self.checks.iter().enumerate() {
264 if i > 0 {
265 s.push(',');
266 }
267 s.push('{');
268 push_kv_str(&mut s, "name", &c.name, true);
269 push_kv_str(&mut s, "status", c.status.as_str(), false);
270 push_kv_str(&mut s, "summary", &c.summary, false);
271 match &c.cause {
272 Some(v) => push_kv_str(&mut s, "cause", v, false),
273 None => s.push_str(",\"cause\":null"),
274 }
275 match &c.fix {
276 Some(v) => push_kv_str(&mut s, "fix", v, false),
277 None => s.push_str(",\"fix\":null"),
278 }
279 s.push('}');
280 }
281 s.push_str("]}");
282 s
283 }
284}
285
286fn push_kv_str(out: &mut String, key: &str, val: &str, first: bool) {
287 if !first {
288 out.push(',');
289 }
290 push_json_str(out, key);
291 out.push(':');
292 push_json_str(out, val);
293}
294
295fn push_json_str(out: &mut String, text: &str) {
296 out.push('"');
297 for ch in text.chars() {
298 match ch {
299 '"' => out.push_str("\\\""),
300 '\\' => out.push_str("\\\\"),
301 '\n' => out.push_str("\\n"),
302 '\r' => out.push_str("\\r"),
303 '\t' => out.push_str("\\t"),
304 c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)),
305 c => out.push(c),
306 }
307 }
308 out.push('"');
309}
310
311pub fn diagnose(options: &Options) -> Report {
313 let cfg = config::get();
314 let interfaces = netif::local_ipv4_interfaces();
315 let mut checks = Vec::new();
316 let mut streams = Vec::new();
317
318 let lan_ifaces: Vec<&Ipv4Interface> = interfaces
320 .iter()
321 .filter(|i| i.is_up && !i.is_loopback)
322 .collect();
323 let mcast_lan: Vec<&Ipv4Interface> = lan_ifaces
324 .iter()
325 .copied()
326 .filter(|i| i.supports_multicast)
327 .collect();
328 if lan_ifaces.is_empty() {
329 checks.push(Check {
330 name: "interfaces".to_string(),
331 status: Status::Warn,
332 summary: "no active non-loopback IPv4 interface found".to_string(),
333 cause: Some("only the loopback interface is up".to_string()),
334 fix: Some("connect to Wi-Fi or Ethernet for multi-machine streams".to_string()),
335 });
336 } else if mcast_lan.is_empty() {
337 checks.push(Check {
338 name: "interfaces".to_string(),
339 status: Status::Warn,
340 summary: format!("{} LAN interface(s), none with multicast", lan_ifaces.len()),
341 cause: Some("no active LAN interface has the MULTICAST flag".to_string()),
342 fix: Some("use fallback discovery or set lab.KnownPeers".to_string()),
343 });
344 } else if lan_ifaces.len() > 1 {
345 let names: Vec<&str> = lan_ifaces.iter().map(|i| i.name.as_str()).collect();
346 checks.push(Check {
347 name: "interfaces".to_string(),
348 status: Status::Ok,
349 summary: format!(
350 "{} active LAN interfaces ({})",
351 lan_ifaces.len(),
352 names.join(", ")
353 ),
354 cause: None,
355 fix: None,
356 });
357 } else {
358 checks.push(Check {
359 name: "interfaces".to_string(),
360 status: Status::Ok,
361 summary: format!(
362 "1 active LAN interface ({} {}/{})",
363 lan_ifaces[0].name, lan_ifaces[0].addr, lan_ifaces[0].prefix_len
364 ),
365 cause: None,
366 fix: None,
367 });
368 }
369
370 let (port_check, mcast_check, bcast_check) = check_local_multicast_and_broadcast(&interfaces);
372 checks.push(port_check);
373 checks.push(mcast_check);
374 checks.push(bcast_check);
375
376 let query = format!("session_id='{}'", cfg.session_id);
378 let half = (options.timeout / 2).max(Duration::from_millis(400));
379 let (mcast_found, fb_found, kp_udp_found, kp_tcp_found) =
380 probe_live_discovery(&query, half, &cfg.known_peers);
381
382 for info in &mcast_found {
383 push_unique_stream(&mut streams, info, "multicast");
384 }
385 for info in &fb_found {
386 push_unique_stream(&mut streams, info, "fallback");
387 }
388 for info in &kp_udp_found {
389 push_unique_stream(&mut streams, info, "known_peers_udp");
390 }
391 for info in &kp_tcp_found {
392 push_unique_stream(&mut streams, info, "known_peers_tcp");
393 }
394
395 let fb_only: Vec<&StreamInfo> = fb_found
396 .iter()
397 .filter(|s| !mcast_found.iter().any(|m| m.uid == s.uid))
398 .collect();
399 let tcp_only: Vec<&StreamInfo> = kp_tcp_found
400 .iter()
401 .filter(|s| {
402 !mcast_found.iter().any(|m| m.uid == s.uid)
403 && !fb_found.iter().any(|f| f.uid == s.uid)
404 && !kp_udp_found.iter().any(|u| u.uid == s.uid)
405 })
406 .collect();
407
408 if !mcast_found.is_empty() && fb_only.is_empty() && tcp_only.is_empty() {
409 checks.push(Check {
410 name: "discovery".to_string(),
411 status: Status::Ok,
412 summary: format!("multicast found {} stream(s)", mcast_found.len()),
413 cause: None,
414 fix: None,
415 });
416 } else if !fb_only.is_empty() {
417 let total = streams.len();
418 checks.push(Check {
419 name: "discovery".to_string(),
420 status: Status::Warn,
421 summary: format!(
422 "multicast found {}, fallback found {} more ({} total)",
423 mcast_found.len(),
424 fb_only.len(),
425 total
426 ),
427 cause: Some("multicast is blocked on this network".to_string()),
428 fix: Some(
429 "labstream fallback discovery works on /24 networks. For larger subnets or liblsl peers, add the outlet IP to lab.KnownPeers."
430 .to_string(),
431 ),
432 });
433 } else if !tcp_only.is_empty() {
434 checks.push(Check {
435 name: "discovery".to_string(),
436 status: Status::Warn,
437 summary: format!(
438 "UDP found 0 streams, TCP KnownPeers found {}",
439 tcp_only.len()
440 ),
441 cause: Some("UDP discovery ports are blocked, while TCP works".to_string()),
442 fix: Some(
443 "open UDP ports 16571-16603 on the firewall, or keep lab.KnownPeers set"
444 .to_string(),
445 ),
446 });
447 } else if !kp_udp_found.is_empty() {
448 checks.push(Check {
449 name: "discovery".to_string(),
450 status: Status::Warn,
451 summary: format!(
452 "multicast found 0 streams, KnownPeers UDP found {}",
453 kp_udp_found.len()
454 ),
455 cause: Some("multicast is blocked on this network".to_string()),
456 fix: Some("keep lab.KnownPeers set or allow multicast on UDP 16571".to_string()),
457 });
458 } else {
459 checks.push(Check {
460 name: "discovery".to_string(),
461 status: Status::Ok,
462 summary: format!("no streams active in session '{}'", cfg.session_id),
463 cause: None,
464 fix: Some(
465 "start an outlet, make sure both sides use the same SessionID, or pass --peer <IP>"
466 .to_string(),
467 ),
468 });
469 }
470
471 for peer in &options.peers {
473 let (check, peer_streams) = check_peer(peer, &query, half);
474 for (info, via) in peer_streams {
475 push_unique_stream(&mut streams, &info, &via);
476 }
477 checks.push(check);
478 }
479
480 Report {
481 config_source: cfg.source.clone(),
482 session_id: cfg.session_id.clone(),
483 features: cfg.features.clone(),
484 fallback_discovery: cfg.fallback_discovery,
485 known_peers: cfg.known_peers.clone(),
486 multicast_port: cfg.multicast_port,
487 base_port: cfg.base_port,
488 port_range: cfg.port_range,
489 interfaces,
490 streams,
491 checks,
492 }
493}
494
495fn push_unique_stream(list: &mut Vec<FoundStream>, info: &StreamInfo, via: &str) {
496 let address = if !info.v4address.is_empty() {
497 info.v4address.clone()
498 } else {
499 info.v6address.clone()
500 };
501 let data_port = if info.v4data_port != 0 {
502 info.v4data_port
503 } else {
504 info.v6data_port
505 };
506 if list
507 .iter()
508 .any(|s| s.name == info.name && s.address == address && s.data_port == data_port)
509 {
510 return;
511 }
512 list.push(FoundStream {
513 name: info.name.clone(),
514 stream_type: info.stream_type.clone(),
515 hostname: info.hostname.clone(),
516 address,
517 data_port,
518 via: via.to_string(),
519 });
520}
521
522fn check_local_multicast_and_broadcast(interfaces: &[Ipv4Interface]) -> (Check, Check, Check) {
523 let cfg = config::get();
524 let addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::UNSPECIFIED), cfg.multicast_port);
525 let sock = match bind_shared_udp4(addr) {
526 Ok(s) => s,
527 Err(e) => {
528 let port_check = Check {
529 name: "multicast_port".to_string(),
530 status: Status::Fail,
531 summary: format!("cannot bind UDP port {}: {e}", cfg.multicast_port),
532 cause: Some(
533 "another process holds the multicast port without SO_REUSEADDR".to_string(),
534 ),
535 fix: Some("stop the other program or change ports.MulticastPort".to_string()),
536 };
537 let skip_mc = Check {
538 name: "multicast_self_test".to_string(),
539 status: Status::Warn,
540 summary: "skipped because the multicast port did not bind".to_string(),
541 cause: None,
542 fix: None,
543 };
544 let skip_bc = Check {
545 name: "broadcast_self_test".to_string(),
546 status: Status::Warn,
547 summary: "skipped because the multicast port did not bind".to_string(),
548 cause: None,
549 fix: None,
550 };
551 return (port_check, skip_mc, skip_bc);
552 }
553 };
554 let _ = sock.set_broadcast(true);
555 let _ = sock.set_read_timeout(Some(Duration::from_millis(120)));
556
557 let group = cfg
558 .multicast_addresses
559 .iter()
560 .filter_map(|a| a.parse::<Ipv4Addr>().ok())
561 .find(|a| a.is_multicast() && !a.is_broadcast() && *a != Ipv4Addr::new(224, 0, 0, 1))
562 .unwrap_or(Ipv4Addr::new(224, 0, 0, 183));
563
564 let mut joined = 0usize;
565 let mut join_addrs: Vec<Ipv4Addr> = interfaces
566 .iter()
567 .filter(|i| i.is_up)
568 .map(|i| i.addr)
569 .collect();
570 if !join_addrs.contains(&Ipv4Addr::UNSPECIFIED) {
571 join_addrs.push(Ipv4Addr::UNSPECIFIED);
572 }
573 for iface in &join_addrs {
574 if sock.join_multicast_v4(&group, iface).is_ok() {
575 joined += 1;
576 }
577 }
578
579 let port_check = Check {
580 name: "multicast_port".to_string(),
581 status: Status::Ok,
582 summary: format!(
583 "UDP port {} bound with reuse ({} group join(s))",
584 cfg.multicast_port, joined
585 ),
586 cause: None,
587 fix: None,
588 };
589
590 let token = format!("__doctor_mc_{}__", crate::make_query_id());
592 let mc_ok = self_test_udp(&sock, &token, |tx| {
593 let _ = tx.set_multicast_loop_v4(true);
594 let _ = tx.set_multicast_ttl_v4(cfg.multicast_ttl);
595 let _ = tx.send_to(token.as_bytes(), (group, cfg.multicast_port));
596 for iface in &join_addrs {
597 if let Ok(if_tx) = UdpSocket::bind((*iface, 0)) {
598 let _ = if_tx.set_multicast_loop_v4(true);
599 let _ = if_tx.set_multicast_ttl_v4(cfg.multicast_ttl);
600 let _ = if_tx.send_to(token.as_bytes(), (group, cfg.multicast_port));
601 }
602 }
603 });
604 let mcast_check = if mc_ok {
605 Check {
606 name: "multicast_self_test".to_string(),
607 status: Status::Ok,
608 summary: format!(
609 "local multicast loopback to {group}:{} passed",
610 cfg.multicast_port
611 ),
612 cause: None,
613 fix: None,
614 }
615 } else {
616 Check {
617 name: "multicast_self_test".to_string(),
618 status: Status::Warn,
619 summary: format!(
620 "no local multicast packet arrived on {group}:{}",
621 cfg.multicast_port
622 ),
623 cause: Some(
624 "local multicast route is missing or a local firewall blocks multicast".to_string(),
625 ),
626 fix: Some(
627 "allow UDP 16571 on the local firewall or rely on fallback discovery".to_string(),
628 ),
629 }
630 };
631
632 let btoken = format!("__doctor_bc_{}__", crate::make_query_id());
634 let bcasts: Vec<Ipv4Addr> = interfaces.iter().filter_map(|i| i.broadcast).collect();
635 let bc_ok = self_test_udp(&sock, &btoken, |tx| {
636 let _ = tx.set_broadcast(true);
637 let _ = tx.send_to(btoken.as_bytes(), (Ipv4Addr::BROADCAST, cfg.multicast_port));
638 for b in &bcasts {
639 let _ = tx.send_to(btoken.as_bytes(), (*b, cfg.multicast_port));
640 }
641 });
642 let bcast_check = if bc_ok {
643 Check {
644 name: "broadcast_self_test".to_string(),
645 status: Status::Ok,
646 summary: format!("local UDP broadcast to port {} passed", cfg.multicast_port),
647 cause: None,
648 fix: None,
649 }
650 } else {
651 Check {
652 name: "broadcast_self_test".to_string(),
653 status: Status::Warn,
654 summary: format!(
655 "no local broadcast packet arrived on port {}",
656 cfg.multicast_port
657 ),
658 cause: Some("local firewall or OS blocked UDP broadcast".to_string()),
659 fix: Some(
660 "unicast fallback and lab.KnownPeers still work without broadcast".to_string(),
661 ),
662 }
663 };
664
665 (port_check, mcast_check, bcast_check)
666}
667
668fn self_test_udp(rx: &UdpSocket, token: &str, send: impl FnOnce(&UdpSocket)) -> bool {
669 let Ok(tx) = UdpSocket::bind((Ipv4Addr::UNSPECIFIED, 0)) else {
670 return false;
671 };
672 send(&tx);
673 let mut buf = [0u8; 512];
674 let end = Instant::now() + Duration::from_millis(200);
675 while Instant::now() < end {
676 match rx.recv_from(&mut buf) {
677 Ok((n, _)) if &buf[..n] == token.as_bytes() => return true,
678 Ok(_) => continue,
679 Err(_) => break,
680 }
681 }
682 false
683}
684
685fn bind_shared_udp4(addr: SocketAddr) -> std::io::Result<UdpSocket> {
686 let sock = socket2::Socket::new(
687 socket2::Domain::IPV4,
688 socket2::Type::DGRAM,
689 Some(socket2::Protocol::UDP),
690 )?;
691 sock.set_reuse_address(true)?;
692 sock.bind(&addr.into())?;
693 Ok(sock.into())
694}
695
696fn probe_live_discovery(
697 query: &str,
698 window: Duration,
699 known_peers: &[String],
700) -> (
701 Vec<StreamInfo>,
702 Vec<StreamInfo>,
703 Vec<StreamInfo>,
704 Vec<StreamInfo>,
705) {
706 let Ok(mut wave) = QueryWave::open() else {
707 return (Vec::new(), Vec::new(), Vec::new(), Vec::new());
708 };
709 wave.send_multicast_only(query);
711 let mcast = wave.collect(window, |_| false);
712
713 let Ok(mut fb_wave) = QueryWave::open() else {
715 return (mcast, Vec::new(), Vec::new(), Vec::new());
716 };
717 fb_wave.send_fallback(query, 0);
718 let fb = fb_wave.collect(window, |_| false);
719
720 let kp_udp = if known_peers.is_empty() {
722 Vec::new()
723 } else if let Ok(mut kp_wave) = QueryWave::open() {
724 kp_wave.send_peers_only(query, known_peers);
725 kp_wave.collect(window, |_| false)
726 } else {
727 Vec::new()
728 };
729 let kp_tcp = if known_peers.is_empty() {
730 Vec::new()
731 } else {
732 probe_peers_tcp(known_peers, query, window)
733 };
734 (mcast, fb, kp_udp, kp_tcp)
735}
736
737fn check_peer(peer: &str, query: &str, window: Duration) -> (Check, Vec<(StreamInfo, String)>) {
738 let cfg = config::get();
739 let peers = vec![peer.to_string()];
740
741 let udp_same = if let Ok(mut w) = QueryWave::open() {
743 w.send_peers_only(query, &peers);
744 w.collect(window, |_| false)
745 } else {
746 Vec::new()
747 };
748
749 let udp_split = probe_peer_split_udp(
751 peer,
752 query,
753 cfg.multicast_port,
754 cfg.base_port,
755 cfg.port_range,
756 window,
757 );
758
759 let tcp = probe_peers_tcp(&peers, query, window);
761
762 let mut found = Vec::new();
763 for s in &udp_same {
764 found.push((s.clone(), format!("peer_udp({peer})")));
765 }
766 for s in &tcp {
767 if !udp_same.iter().any(|u| u.uid == s.uid) {
768 found.push((s.clone(), format!("peer_tcp({peer})")));
769 }
770 }
771
772 let check = if !udp_same.is_empty() && !udp_split.is_empty() {
773 Check {
774 name: format!("peer:{peer}"),
775 status: Status::Ok,
776 summary: format!("{} stream(s) answered on UDP and TCP", found.len()),
777 cause: None,
778 fix: None,
779 }
780 } else if !udp_same.is_empty() && udp_split.is_empty() {
781 Check {
782 name: format!("peer:{peer}"),
783 status: Status::Warn,
784 summary: format!(
785 "{} stream(s) answered on same-port UDP, 0 on split-port UDP",
786 udp_same.len()
787 ),
788 cause: Some(
789 "stateful firewall drops replies to a separate UDP return port".to_string(),
790 ),
791 fix: Some(
792 "labstream handles this automatically. liblsl inlets need an inbound firewall rule."
793 .to_string(),
794 ),
795 }
796 } else if !tcp.is_empty() {
797 Check {
798 name: format!("peer:{peer}"),
799 status: Status::Warn,
800 summary: format!(
801 "UDP timed out, TCP LSL:shortinfo found {} stream(s)",
802 tcp.len()
803 ),
804 cause: Some(format!(
805 "UDP ports {}-{} are blocked to {peer}, while TCP works",
806 cfg.multicast_port,
807 cfg.base_port + cfg.port_range - 1
808 )),
809 fix: Some(format!(
810 "add {peer} to lab.KnownPeers in lsl_api.cfg, or open UDP ports {}-{}",
811 cfg.multicast_port,
812 cfg.base_port + cfg.port_range - 1
813 )),
814 }
815 } else {
816 Check {
817 name: format!("peer:{peer}"),
818 status: Status::Fail,
819 summary: format!("no stream answered on {peer} over UDP or TCP"),
820 cause: Some(format!(
821 "{peer} is unreachable, a firewall blocks ports {}-{}, no outlet runs, or SessionID differs",
822 cfg.multicast_port,
823 cfg.base_port + cfg.port_range - 1
824 )),
825 fix: Some(format!(
826 "make sure that {peer} answers ping and allows TCP/UDP ports {}-{}",
827 cfg.multicast_port,
828 cfg.base_port + cfg.port_range - 1
829 )),
830 }
831 };
832 (check, found)
833}
834
835fn probe_peer_split_udp(
836 peer: &str,
837 query: &str,
838 multicast_port: u16,
839 base_port: u16,
840 port_range: u16,
841 window: Duration,
842) -> Vec<StreamInfo> {
843 let Ok(rx) = UdpSocket::bind((Ipv4Addr::UNSPECIFIED, 0)) else {
844 return Vec::new();
845 };
846 let Ok(tx) = UdpSocket::bind((Ipv4Addr::UNSPECIFIED, 0)) else {
847 return Vec::new();
848 };
849 let Ok(local) = rx.local_addr() else {
850 return Vec::new();
851 };
852 let _ = rx.set_read_timeout(Some(Duration::from_millis(40)));
853 let qid = crate::make_query_id();
854 let msg = discovery::build_query(query, local.port(), &qid);
855 let _ = tx.send_to(&msg, (peer, multicast_port));
856 for p in base_port..base_port + port_range {
857 let _ = tx.send_to(&msg, (peer, p));
858 }
859 let mut out = Vec::new();
860 let mut buf = [0u8; 65536];
861 let end = Instant::now() + window;
862 while Instant::now() < end {
863 match rx.recv_from(&mut buf) {
864 Ok((n, _)) => {
865 if let Some(a) = discovery::parse_answer(&buf[..n]) {
866 if a.query_id == qid {
867 if let Some(info) = StreamInfo::from_shortinfo_xml(&a.xml) {
868 if !out.iter().any(|s: &StreamInfo| s.uid == info.uid) {
869 out.push(info);
870 }
871 }
872 }
873 }
874 }
875 Err(_) => {
876 if !out.is_empty() {
877 break;
878 }
879 }
880 }
881 }
882 out
883}
884
885#[cfg(test)]
886mod tests {
887 use super::*;
888
889 #[test]
890 fn report_formats_text_and_valid_json() {
891 let report = Report {
892 config_source: "defaults".to_string(),
893 session_id: "default".to_string(),
894 features: vec!["seq".to_string(), "resume".to_string()],
895 fallback_discovery: FallbackDiscovery::Auto,
896 known_peers: vec!["10.0.0.2".to_string()],
897 multicast_port: 16571,
898 base_port: 16572,
899 port_range: 32,
900 interfaces: vec![Ipv4Interface {
901 name: "wlan0".to_string(),
902 addr: Ipv4Addr::new(192, 168, 2, 10),
903 prefix_len: 24,
904 broadcast: Some(Ipv4Addr::new(192, 168, 2, 255)),
905 ifindex: 3,
906 is_up: true,
907 is_loopback: false,
908 supports_multicast: true,
909 }],
910 streams: vec![FoundStream {
911 name: "EEG \"1\"".to_string(),
912 stream_type: "EEG".to_string(),
913 hostname: "lab-pc".to_string(),
914 address: "192.168.2.208".to_string(),
915 data_port: 16572,
916 via: "fallback".to_string(),
917 }],
918 checks: vec![Check {
919 name: "discovery".to_string(),
920 status: Status::Warn,
921 summary: "multicast found 0, fallback found 1".to_string(),
922 cause: Some("multicast is blocked on this network".to_string()),
923 fix: Some("use fallback".to_string()),
924 }],
925 };
926 let text = report.format_text();
927 assert!(text.contains("labstream doctor"));
928 assert!(text.contains("multicast is blocked on this network"));
929 assert!(text.contains("via fallback"));
930 let json = report.to_json();
931 assert!(json.starts_with('{') && json.ends_with('}'));
932 assert!(json.contains("\"fallback_discovery\":\"auto\""));
933 assert!(json.contains("EEG \\\"1\\\""));
934 assert!(!report.has_failures());
935 }
936}