aboutsummaryrefslogtreecommitdiff
path: root/src/recv_worker.rs
blob: 2cd8197729df7ba760f3ed513d0b9ad98eae4a32 (plain)
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
use crate::{error::Error, *};
use byteorder::{BigEndian, ReadBytesExt};
use std::{
    cell::Cell,
    collections::HashMap,
    io, result,
    sync::{mpsc, Arc, Mutex, Weak},
    thread, time,
};

fn to_seqnum(seqnum: u16) -> usize {
    (seqnum as usize) & (REL_BUFFER - 1)
}

type PktTx = mpsc::Sender<InPkt>;
type Result = result::Result<(), Error>;

struct Split {
    timestamp: time::Instant,
}

struct Chan {
    packets: Vec<Cell<Option<Vec<u8>>>>, // in the good old days this used to be called char **
    splits: HashMap<u16, Split>,
    seqnum: u16,
    num: u8,
}

pub struct RecvWorker<R: UdpReceiver, S: UdpSender> {
    share: Arc<RudpShare<S>>,
    chans: Arc<Vec<Mutex<Chan>>>,
    pkt_tx: PktTx,
    udp_rx: R,
}

impl<R: UdpReceiver, S: UdpSender> RecvWorker<R, S> {
    pub fn new(udp_rx: R, share: Arc<RudpShare<S>>, pkt_tx: PktTx) -> Self {
        Self {
            udp_rx,
            share,
            pkt_tx,
            chans: Arc::new(
                (0..NUM_CHANS as u8)
                    .map(|num| {
                        Mutex::new(Chan {
                            num,
                            packets: (0..REL_BUFFER).map(|_| Cell::new(None)).collect(),
                            seqnum: INIT_SEQNUM,
                            splits: HashMap::new(),
                        })
                    })
                    .collect(),
            ),
        }
    }

    pub fn run(&self) {
        let cleanup_chans = Arc::downgrade(&self.chans);
        thread::spawn(move || {
            let timeout = time::Duration::from_secs(TIMEOUT);

            while let Some(chans) = Weak::upgrade(&cleanup_chans) {
                for chan in chans.iter() {
                    let mut ch = chan.lock().unwrap();
                    ch.splits = ch
                        .splits
                        .drain_filter(|_k, v| v.timestamp.elapsed() < timeout)
                        .collect();
                }

                thread::sleep(timeout);
            }
        });

        loop {
            if let Err(e) = self.handle(self.recv_pkt()) {
                if let Error::LocalDisco = e {
                    self.share
                        .send(
                            PktType::Ctl,
                            Pkt {
                                unrel: true,
                                chan: 0,
                                data: &[CtlType::Disco as u8],
                            },
                        )
                        .ok();
                }
                break;
            }
        }
    }

    fn recv_pkt(&self) -> Result {
        use Error::*;

        // todo: reset timeout
        let mut cursor = io::Cursor::new(self.udp_rx.recv()?);

        let proto_id = cursor.read_u32::<BigEndian>()?;
        if proto_id != PROTO_ID {
            do yeet InvalidProtoId(proto_id);
        }

        let peer_id = cursor.read_u16::<BigEndian>()?;

        let n_chan = cursor.read_u8()?;
        let mut chan = self
            .chans
            .get(n_chan as usize)
            .ok_or(InvalidChannel(n_chan))?
            .lock()
            .unwrap();

        self.process_pkt(cursor, &mut chan)
    }

    fn process_pkt(&self, mut cursor: io::Cursor<Vec<u8>>, chan: &mut Chan) -> Result {
        use CtlType::*;
        use Error::*;
        use PktType::*;

        match cursor.read_u8()?.try_into()? {
            Ctl => match cursor.read_u8()?.try_into()? {
                Disco => return Err(RemoteDisco),
                _ => {}
            },
            Orig => {
                println!("Orig");

                self.pkt_tx.send(Ok(Pkt {
                    chan: chan.num,
                    unrel: true,
                    data: cursor.remaining_slice().into(),
                }))?;
            }
            Split => {
                println!("Split");
                dbg!(cursor.remaining_slice());
            }
            Rel => {
                println!("Rel");

                let seqnum = cursor.read_u16::<BigEndian>()?;
                chan.packets[to_seqnum(seqnum)].set(Some(cursor.remaining_slice().into()));

                while let Some(pkt) = chan.packets[to_seqnum(chan.seqnum)].take() {
                    self.handle(self.process_pkt(io::Cursor::new(pkt), chan))?;
                    chan.seqnum = chan.seqnum.overflowing_add(1).0;
                }
            }
        }

        Ok(())
    }

    fn handle(&self, res: Result) -> Result {
        use Error::*;

        match res {
            Ok(v) => Ok(v),
            Err(RemoteDisco) => Err(RemoteDisco),
            Err(LocalDisco) => Err(LocalDisco),
            Err(e) => Ok(self.pkt_tx.send(Err(e))?),
        }
    }
}