Skip to content

Commit

Permalink
Cargo fmt update
Browse files Browse the repository at this point in the history
  • Loading branch information
mbolt35 committed Apr 19, 2023
1 parent 2cb5ed2 commit c22ec9e
Show file tree
Hide file tree
Showing 7 changed files with 74 additions and 72 deletions.
7 changes: 3 additions & 4 deletions examples/conntrack_dump.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
use conntrack::*;
use env_logger::Env;


/// This example enables logging, connects to netfilter via socket, dumps
/// conntrack tables, and iterates and logs each flow within the table.
/// This example enables logging, connects to netfilter via socket, dumps
/// conntrack tables, and iterates and logs each flow within the table.
fn main() -> Result<()> {
let env = Env::default()
.filter_or("RUST_LOG", "info")
Expand All @@ -22,4 +21,4 @@ fn main() -> Result<()> {
}

Ok(())
}
}
26 changes: 13 additions & 13 deletions src/connection.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,33 +6,34 @@ use neli::{
types::{Buffer, GenlBuffer},
};

use crate::result::*;
use crate::attributes::*;
use crate::decoders::*;
use crate::message::*;
use crate::model::*;
use crate::decoders::*;
use crate::result::*;

/// The `Conntrack` type is used to connect to a netfilter socket and execute
/// conntrack table specific commands.
/// The `Conntrack` type is used to connect to a netfilter socket and execute
/// conntrack table specific commands.
pub struct Conntrack {
socket: NlSocketHandle,
}

impl Conntrack {
/// This method opens a netfilter socket using a `socket()` syscall, and
/// returns the `Conntrack` instance on success.
/// This method opens a netfilter socket using a `socket()` syscall, and
/// returns the `Conntrack` instance on success.
pub fn connect() -> Result<Self> {
let socket = NlSocketHandle::connect(NlFamily::Netfilter, Some(0), &[])?;
Ok(Self { socket })
}

/// The dump call will list all connection tracking for the `Conntrack` table as a
/// `Vec<Flow>` instances.
/// The dump call will list all connection tracking for the `Conntrack` table as a
/// `Vec<Flow>` instances.
pub fn dump(&mut self) -> Result<Vec<Flow>> {
let genlhdr = Genlmsghdr::new(
0u8,
libc::NFNETLINK_V0 as u8,
GenlBuffer::<ConntrackAttr, Buffer>::new());
0u8,
libc::NFNETLINK_V0 as u8,
GenlBuffer::<ConntrackAttr, Buffer>::new(),
);

self.socket.send({
let len = None;
Expand All @@ -58,8 +59,7 @@ impl Conntrack {
flows.push(Flow::decode(handle)?);
}
}


Ok(flows)
}
}
}
37 changes: 21 additions & 16 deletions src/decoders.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,31 +6,36 @@ use std::time::Duration;
use chrono::TimeZone;
use chrono::Utc;
use neli::types::Buffer;
use neli::{
attr::Attribute,
genl::Nlattr,
consts::genl::*,
};
use neli::{attr::Attribute, consts::genl::*, genl::Nlattr};

use crate::result::*;
use crate::attributes::*;
use crate::model::*;
use crate::result::*;

