1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
//! This crate allows to easily develop Rust plugins for [Tranalyzer2](https://tranalyzer.com/), a
//! network traffic analysis tool.
//!
//! An example Rust plugin for Tranalyzer2 using this crate can be found here:
//! [https://github.com/Tranalyzer/rustExample](https://github.com/Tranalyzer/rustExample)
//!
//! # Create a new plugin
//!
//! 1. [Download](https://tranalyzer.com/downloads) and
//! [install](https://tranalyzer.com/tutorial/installation)
//! Tranalyzer2.
//!
//! 2. Use `t2plugin` to create a new plugin based on the
//! [rustTemplate](https://github.com/Tranalyzer/rustTemplate).
//!
//! ```sh
//! cd $T2HOME/plugins
//! t2plugin --rust -c myPluginName
//! cd myPluginName
//! ```
//!
//! 3. Optional: change the `PLUGINORDER` at the top of `autogen.sh`.
//!
//! 4. Fill the different methods of the [`T2Plugin`] trait implementation in `src/lib.rs`.
extern crate libc;
/// Contains the definition of a [`Flow`].
pub mod flow;
/// Contains the definition of a [`Packet`].
pub mod packet;
/// Contains the definition of the different protocol headers (IP, TCP, UDP, ...).
pub mod nethdr;
/// Contains the [`SliceReader`](slread::SliceReader) which allows to easily read integers and
/// strings from a byte slice.
pub mod slread;
mod status;
pub use status::*;
use packet::Packet;
use flow::Flow;
use libc::c_char;
use std::mem;
use std::iter::Product;
use std::net::IpAddr;
use std::ops::Div;
use std::ffi::CString;
/// `unsigned long` in C: `u32` on 32-bit systems and `u64` on 64-bit systems.
#[allow(non_camel_case_types)]
#[cfg(target_arch = "x86_64")]
pub type c_ulong = u64;
#[allow(non_camel_case_types)]
#[cfg(target_arch = "x86")]
pub type c_ulong = u32;
/// `flow_index` value representing a non-existing [`Flow`].
#[cfg(target_arch = "x86_64")]
pub const HASHTABLE_ENTRY_NOT_FOUND: c_ulong = std::u64::MAX;
#[cfg(target_arch = "x86")]
pub const HASHTABLE_ENTRY_NOT_FOUND: c_ulong = std::u32::MAX;
/// Rust opaque representation of `binary_value_t` struct from Tranalyzer2
pub enum BinaryValue {}
/// Rust opaque representation of `outputBuffer_t` struct from Tranalyzer2
pub enum OutputBuffer {}
/// Types of values which can be outputted in Tranalyzer2 flow files.
///
/// Enum copied from `tranalyzer2/src/binaryValue.h`. These types describe the types of values
/// outputted in Tranalyzer2 columns. They are used when building a [`Header`] in the
/// [`T2Plugin::print_header`] method.
#[repr(u32)]
#[derive(Clone, Copy)]
#[allow(non_camel_case_types)]
pub enum BinaryType {
bt_compound = 0,
// all signed integers
bt_int_8 = 1,
bt_int_16,
bt_int_32,
bt_int_64,
bt_int_128,
bt_int_256,
// all unsigned integers
bt_uint_8,
bt_uint_16,
bt_uint_32,
bt_uint_64, // = 10
bt_uint_128,
bt_uint_256,
// hex values
bt_hex_8,
bt_hex_16,
bt_hex_32,
bt_hex_64,
bt_hex_128,
bt_hex_256, // 32 bytes
// floating point
bt_float,
bt_double, // = 20
bt_long_double,
// char and string
bt_char,
bt_string,
// now the special types
bt_flow_direction,
bt_timestamp, // date whose representation depends on B2T_TIMESTR in utils/bin2txt.h:
// 0: unix timestamp, 1: human readable date and time
bt_duration, // the time struct consists of one uint64 value for the seconds
// and one uint32_t value for the micro-/nano-secs
bt_mac_addr,
bt_ip4_addr,
bt_ip6_addr,
bt_ipx_addr, // version (8 bits), address (0, 4 or 16 bytes)
bt_string_class, // A string for classnames. CAUTION: textOutput doesn't escape control characters.
// Advantage: We don't need '"' chars at the beginning and end of the string
// Disadvantage: Usage of underscore, blank, semicolon, and every non-printable
// ASCII are STRICTLY FORBIDDEN !!! If your classnames contain such chars, you'll
// CORRUPT THE OUTPUT!!!
}
// access to C functions and variables exported by the Tranalyzer2 core
extern {
static mainHashMap: *const HashTable;
static flows: *mut Flow;
static main_output_buffer: *mut OutputBuffer;
fn bv_append_bv(dst: *mut BinaryValue, new: *mut BinaryValue) -> *mut BinaryValue;
fn bv_new_bv(name_short: *const c_char, name_long: *const c_char, repeating: u32, count: u32, ...) -> *mut BinaryValue;
fn outputBuffer_append(buffer: *mut OutputBuffer, output: *const c_char, size: usize);
}
/// Returns the number of flows that Tranalyzer2 can store in its internal hashtable.
///
/// Corresponds to Tranalyzer2 internal `mainHashMap->hashChainTableSize` value.
pub fn hashchaintable_size() -> usize {
unsafe {
(*mainHashMap).hashchaintable_size as usize
}
}
/// Returns the [`flow::Flow`] structure of the flow with `flow_index=index`.
///
/// Corresponds to Tranalyzer2 internal `flows[index]`.
///
/// # Example
///
/// ```
/// use t2plugin::{getflow, HASHTABLE_ENTRY_NOT_FOUND};
/// use t2plugin::flow::Flow;
///
/// fn get_opposite_flow<'a>(flow: &'a Flow) -> Option<&'a mut Flow> {
/// match flow.opposite_flow_index {
/// HASHTABLE_ENTRY_NOT_FOUND => None,
/// index => Some(getflow(index)),
/// }
/// }
/// ```
pub fn getflow<'a>(index: c_ulong) -> &'a mut Flow {
unsafe {
&mut *(flows.offset(index as isize))
}
}
/// Appends a string to Tranalyzer2 output buffer.
///
/// This function can be called in the [`T2Plugin::on_flow_terminate`] method to append a string to
/// the output flow file.
///
/// # Example
///
/// ```
/// struct HttpPlugin {
/// ...
/// host: String,
/// }
///
/// impl T2Plugin for HttpPlugin {
/// ...
/// #[allow(unused_variables)]
/// fn on_flow_terminate(&mut self, flow: &mut Flow) {
/// // output the HTTP host in a bt_string column
/// output_string(&self.host);
/// }
/// }
/// ```
pub fn output_string<T: AsRef<str>>(string: T) {
let cstring = CString::new(string.as_ref()).unwrap();
let len = cstring.as_bytes_with_nul().len();
let cstring = cstring.into_raw();
unsafe {
outputBuffer_append(main_output_buffer, cstring, len);
}
}
/// Appends a list of strings to Tranalyzer2 output buffer.
///
/// This function can be called in the [`T2Plugin::on_flow_terminate`] method to append a
/// repetitive string field to the output flow file.
///
/// # Example
///
/// ```
/// struct HttpPlugin {
/// ...
/// cookies: Vec<String>,
/// }
///
/// impl T2Plugin for HttpPlugin {
/// ...
/// #[allow(unused_variables)]
/// fn on_flow_terminate(&mut self, flow: &mut Flow) {
/// // output the HTTP cookies in a repetitive bt_string column
/// output_strings(&self.cookies);
/// }
/// }
/// ```
pub fn output_strings<T: AsRef<str>>(strings: &[T]) {
output_num(strings.len() as u32);
for string in strings {
output_string(string);
}
}
/// Appends a number (integer or float) to Tranalyzer2 output buffer.
///
/// This function can be called in the [`T2Plugin::on_flow_terminate`] method to append a number to
/// the output flow file.
///
/// # Example
///
/// ```
/// impl T2Plugin for ExamplePlugin {
/// ...
/// #[allow(unused_variables)]
/// fn on_flow_terminate(&mut self, flow: &mut Flow) {
/// // output the flow index in a bt_uint_64 column
/// output_num(flow.findex);
/// }
/// }
/// ```
pub fn output_num<T: Product + Div>(val: T) {
let size = mem::size_of::<T>();
let ptr = &val as *const T;
unsafe {
outputBuffer_append(main_output_buffer, ptr as *const c_char, size);
}
}
/// Appends a list of numbers (integers or floats) to Tranalyzer2 output buffer.
///
/// This function can be called in the [`T2Plugin::on_flow_terminate`] method to append a
/// repetitive number field to the output flow file.
///
/// # Example
///
/// ```
/// struct HttpPlugin {
/// ...
/// status_codes: Vec<u16>,
/// }
///
/// impl T2Plugin for HttpPlugin {
/// ...
/// #[allow(unused_variables)]
/// fn on_flow_terminate(&mut self, flow: &mut Flow) {
/// // output flow HTTP status codes in a repetitive bt_uint_16 column.
/// output_nums(&self.status_codes);
/// }
/// }
/// ```
pub fn output_nums<T: Product + Div>(vals: &[T]) {
output_num(vals.len() as u32);
let size = mem::size_of::<T>();
for val in vals {
let ptr = val as *const T;
unsafe {
outputBuffer_append(main_output_buffer, ptr as *const c_char, size);
}
}
}
/// Appends bytes to Tranalyzer2 output buffer.
///
/// This function can be called in the [`T2Plugin::on_flow_terminate`] function to append raw bytes
/// in Tranalyzer2 output buffer. This can be used to output types which are neither a string, nor
/// a number (e.g. MAC addresses).
///
/// # Example
///
/// ```
/// struct ExamplePlugin {
/// mac_address: [u8; 6],
/// }
///
/// impl T2Plugin for ExamplePlugin {
/// #[allow(unused_variables)]
/// fn on_flow_terminate(&mut self, flow: &mut Flow) {
/// output_bytes(&self.mac_address);
/// }
/// }
/// ```
pub fn output_bytes(val: &[u8]) {
let ptr = val as *const [u8];
let size = val.len();
unsafe {
outputBuffer_append(main_output_buffer, ptr as *const c_char, size);
}
}
/// Appends an IP address to Tranalyzer2 output buffer.
///
/// This function can be called in the [`T2Plugin::on_flow_terminate`] function to append an IP
/// address in Tranalyzer2 output buffer. This functions will panic if the IP address type is not
/// compatible with the column type.
///
/// # Example
///
/// ```
/// impl T2Plugin for ExamplePlugin {
/// ...
/// #[allow(unused_variables)]
/// fn on_flow_terminate(&mut self, flow: &mut Flow) {
/// ...
/// // output flow source IP address in a bt_ipx_addr column
/// output_ip(flow.src_ip(), BinaryType::bt_ipx_addr);
/// }
/// }
/// ```
pub fn output_ip(val: &IpAddr, ip_type: BinaryType) {
match (val, ip_type) {
(IpAddr::V4(ip), BinaryType::bt_ip4_addr) => output_bytes(&ip.octets()),
(IpAddr::V6(ip), BinaryType::bt_ip6_addr) => output_bytes(&ip.octets()),
(IpAddr::V4(ip), BinaryType::bt_ipx_addr) => {
output_num(4 as u8);
output_bytes(&ip.octets());
},
(IpAddr::V6(ip), BinaryType::bt_ipx_addr) => {
output_num(6 as u8);
output_bytes(&ip.octets());
},
_ => panic!("output_ip: incompatible IP and column type."),
}
}
/// Trait to tranform a per flow `struct` into a Tranalyzer2 plugin.
///
/// The [`t2plugin!`] macro can transform any `struct` implementing this trait into a Tranalyzer2
/// plugin.
pub trait T2Plugin {
/// Creates a new per flow plugin structure with default values.
///
/// This function is called when Tranalyzer2 creates a new flow
fn new() -> Self;
/// Returns a list of other plugins which are required by this plugin.
///
/// # Example
///
/// ```
/// impl T2Plugin for ExamplePlugin {
/// ...
/// fn get_dependencies() -> Vec<&'static str> {
/// // this plugin cannot run if "tcpFlags" and "httpSniffer" are not loaded
/// vec!["tcpFlags", "httpSniffer"]
/// }
/// }
/// ```
fn get_dependencies() -> Vec<&'static str> { vec![] }
/// This method is called once when Tranalyzer2 starts.
///
/// Plugin specific global variables and files should be created/opened here.
fn initialize() {}
/// Returns a [`Header`] describing the columns outputted by this plugin.
///
/// # Example
///
/// ```
/// impl T2Plugin for ExamplePlugin {
/// ...
/// fn print_header() -> Header {
/// let mut header = Header::new();
/// header.add_simple_col("IPv4 source address", "srcIP4", false, BinaryType::bt_ip4_addr);
/// header.add_simple_col("HTTP cookies", "httpCookies", true, BinaryType::bt_string);
/// header
/// }
/// }
/// ```
fn print_header() -> Header { Header::new() }
/// Called on the first seen packet of a flow.
///
/// This method is called right after the per flow `struct` of this plugin is created with the
/// [`T2Plugin::new`] method.
#[allow(unused_variables)]
fn on_flow_generated(&mut self, packet: &Packet, flow: &mut Flow) {}
/// Called on each packet which has a layer 2 header.
///
/// The `plugin` and `flow` parameters contain `Some` data only if `ETH_ACTIVATE` (Ethernet
/// flows) is activated in Tranalyzer2. Otherwise they are `None` and only the `packet`
/// contains useful information.
#[allow(unused_variables)]
fn claim_l2_info(packet: &Packet, plugin: Option<&mut Self>, flow: Option<&mut Flow>) {}
/// Called on each packet which has a layer 4 header.
#[allow(unused_variables)]
fn claim_l4_info(&mut self, packet: &Packet, flow: &mut Flow) {}
/// Called when a flow terminates.
///
/// This is where the columns, defined in the [`T2Plugin::print_header`] method, are filled.
///
/// # Example
///
/// ```
/// impl T2Plugin for ExamplePlugin {
/// ...
/// fn on_flow_terminate(&mut self, flow: &mut Flow) {
/// // fill the source IPv4 column (bt_ip4_addr)
/// match flow.src_ip4() {
/// Some(ip) => output_bytes(&ip.octets()),
/// None => output_bytes(&[0u8; 4]),
/// }
/// // fill the HTTP cookies column (repetitive bt_string)
/// output_strings(&self.cookies);
/// }
/// }
/// ```
#[allow(unused_variables)]
fn on_flow_terminate(&mut self, flow: &mut Flow) {}
/// Called before Tranalyzer2 terminates.
///
/// Plugin variables and files should be closed/cleaned here. This method should generally
/// clean what was created in the [`T2Plugin::initialize`] method.
fn on_application_terminate() {}
}
/// This structure represents the output header of this plugin.
///
/// A header is defined as a set of columns. Each column is defined by its short name, long name
/// and a definition of the type of data it contains.
pub struct Header {
main_bv: *mut BinaryValue,
}
impl Header {
/// Creates a new empty header without any column.
pub fn new() -> Header {
Header {
main_bv: 0 as *mut BinaryValue, // NULL pointer
}
}
/// Returns Tranalyzer2 internal buffer representing the built header.
///
/// This method does not need to be manually called when the [`t2plugin!`] macro is used.
pub fn _internal(&self) -> *mut BinaryValue {
self.main_bv
}
/// Adds a simple column (without compound values) to the header.
///
/// # Example
///
/// ```
/// impl T2Plugin for ExamplePlugin {
/// ...
/// fn print_header() -> Header {
/// let mut header = Header::new();
/// header.add_simple_col("IPv4 source address", "srcIP4", false,
/// BinaryType::bt_ip4_addr);
/// header.add_simple_col("HTTP cookies", "httpCookies", true,
/// BinaryType::bt_string);
/// header
/// }
/// }
/// ```
pub fn add_simple_col(&mut self, long_name: &str, short_name: &str, repeating: bool, bin_type: BinaryType) {
let long = CString::new(long_name).unwrap().into_raw();
let short = CString::new(short_name).unwrap().into_raw();
unsafe {
self.main_bv = bv_append_bv(self.main_bv, bv_new_bv(short, long, repeating as u32, 1, bin_type as u32));
}
}
/// Adds a compound column to the header.
///
/// # Example
///
/// ```
/// impl T2Plugin for ExamplePlugin {
/// ...
/// fn print_header() -> Header {
/// let mut header = Header::new();
/// // column which contains for each cookie a compound: count_key_value
/// header.add_compound_col("HTTP cookies", "httpCookies", true,
/// &[BinaryType::bt_uint_16, BinaryType::bt_string, BinaryType::bt_string]);
/// header
/// }
/// }
/// ```
pub fn add_compound_col(&mut self, long_name: &str, short_name: &str, repeating: bool, bin_types: &[BinaryType]) {
let long = CString::new(long_name).unwrap().into_raw();
let short = CString::new(short_name).unwrap().into_raw();
// ugly "solution" to expand a slice to a variadic C function
let t: Vec<u32> = bin_types.into_iter().map(|x| *x as u32).collect();
unsafe {
match bin_types.len() {
0 => return,
1 => self.main_bv = bv_append_bv(self.main_bv, bv_new_bv(short, long, repeating as u32,
1, t[0])),
2 => self.main_bv = bv_append_bv(self.main_bv, bv_new_bv(short, long, repeating as u32,
2, t[0], t[1])),
3 => self.main_bv = bv_append_bv(self.main_bv, bv_new_bv(short, long, repeating as u32,
3, t[0], t[1], t[2])),
4 => self.main_bv = bv_append_bv(self.main_bv, bv_new_bv(short, long, repeating as u32,
4, t[0], t[1], t[2], t[3])),
5 => self.main_bv = bv_append_bv(self.main_bv, bv_new_bv(short, long, repeating as u32,
5, t[0], t[1], t[2], t[3], t[4])),
6 => self.main_bv = bv_append_bv(self.main_bv, bv_new_bv(short, long, repeating as u32,
6, t[0], t[1], t[2], t[3], t[4], t[5])),
7 => self.main_bv = bv_append_bv(self.main_bv, bv_new_bv(short, long, repeating as u32,
7, t[0], t[1], t[2], t[3], t[4], t[5], t[6])),
8 => self.main_bv = bv_append_bv(self.main_bv, bv_new_bv(short, long, repeating as u32,
8, t[0], t[1], t[2], t[3], t[4], t[5], t[6], t[7])),
_ => panic!("add_compound_col: compounds with 9 or more sub-values not implemented."),
}
}
}
}
/// This macro transforms a `struct` implementing the [`T2Plugin`] trait into a plugin which can be
/// loaded by Tranalyzer2.
///
/// This macro creates the necessary `C` interface so the plugin can be loaded by Tranalyzer2. It
/// redirects these `C` functions to their corresponding Rust methods defined when implementing the
/// [`T2Plugin`] trait.
///
/// # Example
///
/// ```
/// struct ExamplePlugin {
/// ...
/// }
///
/// impl T2Plugin for ExamplePlugin {
/// ...
/// }
///
/// // creates the necessary C interface so ExamplePlugin can be loaded in Tranalyzer2
/// t2plugin!(ExamplePlugin);
/// ```
#[macro_export]
macro_rules! t2plugin {
($TYPE:ident) => {
lazy_static! {
static ref FLOWS: std::sync::Mutex<std::collections::HashMap<t2plugin::c_ulong, $TYPE>> =
std::sync::Mutex::new(std::collections::HashMap::new());
}
#[no_mangle]
pub extern "C" fn t2Dependencies() -> *const libc::c_char {
let plugins = $TYPE::get_dependencies().join(",");
std::ffi::CString::new(plugins).unwrap().into_raw()
}
#[no_mangle]
pub extern "C" fn t2Init() {
// allocate memory for flow structures
FLOWS.lock().unwrap().reserve(t2plugin::hashchaintable_size());
// call plugin initialize function
$TYPE::initialize();
}
#[no_mangle]
pub extern "C" fn t2PluginName() -> *const libc::c_char {
std::ffi::CString::new(env!("CARGO_PKG_NAME")).unwrap().into_raw()
}
#[no_mangle]
pub extern "C" fn t2PluginVersion() -> *const libc::c_char {
std::ffi::CString::new(env!("CARGO_PKG_VERSION")).unwrap().into_raw()
}
#[no_mangle]
pub extern "C" fn t2SupportedT2Major() -> libc::c_int {
//env!("CARGO_PKG_VERSION_MAJOR").parse::<libc::c_int>().unwrap()
env!("CARGO_PKG_VERSION_MAJOR").parse::<libc::c_int>().unwrap()
}
#[no_mangle]
pub extern "C" fn t2SupportedT2Minor() -> libc::c_int {
env!("CARGO_PKG_VERSION_MINOR").parse::<libc::c_int>().unwrap()
}
#[no_mangle]
#[allow(non_snake_case)]
pub extern "C" fn t2PrintHeader() -> *const t2plugin::BinaryValue {
let header = $TYPE::print_header();
header._internal()
}
#[no_mangle]
#[allow(non_snake_case)]
pub extern "C" fn t2OnNewFlow(packet: *const Packet, flow_index: t2plugin::c_ulong) {
let mut flow = $TYPE::new();
unsafe {
flow.on_flow_generated(&*packet, t2plugin::getflow(flow_index));
}
FLOWS.lock().unwrap().insert(flow_index, flow);
}
#[no_mangle]
#[allow(non_snake_case)]
pub extern "C" fn t2OnLayer2(packet: *const Packet, flow_index: t2plugin::c_ulong) {
if flow_index == t2plugin::HASHTABLE_ENTRY_NOT_FOUND {
unsafe {
$TYPE::claim_l2_info(&*packet, None, None);
}
} else if flow_index >= t2plugin::hashchaintable_size() as t2plugin::c_ulong {
println!("ERROR: t2OnLayer2 called with flowIndex={}", flow_index);
} else {
let mut hashmap = FLOWS.lock().unwrap();
// let plugin = hashmap.entry(flow_index).or_insert($TYPE::new());
let plugin = hashmap.get_mut(&flow_index).expect("no plugin in hash (l2)");
unsafe {
$TYPE::claim_l2_info(&*packet, Some(plugin), Some(t2plugin::getflow(flow_index)));
}
}
}
#[no_mangle]
#[allow(non_snake_case)]
pub extern "C" fn t2OnLayer4(packet: *const Packet, flow_index: t2plugin::c_ulong) {
if flow_index >= t2plugin::hashchaintable_size() as t2plugin::c_ulong {
println!("ERROR: t2OnLayer4 called with flowIndex={}", flow_index);
return;
}
let mut hashmap = FLOWS.lock().unwrap();
// let flow = hashmap.entry(flow_index).or_insert($TYPE::new());
let flow = hashmap.get_mut(&flow_index).expect("no flow in hash (l4)");
unsafe {
flow.claim_l4_info(&*packet, t2plugin::getflow(flow_index));
}
}
#[no_mangle]
#[allow(non_snake_case)]
pub extern "C" fn t2OnFlowTerminate(flow_index: t2plugin::c_ulong) {
if flow_index >= t2plugin::hashchaintable_size() as t2plugin::c_ulong {
println!("ERROR: onFlowTerminate called with flowIndex={}", flow_index);
return;
}
let mut hashmap = FLOWS.lock().unwrap();
{
// let flow = hashmap.entry(flow_index).or_insert($TYPE::new());
let flow = hashmap.get_mut(&flow_index).expect("no flow in hash (terminate)");
flow.on_flow_terminate(t2plugin::getflow(flow_index));
}
hashmap.remove(&flow_index);
}
#[no_mangle]
#[allow(non_snake_case)]
pub extern "C" fn t2Finalize() {
$TYPE::on_application_terminate();
}
};
}
#[repr(C)]
struct HashTable {
hashtable_size: c_ulong,
hashchaintable_size: c_ulong,
// we do not need the other fields of the hashtable
}