1 use crate::{error::Error, *};
2 use byteorder::{BigEndian, ReadBytesExt};
7 sync::{mpsc, Arc, Mutex, Weak},
11 fn to_seqnum(seqnum: u16) -> usize {
12 (seqnum as usize) & (REL_BUFFER - 1)
15 type PktTx = mpsc::Sender<InPkt>;
16 type Result = result::Result<(), Error>;
19 timestamp: time::Instant,
23 packets: Vec<Cell<Option<Vec<u8>>>>, // in the good old days this used to be called char **
24 splits: HashMap<u16, Split>,
29 pub struct RecvWorker<R: UdpReceiver, S: UdpSender> {
30 share: Arc<RudpShare<S>>,
31 chans: Arc<Vec<Mutex<Chan>>>,
36 impl<R: UdpReceiver, S: UdpSender> RecvWorker<R, S> {
37 pub fn new(udp_rx: R, share: Arc<RudpShare<S>>, pkt_tx: PktTx) -> Self {
47 packets: (0..REL_BUFFER).map(|_| Cell::new(None)).collect(),
49 splits: HashMap::new(),
58 let cleanup_chans = Arc::downgrade(&self.chans);
59 thread::spawn(move || {
60 let timeout = time::Duration::from_secs(TIMEOUT);
62 while let Some(chans) = Weak::upgrade(&cleanup_chans) {
63 for chan in chans.iter() {
64 let mut ch = chan.lock().unwrap();
67 .drain_filter(|_k, v| v.timestamp.elapsed() < timeout)
71 thread::sleep(timeout);
76 if let Err(e) = self.handle(self.recv_pkt()) {
77 if let Error::LocalDisco = e {
84 data: &[CtlType::Disco as u8],
94 fn recv_pkt(&self) -> Result {
97 // todo: reset timeout
98 let mut cursor = io::Cursor::new(self.udp_rx.recv()?);
100 let proto_id = cursor.read_u32::<BigEndian>()?;
101 if proto_id != PROTO_ID {
102 do yeet InvalidProtoId(proto_id);
105 let peer_id = cursor.read_u16::<BigEndian>()?;
107 let n_chan = cursor.read_u8()?;
110 .get(n_chan as usize)
111 .ok_or(InvalidChannel(n_chan))?
115 self.process_pkt(cursor, &mut chan)
118 fn process_pkt(&self, mut cursor: io::Cursor<Vec<u8>>, chan: &mut Chan) -> Result {
123 match cursor.read_u8()?.try_into()? {
124 Ctl => match cursor.read_u8()?.try_into()? {
125 Disco => return Err(RemoteDisco),
131 self.pkt_tx.send(Ok(Pkt {
134 data: cursor.remaining_slice().into(),
139 dbg!(cursor.remaining_slice());
144 let seqnum = cursor.read_u16::<BigEndian>()?;
145 chan.packets[to_seqnum(seqnum)].set(Some(cursor.remaining_slice().into()));
147 while let Some(pkt) = chan.packets[to_seqnum(chan.seqnum)].take() {
148 self.handle(self.process_pkt(io::Cursor::new(pkt), chan))?;
149 chan.seqnum = chan.seqnum.overflowing_add(1).0;
157 fn handle(&self, res: Result) -> Result {
162 Err(RemoteDisco) => Err(RemoteDisco),
163 Err(LocalDisco) => Err(LocalDisco),
164 Err(e) => Ok(self.pkt_tx.send(Err(e))?),