Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 3 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ license = "MIT"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
dhcproto = "0.12.0"
dhcproto = { version = "0.12.0", features = ["serde"] }
anyhow = "1.0"
argh = "=0.1.7"
argh_derive = "=0.1.7"
Expand All @@ -31,6 +31,8 @@ hex = "0.4"
rhai = { version = "1.5.0", optional = true }
socket2 = { version = "0.5", features = ["all"] }
pnet_datalink = "0.31.0"
serde = "1.0"
serde_json = "1.0"
# rhai-rand = { version = "0.1", optional = true }

[features]
Expand Down
28 changes: 28 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@ cargo install dhcpm --features "script" --locked

## Use

There are two levels of options, run `dhcpm --help` to see which commands are available and `dhcpm <addr> <command> --help` to see the options for each command.

```
> dhcpm --help

Expand Down Expand Up @@ -145,6 +147,32 @@ Specify an interface with v6, it is necessary to join the multicast group.
> sudo dhcpm ff02::1:2 -i enp6s0 inforeq
```

### Logging

Use `dhcpm <addr> --output json <command>` to output JSON formatted logs. If you want just a JSON formatted version of the message received, you can use `jq`:

```
dhcpm 255.255.255.255 --output json dora | jq -r ' .fields.msg | fromjson'
```

```json
{
"type": "V4",
"opcode": "BootRequest",
"htype": "Eth",
"hlen": 6,
"hops": 0,
"xid": 2734656336,
"secs": 0,
"flags": 0,
"ciaddr": "0.0.0.0",
"yiaddr": "0.0.0.0",
"siaddr": "0.0.0.0",
"giaddr": "192.168.5.1"
// fields omitted ...
}
```

### Scripting

Scripting support with [rhai](https://github.com/rhaiscript/rhai). Compile `dhcpm` with the `script` feature and give it a path with `--script`:
Expand Down
28 changes: 21 additions & 7 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -167,7 +167,7 @@ fn main() -> Result<()> {
// messages coming from `recv_rx` were received from the socket
let (recv_tx, recv_rx) = crossbeam_channel::bounded(1);

runner::sender_thread(send_rx, soc.clone());
runner::sender_thread(send_rx, soc.clone(), args.output);
runner::recv_thread(recv_tx, soc);

let start = Instant::now();
Expand Down Expand Up @@ -418,8 +418,12 @@ pub mod util {

use anyhow::Result;
use dhcproto::{v4, v6, Encodable};
use serde::Serialize;

#[derive(Clone, PartialEq, Eq)]
use crate::opts::LogStructure;

#[derive(Clone, PartialEq, Eq, Serialize)]
#[serde(tag = "type")]
pub enum Msg {
V4(v4::Message),
V6(v6::Message),
Expand Down Expand Up @@ -475,17 +479,27 @@ pub mod util {
}

#[derive(Copy, Clone, Default, PartialEq, Eq, PartialOrd, Ord)]
pub struct PrettyPrint<T>(pub T);
pub struct PrettyPrint<T>(pub T, pub LogStructure);

impl<T: fmt::Debug> fmt::Display for PrettyPrint<T> {
impl<T: fmt::Debug + serde::Serialize> fmt::Display for PrettyPrint<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{:#?}", &self.0)
match self.1 {
LogStructure::Json => {
write!(f, "{}", serde_json::to_string_pretty(&self.0).unwrap())
}
_ => write!(f, "{:#?}", &self.0),
}
}
}

impl<T: fmt::Debug> fmt::Debug for PrettyPrint<T> {
impl<T: fmt::Debug + serde::Serialize> fmt::Debug for PrettyPrint<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{:?}", self.0)
match self.1 {
LogStructure::Json => {
write!(f, "{}", serde_json::to_string_pretty(&self.0).unwrap())
}
_ => write!(f, "{:#?}", &self.0),
}
}
}

Expand Down
8 changes: 7 additions & 1 deletion src/opts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,13 +26,19 @@ pub fn get_mac() -> MacAddress {
.unwrap()
}

#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, PartialOrd, Ord)]
pub enum LogStructure {
Debug,
Pretty,
Json,
}

impl Default for LogStructure {
fn default() -> Self {
Self::Pretty
}
}

impl FromStr for LogStructure {
type Err = Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Expand Down
12 changes: 8 additions & 4 deletions src/runner.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ use dhcproto::{
};

use crate::{
opts::LogStructure,
util::{Msg, PrettyPrint, PrettyTime},
Args, MsgType,
};
Expand Down Expand Up @@ -53,7 +54,7 @@ impl TimeoutRunner {
recv(self.recv_rx) -> res => {
match res {
Ok((msg, _addr)) => {
info!(msg_type = %msg.get_type(), elapsed = %PrettyTime(start.elapsed()), msg = %PrettyPrint(&msg), "RECEIVED");
info!(msg_type = %msg.get_type(), elapsed = %PrettyTime(start.elapsed()), msg = %PrettyPrint(&msg, self.args.output), "RECEIVED");
return Ok(msg);
}
Err(err) => {
Expand Down Expand Up @@ -118,10 +119,13 @@ impl TimeoutRunner {
}
}

pub fn sender_thread(send_rx: Receiver<(Msg, SocketAddr, bool)>, soc: Arc<UdpSocket>) {
pub fn sender_thread(
send_rx: Receiver<(Msg, SocketAddr, bool)>,
soc: Arc<UdpSocket>,
output: LogStructure,
) {
thread::spawn(move || {
while let Ok((msg, target, brd)) = send_rx.recv() {
trace!("got");
let port = target.port();
// set broadcast appropriately
let target: SocketAddr = match target.ip() {
Expand All @@ -134,7 +138,7 @@ pub fn sender_thread(send_rx: Receiver<(Msg, SocketAddr, bool)>, soc: Arc<UdpSoc
IpAddr::V6(addr) => (IpAddr::V6(addr), port).into(),
};
soc.send_to(&msg.to_vec()?[..], target)?;
info!(msg_type = %msg.get_type(), ?target, msg = %PrettyPrint(&msg), "SENT");
info!(msg_type = %msg.get_type(), ?target, msg = %PrettyPrint(&msg, output), "SENT");
}
trace!("sender thread exited");
Ok::<_, anyhow::Error>(())
Expand Down
Loading