1 use crate::{prelude::*, ticker, RecvChan, RecvWorker, RudpShare, Split};
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>;
20 impl<R: UdpReceiver, S: UdpSender> RecvWorker<R, S> {
23 share: Arc<RudpShare<S>>,
24 close: watch::Receiver<bool>,
25 pkt_tx: mpsc::UnboundedSender<InPkt>,
37 packets: (0..REL_BUFFER).map(|_| None).collect(),
39 splits: HashMap::new(),
47 pub async fn run(&self) {
50 let cleanup_chans = Arc::clone(&self.chans);
51 let mut cleanup_close = self.close.clone();
57 .name("cleanup_splits")*/
59 let timeout = Duration::from_secs(TIMEOUT);
61 ticker!(timeout, cleanup_close, {
62 for chan_mtx in cleanup_chans.iter() {
63 let mut chan = chan_mtx.lock().await;
67 |_k, v| !matches!(v.timestamp, Some(t) if t.elapsed() < timeout),
74 let mut close = self.close.clone();
75 let timeout = tokio::time::sleep(Duration::from_secs(TIMEOUT));
79 if let Err(e) = self.handle(self.recv_pkt(&mut close, timeout.as_mut()).await) {
80 // TODO: figure out whether this is a good idea
81 if let RemoteDisco(to) = e {
82 self.pkt_tx.send(Err(RemoteDisco(to))).ok();
85 #[allow(clippy::single_match)]
87 // anon5's mt notifies the peer on timeout, C++ MT does not
88 LocalDisco /*| RemoteDisco(true)*/ => drop(
95 data: &[CtlType::Disco as u8],
111 close: &mut watch::Receiver<bool>,
112 timeout: Pin<&mut tokio::time::Sleep>,
116 let mut cursor = io::Cursor::new(tokio::select! {
117 pkt = self.udp_rx.recv() => pkt?,
118 _ = tokio::time::sleep_until(timeout.deadline()) => return Err(RemoteDisco(true)),
119 _ = close.changed() => return Err(LocalDisco),
122 timeout.reset(tokio::time::Instant::now() + Duration::from_secs(TIMEOUT));
124 let proto_id = cursor.read_u32::<BigEndian>()?;
125 if proto_id != PROTO_ID {
126 return Err(InvalidProtoId(proto_id));
129 let _peer_id = cursor.read_u16::<BigEndian>()?;
131 let n_chan = cursor.read_u8()?;
134 .get(n_chan as usize)
135 .ok_or(InvalidChannel(n_chan))?
139 self.process_pkt(cursor, true, &mut chan).await
143 async fn process_pkt(
145 mut cursor: io::Cursor<Vec<u8>>,
151 match cursor.read_u8()?.try_into()? {
152 PktType::Ctl => match cursor.read_u8()?.try_into()? {
156 let seqnum = cursor.read_u16::<BigEndian>()?;
157 if let Some(ack) = self.share.chans[chan.num as usize]
163 ack.tx.send(true).ok();
166 CtlType::SetPeerID => {
167 println!("SetPeerID");
169 let mut id = self.share.remote_id.write().await;
171 if *id != PeerID::Nil as u16 {
172 return Err(PeerIDAlreadySet);
175 *id = cursor.read_u16::<BigEndian>()?;
182 return Err(RemoteDisco(false));
188 self.pkt_tx.send(Ok(Pkt {
191 data: cursor.remaining_slice().into(),
197 let seqnum = cursor.read_u16::<BigEndian>()?;
198 let chunk_index = cursor.read_u16::<BigEndian>()? as usize;
199 let chunk_count = cursor.read_u16::<BigEndian>()? as usize;
201 let mut split = chan.splits.entry(seqnum).or_insert_with(|| Split {
203 chunks: (0..chunk_count).map(|_| OnceCell::new()).collect(),
207 if split.chunks.len() != chunk_count {
208 return Err(InvalidChunkCount(split.chunks.len(), chunk_count));
214 .ok_or(InvalidChunkIndex(chunk_index, chunk_count))?
215 .set(cursor.remaining_slice().into())
221 split.timestamp = if unrel { Some(Instant::now()) } else { None };
223 if split.got == chunk_count {
224 self.pkt_tx.send(Ok(Pkt {
230 .flat_map(|chunk| chunk.get().unwrap().iter())
235 chan.splits.remove(&seqnum);
241 let seqnum = cursor.read_u16::<BigEndian>()?;
242 chan.packets[to_seqnum(seqnum)].replace(cursor.remaining_slice().into());
244 let mut ack_data = Vec::with_capacity(3);
245 ack_data.write_u8(CtlType::Ack as u8)?;
246 ack_data.write_u16::<BigEndian>(seqnum)?;
259 fn next_pkt(chan: &mut RecvChan) -> Option<Vec<u8>> {
260 chan.packets[to_seqnum(chan.seqnum)].take()
263 while let Some(pkt) = next_pkt(chan) {
264 self.handle(self.process_pkt(io::Cursor::new(pkt), false, chan).await)?;
265 chan.seqnum = chan.seqnum.overflowing_add(1).0;
273 fn handle(&self, res: Result<()>) -> Result<()> {
278 Err(RemoteDisco(to)) => Err(RemoteDisco(to)),
279 Err(LocalDisco) => Err(LocalDisco),
280 Err(e) => Ok(self.pkt_tx.send(Err(e))?),