-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgroup_session.rs
More file actions
2572 lines (2409 loc) · 107 KB
/
Copy pathgroup_session.rs
File metadata and controls
2572 lines (2409 loc) · 107 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
//! The group state machine — what turns N pairwise sessions into a group.
//!
//! A port of `src/group/GroupSession.js` in the web client, restructured as a
//! sans-IO state machine so it can run anywhere: this crate owns no transport,
//! no timers and no runtime. Every method takes what happened and returns a list
//! of [`Action`]s the platform is expected to perform — put this frame on that
//! session, dial that member, arm that timer. A desktop drives it from a
//! webview, a phone from native WebRTC, a test from a Vec.
//!
//! WHAT THIS IS AND IS NOT
//! -----------------------
//! It owns no transport. Every byte it sends leaves through an existing pairwise
//! session that is already SAS-verified and already ratcheted, and arrives
//! having been authenticated by that session. This adds the group layer on top:
//! who is a member, what epoch it is, what code the humans compare, and which of
//! the N-1 links a given frame should take.
//!
//! DELIVERY: DIRECT WHERE POSSIBLE, RELAYED WHERE NOT
//! --------------------------------------------------
//! A full mesh needs N(N-1)/2 pairwise links, and when a group is created only
//! the admin holds a link to everyone. Rather than block the group until every
//! pair is introduced, a frame for a member we cannot reach directly is handed
//! to a member who can reach both of us.
//!
//! That is safe because it is not a trust decision. Group messages and
//! membership operations are signed with the sender's group identity key, and
//! every member holds every other member's verifying key from the signed roster.
//! A relaying member can drop a frame or read a frame — they are a member, so
//! reading it is what membership already entitles them to — but they cannot
//! forge one, alter one, or attribute one to somebody else. What relaying costs
//! is metadata and availability, which is why a direct link is always preferred.
//!
//! Relaying is single-hop by construction. A frame carries `to`; a member that
//! is not the addressee forwards it once, marked, and a marked frame is never
//! forwarded again. There is no routing table to poison and no loop to form.
//!
//! ORDER OF OPERATIONS
//! -------------------
//! 1. invite admin sends the group's name and its own identity key
//! 2. hello each invitee replies with its identity key
//! 3. roster admin signs the full member set for this epoch and broadcasts
//! 4. commit every member commits to a secret nonce
//! 5. reveal ONLY once every commitment has arrived, nonces are published
//! 6. code every member computes the same digits and the humans compare
//! 7. ready group traffic flows
//! 8. mesh every pair without a link dials one, over the relay path
//!
//! Step 8 is the only one that can fail without the group noticing, and that is
//! deliberate: a pair that cannot connect directly keeps working exactly as it
//! did in step 7.
use crate::error::CoreError;
use crate::group_crypto::{self as gc, GroupIdentity, GroupSasCeremony, MemberOp, MeshKind};
use base64::engine::general_purpose::STANDARD as B64;
use base64::Engine;
use p384::ecdsa::VerifyingKey;
use serde_json::{json, Value};
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
fn bad(m: impl Into<String>) -> CoreError {
CoreError::invalid_input(m.into())
}
fn now_ms() -> i64 {
chrono::Utc::now().timestamp_millis()
}
// ---------------------------------------------------------------------------
// wire vocabulary
// ---------------------------------------------------------------------------
/// Wire frame types. All group traffic rides the ordinary chat message path.
pub mod frames {
pub const INVITE: &str = "g_invite";
pub const HELLO: &str = "g_hello";
pub const MEMBER: &str = "g_member";
pub const ROSTER: &str = "g_roster";
pub const COMMIT: &str = "g_commit";
pub const REVEAL: &str = "g_reveal";
pub const MESSAGE: &str = "g_msg";
pub const RELAY: &str = "g_relay";
pub const LEAVE: &str = "g_leave";
pub const MESH_OFFER: &str = "g_moffer";
pub const MESH_ANSWER: &str = "g_manswer";
pub const MESH_ABORT: &str = "g_mabort";
pub const PROBE: &str = "g_probe";
/// Call control: who opened a call, who is in it, who has left. Media never
/// travels here — see the call section of `GroupSession`.
pub const CALL: &str = "g_call";
/// The outer wrapper every group frame travels inside.
pub const ENVELOPE: &str = "g_env";
pub const ALL: [&str; 14] = [
INVITE, HELLO, MEMBER, ROSTER, COMMIT, REVEAL, MESSAGE, RELAY, LEAVE,
MESH_OFFER, MESH_ANSWER, MESH_ABORT, PROBE, CALL,
];
}
/// Is this something the group layer should be given at all?
pub fn is_group_frame(value: &Value) -> bool {
match value.get("type").and_then(|t| t.as_str()) {
Some(t) => t == frames::ENVELOPE || frames::ALL.contains(&t),
None => false,
}
}
/// The inner type of a frame, without decoding it.
///
/// Callers outside this module need it for exactly one decision — whether an
/// arriving frame is an invitation to a group they do not have yet — and that
/// decision has to be made before any group state exists to decode with. It is a
/// routing hint only; `decode_envelope` re-checks it against the frame it wraps.
pub fn group_frame_type(value: &Value) -> Option<String> {
let t = value.get("type").and_then(|t| t.as_str())?;
if t == frames::ENVELOPE {
return value.get("t").and_then(|t| t.as_str()).map(String::from);
}
if frames::ALL.contains(&t) {
return Some(t.to_string());
}
None
}
/// Wrap a frame so the pairwise chat path cannot alter it.
///
/// Group frames ride the chat send path, which sanitises its payload before
/// encrypting: `<`, `>` and `&` are escaped, control characters are stripped,
/// and the result is truncated. Every one of those is correct for chat text and
/// fatal for a signed frame — a body that came back HTML-escaped no longer
/// matches the hash its signature covers.
///
/// Base64 sidesteps all of it: its alphabet contains nothing a sanitiser
/// rewrites and it has no whitespace to trim. The group id and the inner type
/// stay outside the encoding so a frame can be routed — and an invitation
/// recognised — without decoding anything first. Neither reveals more than the
/// peer on that link already knows.
pub fn encode_envelope(frame: &Value) -> Result<Value, CoreError> {
let json = serde_json::to_string(frame)
.map_err(|e| CoreError::internal_error(format!("group frame is not serializable: {}", e)))?;
let encoded = B64.encode(json.as_bytes());
if encoded.len() > gc::FRAME_BUDGET_CHARS {
return Err(bad("group frame exceeds the transport budget"));
}
Ok(json!({
"type": frames::ENVELOPE,
"gid": frame.get("gid").cloned().unwrap_or(Value::Null),
"t": frame.get("type").cloned().unwrap_or(Value::Null),
"d": encoded,
}))
}
pub fn decode_envelope(envelope: &Value) -> Result<Value, CoreError> {
if envelope.get("type").and_then(|t| t.as_str()) != Some(frames::ENVELOPE) {
return Ok(envelope.clone());
}
let raw = envelope.get("d").and_then(|d| d.as_str()).unwrap_or("");
if raw.len() > gc::FRAME_BUDGET_CHARS {
return Err(bad("group frame exceeds the transport budget"));
}
let bytes = B64.decode(raw).map_err(|_| bad("envelope payload is not valid base64"))?;
let frame: Value = serde_json::from_slice(&bytes)
.map_err(|_| bad("envelope carried no recognisable frame"))?;
let inner_type = frame.get("type").and_then(|t| t.as_str()).unwrap_or("");
if !frames::ALL.contains(&inner_type) {
return Err(bad("envelope carried no recognisable frame"));
}
// The routing hints outside the encoding are conveniences, not authority: if
// they disagree with the frame they wrap, the frame was tampered with.
if let Some(gid) = envelope.get("gid").and_then(|g| g.as_str()) {
if frame.get("gid").and_then(|g| g.as_str()) != Some(gid) {
return Err(bad("envelope group id does not match its frame"));
}
}
if let Some(t) = envelope.get("t").and_then(|t| t.as_str()) {
if inner_type != t {
return Err(bad("envelope type does not match its frame"));
}
}
Ok(frame)
}
// ---------------------------------------------------------------------------
// state vocabulary
// ---------------------------------------------------------------------------
/// A group's lifecycle. The order matters: nothing may be sent or displayed as
/// group traffic until `Ready`, and `Ready` is reachable only through
/// `AwaitingSas`, where a human confirmed the code.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum GroupPhase {
Forming,
Committing,
Revealing,
AwaitingSas,
Ready,
Failed,
}
impl GroupPhase {
pub fn as_str(self) -> &'static str {
match self {
GroupPhase::Forming => "forming",
GroupPhase::Committing => "committing",
GroupPhase::Revealing => "revealing",
GroupPhase::AwaitingSas => "awaiting_sas",
GroupPhase::Ready => "ready",
GroupPhase::Failed => "failed",
}
}
}
/// Per-member link state. `SelfMember` is us; the rest describe the pairwise
/// session that carries them.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MemberState {
SelfMember,
/// Pairwise session up and verified.
Linked,
/// A session exists but is not usable yet, or none does.
Pending,
/// Was linked; the connection dropped.
Lost,
}
impl MemberState {
pub fn as_str(self) -> &'static str {
match self {
MemberState::SelfMember => "self",
MemberState::Linked => "linked",
MemberState::Pending => "pending",
MemberState::Lost => "lost",
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MemberSnapshot {
pub fp: String,
pub name: String,
pub session_id: Option<String>,
pub state: MemberState,
}
/// What the platform is asked to do. Nothing here happens inside the core.
#[derive(Debug, Clone, PartialEq)]
pub enum Action {
/// Put an already-wrapped frame on a pairwise session.
Send { session_id: String, frame: Value },
/// Build a connection to this member and report back with `mesh_offer_ready`.
Dial { fp: String },
/// Answer this member's relayed offer and report back with `mesh_answer_ready`.
Answer { fp: String, descriptor: String },
/// Apply an answer to a dial that is already open.
AcceptAnswer { session_id: String, descriptor: String },
/// Tear down a connection this group asked for.
CloseLink { session_id: String },
/// Call `on_timer` with this kind after `ms` milliseconds.
ArmTimer { kind: TimerKind, ms: u64 },
/// Something the user interface should hear about.
Emit(Event),
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum TimerKind {
/// The commit/reveal round for one epoch must finish or fail.
Ceremony(u64),
/// The admin's wait for invitees to publish their identity keys.
Hello,
/// One dial may only stay in flight so long.
MeshDial(String),
/// A pair whose backoff has expired may be dialled again.
MeshMaintain,
}
#[derive(Debug, Clone, PartialEq)]
pub enum Event {
Phase(GroupPhase),
Members { members: Vec<MemberSnapshot>, epoch: u64 },
Roster { name: String, epoch: u64, admin_fp: String },
Sas(String),
Confirmed,
Message {
fp: String,
name: String,
body: String,
seq: u64,
ts: i64,
/// Whether this copy came straight from its author or was carried by
/// another member. Worth showing: a relayed message is one a third
/// member knew the timing of.
relayed: bool,
},
Left { fp: String, name: String },
/// The group is over — the admin left, or we are the last one in it.
Ended(String),
AddFailed(String),
/// A member sent two different bodies under one sequence number. Both
/// signatures are valid, so this is provable rather than suspected.
Inconsistency { fp: String, name: String, seq: u64 },
/// The group's call changed, or ended. `None` means there is no call.
///
/// One event for the whole roster rather than join/leave deltas: the media
/// layer has to reconcile its legs against the full set anyway, and a delta
/// stream would let a dropped event leave a tile on screen for somebody who
/// hung up ten minutes ago.
Call(Option<CallSnapshot>),
Error(String),
}
/// One member's place in a call, as the interface draws it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CallParticipant {
pub fp: String,
pub name: String,
pub is_self: bool,
/// The pairwise session this member's media leg would ride, if there is one.
/// `None` means the mesh has not built a direct link yet — the person is in
/// the call and is shown as connecting, rather than being invisible.
pub session_id: Option<String>,
pub state: MemberState,
}
/// The call a group is holding, in the shape the interface renders.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CallSnapshot {
pub call_id: String,
pub started_by: String,
pub started_by_name: String,
pub with_video: bool,
pub started_at: i64,
/// Whether WE are in it. A call can be running with three people in it while
/// this device is merely being told about it; only joining changes this.
pub joined: bool,
pub participants: Vec<CallParticipant>,
}
/// The call this group is currently holding.
#[derive(Debug, Clone)]
struct CallState {
call_id: String,
started_by: String,
with_video: bool,
started_at: i64,
/// Ordered, so every device that renders the same call renders it in the
/// same order — a tile grid that reshuffles per member is a bug people
/// report as "the video jumped".
participants: BTreeSet<String>,
joined: bool,
}
/// Who a broadcast could not reach, and how many it did.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct DeliveryReport {
pub delivered: usize,
pub total: usize,
pub unreachable: Vec<(String, String)>,
}
// ---------------------------------------------------------------------------
// timings
// ---------------------------------------------------------------------------
/// A member that has not committed by now is treated as absent and the ceremony
/// FAILS. It must fail rather than proceed: proceeding without a commitment is
/// exactly the grinding freedom the commit round removes.
pub const CEREMONY_MS: u64 = 60_000;
/// How long the admin waits for invitees to publish their identity keys.
pub const HELLO_MS: u64 = 45_000;
/// How long one mesh dial may stay in flight. Generous, because failing early
/// costs a direct link and gains nothing: the pair keeps working over the relay
/// the entire time the dial is running.
pub const MESH_DIAL_MS: u64 = 45_000;
/// Gap before a failed pair is dialled again, doubling per failure.
pub const MESH_RETRY_MS: u64 = 20_000;
/// How many mesh dials one member will have in flight at once.
pub const MESH_MAX_CONCURRENT_DIALS: usize = 2;
/// After this many consecutive failures a pair is left on the relay for good.
pub const MESH_MAX_ATTEMPTS: u32 = 3;
/// Bounded per sender: the pairwise ratchet already refuses genuinely old
/// frames, so this window only has to outlast fan-out and one relay hop.
const TRANSCRIPT_WINDOW: usize = 512;
struct Member {
fp: String,
name: String,
spki: Vec<u8>,
/// Our own key verifies nothing inbound, so it is not kept here.
key: Option<VerifyingKey>,
session_id: Option<String>,
state: MemberState,
}
struct Dial {
role: MeshKind,
session_id: Option<String>,
nonce: Vec<u8>,
epoch: u64,
}
struct Failure {
attempts: u32,
next_at: i64,
}
struct PendingAdd {
op: MemberOp,
epoch: u64,
before: HashSet<String>,
}
// ---------------------------------------------------------------------------
// the session
// ---------------------------------------------------------------------------
pub struct GroupSession {
pub group_id: String,
pub name: String,
pub is_admin: bool,
pub epoch: u64,
pub admin_fp: String,
pub phase: GroupPhase,
pub sas_code: String,
pub sas_confirmed: bool,
identity: GroupIdentity,
members: BTreeMap<String, Member>,
/// sessionId -> fp, so an inbound frame can be attributed to a member.
session_to_fp: HashMap<String, String>,
/// sessionId -> that pairwise session's key fingerprint, for link probes.
link_fingerprints: HashMap<String, String>,
ceremony: Option<GroupSasCeremony>,
seq: u64,
/// Sender fingerprint -> (seq -> body hash). Does double duty: it absorbs
/// the duplicates that fan-out and relay inevitably produce, and it is what
/// catches a member sending two different bodies under one sequence number.
transcript: HashMap<String, BTreeMap<u64, Vec<u8>>>,
/// Invitees the admin is still waiting on, by sessionId.
awaiting_hello: HashMap<String, String>,
/// Commit and reveal frames that arrived before our own ceremony existed.
///
/// Members start their ceremony when the roster reaches them, and the roster
/// does not reach everyone at the same instant. Dropping those frames
/// deadlocks the round for everyone. Bounded, because the sender of these
/// frames chooses how many to send.
pending_ceremony: Vec<Value>,
/// Member identity keys that arrived ahead of the roster that names them.
/// Nothing is applied from here until the admin's signed roster says which
/// fingerprints are actually members.
pending_keys: HashMap<String, (Vec<u8>, VerifyingKey, String)>,
pending_add: Option<PendingAdd>,
/// One entry per PAIR, never per direction.
dials: HashMap<String, Dial>,
failures: HashMap<String, Failure>,
/// Sessions this group built itself, so teardown can close them.
mesh_sessions: HashSet<String>,
/// Sessions a probe has already been sent on, so it is sent once.
probed: HashSet<String>,
/// The call this group is holding, or `None`.
call: Option<CallState>,
/// Our own counter over call frames. Monotonic; never reset within an epoch.
call_seq: u64,
/// fp -> highest call sequence seen, so a captured frame cannot be replayed.
call_seen: HashMap<String, u64>,
destroyed: bool,
}
impl GroupSession {
pub fn new(group_id: &str, name: &str, is_admin: bool) -> Result<Self, CoreError> {
gc::assert_group_id(group_id)?;
gc::assert_name(name)?;
let identity = GroupIdentity::generate()?;
let mut session = Self {
group_id: group_id.to_string(),
name: name.to_string(),
is_admin,
epoch: 1,
admin_fp: String::new(),
phase: GroupPhase::Forming,
sas_code: String::new(),
sas_confirmed: false,
identity,
members: BTreeMap::new(),
session_to_fp: HashMap::new(),
link_fingerprints: HashMap::new(),
ceremony: None,
seq: 0,
transcript: HashMap::new(),
awaiting_hello: HashMap::new(),
pending_ceremony: Vec::new(),
pending_keys: HashMap::new(),
pending_add: None,
dials: HashMap::new(),
failures: HashMap::new(),
mesh_sessions: HashSet::new(),
probed: HashSet::new(),
call: None,
call_seq: 0,
call_seen: HashMap::new(),
destroyed: false,
};
let fp = session.identity.fingerprint.clone();
let spki = session.identity.spki.clone();
session.members.insert(
fp.clone(),
Member { fp: fp.clone(), name: "You".into(), spki, key: None, session_id: None, state: MemberState::SelfMember },
);
if is_admin {
session.admin_fp = fp;
}
Ok(session)
}
pub fn new_group_id() -> String {
gc::new_group_id()
}
pub fn self_fp(&self) -> &str {
&self.identity.fingerprint
}
pub fn self_spki(&self) -> &[u8] {
&self.identity.spki
}
pub fn member_count(&self) -> usize {
self.members.len()
}
pub fn carries_session(&self, session_id: &str) -> bool {
self.session_to_fp.contains_key(session_id)
}
/// The pairwise key fingerprint of a session, as the platform measured it.
///
/// Taken from the platform rather than from any frame: a probe is checked
/// against the fingerprint WE hold for the session it arrived on, which is
/// the whole reason a captured probe cannot be replayed onto another link.
pub fn set_link_fingerprint(&mut self, session_id: &str, fingerprint: &str) {
if fingerprint.is_empty() {
self.link_fingerprints.remove(session_id);
} else {
self.link_fingerprints.insert(session_id.to_string(), fingerprint.to_string());
}
}
pub fn members_snapshot(&self) -> Vec<MemberSnapshot> {
self.members
.values()
.map(|m| MemberSnapshot {
fp: m.fp.clone(),
name: m.name.clone(),
session_id: m.session_id.clone(),
state: m.state,
})
.collect()
}
fn members_event(&self) -> Action {
Action::Emit(Event::Members { members: self.members_snapshot(), epoch: self.epoch })
}
/// The member list changed; anyone no longer in the group leaves the call.
///
/// Membership can change under a call — the admin removes somebody, a roster
/// for a new epoch arrives — and a call roster that outlived it would show a
/// person in the call who is not in the group, which is exactly the state
/// nobody could explain. Emitted separately from the member list because the
/// media layer listens for calls and not for membership.
fn prune_call(&mut self, out: &mut Vec<Action>) {
let Some(call) = self.call.as_mut() else { return };
let before = call.participants.len();
let members: BTreeSet<String> = self.members.keys().cloned().collect();
call.participants.retain(|fp| members.contains(fp));
let changed = call.participants.len() != before;
if call.participants.is_empty() {
self.call = None;
}
if changed || self.call.is_none() {
out.push(Action::Emit(Event::Call(self.call_snapshot())));
}
}
fn set_phase(&mut self, phase: GroupPhase, out: &mut Vec<Action>) {
if self.phase == phase {
return;
}
self.phase = phase;
// Any phase other than Ready means nothing is currently confirmed.
if phase != GroupPhase::Ready {
self.sas_confirmed = false;
}
// The code survives from the moment it is computed (AwaitingSas) until
// the group leaves Ready. Clearing it on the way INTO AwaitingSas would
// erase the digits that were just derived.
if phase != GroupPhase::Ready && phase != GroupPhase::AwaitingSas {
self.sas_code.clear();
}
out.push(Action::Emit(Event::Phase(phase)));
}
fn fail(&mut self, code: &str, out: &mut Vec<Action>) {
if self.destroyed {
return;
}
self.phase = GroupPhase::Failed;
self.ceremony = None;
out.push(Action::Emit(Event::Phase(GroupPhase::Failed)));
out.push(Action::Emit(Event::Error(code.to_string())));
}
// -----------------------------------------------------------------------
// routing
// -----------------------------------------------------------------------
fn direct_peers(&self) -> Vec<&Member> {
self.members
.values()
.filter(|m| m.state == MemberState::Linked && m.session_id.is_some())
.collect()
}
/// Whoever can carry a frame to a member we cannot reach ourselves.
///
/// The admin is preferred because by construction it holds a link to every
/// member; any other directly-linked member is a fallback for when the admin
/// is the one that has gone away.
fn relay_for(&self, to_fp: &str) -> Option<String> {
if let Some(admin) = self.members.get(&self.admin_fp) {
if admin.state == MemberState::Linked && admin.session_id.is_some() && admin.fp != to_fp {
return admin.session_id.clone();
}
}
self.direct_peers()
.into_iter()
.find(|m| m.fp != to_fp)
.and_then(|m| m.session_id.clone())
}
/// Send one frame to one member, directly if we can and relayed if we cannot.
///
/// Returns whether this counts as delivered. A relay hop is unacknowledged:
/// for a member we have never held a link to that is simply the normal path,
/// but for one whose link we LOST it is a guess, and reporting it as
/// delivered would tell the sender their message arrived when there is no
/// reason to believe it did. The frame still goes — the target may be
/// reachable from elsewhere in the mesh — it just does not count.
fn send_to(&self, to_fp: &str, frame: &Value, out: &mut Vec<Action>) -> Result<bool, CoreError> {
let member = match self.members.get(to_fp) {
Some(m) if m.fp != self.self_fp() => m,
_ => return Ok(false),
};
if member.state == MemberState::Linked {
if let Some(session_id) = &member.session_id {
out.push(Action::Send { session_id: session_id.clone(), frame: encode_envelope(frame)? });
return Ok(true);
}
}
let relay = match self.relay_for(to_fp) {
Some(r) => r,
None => return Ok(false),
};
let wrapped = json!({
"type": frames::RELAY,
"gid": self.group_id,
"to": to_fp,
"hopped": false,
"inner": frame,
});
out.push(Action::Send { session_id: relay, frame: encode_envelope(&wrapped)? });
Ok(member.state != MemberState::Lost)
}
/// Fan a frame out to every other member.
///
/// Returns WHO could not be reached as well as how many could, because a
/// count on its own cannot tell "Alice is offline" from "Bob is offline" —
/// and the sender is the only person in a position to know the difference.
fn broadcast(&self, frame: &Value, out: &mut Vec<Action>) -> Result<DeliveryReport, CoreError> {
let targets: Vec<String> = self
.members
.keys()
.filter(|fp| *fp != self.self_fp())
.cloned()
.collect();
let mut report = DeliveryReport { delivered: 0, total: targets.len(), unreachable: Vec::new() };
for fp in targets {
match self.send_to(&fp, frame, out) {
Ok(true) => report.delivered += 1,
_ => {
let name = self.members.get(&fp).map(|m| m.name.clone()).unwrap_or_else(|| "A member".into());
report.unreachable.push((fp, name));
}
}
}
Ok(report)
}
// -----------------------------------------------------------------------
// link bookkeeping
// -----------------------------------------------------------------------
/// Bind a pairwise session to a member.
///
/// A member never holds two links at once. Rebinding to a new session — a
/// mesh dial that succeeded where an old link had dropped, or a chat the
/// user rebuilt by hand — drops the stale mapping, or a frame arriving on
/// the dead session id would still be attributed to them.
pub fn bind_session(&mut self, fp: &str, session_id: &str, state: MemberState) -> Vec<Action> {
let mut out = Vec::new();
let previous = match self.members.get(fp) {
Some(m) => m.session_id.clone(),
None => return out,
};
if let Some(old) = previous {
if old != session_id {
self.session_to_fp.remove(&old);
self.close_mesh_session(&old, &mut out);
}
}
if let Some(member) = self.members.get_mut(fp) {
member.session_id = Some(session_id.to_string());
member.state = state;
}
self.session_to_fp.insert(session_id.to_string(), fp.to_string());
out.push(self.members_event());
out
}
/// Detach a member from whatever link it was on, back to the relay path.
///
/// Deliberately does NOT change the member's state to Lost — they are not
/// offline, we just have no direct route to them.
pub fn unbind_session(&mut self, fp: &str) -> Vec<Action> {
let mut out = Vec::new();
let session_id = match self.members.get(fp).and_then(|m| m.session_id.clone()) {
Some(s) => s,
None => return out,
};
self.session_to_fp.remove(&session_id);
if let Some(member) = self.members.get_mut(fp) {
member.session_id = None;
if member.state == MemberState::Linked || member.state == MemberState::Lost {
member.state = MemberState::Pending;
}
}
self.close_mesh_session(&session_id, &mut out);
out.push(self.members_event());
// The member has no route of their own now, so the mesh should look at
// building one. This is what makes a link dying recoverable rather than
// permanent.
self.mesh_maintain(&mut out);
out
}
/// A pairwise session changed state; reflect it on whichever member owns it.
pub fn set_session_state(&mut self, session_id: &str, connected: bool) -> Vec<Action> {
let mut out = Vec::new();
let fp = match self.session_to_fp.get(session_id) {
Some(fp) => fp.clone(),
None => return out,
};
let next = if connected { MemberState::Linked } else { MemberState::Lost };
match self.members.get_mut(&fp) {
Some(m) if m.state != MemberState::SelfMember && m.state != next => m.state = next,
_ => return out,
}
out.push(self.members_event());
// A dial that reached Linked is finished. A link that DROPPED is also
// settled — the dial is over either way — but the failure counter is
// left alone, because a link that worked and then died says nothing
// about whether the pair can connect.
if connected {
self.settle_dial(&fp);
}
self.mesh_maintain(&mut out);
out
}
// -----------------------------------------------------------------------
// the mesh
// -----------------------------------------------------------------------
//
// WHO DIALS: the member with the smaller fingerprint. That is the entire
// glare protocol — both sides compute it from the roster they already agree
// on, so exactly one side opens each pair and there is no simultaneous-offer
// case to resolve. A member that receives an offer from someone it should
// have been dialling ITSELF refuses it.
//
// WHEN: only once the group is Ready and the code is confirmed. Before that,
// the roster's identity keys are keys nobody has vouched for yet, and a link
// authenticated by an unconfirmed key is a link authenticated by nothing.
fn close_mesh_session(&mut self, session_id: &str, out: &mut Vec<Action>) {
if self.mesh_sessions.remove(session_id) {
out.push(Action::CloseLink { session_id: session_id.to_string() });
}
}
/// A dial is over, one way or another.
fn settle_dial(&mut self, fp: &str) {
self.dials.remove(fp);
self.failures.remove(fp);
}
/// Give up on one pair, for now.
///
/// The half-built connection is closed and the member goes back to being
/// reached through somebody else — which is where they were before the dial
/// started, so nothing the user can see gets worse. The backoff doubles per
/// attempt because a pair that cannot connect is usually a network that will
/// not allow it, and hammering at that produces load rather than links.
fn mesh_fail(&mut self, fp: &str, tell_peer: bool, out: &mut Vec<Action>) {
if let Some(dial) = self.dials.remove(fp) {
let member_session = self.members.get(fp).and_then(|m| m.session_id.clone());
match (&dial.session_id, member_session) {
(Some(dialed), Some(current)) if *dialed == current => {
out.extend(self.unbind_session(fp));
}
(Some(dialed), _) => {
let dialed = dialed.clone();
self.close_mesh_session(&dialed, out);
}
_ => {}
}
}
let failure = self.failures.entry(fp.to_string()).or_insert(Failure { attempts: 0, next_at: 0 });
failure.attempts += 1;
let backoff = MESH_RETRY_MS.saturating_mul(1u64 << (failure.attempts - 1).min(16));
failure.next_at = now_ms() + backoff as i64;
// Tell the peer so their half of the dial does not sit until it times
// out. Best effort by definition — if we could reach them reliably we
// would not be failing.
if tell_peer && self.members.contains_key(fp) {
let frame = json!({
"type": frames::MESH_ABORT, "gid": self.group_id, "epoch": self.epoch,
"from": self.self_fp(), "to": fp,
});
let _ = self.send_to(fp, &frame, out);
}
self.mesh_maintain(out);
}
/// Cancel every dial in flight and forget every backoff.
///
/// Called when the epoch moves: a dial signed against the old epoch will not
/// verify against the new one, and a pair that could not connect under the
/// old membership deserves a fresh chance under the new one. Links that are
/// already up are untouched.
fn mesh_reset(&mut self, out: &mut Vec<Action>) {
for fp in self.dials.keys().cloned().collect::<Vec<_>>() {
let dial = self.dials.remove(&fp);
if let Some(dial) = dial {
let member_session = self.members.get(&fp).and_then(|m| m.session_id.clone());
match (&dial.session_id, member_session) {
(Some(dialed), Some(current)) if *dialed == current => {
out.extend(self.unbind_session(&fp));
}
(Some(dialed), _) => {
let dialed = dialed.clone();
self.close_mesh_session(&dialed, out);
}
_ => {}
}
}
}
self.failures.clear();
self.probed.clear();
}
/// Open dials for whoever still has no link, within the concurrency limit.
fn mesh_maintain(&mut self, out: &mut Vec<Action>) {
if self.destroyed || self.phase != GroupPhase::Ready || !self.sas_confirmed {
return;
}
let now = now_ms();
let mut in_flight = self.dials.len();
let mut soonest = i64::MAX;
// Fingerprint order, so every member walks the same list and the load of
// being dialled is spread the same way everywhere.
let ordered: Vec<String> = self.members.keys().cloned().collect();
for fp in ordered {
if in_flight >= MESH_MAX_CONCURRENT_DIALS {
break;
}
let (state, has_session) = match self.members.get(&fp) {
Some(m) => (m.state, m.session_id.is_some()),
None => continue,
};
if state == MemberState::SelfMember || has_session || self.dials.contains_key(&fp) {
continue;
}
// Their turn to dial, not ours.
if self.self_fp() >= fp.as_str() {
continue;
}
if let Some(failure) = self.failures.get(&fp) {
if failure.attempts >= MESH_MAX_ATTEMPTS {
continue;
}
if now < failure.next_at {
soonest = soonest.min(failure.next_at);
continue;
}
}
// Nothing can carry the offer, so there is no dial to make. When a
// relay appears, that link coming up schedules another pass.
if self.relay_for(&fp).is_none() {
continue;
}
in_flight += 1;
out.push(Action::Dial { fp });
}
if soonest != i64::MAX {
let wait = (soonest - now).max(0) as u64 + 50;
out.push(Action::ArmTimer { kind: TimerKind::MeshMaintain, ms: wait });
}
}
/// The platform built an offer for `fp`: sign it and put it on the relay path.
pub fn mesh_offer_ready(&mut self, fp: &str, session_id: &str, descriptor: &str) -> Result<Vec<Action>, CoreError> {
let mut out = Vec::new();
if self.destroyed || self.members.get(fp).map(|m| m.session_id.is_some()).unwrap_or(true) {
// The world moved while the transport was gathering candidates.
out.push(Action::CloseLink { session_id: session_id.to_string() });
return Ok(out);
}
if self.dials.contains_key(fp) {
out.push(Action::CloseLink { session_id: session_id.to_string() });
return Ok(out);
}
let epoch = self.epoch;
let nonce = random_nonce(gc::MESH_NONCE_BYTES);
let sig = gc::sign_mesh_descriptor(
&self.identity, &self.group_id, epoch, MeshKind::Offer, self.self_fp(), fp, descriptor, &nonce,
)?;
self.dials.insert(fp.to_string(), Dial { role: MeshKind::Offer, session_id: Some(session_id.to_string()), nonce: nonce.clone(), epoch });
self.mesh_sessions.insert(session_id.to_string());
// Bound now, as Pending: it makes this member's link state addressable
// the moment the transport reports in, and Pending keeps every frame on
// the relay path until it actually comes up.
out.extend(self.bind_session(fp, session_id, MemberState::Pending));
let frame = json!({
"type": frames::MESH_OFFER, "gid": self.group_id, "epoch": epoch,
"from": self.self_fp(), "to": fp, "d": descriptor,
"n": B64.encode(&nonce), "sig": B64.encode(&sig),
});
if !self.send_to(fp, &frame, &mut out)? {
self.mesh_fail(fp, false, &mut out);
return Ok(out);
}
out.push(Action::ArmTimer { kind: TimerKind::MeshDial(fp.to_string()), ms: MESH_DIAL_MS });
Ok(out)
}
/// The platform answered `fp`'s relayed offer: sign the answer and send it.
pub fn mesh_answer_ready(&mut self, fp: &str, session_id: &str, descriptor: &str) -> Result<Vec<Action>, CoreError> {
let mut out = Vec::new();
let nonce = match self.dials.get(fp) {
Some(d) if d.role == MeshKind::Answer && d.epoch == self.epoch => d.nonce.clone(),
_ => {
out.push(Action::CloseLink { session_id: session_id.to_string() });
return Ok(out);
}
};
let epoch = self.epoch;
let sig = gc::sign_mesh_descriptor(
&self.identity, &self.group_id, epoch, MeshKind::Answer, self.self_fp(), fp, descriptor, &nonce,
)?;
if let Some(dial) = self.dials.get_mut(fp) {
dial.session_id = Some(session_id.to_string());
}
self.mesh_sessions.insert(session_id.to_string());
out.extend(self.bind_session(fp, session_id, MemberState::Pending));
let frame = json!({
"type": frames::MESH_ANSWER, "gid": self.group_id, "epoch": epoch,
"from": self.self_fp(), "to": fp, "d": descriptor,
"n": B64.encode(&nonce), "sig": B64.encode(&sig),
});
if !self.send_to(fp, &frame, &mut out)? {
self.mesh_fail(fp, false, &mut out);
return Ok(out);
}
out.push(Action::ArmTimer { kind: TimerKind::MeshDial(fp.to_string()), ms: MESH_DIAL_MS });
Ok(out)
}
fn on_mesh_offer(&mut self, frame: &Value, out: &mut Vec<Action>) -> Result<(), CoreError> {
let from = field_fingerprint(frame, "from")?;