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#[derive(Clone, Debug)]
17pub struct TcpMeta {
18 pub src_addr: IpAddr,
20 pub src_port: u16,
22 pub dst_addr: IpAddr,
24 pub dst_port: u16,
26 pub seq_number: u32,
28 pub ack_number: u32,
30 pub flags: TcpFlags,
32 pub window: u16,
34
35 pub option_window_scale: Option<u8>,
38 pub option_timestamp: Option<(u32, u32)>,
40}
41
42#[derive(Clone, Default)]
44pub struct TcpFlags {
45 pub syn: bool,
47 pub ack: bool,
49 pub fin: bool,
51 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 let _ = has_prev;
83 write!(f, "]")?;
84 Ok(())
85 }
86}
87
88pub trait ConnectionHandler
90where
91 Self: Sized,
92{
93 type InitialData: Clone;
95 type ConstructError;
97 fn new(
99 init_data: Self::InitialData,
100 connection: &mut Connection<Self>,
101 ) -> Result<Self, Self::ConstructError>;
102 fn handshake_done(&mut self, _connection: &mut Connection<Self>) {}
104 fn data_received(&mut self, _connection: &mut Connection<Self>, _direction: Direction) {}
106 fn ack_received(&mut self, _connection: &mut Connection<Self>, _direction: Direction) {}
108 fn fin_received(&mut self, _connection: &mut Connection<Self>, _direction: Direction) {}
110 fn rst_received(
112 &mut self,
113 _connection: &mut Connection<Self>,
114 _direction: Direction,
115 _extra: PacketExtra,
116 ) {
117 }
118 fn stream_end(&mut self, _connection: &mut Connection<Self>, _direction: Direction) {}
120 fn connection_desync(&mut self, _connection: &mut Connection<Self>, _direction: Direction) {}
123 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}