tpcpr/src/main.rs

171 lines
6.4 KiB
Rust
Raw Normal View History

2020-05-13 00:03:45 +02:00
extern crate serde_json;
extern crate tokio;
2020-05-21 00:54:56 +02:00
extern crate tokio_postgres;
use std::fs::File;
mod configure;
mod parser;
2020-05-27 00:42:07 +02:00
mod serializer;
2020-05-29 01:05:53 +02:00
use rayon::prelude::*;
2020-05-27 00:42:07 +02:00
use std::collections::HashMap;
use std::fs;
use std::io::prelude::*;
2020-05-13 00:03:45 +02:00
use tokio_postgres::types::ToSql;
2020-05-21 00:54:56 +02:00
use tokio_postgres::{Error, NoTls};
const PCAPNG_SIGNATURE: [u8; 4] = [0x0a, 0x0d, 0x0d, 0x0a];
const PCAP_SIGNATURE: [u8; 4] = [0xed, 0xab, 0xee, 0xdb];
2020-05-13 00:03:45 +02:00
2020-05-21 00:54:56 +02:00
fn query_string(insert_max: &usize) -> String {
2020-05-31 00:44:47 +02:00
// Changed this to String with given capacity after stumbling over https://github.com/hoodie/concatenation_benchmarks-rs
// Impressive performance increase!
let mut insert_template = String::with_capacity(insert_max * 8 + 43);
insert_template.push_str("INSERT INTO json_dump (packet) Values ");
2020-05-13 00:03:45 +02:00
2020-05-21 00:54:56 +02:00
for insert in 0..insert_max - 1 {
insert_template.push_str(&(format!("(${}), ", insert + 1)));
}
insert_template.push_str(&(format!("(${})", insert_max)));
2020-05-13 00:03:45 +02:00
insert_template
}
2020-05-31 00:44:47 +02:00
fn smallest_prime_divisor(remainder: usize ) -> usize {
let smallest_divisor: usize = (2..(remainder/2)).into_par_iter().find_first(|x| remainder % x == 0).unwrap();
smallest_divisor
}
2020-05-13 00:03:45 +02:00
#[tokio::main(core_threads = 4)] // By default, tokio_postgres uses the tokio crate as its runtime.
async fn main() -> Result<(), Error> {
/* Init values from file */
let config: configure::Config = configure::from_json_file().unwrap();
// let mut pcap_map: Hashmap<std::path::Path, bool> = HashMap::new();
2020-05-29 01:05:53 +02:00
// TODO: hash file metadata, so its state is comparable at different times and can be written to a db table
// This db table should include UUIDs so it can be joined effectively
2020-05-27 00:42:07 +02:00
let mut pcap_map = HashMap::new();
2020-05-29 01:05:53 +02:00
if let Ok(entries) = fs::read_dir(config.pcap_dir) {
for entry in entries {
if let Ok(entry) = entry {
2020-05-27 00:42:07 +02:00
if let Ok(_file_type) = entry.file_type() {
if entry.metadata().unwrap().is_file() {
let mut magic_number: [u8; 4] = [0; 4];
let _signature = File::open(entry.path().to_owned())
.unwrap()
.read_exact(&mut magic_number)
.unwrap();
match magic_number {
2020-05-27 00:42:07 +02:00
PCAPNG_SIGNATURE => pcap_map.insert(entry.path(), entry.metadata()),
PCAP_SIGNATURE => pcap_map.insert(entry.path(), entry.metadata()),
_ => None,
2020-05-27 00:42:07 +02:00
};
// println!("{:?}", &entry.metadata().unwrap().modified());
}
} else {
println!("Couldn't get file type for {:?}", entry.path());
}
}
}
}
2020-05-27 00:42:07 +02:00
println!("{:?}", pcap_map.iter());
2020-05-13 00:03:45 +02:00
/* db connection */
2020-05-29 01:05:53 +02:00
let (client, connection) = tokio_postgres::connect(&config.connection, NoTls).await?;
2020-05-13 00:03:45 +02:00
tokio::spawn(async move {
if let Err(e) = connection.await {
eprintln!("connection error: {}", e);
}
});
2020-05-21 00:54:56 +02:00
client
.execute("DROP TABLE IF EXISTS json_dump", &[])
.await?;
client
.execute(
"CREATE TABLE json_dump ( ID serial NOT NULL PRIMARY KEY, packet json NOT NULL)",
&[],
)
.await?;
2020-05-13 00:03:45 +02:00
/* device or file input */
match config.is_device {
false => for _pcap_file in pcap_map.keys() {
2020-05-31 00:44:47 +02:00
// TODO: Tuning vector capacity according to actuarial excpectation, mean average & std dev of packet size
2020-05-29 01:05:53 +02:00
let v: Vec<parser::QryData> = parser::parse(&_pcap_file, &config.filter);
2020-05-31 00:44:47 +02:00
//let mut v = Vec::<parser::QryData>::with_capacity(35536);
//v.extend(parser::parse(&_pcap_file, &config.filter));
2020-05-27 00:42:07 +02:00
let packets_serialized = serializer::serialize_packets(v);
2020-05-31 00:44:47 +02:00
//let mut packets_serialized = Vec::<serde_json::Value>::with_capacity(35536);
//packets_serialized.extend(serializer::serialize_packets(v));
2020-05-21 00:54:56 +02:00
/* Query */
2020-05-29 01:05:53 +02:00
let chunk_count = packets_serialized.len() / config.insert_max;
let remainder: usize = packets_serialized.len() % config.insert_max;
let chunker = &packets_serialized.len() < &config.insert_max;
2020-05-21 00:54:56 +02:00
match chunker {
true => {
let insert_str = query_string(&packets_serialized.len());
let statement_false = client.prepare(&insert_str).await?;
client
.query_raw(
&statement_false,
packets_serialized.iter().map(|p| p as &dyn ToSql),
)
.await?;
}
false => {
2020-05-29 01:05:53 +02:00
let insert_str = query_string(&config.insert_max);
2020-05-21 00:54:56 +02:00
let statement = client.prepare(&insert_str).await?;
2020-05-31 00:44:47 +02:00
2020-05-21 00:54:56 +02:00
for _i in 0..chunk_count {
2020-05-29 01:05:53 +02:00
let (_input, _) = packets_serialized.split_at(config.insert_max);
2020-05-21 00:54:56 +02:00
client
.query_raw(&statement, _input.to_vec().iter().map(|p| p as &dyn ToSql))
.await?;
}
println!("Packets, total:{:?}", packets_serialized.len());
println!("Chunks, total:{}", chunk_count);
println!("Chunks, remainder:{}", remainder);
2020-05-21 00:54:56 +02:00
2020-05-31 00:44:47 +02:00
if remainder > 0 {
2020-05-21 00:54:56 +02:00
let rem_str = query_string(&remainder);
let statement_remainder = client.prepare(&rem_str).await?;
let (_garbage, _input) =
packets_serialized.split_at(packets_serialized.len() - remainder);
client
.query_raw(
&statement_remainder,
_input.to_vec().iter().map(|p| p as &dyn ToSql),
)
.await?;
}
}
}
2020-05-29 01:05:53 +02:00
}
,
true => {
2020-05-29 01:05:53 +02:00
let insert_str = query_string(&config.insert_max);
2020-05-13 00:03:45 +02:00
let statement = client.prepare(&insert_str).await?;
loop {
2020-05-29 01:05:53 +02:00
let v: Vec<parser::QryData> = parser::parse_device(&config.device, &config.filter, &config.insert_max);
2020-05-27 00:42:07 +02:00
let packets_serialized = serializer::serialize_packets(v);
2020-05-21 00:54:56 +02:00
client
.query_raw(
&statement,
packets_serialized.iter().map(|p| p as &dyn ToSql),
)
.await?;
}
},
}
Ok(())
2020-05-13 00:03:45 +02:00
}