2 use async_recursion::async_recursion;
3 use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt};
10 time::{Duration, Instant},
12 use tokio::sync::{mpsc, watch, Mutex};
14 fn to_seqnum(seqnum: u16) -> usize {
15 (seqnum as usize) & (REL_BUFFER - 1)
18 type Result<T> = std::result::Result<T, Error>;
22 timestamp: Option<Instant>,
23 chunks: Vec<OnceCell<Vec<u8>>>,
28 packets: Vec<Option<Vec<u8>>>, // char ** 😛
29 splits: HashMap<u16, Split>,
34 pub(crate) struct RecvWorker<R: UdpReceiver, S: UdpSender> {
35 share: Arc<RudpShare<S>>,
36 close: watch::Receiver<bool>,
37 chans: Arc<Vec<Mutex<RecvChan>>>,
38 pkt_tx: mpsc::UnboundedSender<InPkt>,
42 impl<R: UdpReceiver, S: UdpSender> RecvWorker<R, S> {
45 share: Arc<RudpShare<S>>,
46 close: watch::Receiver<bool>,
47 pkt_tx: mpsc::UnboundedSender<InPkt>,
59 packets: (0..REL_BUFFER).map(|_| None).collect(),
61 splits: HashMap::new(),
69 pub async fn run(&self) {
72 let cleanup_chans = Arc::clone(&self.chans);
73 let mut cleanup_close = self.close.clone();
79 .name("cleanup_splits")*/
81 let timeout = Duration::from_secs(TIMEOUT);
83 ticker!(timeout, cleanup_close, {
84 for chan_mtx in cleanup_chans.iter() {
85 let mut chan = chan_mtx.lock().await;
89 |_k, v| !matches!(v.timestamp, Some(t) if t.elapsed() < timeout),
96 let mut close = self.close.clone();
97 let timeout = tokio::time::sleep(Duration::from_secs(TIMEOUT));
101 if let Err(e) = self.handle(self.recv_pkt(&mut close, timeout.as_mut()).await) {
102 // TODO: figure out whether this is a good idea
103 if let RemoteDisco(to) = e {
104 self.pkt_tx.send(Err(RemoteDisco(to))).ok();
107 #[allow(clippy::single_match)]
109 // anon5's mt notifies the peer on timeout, C++ MT does not
110 LocalDisco /*| RemoteDisco(true)*/ => drop(
117 data: &[CtlType::Disco as u8],
133 close: &mut watch::Receiver<bool>,
134 timeout: Pin<&mut tokio::time::Sleep>,
138 let mut cursor = io::Cursor::new(tokio::select! {
139 pkt = self.udp_rx.recv() => pkt?,
140 _ = tokio::time::sleep_until(timeout.deadline()) => return Err(RemoteDisco(true)),
141 _ = close.changed() => return Err(LocalDisco),
144 timeout.reset(tokio::time::Instant::now() + Duration::from_secs(TIMEOUT));
146 let proto_id = cursor.read_u32::<BigEndian>()?;
147 if proto_id != PROTO_ID {
148 return Err(InvalidProtoId(proto_id));
151 let _peer_id = cursor.read_u16::<BigEndian>()?;
153 let n_chan = cursor.read_u8()?;
156 .get(n_chan as usize)
157 .ok_or(InvalidChannel(n_chan))?
161 self.process_pkt(cursor, true, &mut chan).await
165 async fn process_pkt(
167 mut cursor: io::Cursor<Vec<u8>>,
173 match cursor.read_u8()?.try_into()? {
174 PktType::Ctl => match cursor.read_u8()?.try_into()? {
178 let seqnum = cursor.read_u16::<BigEndian>()?;
179 if let Some(ack) = self.share.chans[chan.num as usize]
185 ack.tx.send(true).ok();
188 CtlType::SetPeerID => {
189 println!("SetPeerID");
191 let mut id = self.share.remote_id.write().await;
193 if *id != PeerID::Nil as u16 {
194 return Err(PeerIDAlreadySet);
197 *id = cursor.read_u16::<BigEndian>()?;
204 return Err(RemoteDisco(false));
210 self.pkt_tx.send(Ok(Pkt {
213 data: cursor.remaining_slice().into(),
219 let seqnum = cursor.read_u16::<BigEndian>()?;
220 let chunk_index = cursor.read_u16::<BigEndian>()? as usize;
221 let chunk_count = cursor.read_u16::<BigEndian>()? as usize;
223 let mut split = chan.splits.entry(seqnum).or_insert_with(|| Split {
225 chunks: (0..chunk_count).map(|_| OnceCell::new()).collect(),
229 if split.chunks.len() != chunk_count {
230 return Err(InvalidChunkCount(split.chunks.len(), chunk_count));
236 .ok_or(InvalidChunkIndex(chunk_index, chunk_count))?
237 .set(cursor.remaining_slice().into())
243 split.timestamp = if unrel { Some(Instant::now()) } else { None };
245 if split.got == chunk_count {
246 self.pkt_tx.send(Ok(Pkt {
252 .flat_map(|chunk| chunk.get().unwrap().iter())
257 chan.splits.remove(&seqnum);
263 let seqnum = cursor.read_u16::<BigEndian>()?;
264 chan.packets[to_seqnum(seqnum)].replace(cursor.remaining_slice().into());
266 let mut ack_data = Vec::with_capacity(3);
267 ack_data.write_u8(CtlType::Ack as u8)?;
268 ack_data.write_u16::<BigEndian>(seqnum)?;
281 fn next_pkt(chan: &mut RecvChan) -> Option<Vec<u8>> {
282 chan.packets[to_seqnum(chan.seqnum)].take()
285 while let Some(pkt) = next_pkt(chan) {
286 self.handle(self.process_pkt(io::Cursor::new(pkt), false, chan).await)?;
287 chan.seqnum = chan.seqnum.overflowing_add(1).0;
295 fn handle(&self, res: Result<()>) -> Result<()> {
300 Err(RemoteDisco(to)) => Err(RemoteDisco(to)),
301 Err(LocalDisco) => Err(LocalDisco),
302 Err(e) => Ok(self.pkt_tx.send(Err(e))?),