1use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
5
6use tokio::io::{AsyncRead, AsyncReadExt};
7use tracing::debug;
8
9use crate::tcp::PcapLog;
10
11#[derive(Clone, Copy, Debug)]
12pub enum ProtocolNumber {
13 Tcp = 6,
14 Udp = 17,
15}
16
17#[derive(Debug)]
18pub struct Ipv4Packet {
19 pub version: u8, pub ihl: u8, pub tos: u8, pub total_length: u16, pub identification: u16, pub flags: u8, pub fragment_offset: u16, pub ttl: u8, pub protocol: u8, pub header_checksum: u16, pub source: Ipv4Addr,
31 pub destination: Ipv4Addr,
32 pub options: Vec<u8>,
33 pub payload: Vec<u8>, }
35
36impl Ipv4Packet {
37 pub fn parse(packet: &[u8]) -> Option<Self> {
38 if packet.len() < 20 {
39 return None;
40 }
41
42 let version_ihl = packet[0];
43 let version = version_ihl >> 4;
44 let ihl = (version_ihl & 0x0F) * 4; if version != 4 || packet.len() < ihl as usize {
47 return None;
48 }
49
50 let tos = packet[1];
51 let total_length = u16::from_be_bytes([packet[2], packet[3]]);
52 let identification = u16::from_be_bytes([packet[4], packet[5]]);
53 let flags_fragment = u16::from_be_bytes([packet[6], packet[7]]);
54 let flags = (flags_fragment >> 13) as u8;
55 let fragment_offset = flags_fragment & 0x1FFF;
56 let ttl = packet[8];
57 let protocol = packet[9];
58 let header_checksum = u16::from_be_bytes([packet[10], packet[11]]);
59 let source = Ipv4Addr::new(packet[12], packet[13], packet[14], packet[15]);
60 let destination = Ipv4Addr::new(packet[16], packet[17], packet[18], packet[19]);
61
62 let options_end = ihl as usize;
63 let options = if options_end > 20 {
64 packet[20..options_end].to_vec()
65 } else {
66 Vec::new()
67 };
68
69 let payload = if total_length as usize > options_end {
70 packet[options_end..total_length as usize].to_vec()
71 } else {
72 Vec::new()
73 };
74
75 Some(Self {
76 version,
77 ihl,
78 tos,
79 total_length,
80 identification,
81 flags,
82 fragment_offset,
83 ttl,
84 protocol,
85 header_checksum,
86 source,
87 destination,
88 options,
89 payload,
90 })
91 }
92
93 pub async fn from_reader<R: AsyncRead + Unpin + AsyncReadExt>(
95 reader: &mut R,
96 log: &Option<PcapLog>,
97 ) -> Result<Self, std::io::Error> {
98 let mut log_packet = Vec::new();
99
100 let mut header = [0u8; 20]; reader.read_exact(&mut header).await?;
102 if log.is_some() {
103 log_packet.extend_from_slice(&header);
104 }
105
106 let version_ihl = header[0];
107 let version = version_ihl >> 4;
108 let ihl = (version_ihl & 0x0F) * 4;
109
110 if version != 4 || ihl < 20 {
111 debug!("Got an invalid IPv4 header from reader");
112 return Err(std::io::Error::new(
113 std::io::ErrorKind::InvalidData,
114 "Invalid IPv4 header",
115 ));
116 }
117
118 let tos = header[1];
119 let total_length = u16::from_be_bytes([header[2], header[3]]);
120 let identification = u16::from_be_bytes([header[4], header[5]]);
121 let flags_fragment = u16::from_be_bytes([header[6], header[7]]);
122 let flags = (flags_fragment >> 13) as u8;
123 let fragment_offset = flags_fragment & 0x1FFF;
124 let ttl = header[8];
125 let protocol = header[9];
126 let header_checksum = u16::from_be_bytes([header[10], header[11]]);
127 let source = Ipv4Addr::new(header[12], header[13], header[14], header[15]);
128 let destination = Ipv4Addr::new(header[16], header[17], header[18], header[19]);
129
130 let options_len = ihl as usize - 20;
132 let mut options = vec![0u8; options_len];
133 if options_len > 0 {
134 reader.read_exact(&mut options).await?;
135 if log.is_some() {
136 log_packet.extend_from_slice(&options);
137 }
138 }
139
140 let payload_len = total_length as usize - ihl as usize;
142 let mut payload = vec![0u8; payload_len];
143 reader.read_exact(&mut payload).await?;
144 if let Some(log) = log {
145 log_packet.extend_from_slice(&payload);
146 crate::tcp::log_packet(log, &log_packet);
147 }
148
149 Ok(Self {
150 version,
151 ihl,
152 tos,
153 total_length,
154 identification,
155 flags,
156 fragment_offset,
157 ttl,
158 protocol,
159 header_checksum,
160 source,
161 destination,
162 options,
163 payload,
164 })
165 }
166
167 pub fn create(
168 source: Ipv4Addr,
169 destination: Ipv4Addr,
170 protocol: ProtocolNumber,
171 ttl: u8,
172 payload: &[u8],
173 ) -> Vec<u8> {
174 let ihl: u8 = 5;
175 let total_length = (ihl as usize * 4 + payload.len()) as u16;
176 let identification: u16 = 0;
177 let flags_fragment: u16 = 0;
178 let header_checksum: u16 = 0;
179
180 let mut packet = vec![0; total_length as usize];
181 packet[0] = (4 << 4) | (ihl & 0x0F);
182 packet[1] = 0;
183 packet[2..4].copy_from_slice(&total_length.to_be_bytes());
184 packet[4..6].copy_from_slice(&identification.to_be_bytes());
185 packet[6..8].copy_from_slice(&flags_fragment.to_be_bytes());
186 packet[8] = ttl;
187 packet[9] = protocol as u8;
188 packet[10..12].copy_from_slice(&header_checksum.to_be_bytes());
189 packet[12..16].copy_from_slice(&source.octets());
190 packet[16..20].copy_from_slice(&destination.octets());
191 packet[20..].copy_from_slice(payload);
192
193 Self::apply_checksum(&mut packet);
194 packet
195 }
196
197 fn apply_checksum(packet: &mut [u8]) {
198 let hdr_len = ((packet[0] & 0x0F) as usize) * 4;
199 debug_assert!(packet.len() >= hdr_len);
200 packet[10] = 0;
201 packet[11] = 0;
202 let mut sum: u32 = 0;
203 let mut i = 0;
204 while i + 1 < hdr_len {
205 sum += u16::from_be_bytes([packet[i], packet[i + 1]]) as u32;
206 i += 2;
207 }
208 while sum >> 16 != 0 {
210 sum = (sum & 0xFFFF) + (sum >> 16);
211 }
212 let checksum = !(sum as u16);
213 packet[10..12].copy_from_slice(&checksum.to_be_bytes());
214 }
215}
216
217pub struct Ipv6Packet {
218 pub version: u8,
219 pub traffic_class: u8,
220 pub flow_label: u32,
221 pub payload_length: u16,
222 pub next_header: u8,
223 pub hop_limit: u8,
224 pub source: Ipv6Addr,
225 pub destination: Ipv6Addr,
226 pub payload: Vec<u8>,
227}
228
229#[derive(Debug, Clone)]
230pub(crate) enum IpParseError<T> {
231 Ok { packet: T, bytes_consumed: usize },
232 NotEnough,
233 Invalid,
234}
235
236impl Ipv6Packet {
237 pub(crate) fn parse(packet: &[u8], log: &Option<PcapLog>) -> IpParseError<Ipv6Packet> {
238 if packet.len() < 40 {
239 return IpParseError::NotEnough;
240 }
241
242 let version = packet[0] >> 4;
243 if version != 6 {
244 return IpParseError::Invalid;
245 }
246
247 let traffic_class = ((packet[0] & 0x0F) << 4) | (packet[1] >> 4);
248 let flow_label =
249 ((packet[1] as u32 & 0x0F) << 16) | ((packet[2] as u32) << 8) | packet[3] as u32;
250 let payload_length = u16::from_be_bytes([packet[4], packet[5]]);
251 let total_packet_len = 40 + payload_length as usize;
252
253 if packet.len() < total_packet_len {
254 return IpParseError::NotEnough;
255 }
256
257 let next_header = packet[6];
258 let hop_limit = packet[7];
259 let source = Ipv6Addr::new(
260 u16::from_be_bytes([packet[8], packet[9]]),
261 u16::from_be_bytes([packet[10], packet[11]]),
262 u16::from_be_bytes([packet[12], packet[13]]),
263 u16::from_be_bytes([packet[14], packet[15]]),
264 u16::from_be_bytes([packet[16], packet[17]]),
265 u16::from_be_bytes([packet[18], packet[19]]),
266 u16::from_be_bytes([packet[20], packet[21]]),
267 u16::from_be_bytes([packet[22], packet[23]]),
268 );
269
270 let destination = Ipv6Addr::new(
271 u16::from_be_bytes([packet[24], packet[25]]),
272 u16::from_be_bytes([packet[26], packet[27]]),
273 u16::from_be_bytes([packet[28], packet[29]]),
274 u16::from_be_bytes([packet[30], packet[31]]),
275 u16::from_be_bytes([packet[32], packet[33]]),
276 u16::from_be_bytes([packet[34], packet[35]]),
277 u16::from_be_bytes([packet[36], packet[37]]),
278 u16::from_be_bytes([packet[38], packet[39]]),
279 );
280 let payload = packet[40..total_packet_len].to_vec();
281
282 if let Some(log) = log {
283 let mut log_packet = Vec::new();
284 log_packet.extend_from_slice(&packet[..40]);
285 log_packet.extend_from_slice(&payload);
286 crate::tcp::log_packet(log, &log_packet);
287 }
288
289 IpParseError::Ok {
290 packet: Self {
291 version,
292 traffic_class,
293 flow_label,
294 payload_length,
295 next_header,
296 hop_limit,
297 source,
298 destination,
299 payload,
300 },
301 bytes_consumed: total_packet_len,
302 }
303 }
304
305 pub async fn from_reader<R: AsyncRead + Unpin>(
306 reader: &mut R,
307 log: &Option<PcapLog>,
308 ) -> Result<Self, std::io::Error> {
309 let mut log_packet = Vec::new();
310
311 let mut header = [0u8; 40]; reader.read_exact(&mut header).await?;
313
314 if log.is_some() {
315 log_packet.extend_from_slice(&header);
316 }
317
318 let version = header[0] >> 4;
319 if version != 6 {
320 debug!("Got an invalid IPv6 header from reader");
321 return Err(std::io::Error::new(
322 std::io::ErrorKind::InvalidData,
323 "Invalid IPv6 header",
324 ));
325 }
326
327 let traffic_class = ((header[0] & 0x0F) << 4) | ((header[1] & 0xF0) >> 4);
328 let flow_label =
329 ((header[1] as u32 & 0x0F) << 16) | ((header[2] as u32) << 8) | (header[3] as u32);
330 let payload_length = u16::from_be_bytes([header[4], header[5]]);
331 let next_header = header[6];
332 let hop_limit = header[7];
333 let source = Ipv6Addr::new(
334 u16::from_be_bytes([header[8], header[9]]),
335 u16::from_be_bytes([header[10], header[11]]),
336 u16::from_be_bytes([header[12], header[13]]),
337 u16::from_be_bytes([header[14], header[15]]),
338 u16::from_be_bytes([header[16], header[17]]),
339 u16::from_be_bytes([header[18], header[19]]),
340 u16::from_be_bytes([header[20], header[21]]),
341 u16::from_be_bytes([header[22], header[23]]),
342 );
343 let destination = Ipv6Addr::new(
344 u16::from_be_bytes([header[24], header[25]]),
345 u16::from_be_bytes([header[26], header[27]]),
346 u16::from_be_bytes([header[28], header[29]]),
347 u16::from_be_bytes([header[30], header[31]]),
348 u16::from_be_bytes([header[32], header[33]]),
349 u16::from_be_bytes([header[34], header[35]]),
350 u16::from_be_bytes([header[36], header[37]]),
351 u16::from_be_bytes([header[38], header[39]]),
352 );
353
354 let mut payload = vec![0u8; payload_length as usize];
356 reader.read_exact(&mut payload).await?;
357 if let Some(log) = log {
358 log_packet.extend_from_slice(&payload);
359 crate::tcp::log_packet(log, &log_packet);
360 }
361
362 Ok(Self {
363 version,
364 traffic_class,
365 flow_label,
366 payload_length,
367 next_header,
368 hop_limit,
369 source,
370 destination,
371 payload,
372 })
373 }
374
375 pub fn create(
376 source: Ipv6Addr,
377 destination: Ipv6Addr,
378 next_header: ProtocolNumber,
379 hop_limit: u8,
380 payload: &[u8],
381 ) -> Vec<u8> {
382 let mut packet = Vec::with_capacity(40 + payload.len());
383
384 let version_traffic_class = 6 << 4;
386 packet.push(version_traffic_class);
387 packet.push(0); let flow_label = 0u16;
391 packet.extend_from_slice(&flow_label.to_be_bytes()[..]);
392
393 packet.extend_from_slice(&(payload.len() as u16).to_be_bytes());
395
396 packet.push(next_header as u8);
398 packet.push(hop_limit);
399
400 packet.extend_from_slice(&source.octets());
402 packet.extend_from_slice(&destination.octets());
403
404 packet.extend_from_slice(payload);
406
407 packet
408 }
409}
410
411impl std::fmt::Debug for Ipv6Packet {
412 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
413 f.debug_struct("Ipv6Packet")
414 .field("version", &self.version)
415 .field("traffic_class", &self.traffic_class)
416 .field("flow_label", &self.flow_label)
417 .field("payload_length", &self.payload_length)
418 .field("next_header", &self.next_header)
419 .field("hop_limit", &self.hop_limit)
420 .field("source", &self.source)
421 .field("destination", &self.destination)
422 .field("payload len", &self.payload.len())
423 .finish()
424 }
425}
426
427#[derive(Debug, Default, Clone, Copy)]
428pub struct TcpFlags {
429 pub urg: bool, pub ack: bool, pub psh: bool, pub rst: bool, pub syn: bool, pub fin: bool, }
436
437impl TcpFlags {
438 pub fn from_byte(flags: u8) -> Self {
440 Self {
441 urg: (flags & 0b0010_0000) != 0, ack: (flags & 0b0001_0000) != 0, psh: (flags & 0b0000_1000) != 0, rst: (flags & 0b0000_0100) != 0, syn: (flags & 0b0000_0010) != 0, fin: (flags & 0b0000_0001) != 0, }
448 }
449
450 pub fn to_byte(&self) -> u8 {
452 let mut flags = 0u8;
453 if self.urg {
454 flags |= 0b0010_0000;
455 }
456 if self.ack {
457 flags |= 0b0001_0000;
458 }
459 if self.psh {
460 flags |= 0b0000_1000;
461 }
462 if self.rst {
463 flags |= 0b0000_0100;
464 }
465 if self.syn {
466 flags |= 0b0000_0010;
467 }
468 if self.fin {
469 flags |= 0b0000_0001;
470 }
471 flags
472 }
473}
474
475pub struct TcpPacket {
476 pub source_port: u16,
477 pub destination_port: u16,
478 pub sequence_number: u32,
479 pub acknowledgment_number: u32,
480 pub data_offset: u8, pub flags: TcpFlags, pub window_size: u16,
483 pub checksum: u16,
484 pub urgent_pointer: u16,
485 pub options: Vec<u8>, pub payload: Vec<u8>, }
488
489impl TcpPacket {
490 pub fn parse(packet: &[u8]) -> Result<Self, std::io::Error> {
491 if packet.len() < 20 {
492 debug!("Got an invalid TCP header");
493 return Err(std::io::Error::new(
494 std::io::ErrorKind::InvalidData,
495 "Not enough bytes for TCP header",
496 ));
497 }
498
499 let source_port = u16::from_be_bytes([packet[0], packet[1]]);
500 let destination_port = u16::from_be_bytes([packet[2], packet[3]]);
501 let sequence_number = u32::from_be_bytes([packet[4], packet[5], packet[6], packet[7]]);
502 let acknowledgment_number =
503 u32::from_be_bytes([packet[8], packet[9], packet[10], packet[11]]);
504 let data_offset = (packet[12] >> 4) * 4; let flags = TcpFlags::from_byte(packet[13]); let window_size = u16::from_be_bytes([packet[14], packet[15]]);
507 let checksum = u16::from_be_bytes([packet[16], packet[17]]);
508 let urgent_pointer = u16::from_be_bytes([packet[18], packet[19]]);
509
510 let options_end = data_offset as usize;
512 let options = if options_end > 20 && options_end <= packet.len() {
513 packet[20..options_end].to_vec()
514 } else {
515 Vec::new()
516 };
517
518 let payload = if packet.len() > options_end {
520 packet[options_end..].to_vec()
521 } else {
522 Vec::new()
523 };
524
525 Ok(Self {
526 source_port,
527 destination_port,
528 sequence_number,
529 acknowledgment_number,
530 data_offset,
531 flags,
532 window_size,
533 checksum,
534 urgent_pointer,
535 options,
536 payload,
537 })
538 }
539
540 #[allow(clippy::too_many_arguments)]
544 pub fn create(
545 source_ip: IpAddr,
546 destination_ip: IpAddr,
547 source_port: u16,
548 destination_port: u16,
549 sequence_number: u32,
550 acknowledgment_number: u32,
551 flags: TcpFlags,
552 window_size: u16,
553 options: &[u8],
554 payload: &[u8],
555 ) -> Vec<u8> {
556 let pad = (4 - options.len() % 4) % 4;
558 let opt_total = options.len() + pad;
559 debug_assert!(opt_total.is_multiple_of(4));
560 let data_offset = 5_u8 + (opt_total / 4) as u8;
561 let mut packet = Vec::with_capacity(20 + opt_total + payload.len());
562
563 packet.extend_from_slice(&source_port.to_be_bytes());
565 packet.extend_from_slice(&destination_port.to_be_bytes());
566
567 packet.extend_from_slice(&sequence_number.to_be_bytes());
569 packet.extend_from_slice(&acknowledgment_number.to_be_bytes());
570
571 packet.push(data_offset << 4); packet.push(flags.to_byte()); packet.extend_from_slice(&window_size.to_be_bytes());
577 packet.extend_from_slice(&[0, 0]); packet.extend_from_slice(&[0, 0]); packet.extend_from_slice(options);
582 packet.extend(std::iter::repeat_n(1, pad));
583 packet.extend_from_slice(payload);
584
585 let checksum = match (source_ip, destination_ip) {
587 (IpAddr::V4(src), IpAddr::V4(dest)) => {
588 let src_bytes = src.octets();
589 let dest_bytes = dest.octets();
590 Self::calculate_checksum(&packet, &src_bytes, &dest_bytes, false)
591 }
592 (IpAddr::V6(src), IpAddr::V6(dest)) => {
593 let src_bytes = src.octets();
594 let dest_bytes = dest.octets();
595 Self::calculate_checksum(&packet, &src_bytes, &dest_bytes, true)
596 }
597 _ => panic!("Source and destination IP versions must match"),
598 };
599
600 packet[16..18].copy_from_slice(&checksum.to_be_bytes());
601
602 packet
603 }
604
605 fn calculate_checksum(
606 packet: &[u8],
607 source_ip: &[u8],
608 destination_ip: &[u8],
609 is_ipv6: bool,
610 ) -> u16 {
611 let mut sum = 0u32;
612
613 if is_ipv6 {
614 for chunk in source_ip.chunks(2) {
617 sum += u16::from_be_bytes([chunk[0], chunk[1]]) as u32;
618 }
619 for chunk in destination_ip.chunks(2) {
620 sum += u16::from_be_bytes([chunk[0], chunk[1]]) as u32;
621 }
622
623 let tcp_length = packet.len() as u32;
625 sum += (tcp_length >> 16) & 0xFFFF;
626 sum += tcp_length & 0xFFFF;
627
628 sum += 6u32; } else {
631 for chunk in source_ip.chunks(2) {
634 sum += u16::from_be_bytes([chunk[0], chunk[1]]) as u32;
635 }
636 for chunk in destination_ip.chunks(2) {
637 sum += u16::from_be_bytes([chunk[0], chunk[1]]) as u32;
638 }
639
640 sum += 6u32; sum += packet.len() as u32;
645 }
646
647 let mut packet_copy = packet.to_vec();
649 if packet_copy.len() >= 18 {
650 packet_copy[16] = 0;
651 packet_copy[17] = 0;
652 }
653
654 for chunk in packet_copy.chunks(2) {
656 let word = if chunk.len() == 2 {
657 u16::from_be_bytes([chunk[0], chunk[1]])
658 } else {
659 u16::from_be_bytes([chunk[0], 0]) };
661 sum += word as u32;
662 }
663
664 while sum >> 16 != 0 {
666 sum = (sum & 0xFFFF) + (sum >> 16);
667 }
668
669 !(sum as u16)
671 }
672}
673
674pub fn window_scale_option(shift: u8) -> [u8; 3] {
676 [3, 3, shift.min(14)]
678}
679
680pub fn parse_window_scale(options: &[u8]) -> Option<u8> {
683 let mut i = 0;
684 while i < options.len() {
685 match options[i] {
686 0 => return None, 1 => {
688 i += 1;
689 continue;
690 } 3 => {
692 if i + 2 < options.len() && options[i + 1] == 3 {
694 return Some(options[i + 2].min(14));
695 }
696 return None;
697 }
698 _ => {
699 if i + 1 >= options.len() {
701 return None;
702 }
703 let len = options[i + 1] as usize;
704 if len < 2 {
705 return None;
706 }
707 i += len;
708 }
709 }
710 }
711 None
712}
713
714impl std::fmt::Debug for TcpPacket {
715 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
716 f.debug_struct("TcpPacket")
717 .field("source_port", &self.source_port)
718 .field("destination_port", &self.destination_port)
719 .field("sequence_number", &self.sequence_number)
720 .field("acknowledgment_number", &self.acknowledgment_number)
721 .field("data_offset", &self.data_offset)
722 .field("flags", &self.flags)
723 .field("window_size", &self.window_size)
724 .field("checksum", &self.checksum)
725 .field("urgent_pointer", &self.urgent_pointer)
726 .field("options", &self.options)
727 .field("payload len", &self.payload.len())
728 .finish()
729 }
730}
731
732pub struct UdpPacket {
733 pub source_port: u16,
734 pub destination_port: u16,
735 pub length: u16,
736 pub checksum: u16,
737 pub payload: Vec<u8>,
738}
739
740impl UdpPacket {
741 pub fn parse(packet: &[u8]) -> Result<Self, std::io::Error> {
742 if packet.len() < 8 {
743 return Err(std::io::Error::new(
744 std::io::ErrorKind::InvalidData,
745 "not enough bytes for UDP header",
746 ));
747 }
748 let source_port = u16::from_be_bytes([packet[0], packet[1]]);
749 let destination_port = u16::from_be_bytes([packet[2], packet[3]]);
750 let length = u16::from_be_bytes([packet[4], packet[5]]);
751 let checksum = u16::from_be_bytes([packet[6], packet[7]]);
752 let payload = packet[8..].to_vec();
753 Ok(Self {
754 source_port,
755 destination_port,
756 length,
757 checksum,
758 payload,
759 })
760 }
761
762 pub fn create(
764 source_ip: IpAddr,
765 destination_ip: IpAddr,
766 source_port: u16,
767 destination_port: u16,
768 payload: &[u8],
769 ) -> Vec<u8> {
770 let length = (8 + payload.len()) as u16;
771 let mut packet = Vec::with_capacity(length as usize);
772 packet.extend_from_slice(&source_port.to_be_bytes());
773 packet.extend_from_slice(&destination_port.to_be_bytes());
774 packet.extend_from_slice(&length.to_be_bytes());
775 packet.extend_from_slice(&[0, 0]); packet.extend_from_slice(payload);
777
778 let checksum = match (source_ip, destination_ip) {
779 (IpAddr::V4(src), IpAddr::V4(dst)) => {
780 Self::checksum(&packet, &src.octets(), &dst.octets(), false)
781 }
782 (IpAddr::V6(src), IpAddr::V6(dst)) => {
783 Self::checksum(&packet, &src.octets(), &dst.octets(), true)
784 }
785 _ => panic!("source and destination IP versions must match"),
786 };
787 let checksum = if checksum == 0 { 0xFFFF } else { checksum };
790 packet[6..8].copy_from_slice(&checksum.to_be_bytes());
791 packet
792 }
793
794 fn checksum(packet: &[u8], source_ip: &[u8], destination_ip: &[u8], _is_ipv6: bool) -> u16 {
795 let mut sum = 0u32;
796 for chunk in source_ip.chunks(2) {
797 sum += u16::from_be_bytes([chunk[0], chunk[1]]) as u32;
798 }
799 for chunk in destination_ip.chunks(2) {
800 sum += u16::from_be_bytes([chunk[0], chunk[1]]) as u32;
801 }
802 let udp_len = packet.len() as u32;
803 sum += (udp_len >> 16) & 0xFFFF;
804 sum += udp_len & 0xFFFF;
805 sum += 17u32;
806
807 for chunk in packet.chunks(2) {
808 let word = if chunk.len() == 2 {
809 u16::from_be_bytes([chunk[0], chunk[1]])
810 } else {
811 u16::from_be_bytes([chunk[0], 0])
812 };
813 sum += word as u32;
814 }
815 while sum >> 16 != 0 {
816 sum = (sum & 0xFFFF) + (sum >> 16);
817 }
818 !(sum as u16)
819 }
820}
821
822impl std::fmt::Debug for UdpPacket {
823 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
824 f.debug_struct("UdpPacket")
825 .field("source_port", &self.source_port)
826 .field("destination_port", &self.destination_port)
827 .field("length", &self.length)
828 .field("checksum", &self.checksum)
829 .field("payload len", &self.payload.len())
830 .finish()
831 }
832}
833
834#[cfg(test)]
835mod tests {
836 use super::*;
837
838 #[test]
839 fn ipv4_checksum_matches_rfc_1071() {
840 let mut pkt = vec![
842 0x45, 0x00, 0x00, 0x73, 0x00, 0x00, 0x40, 0x00, 0x40, 0x11, 0x00, 0x00, 0xC0, 0xA8,
843 0x00, 0x01, 0xC0, 0xA8, 0x00, 0xC7,
844 ];
845 Ipv4Packet::apply_checksum(&mut pkt);
846 let got = u16::from_be_bytes([pkt[10], pkt[11]]);
847 assert_eq!(got, 0xB861);
848
849 let mut sum: u32 = 0;
850 for chunk in pkt.as_chunks::<2>().0 {
851 sum += u16::from_be_bytes([chunk[0], chunk[1]]) as u32;
852 }
853 while sum >> 16 != 0 {
854 sum = (sum & 0xFFFF) + (sum >> 16);
855 }
856 assert_eq!(sum as u16, 0xFFFF);
857 }
858
859 #[test]
860 fn ipv4() {
861 let b1 = Ipv4Packet::create(
862 Ipv4Addr::new(127, 0, 0, 1),
863 Ipv4Addr::new(1, 1, 1, 1),
864 ProtocolNumber::Tcp,
865 255,
866 &[1, 2, 3, 4, 5],
867 );
868 println!("{b1:02X?}");
869
870 let ip1 = Ipv4Packet::parse(&b1);
871 println!("{ip1:#?}");
872 }
873
874 #[test]
875 fn ipv6() {
876 let b1 = Ipv6Packet::create(
877 Ipv6Addr::new(1, 2, 3, 4, 5, 6, 7, 8),
878 Ipv6Addr::new(9, 10, 11, 12, 13, 14, 15, 16),
879 ProtocolNumber::Tcp,
880 255,
881 &[1, 2, 3, 4, 5],
882 );
883 println!("{b1:02X?}");
884
885 let ip1 = Ipv6Packet::parse(&b1, &None);
886 println!("{ip1:#?}");
887 }
888
889 #[test]
890 fn tcp() {
891 let b1 = TcpPacket::create(
892 IpAddr::V4(Ipv4Addr::new(1, 1, 1, 1)),
893 IpAddr::V4(Ipv4Addr::new(1, 1, 1, 1)),
894 1234,
895 5678,
896 420,
897 6969,
898 TcpFlags {
899 urg: false,
900 ack: false,
901 psh: true,
902 rst: false,
903 syn: false,
904 fin: false,
905 },
906 5555,
907 &[],
908 &[1, 2, 3, 4, 5],
909 );
910 let i1 = Ipv6Packet::create(
911 Ipv6Addr::new(1, 2, 3, 4, 5, 6, 7, 8),
912 Ipv6Addr::new(9, 10, 11, 12, 13, 14, 15, 16),
913 ProtocolNumber::Tcp,
914 255,
915 &b1,
916 );
917 println!("{i1:02X?}");
918
919 let t1 = TcpPacket::parse(&b1);
920 println!("{t1:#?}");
921 }
922}