Skip to content

Commit

Permalink
Run rustfmt over all crates and files (fix indentation)
Browse files Browse the repository at this point in the history
  • Loading branch information
pc-anssi committed Sep 25, 2024
1 parent 8e9073d commit db00c5a
Show file tree
Hide file tree
Showing 29 changed files with 182 additions and 134 deletions.
2 changes: 1 addition & 1 deletion libpcap-analyzer/src/analyzer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
2 changes: 1 addition & 1 deletion libpcap-analyzer/src/erspan.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ impl<'a> ErspanPacket<'a> {
#[inline]
pub fn new(packet: &[u8]) -> Option<ErspanPacket> {
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),
})
Expand Down
4 changes: 2 additions & 2 deletions libpcap-analyzer/src/geneve.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ impl<'a> GenevePacket<'a> {
#[inline]
pub fn new(packet: &[u8]) -> Option<GenevePacket> {
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),
})
Expand Down Expand Up @@ -157,7 +157,7 @@ impl<'a> GeneveOptionPacket<'a> {
#[inline]
pub fn new(packet: &'_ [u8]) -> Option<GeneveOptionPacket<'_>> {
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),
})
Expand Down
2 changes: 1 addition & 1 deletion libpcap-analyzer/src/ip_defrag.rs
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,7 @@ impl DefragEngine for IPDefragEngine {
}
Ordering::Less => {
// not fully covered - leave it
},
}
}
}
}
Expand Down
5 changes: 3 additions & 2 deletions libpcap-analyzer/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
2 changes: 1 addition & 1 deletion libpcap-analyzer/src/mpls.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
2 changes: 1 addition & 1 deletion libpcap-analyzer/src/output.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,4 +13,4 @@ pub fn create_file<P: AsRef<str>>(base: &str, filename: P) -> Result<File, Error
let mut path = PathBuf::from(base);
path.push(filename.as_ref());
File::create(path)
}
}
48 changes: 30 additions & 18 deletions libpcap-analyzer/src/plugins/basic_stats.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
use crate::plugin::{Plugin, PluginResult};
use crate::plugin_builder;
use crate::output;
use crate::packet_info::PacketInfo;
use crate::plugin::{Plugin, PluginResult};
use crate::plugin::{PLUGIN_L3, PLUGIN_L4};
use crate::plugin_builder;
use indexmap::IndexMap;
use libpcap_tools::{FiveTuple, FlowID, Packet, ThreeTuple};
use serde::Serialize;
Expand All @@ -11,15 +11,15 @@ use std::any::Any;

#[derive(Default, Serialize)]
struct Stats {
num_bytes : usize,
num_packets : usize,
num_bytes: usize,
num_packets: usize,
flow_id: Option<FlowID>,
}

#[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<ThreeTuple, Stats>,
l4_conversations: IndexMap<FiveTuple, Stats>,
Expand All @@ -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,
Expand All @@ -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);
Expand All @@ -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(())
}
Expand All @@ -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::<usize>();
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());
Expand All @@ -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());
Expand All @@ -117,4 +129,4 @@ impl BasicStats {
});
js
}
}
}
22 changes: 14 additions & 8 deletions libpcap-analyzer/src/plugins/community_id.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand All @@ -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);
Expand Down Expand Up @@ -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(())
}
Expand Down
35 changes: 26 additions & 9 deletions libpcap-analyzer/src/plugins/examples.rs
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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
Expand All @@ -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
);
}
}

Expand All @@ -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()),
Expand Down
21 changes: 13 additions & 8 deletions libpcap-analyzer/src/plugins/hexdump.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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>(
Expand Down Expand Up @@ -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));
Expand Down
16 changes: 9 additions & 7 deletions libpcap-analyzer/src/plugins/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<P>(&self, predicate: P, config: &Config) -> Result<PluginRegistry, PluginBuilderError>
pub fn build_filter_plugins<P>(
&self,
predicate: P,
config: &Config,
) -> Result<PluginRegistry, PluginBuilderError>
where
P: Fn(&str) -> bool,
{
Expand All @@ -66,7 +70,7 @@ impl PluginsFactory {
if predicate(b.name()) {
b.build(&mut registry, config)?;
}
};
}

Ok(registry)
}
Expand All @@ -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()));
}
}

Expand All @@ -88,7 +90,7 @@ impl Default for PluginsFactory {
let mut v: Vec<Box<dyn PluginBuilder>> = vec![
Box::new(basic_stats::BasicStatsBuilder),
Box::new(flows::FlowsInfoBuilder),
];
];

#[cfg(feature = "plugin_community_id")]
v.push(Box::new(community_id::CommunityIDBuilder));
Expand Down
Loading

0 comments on commit db00c5a

Please sign in to comment.