/// The attribute decoder trait is implemented to convert a specific `AttrHandle` to a
/// The attribute decoder trait is implemented to convert a specific `AttrHandle` to a
/// conntrack model. This will be the primary mechanism used to decode nested conntrack
/// attributes.
pub trait AttrDecoder<'a, T, M> where T: NlAttrType {
/// attributes.
pub trait AttrDecoder<'a, T, M>
where
T: NlAttrType,
{
fn decode(attr_handle: CtAttrHandle<'a, T>) -> Result<M>;
}

/// A primitive attribute decoder is used to extract numerical values from
/// A primitive attribute decoder is used to extract numerical values from
/// attributes.
pub trait PrimitiveAttrDecoder<T, M> where T: NlAttrType {
pub trait PrimitiveAttrDecoder<T, M>
where
T: NlAttrType,
{
fn decode(attr: &Nlattr<T, Buffer>) -> Result<M>;
}

/// A decoder capable of decoding `IpAddr` instances from an Attribute.
pub trait IpDecoder<T> where T: NlAttrType {
/// A decoder capable of decoding `IpAddr` instances from an Attribute.
pub trait IpDecoder<T>
where
T: NlAttrType,
{
fn decode_v4(attr: &Nlattr<T, Buffer>) -> Result<IpAddr>;
fn decode_v6(attr: &Nlattr<T, Buffer>) -> Result<IpAddr>;
}
Expand Down Expand Up @@ -213,7 +218,7 @@ impl<'a> AttrDecoder<'a, NatAttr, Nat> for Nat {
}
}

Ok(nat)
Ok(nat)
}
}

Expand Down Expand Up @@ -258,7 +263,7 @@ impl<'a> AttrDecoder<'a, SecCtxAttr, SecCtx> for SecCtx {
}

Ok(sec_ctx)
}
}
}

impl<'a> AttrDecoder<'a, SeqAdjAttr, SeqAdj> for SeqAdj {
Expand Down Expand Up @@ -570,4 +575,4 @@ impl<'a> AttrDecoder<'a, ProtoTupleAttr, ProtoTuple> for ProtoTuple {

Ok(tuple)
}
}
}
4 changes: 2 additions & 2 deletions src/error.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use std::fmt::Debug;

/// Error consolidates and propagates all underlying error types.
/// Error consolidates and propagates all underlying error types.
#[derive(thiserror::Error, Debug)]
pub enum Error {
#[error("netlink error: {0}")]
Expand All @@ -20,4 +20,4 @@ impl<T: Debug, P: Debug> From<neli::err::NlError<T, P>> for Error {
fn from(value: neli::err::NlError<T, P>) -> Self {
Self::Netlink(format!("{:?}", value))
}
}
}
51 changes: 25 additions & 26 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,65 +1,64 @@
//! [![github]](https://github.com/rusty-bolt/conntrack-rs)
//!
//!
//! [github]: https://img.shields.io/badge/github-rusty--bolt/conntrack--rs-blueviolet?style=for-the-badge&labelColor=555555&logo=github
//!
//!
//! ---
//!
//! This library provides access to the [`conntrack`](https://conntrack-tools.netfilter.org/conntrack.html)
//! subsystem in the linux kernel leveraging netlink support via the [`neli`](https://docs.rs/neli/latest/neli/index.html)
//! library.
//!
//! The current version only supplies `Dump()` functionality for the `Conntrack` table. Leveraging the
//! [`conntrack-tools`](https://conntrack-tools.netfilter.org/) utility in linux, the `Dump()` behavior
//! is equivalent to: `conntrack -L`. Most of the model and attribute parsing supported in this library
//! This library provides access to the [`conntrack`](https://conntrack-tools.netfilter.org/conntrack.html)
//! subsystem in the linux kernel leveraging netlink support via the [`neli`](https://docs.rs/neli/latest/neli/index.html)
//! library.
//!
//! The current version only supplies `Dump()` functionality for the `Conntrack` table. Leveraging the
//! [`conntrack-tools`](https://conntrack-tools.netfilter.org/) utility in linux, the `Dump()` behavior
//! is equivalent to: `conntrack -L`. Most of the model and attribute parsing supported in this library
//! extends beyond the `dump()` command, which allows this library to eventually cover the full feature set
//! of the conntrack subsystem.
//!
//! of the conntrack subsystem.
//!
//! You can enable byte and packet counters using `sysctl -w net.netfilter.nf_conntrack_acct=1`
//!
//!
//! # Privileges
//!
//! You need the `CAP_NET_ADMIN` capability in order to allow your application to receive events from and to send commands to kernel-space,
//!
//! You need the `CAP_NET_ADMIN` capability in order to allow your application to receive events from and to send commands to kernel-space,
//! excepting the conntrack table dumping operation.
//!
//!
//! ### WSL2 Conntrack
//!
//!
//! Note that in order to enable connection tracking via `conntrack` on WSL2, you'll need to add the following iptable entry:
//! ```bash
//! iptables -A INPUT -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
//! ```
//!
//!
//! # Example
//!
//! ```rust
//! use conntrack::*;
//!
//!
//! fn main() -> Result<()> {
//! // Create the Conntrack table via netfilter socket syscall
//! let mut ct = Conntrack::connect()?;
//!
//!
//! // Dump conntrack table as a Vec<Flow>
//! let flows = ct.dump()?;
//!
//!
//! for flow in flows {
//! log::info!("{flow:?}");
//! }
//!
//!
//! Ok(())
//! }
//! ```
//!
//! <br>


