Repository navigation
Expand file tree
/
Copy pathmacos-headless.patch
More file actions
2684 lines (2676 loc) · 135 KB
/
Copy pathmacos-headless.patch
File metadata and controls
2684 lines (2676 loc) · 135 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
diff --git a/src/auth.rs b/src/auth.rs
index 13302ad2099aa7c3f734997e0b9c95d387f51e45..431d5413ba9052ffc448ffcdd0e9b28982a5625d 100644
--- a/src/auth.rs
+++ b/src/auth.rs
@@ -59,8 +59,10 @@ impl Credentials {
system_id: get("system_id"), token: get("token"), csrf: get("csrf"),
sign_key: Some(get("sign_key")).filter(|k| !k.is_empty()).unwrap_or_else(|| DEFAULT_SIGN_KEY.into()),
};
+ // Official macOS logins may have an empty system_id claim. The signed
+ // request builder already omits identifiers that are not present.
let missing: Vec<&str> = [("user_id", &creds.user_id), ("device_id", &creds.device_id), ("client_id", &creds.client_id),
- ("system_id", &creds.system_id), ("token", &creds.token), ("csrf", &creds.csrf), ("sign_key", &creds.sign_key)]
+ ("token", &creds.token), ("csrf", &creds.csrf), ("sign_key", &creds.sign_key)]
.iter().filter(|(_, v)| v.is_empty()).map(|(k, _)| *k).collect();
if missing.is_empty() { Ok(creds) } else { Err(format!("missing credential settings: {}", missing.join(", "))) }
}
diff --git a/src/viewer/session.rs b/src/viewer/session.rs
index e850812138da1cb686b488a7c43bdc9ff84fb4c6..0e9e9c575f20037f409ae0fc7f041f1f563ef4f2 100644
--- a/src/viewer/session.rs
+++ b/src/viewer/session.rs
@@ -4,6 +4,23 @@ use std::{sync::atomic::Ordering,time::Duration};
use tokio::sync::mpsc;
use webrtc::api::setting_engine::SettingEngine;
+/// Keep signaling alive across readiness polls and heartbeats. Recreating
+/// Session::step on every tick can discard an already-received SDP while
+/// WebRTC is still applying it. Cancel these futures only when the command ends.
+pub async fn drive_tools(
+ operation:impl std::future::Future<Output=Result<(),String>>,
+ signaling:impl std::future::Future<Output=Result<(),String>>,
+ heartbeat:impl std::future::Future<Output=Result<(),String>>,
+ stopped:impl std::future::Future<Output=()>,
+)->Result<(),String> {
+ tokio::select! {
+ result=operation=>result,
+ result=signaling=>result,
+ result=heartbeat=>result,
+ _=stopped=>Ok(()),
+ }
+}
+
pub struct Options {pub timeout:Duration,pub legacy_prefix:bool,pub ready_policy:ReadyPolicy,pub clipboard:super::clipboard::Bridge}
pub struct Session {pub peer:Peer,signal:Signal,candidates:mpsc::Receiver<Value>,policy:ReadyPolicy}
impl Session {
@@ -25,7 +42,7 @@ impl Session {
log::info!("Control ack ICE entries: {:?}",summary);
}
// Structure and relations only; never the ids or ICE credentials.
- log::info!("Control ack shape={} app_control_id_matches={:?} ice_id_matches={:?}",crate::protocol::json_shape(&result,5),
+ log::info!("Control ack keys={:?} app_control_id_matches={:?} ice_id_matches={:?}",result.as_object().map(|body|body.keys().collect::<Vec<_>>()),
result.get("app_control_id").map(|v|v.as_str()==Some(app.as_str())),result.get("ice_id").map(|v|v.as_str()==Some(ice.as_str())));
if result.get("app_control_id").is_some_and(|v|v.as_str()!=Some(app.as_str())) {return Err("Control acknowledgement belongs to another session".into())}
// Observed live: the cloud assigns the session ice_id in this ack rather than echoing ours.
@@ -60,7 +77,12 @@ impl Session {
Some("soac")=>if let Some(body)=event.get(1) {self.peer.receive(body).await?},
Some("released"|"left"|"leave")=> {
// An event for another peer must not tear down this session.
- if self.peer.matches_route(event.get(1).unwrap_or(&Value::Null)) {return Err("Remote session released".into())}
+ let route=event.get(1).unwrap_or(&Value::Null);
+ let body=route.get("data").unwrap_or(route);
+ let matches=self.peer.matches_route(route);
+ log::info!("Viewer release: matched={} ice_id_present={} app_control_id_present={} client_id_present={}",
+ matches,body.get("ice_id").is_some(),body.get("app_control_id").is_some(),route.get("client_id").is_some());
+ if matches {return Err("Remote session released".into())}
}
_=>{},
}
diff --git a/src/viewer/signal.rs b/src/viewer/signal.rs
index b87d872b959209dac4e126a1892312e8a9cd267a..0948a70035145af62e4c556b5ebbd16a92c79d4d 100644
--- a/src/viewer/signal.rs
+++ b/src/viewer/signal.rs
@@ -1,17 +1,39 @@
//! Framing/ack evidence: internal viewer-evidence-20261016.md section 3.
//! Raw Engine.IO4 attachments and legacy SDK 0x04 framing are explicit alternatives.
use base64::Engine as _;
-use futures_util::{SinkExt, StreamExt};
+use futures_util::{Sink, SinkExt, StreamExt};
use serde_json::Value;
use tokio_tungstenite::tungstenite::{client::IntoClientRequest, Message};
-use std::{collections::VecDeque,time::Duration};
+use std::{collections::VecDeque,pin::Pin,time::Duration};
+use tokio::time::Instant;
pub struct Signal {
ws: crate::ws_transport::Socket,
+
next_ack:u64,
+
pending:VecDeque<Value>,
+
legacy_prefix:bool,
+
+ /// A binary header may arrive before a heartbeat cancels event polling.
+ /// Retain it and any completed attachments until the whole packet arrives.
+ binary:Option<BinaryPacket>,
+
+ /// Retain unsent messages when a heartbeat cancels the caller's future.
+ outbox:VecDeque<Message>,
+
+ refresh:Refresh,
+
+ started:Instant,
+
+ pings:u64,
+
+ pong_queued:u64,
+
+ last_ping:Instant,
}
+
impl Signal {
pub async fn connect(urls:&[String], token:&str, timeout:Duration, legacy_prefix:bool)->Result<Self,String> {
for url in urls {
@@ -19,26 +41,68 @@ impl Signal {
}
Err("Signaling connection failed (details omitted)".into())
}
+
async fn one(url:&str,token:&str,legacy_prefix:bool,timeout:Duration)->Result<Self,String> {
let mut request=format!("{}/socket.io/?transport=websocket&EIO=4",url.trim_end_matches('/')).into_client_request().map_err(|_|"Invalid signaling endpoint")?;
request.headers_mut().insert("X-NRD-AUTH",token.parse().map_err(|_|"Invalid room authentication header")?);
let ws=crate::ws_transport::connect(request,timeout).await?;
- let mut s=Self{ws,next_ack:10,pending:VecDeque::new(),legacy_prefix};
+ let now=Instant::now();
+ let mut s=Self{ws,next_ack:10,pending:VecDeque::new(),legacy_prefix,binary:None,
+ outbox:VecDeque::new(),refresh:Refresh::new(now),started:now,pings:0,pong_queued:0,last_ping:now};
let mut opened=false;
loop {
match s.ws.next().await {
Some(Ok(Message::Text(t))) if t.starts_with('0') && !opened => {
- serde_json::from_str::<Value>(&t[1..]).map_err(|_|"Invalid Engine.IO open")?;
+ let open=serde_json::from_str::<Value>(&t[1..]).map_err(|_|"Invalid Engine.IO open")?;
+ log::info!("Viewer signaling heartbeat config: ping_interval_ms={:?} ping_timeout_ms={:?}",
+ open.get("pingInterval").and_then(Value::as_u64),open.get("pingTimeout").and_then(Value::as_u64));
opened=true;s.send(Message::Text("40".into())).await?;
}
- Some(Ok(Message::Text(t))) if t.starts_with("40") && opened =>return Ok(s),
+ Some(Ok(Message::Text(t))) if t.starts_with("40") && opened => {
+ s.refresh.next=Instant::now()+Duration::from_secs(30);
+ return Ok(s)
+ },
Some(Ok(Message::Text(t))) if t.starts_with('2')=>s.send(Message::Text(format!("3{}",&t[1..]))).await?,
Some(Ok(Message::Ping(b)))=>s.send(Message::Pong(b)).await?,
_=>return Err("Signaling handshake failed".into()),
}
}
}
- async fn send(&mut self,message:Message)->Result<(),String> {self.ws.send(message).await.map_err(|_|"Signaling send failed".into())}
+
+ async fn send(&mut self,message:Message)->Result<(),String> {
+ if self.outbox.len()>=512 {return Err("Too many pending signaling messages".into())}
+ if matches!(&message,Message::Text(text) if text.starts_with('3')) {self.pong_queued+=1;}
+ self.outbox.push_back(message);
+ flush_outbox(&mut self.ws,&mut self.outbox).await
+ }
+
+ async fn refresh_key(&mut self)->Result<(),String> {
+ self.next_ack+=1;
+ let id=self.next_ack;
+ self.refresh.request(id,Instant::now());
+ // Official libstreamer RefreshSignalTokenLoop emits this event without
+ // payload arguments: first/retry after 30s, success every 300s. See also
+ // src/signaling.rs and docs/release-notes/v0.1.5.md for the same wire form.
+ log::info!("Viewer reconnect-key refresh requested: age_s={}",self.started.elapsed().as_secs());
+ self.send(Message::Text(format!("42{id}[\"refresh_reconnect_key\"]"))).await
+ }
+
+ fn accept_packet(&mut self,packet:Packet)->Option<Packet> {
+ if let Packet::Ack(id,value)=&packet {
+ if self.refresh.acknowledge(*id,value,Instant::now()) {
+ log::info!("Viewer reconnect-key refresh acknowledged: age_s={} accepted={}",
+ self.started.elapsed().as_secs(),self.refresh.accepted==*id);
+ return None
+ }
+ }
+ Some(packet)
+ }
+
+ fn closed(&self,kind:&str) {
+ log::info!("Viewer signaling closed: kind={} age_s={} pings={} pong_queued={} last_ping_gap_s={} refresh_success={}",
+ kind,self.started.elapsed().as_secs(),self.pings,self.pong_queued,self.last_ping.elapsed().as_secs(),self.refresh.accepted!=0);
+ }
+
pub async fn control(&mut self, header:Value, app_data:Vec<u8>, timeout:Duration)->Result<Value,String> {
self.next_ack+=1;let id=self.next_ack;
self.send(Message::Text(format!("451-{id}{}",serde_json::json!(["control",header])))).await?;
@@ -48,6 +112,10 @@ impl Signal {
loop {
match self.packet().await? {
Packet::Ack(ack,value) if ack==id=> {
+ // Concurrent connection failures need a structural
+ // diagnostic without exposing room or TURN credentials.
+ log::info!("Viewer control acknowledgement: success={} body_keys={:?}",
+ value.get(0).and_then(Value::as_str)==Some("success"),value.get(1).and_then(Value::as_object).map(|body|body.keys().collect::<Vec<_>>()));
let a=value.as_array().ok_or("Invalid control acknowledgement")?;
if a.len()!=2 || a[0].as_str()!=Some("success") || !a[1].is_object() {return Err("Control refused or malformed acknowledgement".into())}
return Ok(a[1].clone());
@@ -61,64 +129,66 @@ impl Signal {
}
}).await.map_err(|_|"Control acknowledgement timed out")?
}
+
async fn packet(&mut self)->Result<Packet,String> {
loop {
- match self.ws.next().await {
- Some(Ok(Message::Text(t))) if t.starts_with('2')=>self.send(Message::Text(format!("3{}",&t[1..]))).await?,
+ // A previous caller may have been canceled after queuing a pong or
+ // ICE candidate. Flush it before waiting for another inbound frame.
+ flush_outbox(&mut self.ws,&mut self.outbox).await?;
+ let message=tokio::select! {
+ _=tokio::time::sleep_until(self.refresh.next)=>{self.refresh_key().await?;continue;},
+ message=self.ws.next()=>message,
+ };
+ match message {
+ Some(Ok(Message::Text(t))) if t.starts_with('2')=> {
+ self.pings+=1;self.last_ping=Instant::now();
+ self.send(Message::Text(format!("3{}",&t[1..]))).await?;
+ if self.pings==1 || self.pings%12==0 {
+ log::info!("Viewer signaling heartbeat: age_s={} pings={} pong_queued={}",self.started.elapsed().as_secs(),self.pings,self.pong_queued);
+ }
+ },
Some(Ok(Message::Ping(b)))=>self.send(Message::Pong(b)).await?,
Some(Ok(Message::Text(t))) if t.starts_with("43")=> {
let begin=t.find('[').ok_or("Malformed signaling acknowledgement")?;
let id=t[2..begin].parse().map_err(|_|"Malformed signaling acknowledgement id")?;
let value=serde_json::from_str(&t[begin..]).map_err(|_|"Malformed signaling acknowledgement body")?;
- return Ok(Packet::Ack(id,value))
+ if let Some(packet)=self.accept_packet(Packet::Ack(id,value)){return Ok(packet)}
}
Some(Ok(Message::Text(t))) if t.starts_with("42")=> {
let begin=t.find('[').ok_or("Malformed signaling event")?;
let value=serde_json::from_str(&t[begin..]).map_err(|_|"Malformed signaling event body")?;
return Ok(Packet::Event(value))
}
- // Socket.IO binary event (45N-[...] / 46N-[...] ack) followed by N attachment frames.
- // The official host sends its answer this way (binary gzip_sdp); attachments are
- // substituted as base64 strings so the existing gzip_sdp decoder applies.
+ // The tool loop polls signaling alongside its one-second heartbeat.
+ // Keep partial binary packets in Self so cancellation cannot discard
+ // an SDP header while its separate WebSocket attachments are in flight.
Some(Ok(Message::Text(t))) if t.starts_with("45") || t.starts_with("46")=> {
- let dash=t.find('-').ok_or("Malformed binary signaling packet")?;
- let count:usize=t[2..dash].parse().map_err(|_|"Malformed binary attachment count")?;
- if count>8 {return Err("Too many signaling attachments".into())}
- let begin=t.find('[').ok_or("Malformed binary signaling packet")?;
- let mut value:serde_json::Value=serde_json::from_str(&t[begin..]).map_err(|_|"Malformed binary signaling body")?;
- let mut attachments=Vec::with_capacity(count);
- while attachments.len()<count {
- match self.ws.next().await {
- Some(Ok(Message::Binary(mut b)))=>{
- if b.len()>2 && b[0]==4 && b[1]==0x1f {b.remove(0);}
- if b.len()>4*1024*1024 {return Err("Signaling attachment too large".into())}
- attachments.push(base64::engine::general_purpose::STANDARD.encode(&b));
- }
- Some(Ok(Message::Text(t))) if t.starts_with('2')=>self.send(Message::Text(format!("3{}",&t[1..]))).await?,
- Some(Ok(_))=>{},
- _=>return Err("Signaling disconnected".into()),
- }
- }
- fn fill(v:&mut serde_json::Value,a:&[String]) {
- match v {
- serde_json::Value::Object(o) if o.get("_placeholder")==Some(&serde_json::Value::Bool(true))=>{
- if let Some(s)=o.get("num").and_then(|n|n.as_u64()).and_then(|n|a.get(n as usize)) {*v=serde_json::Value::String(s.clone());}
- }
- serde_json::Value::Object(o)=>for x in o.values_mut(){fill(x,a)},
- serde_json::Value::Array(l)=>for x in l{fill(x,a)},
- _=>{},
- }
+ if self.binary.is_some(){return Err("Overlapping binary signaling packets".into())}
+ let packet=BinaryPacket::header(&t)?;
+ if packet.count==0 {
+ if let Some(packet)=self.accept_packet(packet.finish()){return Ok(packet)}
+ continue;
}
- fill(&mut value,&attachments);
- log::info!("Viewer binary signaling event: name={} attachments={}",value.get(0).and_then(|v|v.as_str()).unwrap_or("-"),count);
- if t.starts_with("46") {
- let id=t[dash+1..begin].parse().map_err(|_|"Malformed binary acknowledgement id")?;
- return Ok(Packet::Ack(id,value))
+ self.binary=Some(packet);
+ }
+ Some(Ok(Message::Binary(mut b))) if self.binary.is_some()=> {
+ if b.len()>2 && b[0]==4 && b[1]==0x1f {b.remove(0);}
+ if b.len()>4*1024*1024 {return Err("Signaling attachment too large".into())}
+ let packet=self.binary.as_mut().unwrap();
+ packet.attachments.push(base64::engine::general_purpose::STANDARD.encode(&b));
+ if packet.attachments.len()==packet.count {
+ let packet=self.binary.take().unwrap().finish();
+ if let Some(packet)=self.accept_packet(packet){return Ok(packet)}
}
- return Ok(Packet::Event(value))
}
- Some(Ok(Message::Text(t))) if t=="41" || t=="1"=>return Err("Signaling room closed".into()),
- Some(Ok(Message::Close(_)))|None|Some(Err(_))=>return Err("Signaling disconnected".into()),
+ Some(Ok(Message::Text(t))) if t=="41" || t=="1"=> {
+ self.closed(if t=="41"{"socket_io_disconnect"}else{"engine_io_close"});
+ return Err("Signaling room closed".into())
+ },
+ Some(Ok(Message::Close(_)))|None|Some(Err(_))=> {
+ self.closed("websocket_disconnected");
+ return Err("Signaling disconnected".into())
+ },
// Type, short prefix and length only, to see what else the room delivers.
Some(Ok(Message::Text(t)))=>log::info!("Viewer signaling frame ignored: text prefix={} bytes={}",t.chars().take(3).collect::<String>(),t.len()),
Some(Ok(Message::Binary(b)))=>log::info!("Viewer signaling frame ignored: binary bytes={}",b.len()),
@@ -126,11 +196,242 @@ impl Signal {
}
}
}
+
pub async fn event(&mut self)->Result<Value,String> {
if let Some(v)=self.pending.pop_front(){return Ok(v)}
loop {if let Packet::Event(v)=self.packet().await?{return Ok(v)}}
}
+
pub async fn soac(&mut self, value:Value)->Result<(),String> {self.send(Message::Text(format!("42{}",serde_json::json!(["soac",value])))).await}
+
pub async fn close(&mut self) {let _=self.ws.close(None).await;}
}
+
enum Packet { Ack(u64,Value), Event(Value) }
+
+/// A Socket.IO binary packet spans a JSON header and subsequent binary frames.
+/// Its contents stay private; diagnostics expose only the attachment count.
+struct BinaryPacket {
+ value:Value,
+
+ count:usize,
+
+ attachments:Vec<String>,
+
+ ack:Option<u64>,
+}
+
+impl BinaryPacket {
+ fn header(text:&str)->Result<Self,String> {
+ let dash=text.find('-').ok_or("Malformed binary signaling packet")?;
+ let count:usize=text[2..dash].parse().map_err(|_|"Malformed binary attachment count")?;
+ if count>8 {return Err("Too many signaling attachments".into())}
+ let begin=text.find('[').filter(|begin|*begin>dash).ok_or("Malformed binary signaling packet")?;
+ let value=serde_json::from_str(&text[begin..]).map_err(|_|"Malformed binary signaling body")?;
+ let ack=if text.starts_with("46") {
+ Some(text[dash+1..begin].parse().map_err(|_|"Malformed binary acknowledgement id")?)
+ } else {None};
+ Ok(Self{value,count,attachments:Vec::with_capacity(count),ack})
+ }
+
+ fn finish(mut self)->Packet {
+ fn fill(value:&mut Value,attachments:&[String]) {
+ match value {
+ Value::Object(object) if object.get("_placeholder")==Some(&Value::Bool(true))=> {
+ if let Some(data)=object.get("num").and_then(Value::as_u64).and_then(|n|attachments.get(n as usize)) {
+ *value=Value::String(data.clone());
+ }
+ }
+ Value::Object(object)=>for value in object.values_mut(){fill(value,attachments)},
+ Value::Array(array)=>for value in array{fill(value,attachments)},
+ _=>{},
+ }
+ }
+ fill(&mut self.value,&self.attachments);
+ log::info!("Viewer binary signaling packet: attachments={} acknowledgement={}",self.count,self.ack.is_some());
+ match self.ack {Some(id)=>Packet::Ack(id,self.value),None=>Packet::Event(self.value)}
+ }
+}
+
+/// Commit a queued frame only after the sink is ready. There is no await between
+/// dequeue and start_send; cancellation during flush leaves the frame in the sink.
+pub(super) async fn flush_outbox<S:Sink<Message>+Unpin>(socket:&mut S,outbox:&mut VecDeque<Message>)->Result<(),String> {
+ while !outbox.is_empty() {
+ futures_util::future::poll_fn(|context|Pin::new(&mut *socket).poll_ready(context))
+ .await.map_err(|_|"Signaling send failed")?;
+ let message=outbox.pop_front().unwrap();
+ Pin::new(&mut *socket).start_send(message).map_err(|_|"Signaling send failed")?;
+ }
+ socket.flush().await.map_err(|_|"Signaling send failed".into())
+}
+
+/// Room renewal follows the official native session's schedule. Only ack ids
+/// and deadlines are retained; the returned reconnect credential is never stored.
+struct Refresh {
+ next:Instant,
+
+ pending:VecDeque<u64>,
+
+ accepted:u64,
+}
+
+impl Refresh {
+ fn new(now:Instant)->Self {
+ Self{next:now+Duration::from_secs(30),pending:VecDeque::new(),accepted:0}
+ }
+
+ fn request(&mut self,id:u64,now:Instant) {
+ self.pending.push_back(id);
+ if self.pending.len()>16 {self.pending.pop_front();}
+ self.next=now+Duration::from_secs(30);
+ }
+
+ fn acknowledge(&mut self,id:u64,value:&Value,now:Instant)->bool {
+ if !self.pending.contains(&id){return false}
+ self.pending.retain(|pending|*pending!=id);
+ let valid=value.as_array().is_some_and(|ack| {
+ ack.first().and_then(Value::as_str)==Some("success") && ack.get(1).and_then(|body|body.get("reconnect_key"))
+ .and_then(Value::as_str).is_some_and(|key|!key.is_empty() && key.len()<=16384)
+ });
+ if valid && id>self.accepted {
+ self.accepted=id;
+ self.next=now+Duration::from_secs(300);
+ }
+ true
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use std::task::{Context,Poll};
+ use tokio::net::TcpListener;
+ use tokio_tungstenite::accept_async;
+ use serde_json::json;
+
+ /// Replace sink readiness and flushing with explicit stalls. Accepted frames
+ /// are real ordered writes to this fixture, without network/socket timing.
+ struct StalledSink {
+ ready:bool,
+
+ flush_ready:bool,
+
+ accepted:Vec<Message>,
+ }
+
+ impl Sink<Message> for StalledSink {
+ type Error=();
+
+ fn poll_ready(self:Pin<&mut Self>,_:&mut Context<'_>)->Poll<Result<(),()>> {
+ if self.ready {Poll::Ready(Ok(()))} else {Poll::Pending}
+ }
+
+ fn start_send(mut self:Pin<&mut Self>,message:Message)->Result<(),()> {
+ self.accepted.push(message);Ok(())
+ }
+
+ fn poll_flush(self:Pin<&mut Self>,_:&mut Context<'_>)->Poll<Result<(),()>> {
+ if self.flush_ready {Poll::Ready(Ok(()))} else {Poll::Pending}
+ }
+
+ fn poll_close(self:Pin<&mut Self>,_:&mut Context<'_>)->Poll<Result<(),()>> {
+ Poll::Ready(Ok(()))
+ }
+ }
+
+ /// Cancel both before a write is accepted and after it is buffered. Retrying
+ /// must deliver each frame once and retain the order of pong and ICE data.
+ #[tokio::test]
+ async fn canceled_writes_keep_queued_and_buffered_frames() {
+ let expected=vec![Message::Text("3fixture".into()),Message::Text("42[\"soac\",{}]".into())];
+ let mut queue=VecDeque::from(expected.clone());
+ let mut sink=StalledSink{ready:false,flush_ready:false,accepted:Vec::new()};
+
+ assert!(tokio::time::timeout(Duration::from_millis(5),flush_outbox(&mut sink,&mut queue)).await.is_err());
+ assert_eq!(queue.len(),2);
+ assert!(sink.accepted.is_empty());
+ sink.ready=true;
+ assert!(tokio::time::timeout(Duration::from_millis(5),flush_outbox(&mut sink,&mut queue)).await.is_err());
+ assert!(queue.is_empty());
+ assert_eq!(sink.accepted,expected);
+
+ sink.flush_ready=true;
+ flush_outbox(&mut sink,&mut queue).await.unwrap();
+ assert_eq!(sink.accepted,expected,"a canceled flush must not enqueue a duplicate pong");
+ }
+
+ /// Only a successful renewal with a valid key may defer the next request for
+ /// five minutes; stale replies and failure replies must retain retry timing.
+ #[tokio::test]
+ async fn refresh_schedule_retries_failures_and_rejects_stale_acknowledgements() {
+ let now=Instant::now();
+ let mut refresh=Refresh::new(now);
+ assert_eq!(refresh.next,now+Duration::from_secs(30));
+ refresh.request(11,now+Duration::from_secs(30));
+ assert_eq!(refresh.next,now+Duration::from_secs(60));
+ assert!(!refresh.acknowledge(99,&json!(["success",{"reconnect_key":"synthetic"}]),now));
+ assert!(refresh.acknowledge(11,&json!(["failure",{}]),now+Duration::from_secs(31)));
+ assert_eq!(refresh.next,now+Duration::from_secs(60));
+
+ refresh.request(12,now+Duration::from_secs(60));
+ refresh.request(13,now+Duration::from_secs(90));
+ assert!(refresh.acknowledge(13,&json!(["success",{"reconnect_key":"synthetic"}]),now+Duration::from_secs(91)));
+ let deadline=now+Duration::from_secs(391);
+ assert_eq!(refresh.next,deadline);
+ assert!(refresh.acknowledge(12,&json!(["success",{"reconnect_key":"older"}]),now+Duration::from_secs(92)));
+ assert_eq!(refresh.next,deadline);
+ assert_eq!(refresh.accepted,13);
+ }
+
+ /// Exercise the actual Socket.IO request and acknowledgement on a loopback
+ /// WebSocket. Accelerate only the renewal deadline, without creating a peer.
+ #[tokio::test]
+ async fn refresh_uses_empty_arguments_and_consumes_its_own_ack() {
+ tokio::time::timeout(Duration::from_secs(5),async {
+ let listener=TcpListener::bind((std::net::Ipv4Addr::LOCALHOST,0)).await.unwrap();
+ let url=format!("ws://{}",listener.local_addr().unwrap());
+ let server=tokio::spawn(async move {
+ let (stream,_)=listener.accept().await.unwrap();
+ let mut socket=accept_async(stream).await.unwrap();
+ socket.send(Message::Text("0{}".into())).await.unwrap();
+ assert_eq!(socket.next().await.unwrap().unwrap(),Message::Text("40".into()));
+ socket.send(Message::Text("40{}".into())).await.unwrap();
+ assert_eq!(socket.next().await.unwrap().unwrap(),Message::Text("4211[\"refresh_reconnect_key\"]".into()));
+ socket.send(Message::Text("4311[\"success\",{\"reconnect_key\":\"synthetic\"}]".into())).await.unwrap();
+ socket.send(Message::Text("42[\"fixture\",{}]".into())).await.unwrap();
+ while socket.next().await.is_some() {}
+ });
+ let mut signal=Signal::connect(&[url],"synthetic-ticket",Duration::from_secs(2),false).await.unwrap();
+ signal.refresh.next=Instant::now();
+ assert_eq!(signal.event().await.unwrap(),json!(["fixture",{}]));
+ assert_eq!(signal.refresh.accepted,11);
+ assert!(signal.refresh.pending.is_empty());
+ assert!(signal.refresh.next>Instant::now()+Duration::from_secs(299));
+ signal.close().await;
+ server.await.unwrap();
+ }).await.expect("refresh exchange timed out");
+ }
+
+ /// Server-issued room closures still terminate the connection; renewal never
+ /// turns an explicit disconnect into an automatic fresh control session.
+ #[tokio::test]
+ async fn explicit_room_closures_are_preserved() {
+ for close in ["1","41"] {
+ let listener=TcpListener::bind((std::net::Ipv4Addr::LOCALHOST,0)).await.unwrap();
+ let url=format!("ws://{}",listener.local_addr().unwrap());
+ let server=tokio::spawn(async move {
+ let (stream,_)=listener.accept().await.unwrap();
+ let mut socket=accept_async(stream).await.unwrap();
+ socket.send(Message::Text("0{}".into())).await.unwrap();
+ assert_eq!(socket.next().await.unwrap().unwrap(),Message::Text("40".into()));
+ socket.send(Message::Text("40{}".into())).await.unwrap();
+ socket.send(Message::Text(close.into())).await.unwrap();
+ while socket.next().await.is_some() {}
+ });
+ let mut signal=Signal::connect(&[url],"synthetic-ticket",Duration::from_secs(2),false).await.unwrap();
+ assert_eq!(signal.event().await.unwrap_err(),"Signaling room closed");
+ signal.close().await;
+ server.await.unwrap();
+ }
+ }
+}
diff --git a/src/viewer/tests.rs b/src/viewer/tests.rs
index 5cc95bb0116d52c45997e1ee050ae71dc18630a1..bee77f48d62a94badd5501c4949eb2f2ff158028 100644
--- a/src/viewer/tests.rs
+++ b/src/viewer/tests.rs
@@ -60,6 +60,93 @@ async fn websocket_control_ack_framing_heartbeat_failure_and_timeout() {
assert!(signal.control(json!({}),vec![],Duration::from_millis(20)).await.unwrap_err().contains("timed out"));signal.close().await;job.await.unwrap();
}
+/// The cloud may acknowledge control with a binary packet, including the
+/// zero-attachment form. Both forms must preserve the acknowledgement id.
+#[tokio::test]
+async fn websocket_binary_control_acknowledgements() {
+ for attached in [false,true] {
+ let listener=TcpListener::bind((std::net::Ipv4Addr::LOCALHOST,0)).await.unwrap();
+ let url=format!("ws://{}",listener.local_addr().unwrap());
+ let server=tokio::spawn(async move {
+ let (stream,_)=listener.accept().await.unwrap();
+ let mut ws=accept_async(stream).await.unwrap();
+ ws.send(Message::Text("0{}".into())).await.unwrap();
+ assert_eq!(ws.next().await.unwrap().unwrap(),Message::Text("40".into()));
+ ws.send(Message::Text("40{}".into())).await.unwrap();
+ assert!(matches!(ws.next().await.unwrap().unwrap(),Message::Text(_)));
+ assert!(matches!(ws.next().await.unwrap().unwrap(),Message::Binary(_)));
+
+ if attached {
+ let ack=json!(["success",{"payload":{"_placeholder":true,"num":0}}]);
+ ws.send(Message::Text(format!("461-11{ack}"))).await.unwrap();
+ ws.send(Message::Binary(vec![8,1])).await.unwrap();
+ } else {
+ ws.send(Message::Text("460-11[\"success\",{}]".into())).await.unwrap();
+ }
+ while ws.next().await.is_some() {}
+ });
+ let mut signal=Signal::connect(&[url],"synthetic-ticket",Duration::from_secs(2),false).await.unwrap();
+ let result=signal.control(json!({}),vec![8,1],Duration::from_secs(2)).await.unwrap();
+ assert_eq!(result,if attached {json!({"payload":"CAE="})} else {json!({})});
+ signal.close().await;
+ server.await.unwrap();
+ }
+}
+
+/// Model a slow Socket.IO binary event while the caller's heartbeat repeatedly
+/// cancels event polling. Both completed attachments and the header must survive.
+#[tokio::test]
+async fn websocket_binary_event_survives_repeated_poll_cancellation() {
+ tokio::time::timeout(Duration::from_secs(5),async {
+ let listener=TcpListener::bind((std::net::Ipv4Addr::LOCALHOST,0)).await.unwrap();
+ let url=format!("ws://{}",listener.local_addr().unwrap());
+ let (stage_tx,mut stages)=mpsc::channel(2);
+ let (advance_tx,mut advance)=mpsc::channel(2);
+ let server=tokio::spawn(async move {
+ let (stream,_)=listener.accept().await.unwrap();
+ let mut ws=accept_async(stream).await.unwrap();
+ ws.send(Message::Text("0{}".into())).await.unwrap();
+ assert_eq!(ws.next().await.unwrap().unwrap(),Message::Text("40".into()));
+ ws.send(Message::Text("40{}".into())).await.unwrap();
+
+ let header=json!(["soac",{"data":{
+ "first":{"_placeholder":true,"num":0},
+ "second":{"_placeholder":true,"num":1}
+ }}]);
+ ws.send(Message::Text(format!("452-{header}"))).await.unwrap();
+ stage_tx.send(()).await.unwrap();
+ advance.recv().await.unwrap();
+ ws.send(Message::Binary(vec![1,2])).await.unwrap();
+ stage_tx.send(()).await.unwrap();
+ advance.recv().await.unwrap();
+
+ // Heartbeats at either protocol layer must still work while waiting
+ // for a later attachment; a blocked pong would close the room.
+ ws.send(Message::Text("2fixture".into())).await.unwrap();
+ assert_eq!(ws.next().await.unwrap().unwrap(),Message::Text("3fixture".into()));
+ ws.send(Message::Ping(vec![7])).await.unwrap();
+ assert_eq!(ws.next().await.unwrap().unwrap(),Message::Pong(vec![7]));
+ ws.send(Message::Binary(vec![4,0x1f,0x8b,8])).await.unwrap();
+ while ws.next().await.is_some() {}
+ });
+ let mut signal=Signal::connect(&[url],"synthetic-ticket",Duration::from_secs(2),false).await.unwrap();
+
+ // Interrupt after the header, then again after just one attachment.
+ // The old decoder loses the pending packet at the first interruption.
+ stages.recv().await.unwrap();
+ assert!(tokio::time::timeout(Duration::from_millis(20),signal.event()).await.is_err());
+ advance_tx.send(()).await.unwrap();
+ stages.recv().await.unwrap();
+ assert!(tokio::time::timeout(Duration::from_millis(20),signal.event()).await.is_err());
+ advance_tx.send(()).await.unwrap();
+
+ let event=signal.event().await.unwrap();
+ assert_eq!(event,json!(["soac",{"data":{"first":"AQI=","second":"H4sI"}}]));
+ signal.close().await;
+ server.await.unwrap();
+ }).await.expect("binary signaling cancellation regression timed out");
+}
+
#[tokio::test]
async fn complete_session_uses_loopback_signaling_and_virtual_rtc_through_echo() {
tokio::time::timeout(Duration::from_secs(20),async {
@@ -211,6 +298,38 @@ async fn closing_one_peer_preserves_another_peer() {
second.close().await;router.lock().await.stop().await.unwrap();
}
+/// Applying a received description can span several heartbeat/readiness ticks.
+/// Keep that consumed message's work alive until the application finishes.
+#[tokio::test]
+async fn tool_ticks_do_not_cancel_a_consumed_signaling_message() {
+ use std::sync::atomic::AtomicUsize;
+ let ticks=Arc::new(AtomicUsize::new(0));
+ let counted=ticks.clone();
+ let (received,description)=tokio::sync::oneshot::channel();
+ let (finished,applied)=tokio::sync::oneshot::channel();
+ received.send(()).unwrap();
+
+ let signaling=async {
+ description.await.map_err(|_|"description missing".to_owned())?;
+ tokio::time::sleep(Duration::from_millis(40)).await;
+ let _=finished.send(());
+ std::future::pending::<Result<(),String>>().await
+ };
+ let heartbeat=async move {
+ loop {
+ tokio::time::sleep(Duration::from_millis(1)).await;
+ counted.fetch_add(1,Ordering::Relaxed);
+ }
+ };
+ let operation=async {applied.await.map_err(|_|"description application canceled".to_owned())};
+ let result=tokio::time::timeout(Duration::from_secs(1),super::session::drive_tools(
+ operation,signaling,heartbeat,std::future::pending(),
+ )).await.unwrap();
+
+ result.unwrap();
+ assert!(ticks.load(Ordering::Relaxed)>2,"signaling must survive repeated timer activity");
+}
+
#[tokio::test]
async fn opus_and_video_tracks_are_received_independently_in_memory() {
tokio::time::timeout(Duration::from_secs(10),async {
diff --git a/src/viewer/tools/cli.rs b/src/viewer/tools/cli.rs
index f574e4fbe66ccbbc662bccae2db9502379d9d638..5ffad5fc77989bd8d3753be17878efcbfd1c8f6d 100644
--- a/src/viewer/tools/cli.rs
+++ b/src/viewer/tools/cli.rs
@@ -13,10 +13,17 @@ impl Tty {
}
impl Drop for Tty {fn drop(&mut self){unsafe{libc::tcsetattr(self.fd,libc::TCSANOW,&self.saved);}}}
pub fn size()->(u16,u16){let mut w:libc::winsize=unsafe{std::mem::zeroed()};if unsafe{libc::ioctl(0,libc::TIOCGWINSZ as _,&mut w)}==0{(w.ws_col.max(1),w.ws_row.max(1))}else{(80,24)}}
-pub async fn terminal(io:Transport,rx:mpsc::Receiver<Packet>,session:Option<u32>)->Result<(),String>{
- let(t,output)=terminal::Terminal::new(io,rx);t.check_env().await?;
- let(c,r)=size();let id=match session{Some(id)=>t.attach(id,c,r).await?,None=>t.open(c,r).await?};
- let result=terminal_loop(&t,output,id).await;let _=t.close(id).await;result
+pub async fn terminal(io:Transport,rx:mpsc::Receiver<Packet>,session:Option<u32>,cleanup:lifecycle::Cleanup)->Result<(),String>{
+ let (terminal,output)=terminal::Terminal::new(io,rx);
+ let terminal=Arc::new(terminal);
+ terminal.check_env().await?;
+ let before=if session.is_none(){terminal.list_sessions().await?}else{Vec::new()};
+ cleanup.track(terminal.clone(),session.is_some(),&before);
+ let (cols,rows)=size();
+ let id=match session {Some(id)=>terminal.attach(id,cols,rows).await?,None=>terminal.open(cols,rows).await?};
+ cleanup.opened(id);
+ cleanup.identify().await?;
+ terminal_loop(terminal.as_ref(),output,id).await
}
#[async_trait::async_trait]
pub trait TerminalInput:Sync {
@@ -28,21 +35,41 @@ impl TerminalInput for terminal::Terminal {
async fn write(&self,id:u32,data:&[u8])->Result<(),String>{self.write(id,data).await}
async fn resize(&self,id:u32,cols:u16,rows:u16)->Result<(),String>{self.resize(id,cols,rows).await}
}
+
+/// Ctrl+] ends the local attachment, including for an existing session. Consume
+/// it here so the shell cannot receive the detach key as remote input.
+pub async fn forward_terminal_input(t:&impl TerminalInput,id:u32,data:&[u8])->Result<bool,String> {
+ if data.is_empty() || data.contains(&0x1d) {return Ok(false)}
+ t.write(id,data).await?;
+ Ok(true)
+}
+
+/// Keep reads cancellable when the remote session exits. macOS does not let
+/// kqueue watch the synthetic /dev/tty descriptor, so poll nonblocking reads
+/// without creating a blocking stdin task that could hold runtime shutdown.
+async fn read_tty(input: &mut std::fs::File, buffer: &mut [u8]) -> std::io::Result<usize> {
+ loop {
+ match std::io::Read::read(input, buffer) {
+ Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => {
+ tokio::time::sleep(std::time::Duration::from_millis(15)).await;
+ }
+ Err(error) if error.kind() == std::io::ErrorKind::Interrupted => continue,
+ result => return result,
+ }
+ }
+}
+
pub async fn terminal_loop(t:&impl TerminalInput,mut output:mpsc::Receiver<terminal::Event>,id:u32)->Result<(),String>{
async{
let _tty=Tty::raw()?;
use std::os::unix::fs::OpenOptionsExt;
- let input=std::fs::OpenOptions::new().read(true).custom_flags(libc::O_NONBLOCK).open("/dev/tty").map_err(|_|"Cannot open local TTY")?;
- let input=tokio::io::unix::AsyncFd::new(input).map_err(|_|"Cannot watch local TTY")?;let mut stdout=tokio::io::stdout();let mut buf=vec![0;16*1024];
+ let mut input=std::fs::OpenOptions::new().read(true).custom_flags(libc::O_NONBLOCK).open("/dev/tty").map_err(|_|"Cannot open local TTY")?;
+ let mut stdout=tokio::io::stdout();let mut buf=vec![0;16*1024];
let mut resize=tokio::signal::unix::signal(tokio::signal::unix::SignalKind::window_change()).map_err(|_|"Cannot watch terminal size")?;
let mut terminate=tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()).map_err(|_|"Cannot watch termination")?;
loop{tokio::select!{
_=terminate.recv()=>break,
- n=async {
- loop {let mut ready=input.readable().await?;
- match ready.try_io(|fd|std::io::Read::read(&mut fd.get_ref(),&mut buf)){Ok(n)=>break n,Err(_)=>continue}
- }
- }=>{let n=n.map_err(|_|"TTY read failed")?;if n==0{break}t.write(id,&buf[..n]).await?;},
+ n=read_tty(&mut input,&mut buf)=>{let n=n.map_err(|_|"TTY read failed")?;if !forward_terminal_input(t,id,&buf[..n]).await?{break}},
_=resize.recv()=>{let(c,r)=size();t.resize(id,c,r).await?;},
e=output.recv()=>match e{
Some(terminal::Event::Output{session,data})if session==id=>{stdout.write_all(&data).await.map_err(|_|"TTY write failed")?;stdout.flush().await.map_err(|_|"TTY flush failed")?;},
@@ -71,3 +98,23 @@ pub async fn portmap(io:Transport,rx:mpsc::Receiver<Packet>,local:u16,host:&str,
let result=tokio::select!{r=tokio::signal::ctrl_c()=>r.map_err(|_|"Cannot watch interrupt".to_owned()),_=p.closed()=>Err("Forwarding transport closed".into())};
p.remove_rule(id).await?;result
}
+
+/// Inspect or terminate an identified session without sending OPEN. In particular,
+/// a list request must never allocate another remote shell during cleanup.
+pub async fn terminal_manage(io:Transport,rx:mpsc::Receiver<Packet>,kill:&[u32])->Result<(),String> {
+ let (terminal,_events)=terminal::Terminal::new(io,rx);
+ if kill.is_empty() {
+ println!("{}",serde_json::json!(terminal.list_sessions().await?));
+ } else {
+ let sessions=terminal.list_sessions().await?;
+ for id in kill {
+ if sessions.iter().any(|session|session["session_id"].as_u64()==Some(*id as u64)) {
+ if let Err(error)=terminal.kill(*id).await {
+ if terminal.list_sessions().await?.iter().any(|session|session["session_id"].as_u64()==Some(*id as u64)){return Err(error)}
+ }
+ }
+ println!("{}",serde_json::json!({"killed":id}));
+ }
+ }
+ Ok(())
+}
diff --git a/src/viewer/tools/lifecycle.rs b/src/viewer/tools/lifecycle.rs
new file mode 100644
index 0000000000000000000000000000000000000000..7d5162a4110584f8b29e0e9b2002c8bbe1dd73d9
--- /dev/null
+++ b/src/viewer/tools/lifecycle.rs
@@ -0,0 +1,173 @@
+//! A terminal created for one command belongs to that command. Keep cleanup
+//! outside its cancellable I/O future so signaling errors cannot skip deletion.
+use super::terminal::Terminal;
+use serde_json::Value;
+use std::{
+ collections::HashSet,
+ sync::{Arc, Mutex},
+};
+
+#[derive(Clone, Default)]
+pub struct Cleanup {
+ state: Arc<Mutex<Option<Tracked>>>,
+
+ /// Client disconnect and transport shutdown may race to perform cleanup.
+ finishing: Arc<tokio::sync::Mutex<()>>,
+}
+
+struct Tracked {
+ terminal: Arc<Terminal>,
+
+ /// Session ids observed before OPEN; they can never become owned here.
+ before: HashSet<u32>,
+
+ /// Explicit attachment, or an OPEN reply that reused a preexisting id.
+ existing: bool,
+
+ /// Wire id can be zero on Windows, even though LIST exposes a stable id.
+ wire: Option<u32>,
+
+ /// Stable LIST id confirmed to have been created by this invocation.
+ owned: Option<u32>,
+
+ /// Only the first post-OPEN inventory belongs to the observation window.
+ /// Failure or cancellation must not let a later singleton acquire ownership.
+ identification_started: bool,
+}
+
+fn ids(rows: &[Value]) -> HashSet<u32> {
+ rows.iter()
+ .filter_map(|row| {
+ row["session_id"]
+ .as_u64()
+ .and_then(|id| u32::try_from(id).ok())
+ .filter(|id| *id != 0)
+ })
+ .collect()
+}
+
+impl Cleanup {
+ /// Register the pre-OPEN inventory and retain the worker across cancellation.
+ pub fn track(&self, terminal: Arc<Terminal>, existing: bool, before: &[Value]) {
+ *self.state.lock().unwrap() = Some(Tracked {
+ terminal,
+ before: ids(before),
+ existing,
+ wire: None,
+ owned: None,
+ identification_started: false,
+ });
+ }
+
+ /// Record a successful OPEN acknowledgement before any further await.
+ pub fn opened(&self, id: u32) {
+ if let Some(tracked) = self.state.lock().unwrap().as_mut() {
+ tracked.wire = Some(id);
+ if !tracked.existing && id != 0 {
+ if tracked.before.contains(&id) {
+ tracked.existing = true;
+ } else {
+ tracked.owned = Some(id);
+ }
+ }
+ }
+ }
+
+ /// Return only a confirmed owned id for cleanup over a fresh management peer.
+ pub fn owned(&self) -> Option<u32> {
+ self.state
+ .lock()
+ .unwrap()
+ .as_ref()
+ .and_then(|tracked| tracked.owned)
+ }
+
+ /// Forget ownership only after cleanup succeeded or was explicitly resolved.
+ pub fn complete(&self) {
+ self.state.lock().unwrap().take();
+ }
+
+ /// Windows OPEN may acknowledge only success, with wire id zero. Compare
+ /// inventories immediately, before accepting user input; ambiguity is an
+ /// error rather than permission to terminate someone else's session.
+ pub async fn identify(&self) -> Result<(), String> {
+ let (terminal, before) = {
+ let mut guard = self.state.lock().unwrap();
+ let Some(tracked) = guard.as_mut() else {
+ return Ok(());
+ };
+ if tracked.existing || tracked.owned.is_some() || tracked.wire.is_none() {
+ return Ok(());
+ }
+ if tracked.identification_started {
+ return Err("Terminal ownership was not confirmed by the first inventory".into());
+ }
+ // Set this before awaiting LIST. Cancellation loses the original
+ // snapshot too; a later retry could identify another user's shell.
+ tracked.identification_started = true;
+ (tracked.terminal.clone(), tracked.before.clone())
+ };
+ let after = ids(&terminal.list_sessions().await?);
+ let created: Vec<_> = after.difference(&before).copied().collect();
+ if created.len() != 1 {
+ return Err("Cannot identify the newly created terminal safely".into());
+ }
+ if let Some(tracked) = self.state.lock().unwrap().as_mut() {
+ tracked.owned = created.first().copied();
+ }
+ Ok(())
+ }
+
+ /// Explicitly attached sessions are detached. New sessions are removed with
+ /// KILL, while an already-exited shell needs no further action.
+ pub async fn finish(&self) -> Result<(), String> {
+ let _guard = self.finishing.lock().await;
+ self.identify().await?;
+ let snapshot = self.state.lock().unwrap().as_ref().map(|tracked| {
+ (
+ tracked.terminal.clone(),
+ tracked.existing,
+ tracked.wire,
+ tracked.owned,
+ )
+ });
+ let Some((terminal, existing, wire, owned)) = snapshot else {
+ return Ok(());
+ };
+ if !existing && wire.is_none() {
+ return Err("Terminal open was interrupted before ownership was confirmed".into());
+ }
+ if existing {
+ if let Some(id) = wire {
+ terminal.detach(id).await?;
+ }
+ } else if let Some(id) = owned {
+ if ids(&terminal.list_sessions().await?).contains(&id) {
+ if let Err(error) = terminal.kill(id).await {
+ if ids(&terminal.list_sessions().await?).contains(&id) {
+ return Err(error);
+ }
+ }
+ }
+ }
+ self.complete();
+ Ok(())
+ }
+}
+
+/// Retain every live client's ownership outside the server's cancellable I/O.
+/// Completed entries release their terminal worker and can be pruned safely.
+#[derive(Clone, Default)]
+pub struct Registry(Arc<Mutex<Vec<Cleanup>>>);
+
+impl Registry {
+ pub fn register(&self, cleanup: Cleanup) {
+ let mut entries = self.0.lock().unwrap();
+ entries.retain(|entry| entry.state.lock().unwrap().is_some());
+ entries.push(cleanup);
+ }
+
+ pub fn entries(&self) -> Vec<Cleanup> {
+ self.0.lock().unwrap().clone()
+ }
+}
diff --git a/src/viewer/tools/mod.rs b/src/viewer/tools/mod.rs
index 3fa50362e2245f13bb05859a441eb27b14fa6579..b9175049cb76dc31cbd823dfba17d2f847c9598f 100644
--- a/src/viewer/tools/mod.rs
+++ b/src/viewer/tools/mod.rs
@@ -1,5 +1,6 @@
//! Tool transports use only this peer's ordered channels; payloads are never logged.
pub mod terminal;
+pub mod lifecycle;
pub mod files;
pub mod portmap;
pub mod cli;
diff --git a/src/viewer/tools/terminal.rs b/src/viewer/tools/terminal.rs
index 6af986b358655efbf69a2945fba7c6f5374418ee..9ea9b3570eec4e47f672fd163ea215a5646ab194 100644
--- a/src/viewer/tools/terminal.rs
+++ b/src/viewer/tools/terminal.rs
@@ -5,6 +5,7 @@ use tokio::sync::oneshot;
use serde_json::{json,Value};
pub const OPEN:u8=1;pub const STDIN:u8=2;pub const RESIZE:u8=3;pub const CLOSE:u8=4;
pub const STDOUT:u8=5;pub const EXIT:u8=6;pub const ERROR:u8=8;
+pub const DETACH:u8=16;
pub const LIST_REQ:u8=9;pub const LIST_RESP:u8=10;pub const KILL_REQ:u8=11;pub const KILL_RESP:u8=12;pub const OPEN_RESP:u8=13;
pub struct Frame {pub kind:u8,pub session:u32,pub payload:Vec<u8>}
pub fn encode(kind:u8,session:u32,payload:&[u8])->Vec<u8>{
@@ -56,7 +57,15 @@ impl Terminal {
EXIT=>Some(Event::Exit{session:f.session,code:serde_json::from_slice::<Value>(&f.payload).ok().and_then(|v|v["exit_code"].as_i64()).unwrap_or(-1)}),
ERROR=>Some(Event::Error{session:f.session}),_=>None,
};
- if let Some(event)=event {if tx.try_send(event).is_err(){overflow=true;break}}
+ if let Some(event)=event {
+ match tx.try_send(event) {
+ Ok(())|Err(mpsc::error::TrySendError::Closed(_))=>{},
+ Err(mpsc::error::TrySendError::Full(_))=>{overflow=true;break},
+ }
+ // The terminal reader is dropped before task cleanup.
+ // Keep routing LIST/KILL replies even after its output
+ // receiver closes; the owning Terminal still bounds this worker.
+ }