1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
use crate::consts::*;
use crate::id::*;
use core::sync::atomic::{AtomicU8, Ordering};
use spin::Lazy;
pub(crate) const VERSION: u8 = 0x03;
pub const MIN_LEN: usize = 5;
static SN: Lazy<AtomicU8> = Lazy::new(|| {
AtomicU8::new({
let mut data: [u8; 1] = [0; 1];
if let Ok(_) = getrandom::getrandom(&mut data) {
data[0]
} else {
0
}
})
});
pub fn set_sn(sn: u8) {
SN.store(sn, Ordering::Relaxed);
}
#[derive(Clone)]
pub struct PacketHeader {
sn: u8,
src: Id,
dst: Id,
ttl: u8,
protocol: u8,
}
impl PacketHeader {
pub fn new(src: Id, dst: Id) -> Self {
PacketHeader {
sn: SN.fetch_add(1, Ordering::Relaxed),
src: src,
dst: dst,
ttl: 8,
protocol: 0,
}
}
pub fn sn(&self) -> u8 {
self.sn
}
pub fn src(&self) -> &Id {
&self.src
}
pub fn dst(&self) -> &Id {
&self.dst
}
pub fn ttl(&self) -> u8 {
self.ttl
}
pub fn set_ttl(&mut self, ttl: u8) {
self.ttl = ttl;
}
pub fn protocol(&self) -> u8 {
self.protocol
}
pub fn set_protocol(&mut self, protocol: u8) {
self.protocol = protocol;
}
pub fn generate(&self, data: &[u8]) -> VecPacket {
let head = self;
let mut output: VecPacket = VecPacket::new();
output.push(VERSION);
output.push(head.sn);
output.extend_from_slice(&head.src);
output.extend_from_slice(&head.dst);
output.push(head.ttl);
output.push(head.protocol);
output.extend_from_slice(data);
return output;
}
}
pub struct Packet<'a> {
head: PacketHeader,
data: &'a [u8],
}
impl<'a> Packet<'a> {
pub fn head(&self) -> &PacketHeader {
&self.head
}
pub fn data(&self) -> &[u8] {
&self.data
}
pub fn parse(buf: &'a [u8]) -> Result<Packet<'a>, &'static str> {
let buf_len = buf.len();
if buf_len < MIN_LEN {
return Err("Packet buf too short.");
} else if buf_len > PACKET_LEN {
return Err("Packet buf too long.");
}
if buf[0] == VERSION {
let sn = buf[1];
let (src, rest) = Id::split_buf(&buf[2..]);
let (dst, rest) = Id::split_buf(rest);
let ttl = rest[0];
let protocol = rest[1];
let data = &rest[2..];
if data.len() > DATA_LEN {
return Err("Packet data too long.");
}
let head = PacketHeader {
sn,
src,
dst,
ttl,
protocol,
};
let pkt = Packet { head, data };
return Ok(pkt);
} else {
return Err("Packet no version.");
}
}
}