1 use crate::{prelude::*, ticker, RecvChan, RecvWorker, RudpShare, Split};
2 use async_recursion::async_recursion;
3 use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt};
5 cell::{Cell, OnceCell},
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(|_| Cell::new(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();
86 // anon5's mt notifies the peer on timeout, C++ MT does not
87 LocalDisco /*| RemoteDisco(true)*/ => drop(
94 data: &[CtlType::Disco as u8],
110 close: &mut watch::Receiver<bool>,
111 timeout: Pin<&mut tokio::time::Sleep>,
115 let mut cursor = io::Cursor::new(tokio::select! {
116 pkt = self.udp_rx.recv() => pkt?,
117 _ = tokio::time::sleep_until(timeout.deadline()) => return Err(RemoteDisco(true)),
118 _ = close.changed() => return Err(LocalDisco),
121 timeout.reset(tokio::time::Instant::now() + Duration::from_secs(TIMEOUT));
123 let proto_id = cursor.read_u32::<BigEndian>()?;
124 if proto_id != PROTO_ID {
125 return Err(InvalidProtoId(proto_id));
128 let _peer_id = cursor.read_u16::<BigEndian>()?;
130 let n_chan = cursor.read_u8()?;
133 .get(n_chan as usize)
134 .ok_or(InvalidChannel(n_chan))?
138 self.process_pkt(cursor, true, &mut chan).await
142 async fn process_pkt(
144 mut cursor: io::Cursor<Vec<u8>>,
150 match cursor.read_u8()?.try_into()? {
151 PktType::Ctl => match cursor.read_u8()?.try_into()? {
155 let seqnum = cursor.read_u16::<BigEndian>()?;
156 if let Some(ack) = self.share.chans[chan.num as usize]
162 ack.tx.send(true).ok();
165 CtlType::SetPeerID => {
166 println!("SetPeerID");
168 let mut id = self.share.remote_id.write().await;
170 if *id != PeerID::Nil as u16 {
171 return Err(PeerIDAlreadySet);
174 *id = cursor.read_u16::<BigEndian>()?;
181 return Err(RemoteDisco(false));
187 self.pkt_tx.send(Ok(Pkt {
190 data: cursor.remaining_slice().into(),
196 let seqnum = cursor.read_u16::<BigEndian>()?;
197 let chunk_index = cursor.read_u16::<BigEndian>()? as usize;
198 let chunk_count = cursor.read_u16::<BigEndian>()? as usize;
200 let mut split = chan.splits.entry(seqnum).or_insert_with(|| Split {
202 chunks: (0..chunk_count).map(|_| OnceCell::new()).collect(),
206 if split.chunks.len() != chunk_count {
207 return Err(InvalidChunkCount(split.chunks.len(), chunk_count));
213 .ok_or(InvalidChunkIndex(chunk_index, chunk_count))?
214 .set(cursor.remaining_slice().into())
220 split.timestamp = if unrel { Some(Instant::now()) } else { None };
222 if split.got == chunk_count {
223 self.pkt_tx.send(Ok(Pkt {
229 .flat_map(|chunk| chunk.get().unwrap().iter())
234 chan.splits.remove(&seqnum);
240 let seqnum = cursor.read_u16::<BigEndian>()?;
241 chan.packets[to_seqnum(seqnum)].set(Some(cursor.remaining_slice().into()));
243 let mut ack_data = Vec::with_capacity(3);
244 ack_data.write_u8(CtlType::Ack as u8)?;
245 ack_data.write_u16::<BigEndian>(seqnum)?;
258 fn next_pkt(chan: &mut RecvChan) -> Option<Vec<u8>> {
259 chan.packets[to_seqnum(chan.seqnum)].take()
262 while let Some(pkt) = next_pkt(chan) {
263 self.handle(self.process_pkt(io::Cursor::new(pkt), false, chan).await)?;
264 chan.seqnum = chan.seqnum.overflowing_add(1).0;
272 fn handle(&self, res: Result<()>) -> Result<()> {
277 Err(RemoteDisco(to)) => Err(RemoteDisco(to)),
278 Err(LocalDisco) => Err(LocalDisco),
279 Err(e) => Ok(self.pkt_tx.send(Err(e))?),