add ttl for packet

This commit is contained in:
sijie.sun 2024-05-11 22:59:00 +08:00
parent 43e076ef18
commit 51aa23b635
2 changed files with 13 additions and 3 deletions

View File

@ -324,14 +324,20 @@ impl PeerManager {
self.tasks.lock().await.spawn(async move {
log::trace!("start_peer_recv");
while let Some(mut ret) = recv.next().await {
let Some(hdr) = ret.peer_manager_header() else {
let Some(hdr) = ret.mut_peer_manager_header() else {
tracing::warn!(?ret, "invalid packet, skip");
continue;
};
tracing::trace!(?hdr, ?ret, "peer recv a packet...");
tracing::trace!(?hdr, "peer recv a packet...");
let from_peer_id = hdr.from_peer_id.get();
let to_peer_id = hdr.to_peer_id.get();
if to_peer_id != my_peer_id {
if hdr.ttl <= 1 {
tracing::warn!(?hdr, "ttl is 0, drop packet");
continue;
}
hdr.ttl -= 1;
tracing::trace!(?to_peer_id, ?my_peer_id, "need forward");
let ret = peers.send_msg(ret, to_peer_id).await;
if ret.is_err() {

View File

@ -7,6 +7,8 @@ use zerocopy::FromZeroes;
type DefaultEndian = LittleEndian;
pub const DEFAULT_TTL: u8 = 8;
// TCP TunnelHeader
#[repr(C, packed)]
#[derive(AsBytes, FromBytes, FromZeroes, Clone, Debug, Default)]
@ -69,7 +71,8 @@ pub struct PeerManagerHeader {
pub to_peer_id: U32<DefaultEndian>,
pub packet_type: u8,
pub flags: u8,
reserved: U16<DefaultEndian>,
pub ttl: u8,
reserved: u8,
pub len: U32<DefaultEndian>,
}
pub const PEER_MANAGER_HEADER_SIZE: usize = std::mem::size_of::<PeerManagerHeader>();
@ -362,6 +365,7 @@ impl ZCPacket {
hdr.to_peer_id.set(to_peer_id);
hdr.packet_type = packet_type;
hdr.flags = 0;
hdr.ttl = DEFAULT_TTL;
hdr.len.set(payload_len as u32);
}