Debian Codegraph @

crt/s2n/tests/pcap/src/packet.rs

raw symbols SCIP
1 // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2 // SPDX-License-Identifier: Apache-2.0
3
4 use rtshark::Metadata;
5 use std::collections::HashMap;
6
7 /// According to the Wireshark docs, the frame number (frame.number)
8 /// is an unsigned 32-bit integer.
9 /// See https://www.wireshark.org/docs/dfref/f/frame.html.
10 pub(crate) type PacketId = u32;
11
12 #[derive(Debug, Clone, Default)]
13 pub struct Packet(rtshark::Packet);
14
15 /// rtshark represents entries / elements in a capture as "packets".
16 ///
17 /// rtshark packets can be thought of as equivalent to Wireshark "frames".
18 /// From https://wiki.wireshark.org/Protocols/frame:
19 /// > The frame protocol isn't a real protocol itself, but used by Wireshark
20 /// > as a base for all the protocols on top of it.
21 impl Packet {
22 /// The frame number uniquely identifies a frame / packet.
23 pub(crate) const PACKET_ID: &'static str = "frame.number";
24
25 pub fn id(&self) -> PacketId {
26 self.metadata(Self::PACKET_ID)
27 .expect("Packet missing id / frame number")
28 .parse::<PacketId>()
29 .expect("Packet id / frame number invalid")
30 }
31
32 /// Retrieve packet metadata by key.
33 ///
34 /// Some metadata keys are associated with multiple values. In that case,
35 /// `all_metadata` should be called instead of `metadata`.
36 ///
37 /// Metadata keys are equivalent to Wireshark filters.
38 /// TLS values: https://www.wireshark.org/docs/dfref/t/tls.html
39 /// TCP values: https://www.wireshark.org/docs/dfref/t/tcp.html
40 pub(crate) fn metadata(&self, key: &str) -> Option<&str> {
41 let (layer_name, _) = key.split_once('.').expect("key is layer");
42 self.0
43 .layer_name(layer_name)
44 .and_then(|layer| layer.metadata(key))
45 .map(Metadata::value)
46 }
47
48 /// Retrieve a list of packet metadata by key.
49 ///
50 /// Metadata is equivalent to Wireshark filters.
51 /// TLS values: https://www.wireshark.org/docs/dfref/t/tls.html
52 /// TCP values: https://www.wireshark.org/docs/dfref/t/tcp.html
53 pub(crate) fn all_metadata(&self, key: &str) -> Vec<&str> {
54 let (layer_name, _) = key.split_once('.').expect("key is layer");
55 if let Some(layer) = self.0.layer_name(layer_name) {
56 layer
57 .iter()
58 .filter(|metadata| metadata.name() == key)
59 .map(Metadata::value)
60 .collect()
61 } else {
62 Vec::new()
63 }
64 }
65 }
66
67 pub(crate) struct PacketIterator(pub(crate) rtshark::RTShark);
68 impl Iterator for PacketIterator {
69 type Item = Packet;
70
71 fn next(&mut self) -> Option<Self::Item> {
72 let packet = self.0.read().expect("Failed to read from tshark");
73 packet.map(Packet)
74 }
75 }
76
77 impl PacketIterator {
78 pub(crate) fn into_lookup(self) -> HashMap<PacketId, Packet> {
79 self.map(|packet| (packet.id(), packet)).collect()
80 }
81 }