From db00c5a170e440ce8c6374c2c89b672d8d9cbfa0 Mon Sep 17 00:00:00 2001 From: Pierre Chifflier Date: Wed, 25 Sep 2024 12:13:40 +0200 Subject: [PATCH] Run rustfmt over all crates and files (fix indentation) --- libpcap-analyzer/src/analyzer.rs | 2 +- libpcap-analyzer/src/erspan.rs | 2 +- libpcap-analyzer/src/geneve.rs | 4 +- libpcap-analyzer/src/ip_defrag.rs | 2 +- libpcap-analyzer/src/lib.rs | 5 +- libpcap-analyzer/src/mpls.rs | 2 +- libpcap-analyzer/src/output.rs | 2 +- libpcap-analyzer/src/plugins/basic_stats.rs | 48 ++++++++++++------- libpcap-analyzer/src/plugins/community_id.rs | 22 +++++---- libpcap-analyzer/src/plugins/examples.rs | 35 ++++++++++---- libpcap-analyzer/src/plugins/hexdump.rs | 21 ++++---- libpcap-analyzer/src/plugins/mod.rs | 16 ++++--- libpcap-analyzer/src/plugins/ospf.rs | 22 +++------ libpcap-analyzer/src/plugins/rusticata.rs | 4 +- libpcap-analyzer/src/ppp.rs | 2 +- libpcap-analyzer/src/pppoe.rs | 4 +- libpcap-analyzer/src/tcp_reassembly.rs | 3 +- libpcap-analyzer/src/vxlan.rs | 23 +++++---- libpcap-tools/src/duration.rs | 24 +++++----- libpcap-tools/src/error.rs | 6 ++- pcap-rewrite/src/filters/fragmentation/mod.rs | 2 +- .../two_tuple_proto_ipid_five_tuple.rs | 2 +- pcap-rewrite/src/filters/ipaddr_pair.rs | 4 +- pcap-rewrite/src/filters/ipv6_utils.rs | 4 +- pcap-rewrite/src/filters/key_parser_ipv6.rs | 28 +++++------ pcap-rewrite/src/main.rs | 10 ++-- pcap-rewrite/src/rewriter.rs | 9 ++-- pcap-rewrite/src/traits.rs | 7 ++- pcap-rewrite/tests/test_dispatch_filter.rs | 1 - 29 files changed, 182 insertions(+), 134 deletions(-) diff --git a/libpcap-analyzer/src/analyzer.rs b/libpcap-analyzer/src/analyzer.rs index 870d717..efb2d3d 100644 --- a/libpcap-analyzer/src/analyzer.rs +++ b/libpcap-analyzer/src/analyzer.rs @@ -15,11 +15,11 @@ use libpcap_tools::*; use pcap_parser::data::{get_packetdata_raw, PacketData}; use pcap_parser::Linktype; -use tracing::{span, Level}; use std::cmp::min; use std::net::IpAddr; use std::ops::DerefMut; use std::sync::Arc; +use tracing::{span, Level}; use pnet_packet::ethernet::{EtherType, EtherTypes, EthernetPacket}; use pnet_packet::gre::GrePacket; diff --git a/libpcap-analyzer/src/erspan.rs b/libpcap-analyzer/src/erspan.rs index cf42c44..c1e259e 100644 --- a/libpcap-analyzer/src/erspan.rs +++ b/libpcap-analyzer/src/erspan.rs @@ -12,7 +12,7 @@ impl<'a> ErspanPacket<'a> { #[inline] pub fn new(packet: &[u8]) -> Option { if packet.len() >= ErspanPacket::minimum_packet_size() { - use ::pnet_macros_support::packet::PacketData; + use pnet_macros_support::packet::PacketData; Some(ErspanPacket { packet: PacketData::Borrowed(packet), }) diff --git a/libpcap-analyzer/src/geneve.rs b/libpcap-analyzer/src/geneve.rs index 417c1d5..bb53b11 100644 --- a/libpcap-analyzer/src/geneve.rs +++ b/libpcap-analyzer/src/geneve.rs @@ -14,7 +14,7 @@ impl<'a> GenevePacket<'a> { #[inline] pub fn new(packet: &[u8]) -> Option { if packet.len() >= GenevePacket::minimum_packet_size() { - use ::pnet_macros_support::packet::PacketData; + use pnet_macros_support::packet::PacketData; Some(GenevePacket { packet: PacketData::Borrowed(packet), }) @@ -157,7 +157,7 @@ impl<'a> GeneveOptionPacket<'a> { #[inline] pub fn new(packet: &'_ [u8]) -> Option> { if packet.len() >= GeneveOptionPacket::minimum_packet_size() { - use ::pnet_macros_support::packet::PacketData; + use pnet_macros_support::packet::PacketData; Some(GeneveOptionPacket { packet: PacketData::Borrowed(packet), }) diff --git a/libpcap-analyzer/src/ip_defrag.rs b/libpcap-analyzer/src/ip_defrag.rs index 5943628..faeb516 100644 --- a/libpcap-analyzer/src/ip_defrag.rs +++ b/libpcap-analyzer/src/ip_defrag.rs @@ -149,7 +149,7 @@ impl DefragEngine for IPDefragEngine { } Ordering::Less => { // not fully covered - leave it - }, + } } } } diff --git a/libpcap-analyzer/src/lib.rs b/libpcap-analyzer/src/lib.rs index bf5d4a4..c032d71 100644 --- a/libpcap-analyzer/src/lib.rs +++ b/libpcap-analyzer/src/lib.rs @@ -12,12 +12,13 @@ pub use layers::*; pub use packet_info::*; mod plugin; -#[macro_use] mod plugin_registry; +#[macro_use] +mod plugin_registry; pub use plugin::*; pub use plugin_registry::*; -pub mod plugins; pub mod output; +pub mod plugins; mod analyzer; mod threaded_analyzer; diff --git a/libpcap-analyzer/src/mpls.rs b/libpcap-analyzer/src/mpls.rs index c19f33f..366a5ef 100644 --- a/libpcap-analyzer/src/mpls.rs +++ b/libpcap-analyzer/src/mpls.rs @@ -59,7 +59,7 @@ impl<'a> MplsPacket<'a> { if ptr.len() < 4 || packet.len() < stack_size || stack_size < 4 { return None; } - use ::pnet_macros_support::packet::PacketData; + use pnet_macros_support::packet::PacketData; Some(MplsPacket { packet: PacketData::Borrowed(packet), stack_size, diff --git a/libpcap-analyzer/src/output.rs b/libpcap-analyzer/src/output.rs index f60c188..5a08b13 100644 --- a/libpcap-analyzer/src/output.rs +++ b/libpcap-analyzer/src/output.rs @@ -13,4 +13,4 @@ pub fn create_file>(base: &str, filename: P) -> Result, } #[derive(Default)] pub struct BasicStats { - pub total_bytes_l3 : usize, - pub total_packets : usize, + pub total_bytes_l3: usize, + pub total_packets: usize, l3_conversations: IndexMap, l4_conversations: IndexMap, @@ -28,8 +28,12 @@ pub struct BasicStats { plugin_builder!(BasicStats, BasicStatsBuilder); impl Plugin for BasicStats { - fn name(&self) -> &'static str { "BasicStats" } - fn plugin_type(&self) -> u16 { PLUGIN_L3|PLUGIN_L4 } + fn name(&self) -> &'static str { + "BasicStats" + } + fn plugin_type(&self) -> u16 { + PLUGIN_L3 | PLUGIN_L4 + } fn handle_layer_network<'s, 'i>( &'s mut self, @@ -51,7 +55,10 @@ impl Plugin for BasicStats { _packet: &'s Packet, pinfo: &PacketInfo, ) -> PluginResult<'i> { - let entry = self.l4_conversations.entry(pinfo.five_tuple.clone()).or_default(); + let entry = self + .l4_conversations + .entry(pinfo.five_tuple.clone()) + .or_default(); entry.num_bytes += pinfo.l4_payload.map(|l4| l4.len()).unwrap_or(0); if let Some(flow) = pinfo.flow { entry.flow_id = Some(flow.flow_id); @@ -68,8 +75,8 @@ impl Plugin for BasicStats { fn save_results(&mut self, path: &str) -> Result<(), &'static str> { let results = self.get_results_json(); // save data to file - let file = output::create_file(path, "basic-stats.json") - .or(Err("Cannot create output file"))?; + let file = + output::create_file(path, "basic-stats.json").or(Err("Cannot create output file"))?; serde_json::to_writer(file, &results).or(Err("Cannot save results to file"))?; Ok(()) } @@ -79,12 +86,15 @@ impl BasicStats { fn get_results_json(&mut self) -> Value { self.l3_conversations.sort_keys(); self.l4_conversations.sort_keys(); - let total_l4 = self.l4_conversations + let total_l4 = self + .l4_conversations .iter() - .map(|(_,stats)| stats.num_bytes) + .map(|(_, stats)| stats.num_bytes) .sum::(); - let l3 : Vec<_> = self.l3_conversations.iter() - .map(|(t3,s)| { + let l3: Vec<_> = self + .l3_conversations + .iter() + .map(|(t3, s)| { if let Value::Object(mut m) = json!(t3) { m.insert("num_bytes".into(), s.num_bytes.into()); m.insert("num_packets".into(), s.num_packets.into()); @@ -94,8 +104,10 @@ impl BasicStats { } }) .collect(); - let l4 : Vec<_> = self.l4_conversations.iter() - .map(|(t5,s)| { + let l4: Vec<_> = self + .l4_conversations + .iter() + .map(|(t5, s)| { if let Value::Object(mut m) = json!(t5) { m.insert("num_bytes".into(), s.num_bytes.into()); m.insert("num_packets".into(), s.num_packets.into()); @@ -117,4 +129,4 @@ impl BasicStats { }); js } -} \ No newline at end of file +} diff --git a/libpcap-analyzer/src/plugins/community_id.rs b/libpcap-analyzer/src/plugins/community_id.rs index 41df6f4..3e7cc64 100644 --- a/libpcap-analyzer/src/plugins/community_id.rs +++ b/libpcap-analyzer/src/plugins/community_id.rs @@ -5,14 +5,14 @@ use crate::output; use crate::plugin_registry::PluginRegistry; use libpcap_tools::{Config, FlowID}; -use crate::plugin::{Plugin, PluginBuilderError, PluginResult}; use crate::packet_info::PacketInfo; use crate::plugin::PLUGIN_L4; +use crate::plugin::{Plugin, PluginBuilderError, PluginResult}; use base64ct::{Base64, Encoding}; use indexmap::IndexMap; use libpcap_tools::{FiveTuple, Packet}; use serde_json::json; -use sha1::{Sha1, Digest}; +use sha1::{Digest, Sha1}; use std::any::Any; use std::net::IpAddr; @@ -25,12 +25,18 @@ pub struct CommunityID { pub struct CommunityIDBuilder; impl crate::plugin::PluginBuilder for CommunityIDBuilder { - fn name(&self) -> &'static str { "CommunityIDBuilder" } - fn build(&self, registry:&mut PluginRegistry, config:&Config) -> Result<(), PluginBuilderError> { + fn name(&self) -> &'static str { + "CommunityIDBuilder" + } + fn build( + &self, + registry: &mut PluginRegistry, + config: &Config, + ) -> Result<(), PluginBuilderError> { let seed = config.get_usize("plugin.community_id.seed").unwrap_or(0) as u16; - let plugin = CommunityID{ + let plugin = CommunityID { seed, - ids:IndexMap::new(), + ids: IndexMap::new(), }; let safe_p = build_safeplugin!(plugin); let id = registry.add_plugin(safe_p); @@ -121,8 +127,8 @@ impl Plugin for CommunityID { fn save_results(&mut self, path: &str) -> Result<(), &'static str> { let results = self.get_results_json(); // save data to file - let file = output::create_file(path, "community-ids.json") - .or(Err("Cannot create output file"))?; + let file = + output::create_file(path, "community-ids.json").or(Err("Cannot create output file"))?; serde_json::to_writer(file, &results).or(Err("Cannot save results to file"))?; Ok(()) } diff --git a/libpcap-analyzer/src/plugins/examples.rs b/libpcap-analyzer/src/plugins/examples.rs index 030872e..70db7b6 100644 --- a/libpcap-analyzer/src/plugins/examples.rs +++ b/libpcap-analyzer/src/plugins/examples.rs @@ -1,6 +1,6 @@ -use crate::plugin_registry::PluginRegistry; -use crate::plugin::{Plugin, PluginBuilderError, PLUGIN_NONE}; use crate::default_plugin_builder; +use crate::plugin::{Plugin, PluginBuilderError, PLUGIN_NONE}; +use crate::plugin_registry::PluginRegistry; use libpcap_tools::Config; /// Example plugin, without configuration @@ -11,8 +11,12 @@ pub struct Empty; default_plugin_builder!(Empty, EmptyBuilder); impl Plugin for Empty { - fn name(&self) -> &'static str { "Empty" } - fn plugin_type(&self) -> u16 { PLUGIN_NONE } + fn name(&self) -> &'static str { + "Empty" + } + fn plugin_type(&self) -> u16 { + PLUGIN_NONE + } } /// Example plugin, reading a configuration value @@ -22,11 +26,18 @@ pub struct EmptyWithConfig { } impl Plugin for EmptyWithConfig { - fn name(&self) -> &'static str { "EmptyWithConfig" } - fn plugin_type(&self) -> u16 { PLUGIN_NONE } + fn name(&self) -> &'static str { + "EmptyWithConfig" + } + fn plugin_type(&self) -> u16 { + PLUGIN_NONE + } fn pre_process(&mut self) { - info!("Hello, I am plugin EmptyWithConfig, with name {:?}", self.name); + info!( + "Hello, I am plugin EmptyWithConfig, with name {:?}", + self.name + ); } } @@ -36,8 +47,14 @@ impl Plugin for EmptyWithConfig { pub struct EmptyWithConfigBuilder; impl crate::plugin::PluginBuilder for EmptyWithConfigBuilder { - fn name(&self) -> &'static str { "EmptyWithConfigBuilder" } - fn build(&self, registry:&mut PluginRegistry, config:&Config) -> Result<(), PluginBuilderError> { + fn name(&self) -> &'static str { + "EmptyWithConfigBuilder" + } + fn build( + &self, + registry: &mut PluginRegistry, + config: &Config, + ) -> Result<(), PluginBuilderError> { let name = config.get("plugin.emptywithconfig.name"); let plugin = EmptyWithConfig { name: name.map(|s| s.to_string()), diff --git a/libpcap-analyzer/src/plugins/hexdump.rs b/libpcap-analyzer/src/plugins/hexdump.rs index 437e74d..83eaceb 100644 --- a/libpcap-analyzer/src/plugins/hexdump.rs +++ b/libpcap-analyzer/src/plugins/hexdump.rs @@ -16,7 +16,7 @@ impl Plugin for HexDump { "HexDump" } fn plugin_type(&self) -> u16 { - PLUGIN_L3|PLUGIN_L4 + PLUGIN_L3 | PLUGIN_L4 } fn handle_layer_network<'s, 'i>( @@ -44,15 +44,20 @@ impl Plugin for HexDump { debug!(" l3_type: 0x{:x}", pinfo.l3_type); debug!(" l4_data_len: {}", pinfo.l4_data.len()); debug!(" l4_type: {}", pinfo.l4_type); - debug!(" l4_payload_len: {}", pinfo.l4_payload.map_or(0, |d| d.len())); + debug!( + " l4_payload_len: {}", + pinfo.l4_payload.map_or(0, |d| d.len()) + ); if let Some(flow) = pinfo.flow { let five_tuple = &flow.five_tuple; - debug!(" flow: [{}]:{} -> [{}]:{} [{}]", - five_tuple.src, - five_tuple.src_port, - five_tuple.dst, - five_tuple.dst_port, - five_tuple.proto); + debug!( + " flow: [{}]:{} -> [{}]:{} [{}]", + five_tuple.src, + five_tuple.src_port, + five_tuple.dst, + five_tuple.dst_port, + five_tuple.proto + ); } if let Some(d) = pinfo.l4_payload { debug!(" l4_payload:\n{}", d.to_hex(16)); diff --git a/libpcap-analyzer/src/plugins/mod.rs b/libpcap-analyzer/src/plugins/mod.rs index 3858c2c..dd4171c 100644 --- a/libpcap-analyzer/src/plugins/mod.rs +++ b/libpcap-analyzer/src/plugins/mod.rs @@ -50,13 +50,17 @@ impl PluginsFactory { for b in &self.list { b.build(&mut registry, config)?; - }; + } Ok(registry) } /// Instantiate plugins if they match predicate - pub fn build_filter_plugins

(&self, predicate: P, config: &Config) -> Result + pub fn build_filter_plugins

( + &self, + predicate: P, + config: &Config, + ) -> Result where P: Fn(&str) -> bool, { @@ -66,7 +70,7 @@ impl PluginsFactory { if predicate(b.name()) { b.build(&mut registry, config)?; } - }; + } Ok(registry) } @@ -76,9 +80,7 @@ impl PluginsFactory { where Op: Fn(&str), { - self.list.iter().for_each(|b| { - op(b.name()) - }); + self.list.iter().for_each(|b| op(b.name())); } } @@ -88,7 +90,7 @@ impl Default for PluginsFactory { let mut v: Vec> = vec![ Box::new(basic_stats::BasicStatsBuilder), Box::new(flows::FlowsInfoBuilder), - ]; + ]; #[cfg(feature = "plugin_community_id")] v.push(Box::new(community_id::CommunityIDBuilder)); diff --git a/libpcap-analyzer/src/plugins/ospf.rs b/libpcap-analyzer/src/plugins/ospf.rs index b1a45d7..49aacc5 100644 --- a/libpcap-analyzer/src/plugins/ospf.rs +++ b/libpcap-analyzer/src/plugins/ospf.rs @@ -206,40 +206,30 @@ impl OspfLog { l.metric, l.destination_router_id ); } - Ospfv3LinkStateAdvertisement::ASExternal(l) | - Ospfv3LinkStateAdvertisement::NSSA(l) => { - debug!( - " type={} metric={}", - l.header.link_state_type, - l.metric - ); + Ospfv3LinkStateAdvertisement::ASExternal(l) | Ospfv3LinkStateAdvertisement::NSSA(l) => { + debug!(" type={} metric={}", l.header.link_state_type, l.metric); } Ospfv3LinkStateAdvertisement::Link(l) => { debug!( " LinksLSA link_local_interface_address={:x?} #prefixes={}", - &l.link_local_interface_address, - l.num_prefixes, + &l.link_local_interface_address, l.num_prefixes, ); for prefix in &l.address_prefixes { debug!( " IPv6 prefix {:02x?}/{}", - prefix.address_prefix, - prefix.prefix_length, + prefix.address_prefix, prefix.prefix_length, ); } } Ospfv3LinkStateAdvertisement::IntraAreaPrefix(l) => { debug!( " IntraAreaPrefixLSA referenced_ls_type={} #prefixes={}", - l.referenced_ls_type, - l.num_prefixes, + l.referenced_ls_type, l.num_prefixes, ); for prefix in &l.address_prefixes { debug!( " IPv6 prefix {:02x?}/{} metric={}", - prefix.address_prefix, - prefix.prefix_length, - prefix.reserved, + prefix.address_prefix, prefix.prefix_length, prefix.reserved, ); } } diff --git a/libpcap-analyzer/src/plugins/rusticata.rs b/libpcap-analyzer/src/plugins/rusticata.rs index d65c64e..b2d521e 100644 --- a/libpcap-analyzer/src/plugins/rusticata.rs +++ b/libpcap-analyzer/src/plugins/rusticata.rs @@ -1,7 +1,7 @@ use crate::default_plugin_builder; +use crate::output; use crate::packet_info::PacketInfo; use crate::plugin::{Plugin, PluginResult, PLUGIN_FLOW_DEL, PLUGIN_L4}; -use crate::output; use fnv::{FnvHashMap, FnvHashSet}; use libpcap_tools::{Flow, FlowID, Packet}; use rusticata::prologue::*; @@ -211,7 +211,7 @@ impl Plugin for Rusticata { let v = self.get_results_json(); Some(Box::new(v)) } - + fn save_results(&mut self, path: &str) -> Result<(), &'static str> { let results = self.get_results_json(); // save data to file diff --git a/libpcap-analyzer/src/ppp.rs b/libpcap-analyzer/src/ppp.rs index a2ce714..a7c7f49 100644 --- a/libpcap-analyzer/src/ppp.rs +++ b/libpcap-analyzer/src/ppp.rs @@ -29,7 +29,7 @@ impl<'a> PppPacket<'a> { if packet[0] == 0xff && packet[1] == 0x03 && packet.len() < 4 { return None; } - use ::pnet_macros_support::packet::PacketData; + use pnet_macros_support::packet::PacketData; Some(PppPacket { packet: PacketData::Borrowed(packet), }) diff --git a/libpcap-analyzer/src/pppoe.rs b/libpcap-analyzer/src/pppoe.rs index 90a1111..89162f2 100644 --- a/libpcap-analyzer/src/pppoe.rs +++ b/libpcap-analyzer/src/pppoe.rs @@ -12,7 +12,7 @@ impl<'a> PppoeSessionPacket<'a> { #[inline] pub fn new(packet: &[u8]) -> Option { if packet.len() >= PppoeSessionPacket::minimum_packet_size() { - use ::pnet_macros_support::packet::PacketData; + use pnet_macros_support::packet::PacketData; Some(PppoeSessionPacket { packet: PacketData::Borrowed(packet), }) @@ -76,4 +76,4 @@ impl<'a> ::pnet_macros_support::packet::Packet for PppoeSessionPacket<'a> { } &_self.packet[start..end] } -} \ No newline at end of file +} diff --git a/libpcap-analyzer/src/tcp_reassembly.rs b/libpcap-analyzer/src/tcp_reassembly.rs index 6f2f250..3073f32 100644 --- a/libpcap-analyzer/src/tcp_reassembly.rs +++ b/libpcap-analyzer/src/tcp_reassembly.rs @@ -9,8 +9,7 @@ use std::num::Wrapping; const EARLY_DETECT_OVERLAP: bool = false; -#[derive(Debug, Eq, PartialEq)] -#[derive(Default)] +#[derive(Debug, Eq, PartialEq, Default)] #[allow(dead_code)] pub enum TcpStatus { #[default] diff --git a/libpcap-analyzer/src/vxlan.rs b/libpcap-analyzer/src/vxlan.rs index b348920..9485972 100644 --- a/libpcap-analyzer/src/vxlan.rs +++ b/libpcap-analyzer/src/vxlan.rs @@ -12,7 +12,9 @@ pub struct VxlanFlag(pub u16); impl VxlanFlag { /// Create a new `VxlanFlag` instance. - pub fn new(value: u16) -> VxlanFlag { VxlanFlag(value) } + pub fn new(value: u16) -> VxlanFlag { + VxlanFlag(value) + } } /// Vxlan flags as defined in RFC7348 @@ -25,21 +27,26 @@ pub mod VxlanFlags { pub const VNI: VxlanFlag = VxlanFlag(0x0800); } - -impl <'a> VxlanPacket<'a> { +impl<'a> VxlanPacket<'a> { /// Constructs a new VxlanPacket. If the provided buffer is less than the minimum required /// packet size, this will return None. #[inline] pub fn new(packet: &[u8]) -> Option { if packet.len() >= VxlanPacket::minimum_packet_size() { - use ::pnet_macros_support::packet::PacketData; - Some(VxlanPacket{packet: PacketData::Borrowed(packet),}) - } else { None } + use pnet_macros_support::packet::PacketData; + Some(VxlanPacket { + packet: PacketData::Borrowed(packet), + }) + } else { + None + } } /// The minimum size (in bytes) a packet of this type can be. It's based on the total size /// of the fixed-size fields. #[inline] - pub const fn minimum_packet_size() -> usize { 8 } + pub const fn minimum_packet_size() -> usize { + 8 + } /// Get the flags field. This field is always stored big-endian /// within the struct, but this accessor returns host order. #[inline] @@ -90,4 +97,4 @@ mod tests { assert_eq!(packet.get_vlan_identifier(), 123); assert_eq!(packet.get_flags(), VxlanFlags::VNI.0); } -} \ No newline at end of file +} diff --git a/libpcap-tools/src/duration.rs b/libpcap-tools/src/duration.rs index d3cfffc..30a14c4 100644 --- a/libpcap-tools/src/duration.rs +++ b/libpcap-tools/src/duration.rs @@ -1,4 +1,4 @@ -use std::ops::{Add,Sub}; +use std::ops::{Add, Sub}; /// Reimplementation of std::time::Duration, but panic-free /// and partial, only to match our needs: @@ -14,8 +14,8 @@ pub const MICROS_PER_SEC: u32 = 1_000_000; impl Duration { /// Build Duration from secs and micros - pub fn new(secs:u32, micros:u32) -> Duration { - Duration{ secs, micros } + pub fn new(secs: u32, micros: u32) -> Duration { + Duration { secs, micros } } /// Test if Duration object is null #[inline] @@ -31,13 +31,13 @@ impl Add for Duration { fn add(self, other: Duration) -> Self::Output { let secs = self.secs.wrapping_add(other.secs); let micros = self.micros.wrapping_add(other.micros); - let (secs,micros) = if micros > MICROS_PER_SEC { + let (secs, micros) = if micros > MICROS_PER_SEC { (secs + (micros / MICROS_PER_SEC), micros % MICROS_PER_SEC) } else { - (secs,micros) + (secs, micros) }; - Duration{ secs, micros } + Duration { secs, micros } } } @@ -47,16 +47,16 @@ impl Sub for Duration { #[allow(clippy::suspicious_arithmetic_impl)] fn sub(self, other: Duration) -> Self::Output { let secs = self.secs.wrapping_sub(other.secs); - let (secs,micros) = if self.micros >= other.micros { - (secs,self.micros - other.micros) + let (secs, micros) = if self.micros >= other.micros { + (secs, self.micros - other.micros) } else { let diff = other.micros.wrapping_sub(self.micros); let secs_less = diff / MICROS_PER_SEC; let micros = MICROS_PER_SEC - diff; - (secs.wrapping_sub(1 + secs_less),micros) + (secs.wrapping_sub(1 + secs_less), micros) }; - Duration{ secs, micros } + Duration { secs, micros } } } @@ -68,7 +68,7 @@ mod tests { let d1 = Duration::new(1234, 5678); let d2 = Duration::new(1234, 6789); let d = d2 - d1; - assert_eq!(d.secs,0); - assert_eq!(d.micros,1111); + assert_eq!(d.secs, 0); + assert_eq!(d.micros, 1111); } } diff --git a/libpcap-tools/src/error.rs b/libpcap-tools/src/error.rs index e636f42..30b7f09 100644 --- a/libpcap-tools/src/error.rs +++ b/libpcap-tools/src/error.rs @@ -41,7 +41,11 @@ impl<'a> From>> for Error { fn from(err: Err>) -> Self { match err { Err::Incomplete(needed) => { - let sz = if let Needed::Size(sz) = needed { usize::from(sz) } else { 0 }; + let sz = if let Needed::Size(sz) = needed { + usize::from(sz) + } else { + 0 + }; Error::Pcap(PcapError::Incomplete(sz)) } Err::Error(e) | Err::Failure(e) => Error::Pcap(e.to_owned_vec()), diff --git a/pcap-rewrite/src/filters/fragmentation/mod.rs b/pcap-rewrite/src/filters/fragmentation/mod.rs index dfc8ece..f2abde6 100644 --- a/pcap-rewrite/src/filters/fragmentation/mod.rs +++ b/pcap-rewrite/src/filters/fragmentation/mod.rs @@ -1,6 +1,6 @@ pub mod convert_fn; pub mod fragmentation_filter; pub mod fragmentation_test; +pub mod key_fragmentation_matching; pub mod two_tuple_proto_ipid; pub mod two_tuple_proto_ipid_five_tuple; -pub mod key_fragmentation_matching; diff --git a/pcap-rewrite/src/filters/fragmentation/two_tuple_proto_ipid_five_tuple.rs b/pcap-rewrite/src/filters/fragmentation/two_tuple_proto_ipid_five_tuple.rs index 29f7555..624ee72 100644 --- a/pcap-rewrite/src/filters/fragmentation/two_tuple_proto_ipid_five_tuple.rs +++ b/pcap-rewrite/src/filters/fragmentation/two_tuple_proto_ipid_five_tuple.rs @@ -30,4 +30,4 @@ impl TwoTupleProtoIpidFiveTuple { pub fn get_five_tuple_option(&self) -> Option<&FiveTuple> { self.five_tuple_option.as_ref() } -} \ No newline at end of file +} diff --git a/pcap-rewrite/src/filters/ipaddr_pair.rs b/pcap-rewrite/src/filters/ipaddr_pair.rs index 12cf37f..76f2a12 100644 --- a/pcap-rewrite/src/filters/ipaddr_pair.rs +++ b/pcap-rewrite/src/filters/ipaddr_pair.rs @@ -1,9 +1,9 @@ use std::net::IpAddr; -pub struct IpAddrPair (pub IpAddr,pub IpAddr); +pub struct IpAddrPair(pub IpAddr, pub IpAddr); impl IpAddrPair { pub fn new(ipaddr_0: IpAddr, ipaddr_1: IpAddr) -> IpAddrPair { - IpAddrPair (ipaddr_0, ipaddr_1 ) + IpAddrPair(ipaddr_0, ipaddr_1) } } diff --git a/pcap-rewrite/src/filters/ipv6_utils.rs b/pcap-rewrite/src/filters/ipv6_utils.rs index f0c2c4d..b02cd99 100644 --- a/pcap-rewrite/src/filters/ipv6_utils.rs +++ b/pcap-rewrite/src/filters/ipv6_utils.rs @@ -40,7 +40,9 @@ pub fn get_fragment_packet_option_l4_protol4_payload<'a>( if data.len() >= 40 { payload = &data[40..]; } else { - return Err(Error::DataParser("IPv6 length is 0, but frame is too short for an IPv6 header")); + return Err(Error::DataParser( + "IPv6 length is 0, but frame is too short for an IPv6 header", + )); } } diff --git a/pcap-rewrite/src/filters/key_parser_ipv6.rs b/pcap-rewrite/src/filters/key_parser_ipv6.rs index d950ba0..bb48349 100644 --- a/pcap-rewrite/src/filters/key_parser_ipv6.rs +++ b/pcap-rewrite/src/filters/key_parser_ipv6.rs @@ -12,9 +12,9 @@ use libpcap_tools::{Error, FiveTuple, ParseContext}; use super::fragmentation::two_tuple_proto_ipid::TwoTupleProtoIpid; use super::fragmentation::two_tuple_proto_ipid_five_tuple::TwoTupleProtoIpidFiveTuple; +use crate::filters::fragmentation::fragmentation_test; use crate::filters::fragmentation::key_fragmentation_matching::KeyFragmentationMatching; use crate::filters::ipaddr_pair::IpAddrPair; -use crate::filters::fragmentation::fragmentation_test; pub fn parse_src_ipaddr(ctx: &ParseContext, payload: &[u8]) -> Result { let ipv6 = Ipv6Packet::new(payload).ok_or_else(|| { @@ -274,7 +274,7 @@ pub fn parse_key_fragmentation_transport( payload: &[u8], ) -> Result>, Error> { if fragmentation_test::is_ipv6_fragment(ctx, payload)? { - let two_tuple_proto_ipid = + let two_tuple_proto_ipid = parse_two_tuple_proto_ipid(ctx, payload)?.ok_or_else(|| { warn!( "Could not parse TwoTupleProtoId, expected fragmented IPv6 packet but could not parse at index {}", @@ -287,21 +287,17 @@ pub fn parse_key_fragmentation_transport( )?; if fragmentation_test::is_ipv6_first_fragment(ctx, payload)? { match key_parse(ctx, payload)? { - Some(key) => { - Ok(KeyFragmentationMatching::FirstFragment( - two_tuple_proto_ipid, - Some(key) - )) - }, + Some(key) => Ok(KeyFragmentationMatching::FirstFragment( + two_tuple_proto_ipid, + Some(key), + )), // NB // This case happens when the first fragment does have enough data to parse transport header. // The clean approach would be to a full IP fragmentation reassembly. // We hope this case is rare. :) - None => { - Ok(KeyFragmentationMatching::FragmentAfterFirst( - two_tuple_proto_ipid, - )) - } + None => Ok(KeyFragmentationMatching::FragmentAfterFirst( + two_tuple_proto_ipid, + )), } } else { Ok(KeyFragmentationMatching::FragmentAfterFirst( @@ -309,9 +305,9 @@ pub fn parse_key_fragmentation_transport( )) } } else { - Ok(KeyFragmentationMatching::NotFragment( - key_parse(ctx, payload)?, - )) + Ok(KeyFragmentationMatching::NotFragment(key_parse( + ctx, payload, + )?)) } } diff --git a/pcap-rewrite/src/main.rs b/pcap-rewrite/src/main.rs index f96b91e..7f1f69b 100644 --- a/pcap-rewrite/src/main.rs +++ b/pcap-rewrite/src/main.rs @@ -4,11 +4,11 @@ use clap::{crate_version, Parser}; use libpcap_tools::Config; use log::{debug, error}; -use tracing::Level; -use tracing_subscriber::EnvFilter; use std::fs::File; use std::io; use std::path::Path; +use tracing::Level; +use tracing_subscriber::EnvFilter; use pcap_rewrite::filters::dispatch_filter::DispatchFilterBuilder; use pcap_rewrite::filters::filtering_action::FilteringAction; @@ -32,18 +32,18 @@ struct Args { /// -f Source:192.168.1.1 /// -f Dispatch:fk%fa%path /// -f Dispatch:fk%fa - /// + /// /// fk: filtering key=si|di|sdi|sipdp|sdipsdp /// with si: src IP /// di: dst IP /// sdi: srd/dst IP /// sipdp: src IP, proto, dst port /// sdipsdp: src/dst IP, proto, src/dst port - /// + /// /// fa: filtering action=k|d /// with k: keep /// d: drop - /// + /// /// path: path to a csv formatted file without header that contains filtering keys #[clap(verbatim_doc_comment)] #[arg(short, long)] diff --git a/pcap-rewrite/src/rewriter.rs b/pcap-rewrite/src/rewriter.rs index 8e56c25..60febde 100644 --- a/pcap-rewrite/src/rewriter.rs +++ b/pcap-rewrite/src/rewriter.rs @@ -7,9 +7,8 @@ use log::{debug, error, info}; use pcap_parser::data::*; use pcap_parser::Linktype; use pcap_parser::{Block, PcapBlockOwned}; -use tracing::span; -use tracing::Level; use std::io::Write; +use tracing::{span, Level}; #[derive(Copy, Clone, Debug)] pub enum FileFormat { @@ -127,7 +126,11 @@ impl PcapAnalyzer for Rewriter { ) -> Result<(), Error> { // handle specific pcapng blocks if let PcapBlockOwned::NG(b) = block { - let span = span!(Level::DEBUG, "handle_block", block_index = block_ctx.block_index); + let span = span!( + Level::DEBUG, + "handle_block", + block_index = block_ctx.block_index + ); let _enter = span.enter(); match b { diff --git a/pcap-rewrite/src/traits.rs b/pcap-rewrite/src/traits.rs index c9321bc..5dff68b 100644 --- a/pcap-rewrite/src/traits.rs +++ b/pcap-rewrite/src/traits.rs @@ -7,5 +7,10 @@ pub trait Writer { fn write_block(&mut self, _block: &PcapBlockOwned) -> Result; - fn write_packet(&mut self, packet: &Packet, data: &[u8], payload_length_offset: u32) -> Result; + fn write_packet( + &mut self, + packet: &Packet, + data: &[u8], + payload_length_offset: u32, + ) -> Result; } diff --git a/pcap-rewrite/tests/test_dispatch_filter.rs b/pcap-rewrite/tests/test_dispatch_filter.rs index 92d9853..0af8963 100644 --- a/pcap-rewrite/tests/test_dispatch_filter.rs +++ b/pcap-rewrite/tests/test_dispatch_filter.rs @@ -163,7 +163,6 @@ fn test_filter_ipv6_src_ipaddr_proto_dst_port() { ) } - #[test] fn test_filter_ipv6_five_tuple() { generic_test(