parse_tcp/
lib.rs

1use std::fmt::Debug;
2use std::net::IpAddr;
3
4use connection::{Connection, Direction};
5use serialized::PacketExtra;
6
7pub mod connection;
8pub mod emit;
9pub mod flow_table;
10pub mod handler;
11pub mod parser;
12pub mod serialized;
13pub mod stream;
14
15/// TCP packet metadata
16#[derive(Clone, Debug)]
17pub struct TcpMeta {
18    /// source address
19    pub src_addr: IpAddr,
20    /// source port
21    pub src_port: u16,
22    /// destination address
23    pub dst_addr: IpAddr,
24    /// destination port
25    pub dst_port: u16,
26    /// sequence number
27    pub seq_number: u32,
28    /// acknowledgment number
29    pub ack_number: u32,
30    /// packet flags
31    pub flags: TcpFlags,
32    /// raw window value
33    pub window: u16,
34
35    // options
36    /// window scale option
37    pub option_window_scale: Option<u8>,
38    /// timestamp option (value, echo)
39    pub option_timestamp: Option<(u32, u32)>,
40}
41
42/// TCP packet flags (at least, the ones we care about)
43#[derive(Clone, Default)]
44pub struct TcpFlags {
45    /// SYN flag
46    pub syn: bool,
47    /// ACK flag
48    pub ack: bool,
49    /// FIN flag
50    pub fin: bool,
51    /// RST flag
52    pub rst: bool,
53}
54
55impl Debug for TcpFlags {
56    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
57        write!(f, "[")?;
58        let mut has_prev = false;
59        macro_rules! write_flag {
60            ($flag:expr) => {
61                if has_prev {
62                    write!(f, ", ")?;
63                } else {
64                    has_prev = true;
65                }
66                write!(f, $flag)?;
67            };
68        }
69        if self.syn {
70            write_flag!("SYN");
71        }
72        if self.ack {
73            write_flag!("ACK");
74        }
75        if self.fin {
76            write_flag!("FIN");
77        }
78        if self.rst {
79            write_flag!("RST");
80        }
81        // silence warning
82        let _ = has_prev;
83        write!(f, "]")?;
84        Ok(())
85    }
86}
87
88/// event handler for connection object
89pub trait ConnectionHandler
90where
91    Self: Sized,
92{
93    /// initial data provided to new
94    type InitialData: Clone;
95    /// error type raised from new
96    type ConstructError;
97    /// construct handler object
98    fn new(
99        init_data: Self::InitialData,
100        connection: &mut Connection<Self>,
101    ) -> Result<Self, Self::ConstructError>;
102    /// called on handshake finish (or incomplete handshake)
103    fn handshake_done(&mut self, _connection: &mut Connection<Self>) {}
104    /// called on data received
105    fn data_received(&mut self, _connection: &mut Connection<Self>, _direction: Direction) {}
106    /// called when data is acked, direction is of the ack packet, not the stream
107    fn ack_received(&mut self, _connection: &mut Connection<Self>, _direction: Direction) {}
108    /// called on FIN
109    fn fin_received(&mut self, _connection: &mut Connection<Self>, _direction: Direction) {}
110    /// called on RST
111    fn rst_received(
112        &mut self,
113        _connection: &mut Connection<Self>,
114        _direction: Direction,
115        _extra: PacketExtra,
116    ) {
117    }
118    /// ACK for FIN received for stream
119    fn stream_end(&mut self, _connection: &mut Connection<Self>, _direction: Direction) {}
120    /// connection fatally desynchronized, `direction` is our best guess for the
121    /// direction of the packet which caused the desync
122    fn connection_desync(&mut self, _connection: &mut Connection<Self>, _direction: Direction) {}
123    /// called when the connection is removed from the hashtable
124    fn will_retire(&mut self, _connection: &mut Connection<Self>) {}
125}
126
127pub fn setup_log_handlers() {
128    use tracing_error::ErrorLayer;
129    use tracing_subscriber::prelude::*;
130    use tracing_subscriber::{fmt, EnvFilter};
131
132    color_eyre::install().unwrap();
133
134    let fmt_layer = fmt::layer();
135    let filter_layer = EnvFilter::try_from_default_env()
136        .or_else(|_| EnvFilter::try_new("info"))
137        .unwrap();
138
139    tracing_subscriber::registry()
140        .with(filter_layer)
141        .with(fmt_layer)
142        .with(ErrorLayer::default())
143        .init();
144}
145
146pub fn initialize_logging() {
147    use parking_lot::Once;
148
149    static INITIALIZE: Once = Once::new();
150    INITIALIZE.call_once(setup_log_handlers);
151}