1use bytes::{BufMut, Bytes, BytesMut};
2use error::Error;
3use log::warn;
4use ndn_ndnlp::{LpPacket, Packet};
5use ndn_protocol::{Data, Interest, Name};
6use ndn_tlv::{Tlv, TlvDecode, TlvEncode, VarNum};
7use tokio::io::{AsyncRead, AsyncReadExt};
8
9pub mod app;
10pub mod error;
11mod util;
12pub mod verifier;
13
14pub type Result<T> = std::result::Result<T, Error>;
15
16trait ToName {
17 fn to_name(self) -> Name;
18}
19
20impl ToName for &str {
21 fn to_name(self) -> Name {
22 Name::from_str(self).unwrap()
23 }
24}
25
26impl ToName for Name {
27 fn to_name(self) -> Name {
28 self
29 }
30}
31
32trait DataExt: Sized {
33 async fn from_async_reader(reader: impl AsyncRead + Unpin) -> Option<Self>;
34}
35
36impl DataExt for Packet {
37 async fn from_async_reader(mut reader: impl AsyncRead + Unpin) -> Option<Self> {
38 const BUFFER_SIZE: usize = 1024;
39
40 let mut header_buf = [0; 18];
41 let bytes_read = reader.read(&mut header_buf).await.ok()?;
42 let mut header_bytes = Bytes::copy_from_slice(&header_buf);
43
44 if bytes_read == 0 {
45 return None;
46 }
47
48 let typ = VarNum::decode(&mut header_bytes).ok()?;
49 let len = VarNum::decode(&mut header_bytes).ok()?;
50 if typ.value() as usize != Interest::<()>::TYP
51 && typ.value() as usize != Data::<()>::TYP
52 && typ.value() as usize != LpPacket::TYP
53 {
54 warn!("Unknown TLV type {typ} received");
56 let remaining_len = len.value() as usize - bytes_read;
57 tokio::io::copy(
58 &mut reader.take(remaining_len as u64),
59 &mut tokio::io::sink(),
60 )
61 .await
62 .expect("Failed to read unknown packet");
63 return None;
64 }
65
66 let total_len = typ.size() + len.size() + len.value() as usize;
67
68 let mut bytes = BytesMut::with_capacity(total_len);
69 bytes.put(&header_buf[0..bytes_read]);
70
71 let mut left_to_read = total_len - bytes_read;
72 let mut buf = [0; BUFFER_SIZE];
73 while left_to_read > 0 {
74 let bytes_read = reader
75 .read(&mut buf[0..left_to_read.min(BUFFER_SIZE)])
76 .await
77 .ok()?;
78 bytes.put(&buf[..left_to_read.min(BUFFER_SIZE)]);
79 left_to_read -= bytes_read;
80 }
81
82 Self::decode(&mut bytes.freeze()).ok()
83 }
84}