interplane.Get Omega
Read in your language

aienux

Aienux, the AienOS kernel: boot, scheduling, IPC and capability boundaries. Pre-alpha; host, emulator and physical evidence are labelled separately.

Brought by drakestapleton

branch main Branches Tags History

aienux / crates / aienos-kernel / src / net.rs

516 lines · 16183 bytes Raw Blame History
1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 Drake Stapleton (AIEN / aien-dev)
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16//! Pure, bounded network protocol primitives. All packet offsets are checked.
17
18#[derive(Clone, Copy, Debug, Eq, PartialEq)]
19pub enum Error {
20 Truncated,
21 Invalid,
22 Unsupported,
23 Capacity,
24}
25
26#[derive(Clone, Copy, Debug, Eq, PartialEq)]
27pub struct MacAddress(pub [u8; 6]);
28#[derive(Clone, Copy, Debug, Eq, PartialEq)]
29pub struct Ipv4Address(pub [u8; 4]);
30
31fn be16(b: &[u8], n: usize) -> Result<u16, Error> {
32 Ok(u16::from_be_bytes([
33 *b.get(n).ok_or(Error::Truncated)?,
34 *b.get(n + 1).ok_or(Error::Truncated)?,
35 ]))
36}
37fn put16(b: &mut [u8], n: usize, v: u16) -> Result<(), Error> {
38 let x = b.get_mut(n..n + 2).ok_or(Error::Truncated)?;
39 x.copy_from_slice(&v.to_be_bytes());
40 Ok(())
41}
42
43/// RFC 1071 one's-complement checksum. The final odd byte occupies the high octet.
44pub fn checksum(data: &[u8]) -> u16 {
45 let mut sum = 0u32;
46 for c in data.chunks(2) {
47 sum += if c.len() == 2 {
48 u16::from_be_bytes([c[0], c[1]]) as u32
49 } else {
50 (c[0] as u32) << 8
51 };
52 }
53 while sum >> 16 != 0 {
54 sum = (sum & 0xffff) + (sum >> 16);
55 }
56 !(sum as u16)
57}
58
59#[derive(Clone, Copy, Debug, Eq, PartialEq)]
60pub struct EthernetFrame<'a> {
61 pub destination: MacAddress,
62 pub source: MacAddress,
63 pub ethertype: u16,
64 pub payload: &'a [u8],
65}
66impl<'a> EthernetFrame<'a> {
67 pub fn parse(b: &'a [u8]) -> Result<Self, Error> {
68 if b.len() < 14 {
69 return Err(Error::Truncated);
70 };
71 let mut d = [0; 6];
72 d.copy_from_slice(&b[..6]);
73 let mut s = [0; 6];
74 s.copy_from_slice(&b[6..12]);
75 Ok(Self {
76 destination: MacAddress(d),
77 source: MacAddress(s),
78 ethertype: be16(b, 12)?,
79 payload: &b[14..],
80 })
81 }
82 pub fn build(&self, out: &mut [u8]) -> Result<usize, Error> {
83 let n = 14usize
84 .checked_add(self.payload.len())
85 .ok_or(Error::Capacity)?;
86 if out.len() < n {
87 return Err(Error::Truncated);
88 };
89 out[..6].copy_from_slice(&self.destination.0);
90 out[6..12].copy_from_slice(&self.source.0);
91 put16(out, 12, self.ethertype)?;
92 out[14..n].copy_from_slice(self.payload);
93 Ok(n)
94 }
95}
96
97pub const ETHERTYPE_IPV4: u16 = 0x0800;
98pub const ETHERTYPE_ARP: u16 = 0x0806;
99pub const ARP_REQUEST: u16 = 1;
100pub const ARP_REPLY: u16 = 2;
101#[derive(Clone, Copy, Debug, Eq, PartialEq)]
102pub struct ArpPacket {
103 pub operation: u16,
104 pub sender_mac: MacAddress,
105 pub sender_ip: Ipv4Address,
106 pub target_mac: MacAddress,
107 pub target_ip: Ipv4Address,
108}
109impl ArpPacket {
110 pub fn parse(b: &[u8]) -> Result<Self, Error> {
111 if b.len() < 28 {
112 return Err(Error::Truncated);
113 };
114 if be16(b, 0)? != 1 || be16(b, 2)? != ETHERTYPE_IPV4 || b[4] != 6 || b[5] != 4 {
115 return Err(Error::Invalid);
116 };
117 let op = be16(b, 6)?;
118 if op != ARP_REQUEST && op != ARP_REPLY {
119 return Err(Error::Unsupported);
120 };
121 let mut sm = [0; 6];
122 sm.copy_from_slice(&b[8..14]);
123 let mut si = [0; 4];
124 si.copy_from_slice(&b[14..18]);
125 let mut tm = [0; 6];
126 tm.copy_from_slice(&b[18..24]);
127 let mut ti = [0; 4];
128 ti.copy_from_slice(&b[24..28]);
129 Ok(Self {
130 operation: op,
131 sender_mac: MacAddress(sm),
132 sender_ip: Ipv4Address(si),
133 target_mac: MacAddress(tm),
134 target_ip: Ipv4Address(ti),
135 })
136 }
137 pub fn build(&self, out: &mut [u8]) -> Result<usize, Error> {
138 if out.len() < 28 {
139 return Err(Error::Truncated);
140 };
141 out[..8].copy_from_slice(&[
142 0,
143 1,
144 8,
145 0,
146 6,
147 4,
148 (self.operation >> 8) as u8,
149 self.operation as u8,
150 ]);
151 out[8..14].copy_from_slice(&self.sender_mac.0);
152 out[14..18].copy_from_slice(&self.sender_ip.0);
153 out[18..24].copy_from_slice(&self.target_mac.0);
154 out[24..28].copy_from_slice(&self.target_ip.0);
155 Ok(28)
156 }
157}
158
159#[derive(Clone, Copy)]
160struct ArpEntry {
161 ip: Ipv4Address,
162 mac: MacAddress,
163 expires: u64,
164}
165/// Fixed capacity ARP cache. Caller owns the clock and expiry policy.
166pub struct ArpCache<const N: usize> {
167 entries: [Option<ArpEntry>; N],
168}
169impl<const N: usize> ArpCache<N> {
170 pub const fn new() -> Self {
171 Self { entries: [None; N] }
172 }
173 pub fn lookup(&mut self, ip: Ipv4Address, now: u64) -> Option<MacAddress> {
174 for e in &mut self.entries {
175 if e.map(|x| x.expires <= now).unwrap_or(false) {
176 *e = None
177 }
178 if let Some(x) = e {
179 if x.ip == ip {
180 return Some(x.mac);
181 }
182 }
183 }
184 None
185 }
186 /// Learn only solicited senders unless `allow_unsolicited` is explicitly true.
187 pub fn learn(
188 &mut self,
189 p: ArpPacket,
190 solicited: bool,
191 allow_unsolicited: bool,
192 now: u64,
193 ttl: u64,
194 ) -> Result<(), Error> {
195 if !solicited && !allow_unsolicited {
196 return Err(Error::Invalid);
197 };
198 let expires = now.saturating_add(ttl);
199 let mut slot = None;
200 for (i, e) in self.entries.iter().enumerate() {
201 if e.map(|x| x.ip == p.sender_ip).unwrap_or(false) {
202 slot = Some(i);
203 break;
204 }
205 if e.is_none() && slot.is_none() {
206 slot = Some(i)
207 }
208 }
209 let i = slot.ok_or(Error::Capacity)?;
210 self.entries[i] = Some(ArpEntry {
211 ip: p.sender_ip,
212 mac: p.sender_mac,
213 expires,
214 });
215 Ok(())
216 }
217}
218impl<const N: usize> Default for ArpCache<N> {
219 fn default() -> Self {
220 Self::new()
221 }
222}
223
224#[derive(Clone, Copy, Debug, Eq, PartialEq)]
225pub struct Ipv4Header {
226 pub dscp_ecn: u8,
227 pub identification: u16,
228 pub ttl: u8,
229 pub protocol: u8,
230 pub source: Ipv4Address,
231 pub destination: Ipv4Address,
232}
233impl Ipv4Header {
234 pub fn parse(b: &[u8]) -> Result<(Self, &[u8]), Error> {
235 if b.len() < 20 {
236 return Err(Error::Truncated);
237 };
238 if b[0] >> 4 != 4 {
239 return Err(Error::Invalid);
240 };
241 let h = ((b[0] & 15) as usize) * 4;
242 if h < 20 || b.len() < h {
243 return Err(Error::Invalid);
244 };
245 let total = be16(b, 2)? as usize;
246 if total < h || total > b.len() {
247 return Err(Error::Truncated);
248 };
249 let flags_fragment = be16(b, 6)?;
250 // RFC 791: the reserved flag bit (0x8000) must be zero.
251 if flags_fragment & 0x8000 != 0 {
252 return Err(Error::Invalid);
253 };
254 // More-fragments or a non-zero offset: reassembly is not supported.
255 if flags_fragment & 0x3fff != 0 {
256 return Err(Error::Unsupported);
257 };
258 if b[8] == 0 {
259 return Err(Error::Invalid);
260 };
261 if checksum(&b[..h]) != 0 {
262 return Err(Error::Invalid);
263 };
264 let mut s = [0; 4];
265 s.copy_from_slice(&b[12..16]);
266 let mut d = [0; 4];
267 d.copy_from_slice(&b[16..20]);
268 Ok((
269 Self {
270 dscp_ecn: b[1],
271 identification: be16(b, 4)?,
272 ttl: b[8],
273 protocol: b[9],
274 source: Ipv4Address(s),
275 destination: Ipv4Address(d),
276 },
277 &b[h..total],
278 ))
279 }
280 pub fn build(&self, payload: &[u8], out: &mut [u8]) -> Result<usize, Error> {
281 let total = 20usize.checked_add(payload.len()).ok_or(Error::Capacity)?;
282 if total > u16::MAX as usize || out.len() < total {
283 return Err(Error::Truncated);
284 };
285 out[..20].fill(0);
286 out[0] = 0x45;
287 out[1] = self.dscp_ecn;
288 put16(out, 2, total as u16)?;
289 put16(out, 4, self.identification)?;
290 out[8] = self.ttl;
291 out[9] = self.protocol;
292 out[12..16].copy_from_slice(&self.source.0);
293 out[16..20].copy_from_slice(&self.destination.0);
294 put16(out, 10, checksum(&out[..20]))?;
295 out[20..total].copy_from_slice(payload);
296 Ok(total)
297 }
298}
299
300#[derive(Clone, Copy, Debug, Eq, PartialEq)]
301pub struct IcmpEcho {
302 pub reply: bool,
303 pub identifier: u16,
304 pub sequence: u16,
305 pub data_len: usize,
306}
307impl IcmpEcho {
308 pub fn parse(b: &[u8]) -> Result<Self, Error> {
309 if b.len() < 8 {
310 return Err(Error::Truncated);
311 };
312 if b[0] != 0 && b[0] != 8 || b[1] != 0 {
313 return Err(Error::Unsupported);
314 };
315 if checksum(b) != 0 {
316 return Err(Error::Invalid);
317 };
318 Ok(Self {
319 reply: b[0] == 0,
320 identifier: be16(b, 4)?,
321 sequence: be16(b, 6)?,
322 data_len: b.len() - 8,
323 })
324 }
325 pub fn build(&self, data: &[u8], out: &mut [u8]) -> Result<usize, Error> {
326 let n = 8 + data.len();
327 if out.len() < n {
328 return Err(Error::Truncated);
329 };
330 out[..n].fill(0);
331 out[0] = if self.reply { 0 } else { 8 };
332 put16(out, 4, self.identifier)?;
333 put16(out, 6, self.sequence)?;
334 out[8..n].copy_from_slice(data);
335 put16(out, 2, checksum(&out[..n]))?;
336 Ok(n)
337 }
338}
339
340fn pseudo(src: Ipv4Address, dst: Ipv4Address, len: u16) -> u32 {
341 let mut b = [0u8; 12];
342 b[..4].copy_from_slice(&src.0);
343 b[4..8].copy_from_slice(&dst.0);
344 b[9] = 17;
345 b[10..].copy_from_slice(&len.to_be_bytes());
346 let mut s = 0u32;
347 for c in b.chunks(2) {
348 s += u16::from_be_bytes([c[0], c[1]]) as u32
349 }
350 s
351}
352#[derive(Clone, Copy, Debug, Eq, PartialEq)]
353pub struct UdpDatagram {
354 pub source_port: u16,
355 pub destination_port: u16,
356}
357impl UdpDatagram {
358 pub fn parse(b: &[u8], src: Ipv4Address, dst: Ipv4Address) -> Result<(Self, &[u8]), Error> {
359 if b.len() < 8 {
360 return Err(Error::Truncated);
361 };
362 let n = be16(b, 4)? as usize;
363 if n < 8 || n > b.len() {
364 return Err(Error::Invalid);
365 };
366 let c = be16(b, 6)?;
367 if c != 0 {
368 let mut sum = pseudo(src, dst, n as u16);
369 for x in b[..n].chunks(2) {
370 sum += if x.len() == 2 {
371 u16::from_be_bytes([x[0], x[1]]) as u32
372 } else {
373 (x[0] as u32) << 8
374 };
375 while sum >> 16 != 0 {
376 sum = (sum & 0xffff) + (sum >> 16)
377 }
378 }
379 if sum as u16 != 0xffff {
380 return Err(Error::Invalid);
381 }
382 }
383 Ok((
384 Self {
385 source_port: be16(b, 0)?,
386 destination_port: be16(b, 2)?,
387 },
388 &b[8..n],
389 ))
390 }
391 pub fn build(
392 &self,
393 data: &[u8],
394 src: Ipv4Address,
395 dst: Ipv4Address,
396 out: &mut [u8],
397 ) -> Result<usize, Error> {
398 let n = 8 + data.len();
399 if n > u16::MAX as usize || out.len() < n {
400 return Err(Error::Truncated);
401 };
402 out[..n].fill(0);
403 put16(out, 0, self.source_port)?;
404 put16(out, 2, self.destination_port)?;
405 put16(out, 4, n as u16)?;
406 out[8..n].copy_from_slice(data);
407 let mut sum = pseudo(src, dst, n as u16);
408 for x in out[..n].chunks(2) {
409 sum += if x.len() == 2 {
410 u16::from_be_bytes([x[0], x[1]]) as u32
411 } else {
412 (x[0] as u32) << 8
413 };
414 while sum >> 16 != 0 {
415 sum = (sum & 0xffff) + (sum >> 16)
416 }
417 }
418 let c = !(sum as u16);
419 put16(out, 6, if c == 0 { 0xffff } else { c })?;
420 Ok(n)
421 }
422}
423
424#[cfg(test)]
425mod tests {
426 use super::*;
427 #[test]
428 fn checksum_vectors() {
429 assert_eq!(checksum(&[0, 1, 0xf2, 3, 0xf4, 0xf5, 0xf6, 0xf7]), 0x220d);
430 assert_eq!(checksum(&[1]), 0xfeff)
431 }
432 #[test]
433 fn ethernet_and_arp_vector() {
434 let req = [
435 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x52, 0x54, 0, 0x12, 0x34, 0x56, 0x08, 0x06, 0, 1,
436 8, 0, 6, 4, 0, 1, 0x52, 0x54, 0, 0x12, 0x34, 0x56, 192, 168, 1, 10, 0, 0, 0, 0, 0, 0,
437 192, 168, 1, 1,
438 ];
439 let f = EthernetFrame::parse(&req).unwrap();
440 assert_eq!(f.ethertype, ETHERTYPE_ARP);
441 let a = ArpPacket::parse(f.payload).unwrap();
442 assert_eq!(a.operation, ARP_REQUEST);
443 let mut out = [0; 28];
444 a.build(&mut out).unwrap();
445 assert_eq!(out, &req[14..]);
446 }
447 #[test]
448 fn ipv4_icmp_ping_vector() {
449 let p = [
450 0x45, 0, 0, 0x1c, 0, 1, 0, 0, 64, 1, 0x8e, 0xa9, 192, 0, 2, 1, 198, 51, 100, 2, 8, 0,
451 0xe5, 0xca, 0x12, 0x34, 0, 1,
452 ];
453 let (h, body) = Ipv4Header::parse(&p).unwrap();
454 assert_eq!(h.protocol, 1);
455 let e = IcmpEcho::parse(body).unwrap();
456 assert_eq!(e.identifier, 0x1234);
457 let mut out = [0; 28];
458 assert_eq!(h.build(body, &mut out).unwrap(), 28);
459 assert_eq!(out, p);
460 }
461 #[test]
462 fn udp_known_checksum() {
463 let src = Ipv4Address([192, 0, 2, 1]);
464 let dst = Ipv4Address([198, 51, 100, 2]);
465 let d = UdpDatagram {
466 source_port: 1234,
467 destination_port: 53,
468 };
469 let mut b = [0; 11];
470 d.build(b"abc", src, dst, &mut b).unwrap();
471 assert_eq!(&b[6..8], &[0x4a, 0x37]);
472 assert_eq!(UdpDatagram::parse(&b, src, dst).unwrap().1, b"abc");
473 }
474 #[test]
475 fn rejects_short_bad_and_fragments() {
476 assert_eq!(EthernetFrame::parse(&[]), Err(Error::Truncated));
477 assert_eq!(ArpPacket::parse(&[0; 27]), Err(Error::Truncated));
478 assert_eq!(Ipv4Header::parse(&[0; 20]), Err(Error::Invalid));
479 let mut b = [
480 0x45, 0, 0, 20, 0, 0, 0x20, 0, 64, 17, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
481 ];
482 let c = checksum(&b[..20]);
483 b[10..12].copy_from_slice(&c.to_be_bytes());
484 assert_eq!(Ipv4Header::parse(&b), Err(Error::Unsupported));
485 }
486 #[test]
487 fn cache_requires_solicited_and_expires() {
488 let mut c = ArpCache::<1>::new();
489 let p = ArpPacket {
490 operation: 2,
491 sender_mac: MacAddress([1; 6]),
492 sender_ip: Ipv4Address([1; 4]),
493 target_mac: MacAddress([0; 6]),
494 target_ip: Ipv4Address([2; 4]),
495 };
496 assert_eq!(c.learn(p, false, false, 0, 5), Err(Error::Invalid));
497 c.learn(p, true, false, 0, 5).unwrap();
498 assert_eq!(c.lookup(p.sender_ip, 4), Some(p.sender_mac));
499 assert_eq!(c.lookup(p.sender_ip, 5), None);
500 }
501 #[test]
502 fn ipv4_reserved_flag_is_rejected() {
503 let mut h = [
504 0x45u8, 0, 0, 20, 0x12, 0x34, 0x80, 0x00, 64, 17, 0, 0, 10, 0, 0, 1, 10, 0, 0, 2,
505 ];
506 let c = checksum(&h);
507 h[10..12].copy_from_slice(&c.to_be_bytes());
508 assert_eq!(Ipv4Header::parse(&h).map(|_| ()), Err(Error::Invalid));
509 // Don't-fragment (0x4000) alone stays valid.
510 h[6] = 0x40;
511 h[10..12].copy_from_slice(&[0, 0]);
512 let c = checksum(&h);
513 h[10..12].copy_from_slice(&c.to_be_bytes());
514 assert!(Ipv4Header::parse(&h).is_ok());
515 }
516}