1pub mod audit;
23pub mod cert;
24pub mod client;
25pub mod feed;
26pub mod filter;
27pub mod origin;
28pub mod pairing;
29pub mod panes;
30pub mod sends;
31pub mod signing;
32pub mod terminal;
33
34use std::collections::HashMap;
35use std::net::IpAddr;
36use std::path::PathBuf;
37use std::sync::atomic::{AtomicU16, Ordering};
38use std::sync::{Arc, OnceLock};
39
40use tokio_util::sync::CancellationToken;
41
42pub const MAX_FEEDS_PER_DEVICE: usize = 4;
44pub const MAX_FEEDS: usize = 16;
46pub const LAST_SEEN_EVERY_MS: i64 = 60_000;
48
49#[derive(Debug, Clone, Copy, PartialEq, Eq)]
51pub enum FeedRefused {
52 PerDevice,
53 Total,
54 Stopped,
56}
57
58struct OpenFeed {
60 id: u64,
61 token: CancellationToken,
62 agent: Option<(String, i64)>,
63}
64
65pub type WatchingHook = Arc<dyn Fn() + Send + Sync>;
67
68#[derive(Default)]
69struct FeedRegistry {
70 by_device: HashMap<String, Vec<OpenFeed>>,
71 next_id: u64,
72 hook: Option<WatchingHook>,
73 stopped: std::collections::HashSet<String>,
75}
76
77impl FeedRegistry {
78 fn total(&self) -> usize {
79 self.by_device.values().map(Vec::len).sum()
80 }
81}
82
83#[derive(Debug, Clone, PartialEq, Eq)]
85pub struct Watch {
86 pub device_id: String,
87 pub agent: String,
88 pub since_ms: i64,
89 pub last_sent_ms: Option<i64>,
91}
92
93pub struct FeedLease {
96 registry: Arc<parking_lot::Mutex<FeedRegistry>>,
97 device_id: String,
98 id: u64,
99 pub token: CancellationToken,
100 on_close: Option<Box<dyn FnOnce() + Send + Sync>>,
102}
103
104impl FeedLease {
105 pub fn on_close(mut self, f: impl FnOnce() + Send + Sync + 'static) -> Self {
107 self.on_close = Some(Box::new(f));
108 self
109 }
110}
111
112impl Drop for FeedLease {
113 fn drop(&mut self) {
114 if let Some(f) = self.on_close.take() {
115 f();
116 }
117 let mut reg = self.registry.lock();
118 let mut watched = false;
119 if let Some(list) = reg.by_device.get_mut(&self.device_id) {
120 watched = list.iter().any(|f| f.id == self.id && f.agent.is_some());
121 list.retain(|f| f.id != self.id);
122 if list.is_empty() {
123 reg.by_device.remove(&self.device_id);
124 }
125 }
126 let hook = reg.hook.clone().filter(|_| watched);
127 drop(reg);
128 if let Some(hook) = hook {
129 hook();
130 }
131 }
132}
133
134static ADVERTISED_PORT: OnceLock<Arc<AtomicU16>> = OnceLock::new();
138
139pub fn advertised_viewer_port() -> Option<u16> {
141 ADVERTISED_PORT.get().map(|p| p.load(Ordering::Relaxed)).filter(|p| *p != 0)
142}
143
144pub struct ViewerService {
145 data_dir: Option<PathBuf>,
147 tls: parking_lot::Mutex<Option<Arc<cert::ViewerTls>>>,
148 pub pairing: pairing::Pairing,
149 pub hub: Arc<feed::FeedHub>,
150 feeds: Arc<parking_lot::Mutex<FeedRegistry>>,
151 max_per_device: usize,
152 max_total: usize,
153 advertised_port: Arc<AtomicU16>,
155 bound: parking_lot::Mutex<Vec<IpAddr>>,
157 reservation: parking_lot::Mutex<Option<(u16, socket2::Socket)>>,
162 last_seen_written: parking_lot::Mutex<HashMap<String, i64>>,
164 pub sends: parking_lot::Mutex<sends::SendLedger>,
166 pub nonces: parking_lot::Mutex<signing::NonceLog>,
168 sent_to: parking_lot::Mutex<HashMap<(String, String), i64>>,
170}
171
172impl ViewerService {
173 pub fn new(data_dir: Option<PathBuf>, broker: &crate::backend::mps::Broker) -> Arc<Self> {
175 Self::with_limits(data_dir, broker, Arc::new(feed::FeedHub::default()), MAX_FEEDS_PER_DEVICE, MAX_FEEDS)
176 }
177
178 pub fn with_limits(
179 data_dir: Option<PathBuf>,
180 broker: &crate::backend::mps::Broker,
181 hub: Arc<feed::FeedHub>,
182 max_per_device: usize,
183 max_total: usize,
184 ) -> Arc<Self> {
185 hub.install(broker);
186 Arc::new(Self {
187 data_dir,
188 tls: parking_lot::Mutex::new(None),
189 pairing: pairing::Pairing::new(),
190 hub,
191 feeds: Arc::new(parking_lot::Mutex::new(FeedRegistry::default())),
192 max_per_device,
193 max_total,
194 advertised_port: Arc::new(AtomicU16::new(0)),
195 bound: parking_lot::Mutex::new(Vec::new()),
196 reservation: parking_lot::Mutex::new(None),
197 last_seen_written: parking_lot::Mutex::new(HashMap::new()),
198 sends: parking_lot::Mutex::new(sends::SendLedger::default()),
199 nonces: parking_lot::Mutex::new(signing::NonceLog::default()),
200 sent_to: parking_lot::Mutex::new(HashMap::new()),
201 })
202 }
203
204 pub fn install_global(&self, broker: Arc<crate::backend::mps::Broker>) {
208 let _ = ADVERTISED_PORT.set(Arc::clone(&self.advertised_port));
209 self.set_watching_hook(Arc::new(move || {
210 broker.publish_event::<crate::backend::mps_events::ViewerWatchingChanged>(&(), vec![], 0);
211 }));
212 }
213
214 pub fn advertised_port_handle(&self) -> Arc<AtomicU16> {
216 Arc::clone(&self.advertised_port)
217 }
218
219 pub fn advertised_port(&self) -> Option<u16> {
220 Some(self.advertised_port.load(Ordering::Relaxed)).filter(|p| *p != 0)
221 }
222
223 pub fn tls(&self) -> Result<Arc<cert::ViewerTls>, String> {
225 let mut slot = self.tls.lock();
226 if let Some(tls) = slot.as_ref() {
227 return Ok(Arc::clone(tls));
228 }
229 let tls = Arc::new(match &self.data_dir {
230 Some(dir) => cert::load_or_create(dir)?,
231 None => return Err("the viewer has no data directory for its certificate".to_string()),
232 });
233 *slot = Some(Arc::clone(&tls));
234 Ok(tls)
235 }
236
237 pub fn reserve_port(&self, candidates: impl IntoIterator<Item = u16>) -> Option<u16> {
240 let mut slot = self.reservation.lock();
241 if let Some((port, _)) = slot.as_ref() {
242 return Some(*port);
243 }
244 for port in candidates {
245 let Ok(socket) = socket2::Socket::new(socket2::Domain::IPV4, socket2::Type::STREAM, None) else {
246 continue;
247 };
248 let addr = std::net::SocketAddr::from(([127, 0, 0, 1], port));
249 if socket.bind(&addr.into()).is_ok() {
250 *slot = Some((port, socket));
251 return Some(port);
252 }
253 }
254 None
255 }
256
257 pub fn set_bound(&self, addrs: Vec<IpAddr>, port: u16) {
260 let up = !addrs.is_empty();
261 *self.bound.lock() = addrs;
262 self.advertised_port.store(if up { port } else { 0 }, Ordering::Relaxed);
263 }
264
265 pub fn pair_host(&self) -> Option<IpAddr> {
268 let bound = self.bound.lock().clone();
269 let primary = crate::backend::lan::listeners::primary_lan_ipv4();
270 primary
271 .filter(|p| bound.contains(p))
272 .or_else(|| bound.iter().copied().find(IpAddr::is_ipv4))
273 }
274
275 pub fn open_feed(&self, device_id: &str, agent: Option<&str>) -> Result<FeedLease, FeedRefused> {
279 let mut reg = self.feeds.lock();
280 if reg.stopped.contains(device_id) {
281 return Err(FeedRefused::Stopped);
282 }
283 if reg.total() >= self.max_total {
284 return Err(FeedRefused::Total);
285 }
286 if reg.by_device.get(device_id).map_or(0, Vec::len) >= self.max_per_device {
287 return Err(FeedRefused::PerDevice);
288 }
289 reg.next_id += 1;
290 let id = reg.next_id;
291 let token = CancellationToken::new();
292 let agent = agent.map(|a| (a.to_string(), agentmux_common::time::now_ms()));
293 let hook = reg.hook.clone().filter(|_| agent.is_some());
294 reg.by_device.entry(device_id.to_string()).or_default().push(OpenFeed { id, token: token.clone(), agent });
295 drop(reg);
296 if let Some(hook) = hook {
297 hook();
298 }
299 Ok(FeedLease { registry: Arc::clone(&self.feeds), device_id: device_id.to_string(), id, token, on_close: None })
300 }
301
302 pub fn close_device_feeds(&self, device_id: &str) -> usize {
305 let reg = self.feeds.lock();
306 let Some(list) = reg.by_device.get(device_id) else { return 0 };
307 for feed in list {
308 feed.token.cancel();
309 }
310 list.len()
311 }
312
313 pub fn stop_viewing(&self, device_id: &str) -> usize {
316 self.feeds.lock().stopped.insert(device_id.to_string());
317 self.close_device_feeds(device_id)
318 }
319
320 pub fn allow_viewing(&self, device_id: &str) {
322 self.feeds.lock().stopped.remove(device_id);
323 }
324
325 pub fn viewing_stopped(&self, device_id: &str) -> bool {
327 self.feeds.lock().stopped.contains(device_id)
328 }
329
330 pub fn set_watching_hook(&self, hook: WatchingHook) {
332 self.feeds.lock().hook = Some(hook);
333 }
334
335 pub fn note_sent(&self, device_id: &str, agent: &str, now_ms: i64) {
337 self.sent_to.lock().insert((device_id.to_string(), agent.to_string()), now_ms);
338 let hook = self.feeds.lock().hook.clone();
339 if let Some(hook) = hook {
340 hook();
341 }
342 }
343
344 pub fn watching(&self) -> Vec<Watch> {
346 let mut by: std::collections::BTreeMap<(String, String), i64> = std::collections::BTreeMap::new();
347 for (device_id, list) in &self.feeds.lock().by_device {
348 for (agent, opened_ms) in list.iter().filter_map(|f| f.agent.as_ref()) {
349 let since = by.entry((device_id.clone(), agent.clone())).or_insert(*opened_ms);
350 *since = (*since).min(*opened_ms);
351 }
352 }
353 let sent_to = self.sent_to.lock();
354 by.into_iter()
355 .map(|((device_id, agent), since_ms)| {
356 let last_sent_ms = sent_to.get(&(device_id.clone(), agent.clone())).copied();
357 Watch { device_id, agent, since_ms, last_sent_ms }
358 })
359 .collect()
360 }
361
362 #[cfg(any(test, feature = "test-support"))]
363 pub fn open_feeds(&self) -> usize {
364 self.feeds.lock().total()
365 }
366
367 pub fn last_seen_due(&self, device_id: &str, now_ms: i64) -> bool {
370 let mut written = self.last_seen_written.lock();
371 match written.get(device_id) {
372 Some(at) if now_ms - at < LAST_SEEN_EVERY_MS => false,
373 _ => {
374 written.insert(device_id.to_string(), now_ms);
375 true
376 }
377 }
378 }
379
380 pub fn forget_device(&self, device_id: &str) {
382 self.last_seen_written.lock().remove(device_id);
383 self.sends.lock().forget_device(device_id);
384 self.sent_to.lock().retain(|(device, _), _| device != device_id);
385 self.allow_viewing(device_id);
386 }
387}
388
389#[cfg(test)]
390mod tests {
391 use super::*;
392
393 fn service(per_device: usize, total: usize) -> Arc<ViewerService> {
394 let broker = crate::backend::mps::Broker::new();
395 ViewerService::with_limits(None, &broker, Arc::new(feed::FeedHub::default()), per_device, total)
396 }
397
398 #[test]
399 fn feeds_are_capped_per_device_and_in_all() {
400 let v = service(2, 3);
401 let a1 = v.open_feed("a", None).unwrap();
402 let _a2 = v.open_feed("a", None).unwrap();
403 assert_eq!(v.open_feed("a", None).err(), Some(FeedRefused::PerDevice));
404 let _b1 = v.open_feed("b", None).unwrap();
405 assert_eq!(v.open_feed("c", None).err(), Some(FeedRefused::Total));
406 drop(a1);
407 assert_eq!(v.open_feeds(), 2);
408 assert!(v.open_feed("c", None).is_ok(), "a closed feed frees its place");
409 }
410
411 #[test]
412 fn closing_a_devices_feeds_cancels_only_its_own() {
413 let v = service(4, 16);
414 let a1 = v.open_feed("a", None).unwrap();
415 let a2 = v.open_feed("a", None).unwrap();
416 let b1 = v.open_feed("b", None).unwrap();
417 assert_eq!(v.close_device_feeds("a"), 2);
418 assert!(a1.token.is_cancelled() && a2.token.is_cancelled());
419 assert!(!b1.token.is_cancelled());
420 assert_eq!(v.close_device_feeds("nobody"), 0);
421 }
422
423 #[test]
424 fn who_watches_which_agent_is_listed_and_each_change_calls_the_hook() {
425 let v = service(4, 16);
426 let calls = Arc::new(std::sync::atomic::AtomicUsize::new(0));
427 let counted = Arc::clone(&calls);
428 v.set_watching_hook(Arc::new(move || {
429 counted.fetch_add(1, Ordering::SeqCst);
430 }));
431 let _terminal = v.open_feed("pixel", None).unwrap();
432 assert!(v.watching().is_empty(), "a terminal's feed watches no agent");
433 assert_eq!(calls.load(Ordering::SeqCst), 0);
434 let first = v.open_feed("studio", Some("Clamk")).unwrap();
435 let second = v.open_feed("studio", Some("Clamk")).unwrap();
436 let _other = v.open_feed("pixel", Some("Korp")).unwrap();
437 let listed = v.watching();
438 assert_eq!(listed.iter().map(|w| (w.device_id.as_str(), w.agent.as_str())).collect::<Vec<_>>(), [("pixel", "Korp"), ("studio", "Clamk")]);
439 assert_eq!(calls.load(Ordering::SeqCst), 3);
440 v.note_sent("studio", "Clamk", 42);
441 assert_eq!(v.watching()[1].last_sent_ms, Some(42));
442 drop(first);
443 assert_eq!(v.watching().len(), 2, "still open in its second feed");
444 drop(second);
445 assert_eq!(v.watching().len(), 1);
446 assert_eq!(calls.load(Ordering::SeqCst), 6, "three opens, a send and two closes");
447 }
448
449 #[test]
450 fn a_stopped_device_opens_no_feed_until_it_is_allowed_again_or_forgotten() {
451 let v = service(4, 16);
452 let open = v.open_feed("studio", Some("Clamk")).unwrap();
453 assert_eq!(v.stop_viewing("studio"), 1);
454 assert!(open.token.is_cancelled() && v.viewing_stopped("studio"));
455 assert_eq!(v.open_feed("studio", Some("Clamk")).err(), Some(FeedRefused::Stopped));
456 assert!(v.open_feed("pixel", Some("Clamk")).is_ok(), "only that device");
457 v.allow_viewing("studio");
458 assert!(v.open_feed("studio", Some("Clamk")).is_ok());
459 v.stop_viewing("studio");
460 v.forget_device("studio");
461 assert!(!v.viewing_stopped("studio"), "revoking clears it");
462 }
463
464 #[test]
465 fn last_seen_is_written_at_most_once_a_minute() {
466 let v = service(4, 16);
467 assert!(v.last_seen_due("a", 1_000));
468 assert!(!v.last_seen_due("a", 1_000 + LAST_SEEN_EVERY_MS - 1));
469 assert!(v.last_seen_due("b", 1_000), "per device");
470 assert!(v.last_seen_due("a", 1_000 + LAST_SEEN_EVERY_MS));
471 }
472
473 #[test]
474 fn the_port_is_reserved_once_and_skips_a_taken_one() {
475 let taken = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
476 let taken_port = taken.local_addr().unwrap().port();
477 let free = std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port();
478 let v = service(4, 16);
479 assert_eq!(v.reserve_port([taken_port, free]), Some(free));
480 assert!(
481 std::net::TcpListener::bind(("127.0.0.1", free)).is_err(),
482 "the reservation holds the port against other instances"
483 );
484 assert_eq!(v.reserve_port([taken_port]), Some(free), "kept, not chosen again");
485 }
486
487 #[test]
488 fn the_port_is_advertised_only_while_bound() {
489 let v = service(4, 16);
490 assert_eq!(v.advertised_port(), None);
491 v.set_bound(vec![IpAddr::from([198, 51, 100, 7])], 29702);
492 assert_eq!(v.advertised_port(), Some(29702));
493 assert_eq!(v.pair_host(), Some(IpAddr::from([198, 51, 100, 7])));
494 v.set_bound(Vec::new(), 29702);
495 assert_eq!(v.advertised_port(), None);
496 assert_eq!(v.pair_host(), None);
497 }
498
499 #[test]
500 fn without_a_data_directory_there_is_no_certificate() {
501 assert!(service(4, 16).tls().is_err());
502 }
503}