Skip to main content

hatchery_node/
restream_session.rs

1//! Node end of a live restreamer session (A2 / A3).
2//!
3//! The node dials C2's uplink, OPENs a channel, then runs the inner Noise_NK
4//! handshake toward the relayed recipient key as ordinary DATA frames:
5//! msg1 goes up through C2 into the core drain, msg2 comes back down the same
6//! stream. After that every request and reply is Noise transport ciphertext,
7//! wrapped in C2's outer layer on the way up. C2 only ever sees opaque bytes,
8//! and the node never learns what sits behind C2.
9//!
10//! One TCP carries every channel (C2 routes downlink by node id). A single
11//! FIFO send queue would let browser frames or a stuck mail channel wedge PTY
12//! control (head-of-line blocking). Outbound traffic is therefore queued
13//! per-channel with priority scheduling, browser frames are coalesced under
14//! pressure, and a write timeout tears the socket down so the bridge reconnects.
15
16use crate::uplink_journal::UplinkJournal;
17use hatchery_core::inner::{decode_inner, encode_inner, InnerKind};
18use hatchery_core::nested::{node_seal_outer, NoiseInitiator, NoiseTransport, PublicKeyBytes};
19use hatchery_core::{ChannelKind, Frame, FrameError, FrameType, OpenPayload};
20use serde_json::{json, Value};
21use std::collections::{BTreeMap, VecDeque};
22use std::net::SocketAddr;
23use std::sync::atomic::{AtomicBool, Ordering};
24use std::sync::{Arc, Mutex};
25use std::time::Duration;
26use tokio::io::{AsyncReadExt, AsyncWriteExt};
27use tokio::net::TcpStream;
28use tokio::sync::{mpsc, Notify};
29use tokio::task::JoinHandle;
30
31/// Keys C2 hands a node at enrollment: its own outer key and the upstream recipient key.
32#[derive(Clone, Copy, Debug)]
33pub struct UpstreamKeys {
34    pub c2_public: PublicKeyBytes,
35    pub recipient_public: PublicKeyBytes,
36}
37
38/// Outbound priority on the shared uplink. Lower ordinal = sent first.
39#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
40pub enum SendPrio {
41    /// OPEN, Noise handshake, journal replies, g4a request/response (incl. PTY input path).
42    Control = 0,
43    /// g4a terminal / event frames.
44    Pty = 1,
45    /// m4a mail/task calls.
46    Mail = 2,
47    /// dig2browser frames — droppable / coalesced under pressure.
48    Browser = 3,
49}
50
51const WRITE_TIMEOUT: Duration = Duration::from_secs(5);
52const CHAN_CAP_CONTROL: usize = 64;
53const CHAN_CAP_PTY: usize = 128;
54const CHAN_CAP_MAIL: usize = 16;
55const CHAN_CAP_BROWSER: usize = 8;
56
57struct Queued {
58    prio: SendPrio,
59    frame: Frame,
60}
61
62struct ChanQ {
63    q: VecDeque<Queued>,
64    /// Remaining WINDOW credit for DATA frames; None until the first WINDOW.
65    credit: Option<u32>,
66}
67
68impl ChanQ {
69    fn new() -> Self {
70        Self { q: VecDeque::new(), credit: None }
71    }
72
73    fn cap_for(prio: SendPrio) -> usize {
74        match prio {
75            SendPrio::Control => CHAN_CAP_CONTROL,
76            SendPrio::Pty => CHAN_CAP_PTY,
77            SendPrio::Mail => CHAN_CAP_MAIL,
78            SendPrio::Browser => CHAN_CAP_BROWSER,
79        }
80    }
81}
82
83struct OutState {
84    chans: BTreeMap<u32, ChanQ>,
85}
86
87/// One TCP uplink to C2 carrying any number of channels.
88pub struct NodeUplink {
89    enqueue: mpsc::UnboundedSender<(u32, SendPrio, Frame)>,
90    routes: Arc<Mutex<BTreeMap<u32, mpsc::UnboundedSender<Vec<u8>>>>>,
91    /// Last WINDOW credit per channel (updated by the reader).
92    credits: Arc<Mutex<BTreeMap<u32, u32>>>,
93    credit_pulse: Arc<Notify>,
94    journal: Option<Arc<UplinkJournal>>,
95    alive: Arc<AtomicBool>,
96    dead: Arc<Notify>,
97    tasks: Vec<JoinHandle<()>>,
98}
99
100impl Drop for NodeUplink {
101    fn drop(&mut self) {
102        self.alive.store(false, Ordering::SeqCst);
103        for t in &self.tasks {
104            t.abort();
105        }
106    }
107}
108
109impl NodeUplink {
110    pub async fn connect(uplink: SocketAddr, journal: Option<Arc<UplinkJournal>>) -> Result<Arc<Self>, String> {
111        let stream = TcpStream::connect(uplink).await.map_err(|e| e.to_string())?;
112        let _ = stream.set_nodelay(true);
113        let (mut rd, mut wr) = stream.into_split();
114        let (enq_tx, mut enq_rx) = mpsc::unbounded_channel::<(u32, SendPrio, Frame)>();
115        let routes: Arc<Mutex<BTreeMap<u32, mpsc::UnboundedSender<Vec<u8>>>>> = Arc::default();
116        let credits: Arc<Mutex<BTreeMap<u32, u32>>> = Arc::default();
117        let credit_pulse = Arc::new(Notify::new());
118        let alive = Arc::new(AtomicBool::new(true));
119        let dead = Arc::new(Notify::new());
120        let wake = Arc::new(Notify::new());
121
122        let out_state = Arc::new(Mutex::new(OutState { chans: BTreeMap::new() }));
123
124        // Ingress into per-channel queues (never blocks the producer on TCP).
125        let state_in = Arc::clone(&out_state);
126        let wake_in = Arc::clone(&wake);
127        let alive_in = Arc::clone(&alive);
128        let ingress = tokio::spawn(async move {
129            while let Some((ch, prio, frame)) = enq_rx.recv().await {
130                if !alive_in.load(Ordering::SeqCst) {
131                    break;
132                }
133                let mut st = state_in.lock().expect("out");
134                let q = st.chans.entry(ch).or_insert_with(ChanQ::new);
135                let cap = ChanQ::cap_for(prio);
136                if prio == SendPrio::Browser {
137                    // Coalesce: keep only the newest browser frame under pressure.
138                    q.q.retain(|x| x.prio != SendPrio::Browser);
139                    if q.q.len() >= cap {
140                        // Still full of higher-prio work: drop this browser frame.
141                        continue;
142                    }
143                } else {
144                    while q.q.len() >= cap {
145                        // Drop lowest-priority (browser first, then mail) before refusing control/PTY.
146                        if let Some(i) = q
147                            .q
148                            .iter()
149                            .enumerate()
150                            .filter(|(_, x)| x.prio >= SendPrio::Mail)
151                            .max_by_key(|(_, x)| x.prio)
152                            .map(|(i, _)| i)
153                        {
154                            q.q.remove(i);
155                        } else if prio <= SendPrio::Pty {
156                            // Control/PTY: drop oldest same-or-lower in this channel.
157                            q.q.pop_front();
158                        } else {
159                            break;
160                        }
161                    }
162                    if q.q.len() >= cap {
163                        continue;
164                    }
165                }
166                q.q.push_back(Queued { prio, frame });
167                drop(st);
168                wake_in.notify_one();
169            }
170        });
171
172        // Fair/priority writer: always pick the globally highest-priority waiting frame
173        // whose channel has credit (DATA) or needs no credit (OPEN/control non-DATA).
174        let state_wr = Arc::clone(&out_state);
175        let wake_wr = Arc::clone(&wake);
176        let alive_wr = Arc::clone(&alive);
177        let dead_wr = Arc::clone(&dead);
178        let routes_wr = Arc::clone(&routes);
179        let writer = tokio::spawn(async move {
180            loop {
181                if !alive_wr.load(Ordering::SeqCst) {
182                    break;
183                }
184                let next = {
185                    let mut st = state_wr.lock().expect("out");
186                    pick_next(&mut st)
187                };
188                let Some((ch, is_data, frame)) = next else {
189                    wake_wr.notified().await;
190                    continue;
191                };
192                let Ok(bytes) = frame.encode() else {
193                    kill(&alive_wr, &dead_wr, &routes_wr);
194                    break;
195                };
196                match tokio::time::timeout(WRITE_TIMEOUT, wr.write_all(&bytes)).await {
197                    Ok(Ok(())) => {
198                        if is_data {
199                            let mut st = state_wr.lock().expect("out");
200                            if let Some(q) = st.chans.get_mut(&ch) {
201                                if let Some(c) = q.credit.as_mut() {
202                                    *c = c.saturating_sub(1);
203                                }
204                            }
205                        }
206                    }
207                    Ok(Err(_)) | Err(_) => {
208                        tracing::warn!(%ch, "uplink write timed out or failed; reconnecting");
209                        kill(&alive_wr, &dead_wr, &routes_wr);
210                        break;
211                    }
212                }
213            }
214        });
215
216        let enq_reader = enq_tx.clone();
217        let reader_journal = journal.clone();
218        let reader_routes = Arc::clone(&routes);
219        let alive_rd = Arc::clone(&alive);
220        let dead_rd = Arc::clone(&dead);
221        let state_rd = Arc::clone(&out_state);
222        let wake_rd = Arc::clone(&wake);
223        let credits_rd = Arc::clone(&credits);
224        let credit_pulse_rd = Arc::clone(&credit_pulse);
225        let reader = tokio::spawn(async move {
226            let mut buf = vec![0u8; 128 * 1024];
227            let mut filled = 0usize;
228            loop {
229                let Ok(n) = rd.read(&mut buf[filled..]).await else { break };
230                if n == 0 {
231                    break;
232                }
233                filled += n;
234                loop {
235                    match Frame::decode(&buf[..filled]) {
236                        Ok((frame, used)) => {
237                            buf.copy_within(used..filled, 0);
238                            filled -= used;
239                            match frame.frame_type {
240                                FrameType::Data => {
241                                    let tx = reader_routes.lock().expect("routes").get(&frame.channel_id).cloned();
242                                    if let Some(tx) = tx {
243                                        let _ = tx.send(frame.payload);
244                                    }
245                                }
246                                FrameType::Window => {
247                                    let credit = frame.seq.min(u64::from(u32::MAX)) as u32;
248                                    {
249                                        let mut st = state_rd.lock().expect("out");
250                                        st.chans.entry(frame.channel_id).or_insert_with(ChanQ::new).credit = Some(credit);
251                                    }
252                                    credits_rd.lock().expect("credits").insert(frame.channel_id, credit);
253                                    credit_pulse_rd.notify_waiters();
254                                    wake_rd.notify_one();
255                                }
256                                FrameType::JournalReq => {
257                                    let Some(j) = reader_journal.as_ref() else { continue };
258                                    let limit = frame.journal_req_limit().unwrap_or(64) as usize;
259                                    if let Ok(body) = j.journal().reply_body(frame.channel_id, frame.seq, limit) {
260                                        if let Ok(reply) = Frame::journal_reply(frame.channel_id, &body) {
261                                            let _ = enq_reader.send((frame.channel_id, SendPrio::Control, reply));
262                                        }
263                                    }
264                                }
265                                FrameType::GoAway | FrameType::Close => {
266                                    kill(&alive_rd, &dead_rd, &reader_routes);
267                                    return;
268                                }
269                                _ => {}
270                            }
271                        }
272                        Err(FrameError::Truncated) => break,
273                        Err(_) => {
274                            kill(&alive_rd, &dead_rd, &reader_routes);
275                            return;
276                        }
277                    }
278                }
279                if filled == buf.len() {
280                    break;
281                }
282            }
283            kill(&alive_rd, &dead_rd, &reader_routes);
284        });
285
286        Ok(Arc::new(Self {
287            enqueue: enq_tx,
288            routes,
289            credits,
290            credit_pulse,
291            journal,
292            alive,
293            dead,
294            tasks: vec![ingress, writer, reader],
295        }))
296    }
297
298    pub fn is_alive(&self) -> bool {
299        self.alive.load(Ordering::SeqCst)
300    }
301
302    /// Wait until the uplink is marked dead (write timeout / peer close).
303    pub async fn closed(&self) {
304        if !self.is_alive() {
305            return;
306        }
307        self.dead.notified().await;
308    }
309
310    fn push(&self, channel_id: u32, prio: SendPrio, frame: Frame) -> Result<(), String> {
311        if !self.is_alive() {
312            return Err("uplink closed".into());
313        }
314        self.enqueue
315            .send((channel_id, prio, frame))
316            .map_err(|_| "uplink closed".to_owned())
317    }
318
319    /// OPEN `channel_id`, wait for WINDOW credit, then complete Noise_NK.
320    pub async fn open(
321        self: &Arc<Self>,
322        node_id: &str,
323        channel_id: u32,
324        kind: ChannelKind,
325        keys: UpstreamKeys,
326        handshake_timeout: Duration,
327    ) -> Result<NodeSession, String> {
328        let (down_tx, mut down_rx) = mpsc::unbounded_channel::<Vec<u8>>();
329        self.routes.lock().expect("routes").insert(channel_id, down_tx);
330        self.credits.lock().expect("credits").remove(&channel_id);
331        let open = Frame::open(channel_id, &OpenPayload { channel_kind: kind, node_id: node_id.to_owned() })
332            .map_err(|e| e.to_string())?;
333        self.push(channel_id, SendPrio::Control, open)?;
334
335        // Wait until C2 grants WINDOW credit after OPEN (avoids sending Handshake1
336        // into a stream that still has credit 0 from a previous session).
337        tokio::time::timeout(handshake_timeout, async {
338            loop {
339                if !self.is_alive() {
340                    return Err("uplink closed".to_owned());
341                }
342                if self.credits.lock().expect("credits").get(&channel_id).copied().unwrap_or(0) > 0 {
343                    return Ok(());
344                }
345                tokio::select! {
346                    _ = self.credit_pulse.notified() => {}
347                    _ = self.closed() => return Err("uplink closed".to_owned()),
348                }
349            }
350        })
351        .await
352        .map_err(|_| "window credit timeout after OPEN".to_owned())??;
353
354        let mut initiator = NoiseInitiator::new(keys.recipient_public).map_err(|e| e.to_string())?;
355        let msg1 = initiator.write_message1().map_err(|e| e.to_string())?;
356        self.send_inner(channel_id, keys, SendPrio::Control, &encode_inner(InnerKind::Handshake1, &msg1))?;
357
358        let msg2 = tokio::time::timeout(handshake_timeout, async {
359            loop {
360                let Some(bytes) = down_rx.recv().await else { return Err("uplink closed".to_owned()) };
361                if let Some((InnerKind::Handshake2, body)) = decode_inner(&bytes) {
362                    return Ok(body.to_vec());
363                }
364            }
365        })
366        .await
367        .map_err(|_| "handshake timeout".to_owned())??;
368        let transport = initiator.read_message2(&msg2).map_err(|e| e.to_string())?;
369        Ok(NodeSession {
370            channel_id,
371            keys,
372            default_prio: match kind {
373                ChannelKind::M4a => SendPrio::Mail,
374                ChannelKind::G4aControl | ChannelKind::G4aPty | ChannelKind::G4aEvents => SendPrio::Pty,
375                ChannelKind::Vault | ChannelKind::Observation => SendPrio::Mail,
376            },
377            down: down_rx,
378            transport,
379            journal: self.journal.clone(),
380            uplink: Arc::clone(self),
381        })
382    }
383
384    fn send_inner(&self, channel_id: u32, keys: UpstreamKeys, prio: SendPrio, inner: &[u8]) -> Result<(), String> {
385        if let Some(j) = &self.journal {
386            j.append(channel_id, inner)?;
387        }
388        let sealed = node_seal_outer(keys.c2_public, inner).map_err(|e| e.to_string())?;
389        let frame = Frame::data(channel_id, 0, sealed).map_err(|e| e.to_string())?;
390        self.push(channel_id, prio, frame)
391    }
392}
393
394fn kill(alive: &AtomicBool, dead: &Notify, routes: &Mutex<BTreeMap<u32, mpsc::UnboundedSender<Vec<u8>>>>) {
395    if alive.swap(false, Ordering::SeqCst) {
396        routes.lock().expect("routes").clear();
397        dead.notify_waiters();
398    }
399}
400
401/// Pick the highest-priority queued frame that may be sent now.
402fn pick_next(st: &mut OutState) -> Option<(u32, bool, Frame)> {
403    // Flatten candidates: (prio, channel, index)
404    let mut best: Option<(SendPrio, u32, usize)> = None;
405    for (&ch, cq) in &st.chans {
406        for (i, item) in cq.q.iter().enumerate() {
407            let needs_credit = matches!(item.frame.frame_type, FrameType::Data);
408            if needs_credit {
409                match cq.credit {
410                    Some(0) => continue,
411                    None => {
412                        // No WINDOW yet: allow Control DATA (handshake) so OPEN→Handshake1 works;
413                        // hold back bulk traffic.
414                        if item.prio > SendPrio::Control {
415                            continue;
416                        }
417                    }
418                    Some(_) => {}
419                }
420            }
421            let cand = (item.prio, ch, i);
422            if best.is_none_or(|b| cand.0 < b.0 || (cand.0 == b.0 && cand.1 < b.1)) {
423                best = Some(cand);
424            }
425        }
426    }
427    let (prio, ch, idx) = best?;
428    let cq = st.chans.get_mut(&ch)?;
429    let item = cq.q.remove(idx)?;
430    debug_assert_eq!(item.prio, prio);
431    let is_data = matches!(item.frame.frame_type, FrameType::Data);
432    Some((ch, is_data, item.frame))
433}
434
435pub struct NodeSession {
436    channel_id: u32,
437    keys: UpstreamKeys,
438    default_prio: SendPrio,
439    down: mpsc::UnboundedReceiver<Vec<u8>>,
440    transport: NoiseTransport,
441    journal: Option<Arc<UplinkJournal>>,
442    uplink: Arc<NodeUplink>,
443}
444
445impl NodeSession {
446    pub async fn connect(
447        uplink: SocketAddr,
448        node_id: &str,
449        channel_id: u32,
450        kind: ChannelKind,
451        keys: UpstreamKeys,
452        journal: Option<Arc<UplinkJournal>>,
453        handshake_timeout: Duration,
454    ) -> Result<Self, String> {
455        let link = NodeUplink::connect(uplink, journal).await?;
456        link.open(node_id, channel_id, kind, keys, handshake_timeout).await
457    }
458
459    pub fn uplink(&self) -> Arc<NodeUplink> {
460        Arc::clone(&self.uplink)
461    }
462
463    pub async fn send(&mut self, plaintext: &[u8]) -> Result<(), String> {
464        self.send_prio(plaintext, self.default_prio).await
465    }
466
467    pub async fn send_prio(&mut self, plaintext: &[u8], prio: SendPrio) -> Result<(), String> {
468        if !self.uplink.is_alive() {
469            return Err("uplink closed".into());
470        }
471        let ct = self.transport.encrypt(plaintext).map_err(|e| e.to_string())?;
472        let inner = encode_inner(InnerKind::Transport, &ct);
473        self.uplink.send_inner(self.channel_id, self.keys, prio, &inner)
474    }
475
476    pub async fn recv(&mut self, timeout: Duration) -> Result<Vec<u8>, String> {
477        tokio::time::timeout(timeout, async {
478            loop {
479                tokio::select! {
480                    bytes = self.down.recv() => {
481                        let Some(bytes) = bytes else { return Err("uplink closed".to_owned()) };
482                        if let Some((InnerKind::Transport, ct)) = decode_inner(&bytes) {
483                            return self.transport.decrypt(ct).map_err(|e| e.to_string());
484                        }
485                    }
486                    _ = self.uplink.closed() => return Err("uplink closed".to_owned()),
487                }
488            }
489        })
490        .await
491        .map_err(|_| "reply timeout".to_owned())?
492    }
493
494    pub async fn call(&mut self, op: &str, payload: &Value, timeout: Duration) -> Result<Value, String> {
495        let req = serde_json::to_vec(&json!({ "op": op, "payload": payload })).map_err(|e| e.to_string())?;
496        self.send_prio(&req, SendPrio::Mail).await?;
497        let reply = self.recv(timeout).await?;
498        let reply: Value = serde_json::from_slice(&reply).map_err(|e| e.to_string())?;
499        let status = reply.get("status").and_then(Value::as_u64).unwrap_or(500);
500        let body = reply.get("body").cloned().unwrap_or(Value::Null);
501        if status == 200 {
502            Ok(body)
503        } else {
504            let msg = body.get("error").and_then(Value::as_str).unwrap_or("error");
505            Err(format!("{status}: {msg}"))
506        }
507    }
508}
509
510#[cfg(test)]
511mod tests {
512    use super::*;
513
514    #[test]
515    fn pick_prefers_control_over_browser() {
516        let mut st = OutState { chans: BTreeMap::new() };
517        let q = st.chans.entry(1).or_insert_with(ChanQ::new);
518        q.credit = Some(10);
519        q.q.push_back(Queued {
520            prio: SendPrio::Browser,
521            frame: Frame::data(1, 0, vec![1]).unwrap(),
522        });
523        q.q.push_back(Queued {
524            prio: SendPrio::Control,
525            frame: Frame::data(1, 0, vec![2]).unwrap(),
526        });
527        q.q.push_back(Queued {
528            prio: SendPrio::Pty,
529            frame: Frame::data(1, 0, vec![3]).unwrap(),
530        });
531        let (_, _, f) = pick_next(&mut st).unwrap();
532        assert_eq!(f.payload, vec![2]);
533        let (_, _, f) = pick_next(&mut st).unwrap();
534        assert_eq!(f.payload, vec![3]);
535        let (_, _, f) = pick_next(&mut st).unwrap();
536        assert_eq!(f.payload, vec![1]);
537    }
538
539    #[test]
540    fn pick_holds_bulk_until_window() {
541        let mut st = OutState { chans: BTreeMap::new() };
542        let q = st.chans.entry(2).or_insert_with(ChanQ::new);
543        q.credit = None;
544        q.q.push_back(Queued {
545            prio: SendPrio::Mail,
546            frame: Frame::data(2, 0, vec![9]).unwrap(),
547        });
548        q.q.push_back(Queued {
549            prio: SendPrio::Control,
550            frame: Frame::data(2, 0, vec![1]).unwrap(),
551        });
552        let (_, _, f) = pick_next(&mut st).unwrap();
553        assert_eq!(f.payload, vec![1]);
554        assert!(pick_next(&mut st).is_none());
555        st.chans.get_mut(&2).unwrap().credit = Some(4);
556        let (_, _, f) = pick_next(&mut st).unwrap();
557        assert_eq!(f.payload, vec![9]);
558    }
559}