pub use crate::connection::*;
pub use crate::result::*;
pub use crate::error::*;
pub use crate::result::*;

pub mod attributes;
pub mod decoders;
pub mod message;
pub mod model;
pub mod decoders;

mod result;
mod connection;
mod error;
mod error;
mod result;
19 changes: 9 additions & 10 deletions src/model.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
use bitflags::bitflags;
use chrono::prelude::*;
use neli::neli_enum;
use std::{net, time::Duration};
use bitflags::bitflags;

/// The `Flow` type contains all the information of a connection dumped from the
/// conntrack table. Note that the `Flow` type can be used to support multiple
/// extended formats as well to allow for expansions on the library. Thus, all
/// fields will be optional to support the various formats/options/configs
/// that can be set by the linux kernel.
/// The `Flow` type contains all the information of a connection dumped from the
/// conntrack table. Note that the `Flow` type can be used to support multiple
/// extended formats as well to allow for expansions on the library. Thus, all
/// fields will be optional to support the various formats/options/configs
/// that can be set by the linux kernel.
#[derive(Default, Debug)]
pub struct Flow {
/// Unique id assigned to this conntrack entry.
Expand All @@ -20,16 +20,16 @@ pub struct Flow {
pub reply: Option<IpTuple>,
/// Metadata specific to the protocol being used to facilitate the network transfer.
pub proto_info: Option<ProtoInfo>,
/// Byte and packet counter data relative to the traffic origin. Enable with `sysctl
/// Byte and packet counter data relative to the traffic origin. Enable with `sysctl
/// -w net.netfilter.nf_conntrack_acct=1`
pub counter_origin: Option<Counter>,
/// Byte and packet counter data relative to the traffic reply. Enable with `sysctl
/// Byte and packet counter data relative to the traffic reply. Enable with `sysctl
/// -w net.netfilter.nf_conntrack_acct=1`
pub counter_reply: Option<Counter>,
/// Duration until conntrack entry is invalidated; reset to initial value when connection sees a new packet.
/// Default TCP connection timeout is 5 days.
pub timeout: Option<Duration>,
/// Contains the status values parsed into the various status flags, represented as strings.
/// Contains the status values parsed into the various status flags, represented as strings.
pub status: Option<Vec<String>>,
/// Use is a reference count for the connection used internally for garbage collection.
pub entry_use: Option<u32>,
Expand Down Expand Up @@ -246,7 +246,6 @@ pub struct Timestamp {
pub end: Option<DateTime<Utc>>,
}


// NatInfo contains addition NAT information of a connection
#[derive(Default, Debug)]
pub struct NatInfo {
Expand Down
2 changes: 1 addition & 1 deletion src/result.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
pub use crate::error::Error;

/// Result is an alias for `core::result::Result<T, conntrack::error::Error>`
pub type Result<T> = core::result::Result<T, Error>;
pub type Result<T> = core::result::Result<T, Error>;

0 comments on commit c22ec9e

Please sign in to comment.