Skip to content

Commit

Permalink
move to lib/bin split
Browse files Browse the repository at this point in the history
  • Loading branch information
dandyvica committed Jan 31, 2025
1 parent 52a3176 commit 861e568
Show file tree
Hide file tree
Showing 38 changed files with 601 additions and 461 deletions.
10 changes: 9 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
[package]
name = "dqy"
name = "dnslib"
edition = "2021"
version = "0.5.2" #:version
authors = ["Alain Viguier <[email protected]>"]
Expand All @@ -14,6 +14,10 @@ categories = ["command-line-utilities"]
license = "MIT"
rust-version = "1.82.0"

[lib]
name = "dnslib"
path = "src/lib.rs"

[dependencies]
base16 = "0.2.1"
base64 = "0.21.5"
Expand Down Expand Up @@ -63,3 +67,7 @@ unnecessary_cast = "allow"
[[bin]]
name = "certgen"
path = "src/certgen.rs"

# [[bin]]
# name = "dqy"
# path = "src/main.rs"
21 changes: 11 additions & 10 deletions src/args.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,14 @@ use log::trace;
use rustc_version_runtime::version;
use simplelog::*;

use dnslib::dns::rfc::domain::DomainName;
use dnslib::dns::rfc::{flags::BitFlags, qclass::QClass, qtype::QType};
use dnslib::error::Error;
use dnslib::transport::network::{IPVersion, Protocol};
use dnslib::transport::{endpoint::EndPoint, TransportOptions};

use crate::cli_options::{DnsProtocolOptions, EdnsOptions};
use crate::dns::rfc::domain::DomainName;
use crate::dns::rfc::{flags::BitFlags, qclass::QClass, qtype::QType};
use crate::error::Error;
use crate::show::{DisplayOptions, DumpOptions};
use crate::transport::network::{IPVersion, Protocol};
use crate::transport::{endpoint::EndPoint, TransportOptions};

// value of the environment variable for flags if any
const ENV_FLAGS: &str = "DQY_FLAGS";
Expand Down Expand Up @@ -60,7 +61,7 @@ pub struct CliOptions {
}

impl FromStr for CliOptions {
type Err = crate::error::Error;
type Err = dnslib::error::Error;

fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
let args: Vec<_> = s.split_ascii_whitespace().map(|a| a.to_string()).collect();
Expand All @@ -80,7 +81,7 @@ impl CliOptions {
}
}

pub fn options(args: &[String]) -> crate::error::Result<Self> {
pub fn options(args: &[String]) -> dnslib::error::Result<Self> {
// save all cli options into a structure
let mut options = CliOptions::default();

Expand Down Expand Up @@ -1012,7 +1013,7 @@ fn validate_qtypes(s: &str) -> std::result::Result<QType, String> {
}

// Initialize write logger: either create it or use it
fn init_write_logger(logfile: &PathBuf, level: log::LevelFilter) -> crate::error::Result<()> {
fn init_write_logger(logfile: &PathBuf, level: log::LevelFilter) -> dnslib::error::Result<()> {
if level == log::LevelFilter::Off {
return Ok(());
}
Expand All @@ -1039,7 +1040,7 @@ fn init_write_logger(logfile: &PathBuf, level: log::LevelFilter) -> crate::error
}

// Initialize terminal logger
fn init_term_logger(level: log::LevelFilter) -> crate::error::Result<()> {
fn init_term_logger(level: log::LevelFilter) -> dnslib::error::Result<()> {
if level == log::LevelFilter::Off {
return Ok(());
}
Expand All @@ -1051,7 +1052,7 @@ fn init_term_logger(level: log::LevelFilter) -> crate::error::Result<()> {
#[cfg(test)]
mod tests {
use super::*;
use crate::dns::rfc::domain::ROOT;
use dnslib::dns::rfc::domain::ROOT;

#[test]
fn _split_args() {
Expand Down
11 changes: 6 additions & 5 deletions src/cli_options.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,10 @@ use std::net::SocketAddr;

use log::trace;

use crate::args::CliOptions;
use crate::dns::rfc::domain::ROOT;
use crate::dns::rfc::opt::cookie::COOKIE;
use crate::dns::rfc::opt::zoneversion::ZONEVERSION;
use crate::dns::rfc::{
use dnslib::dns::rfc::domain::ROOT;
use dnslib::dns::rfc::opt::cookie::COOKIE;
use dnslib::dns::rfc::opt::zoneversion::ZONEVERSION;
use dnslib::dns::rfc::{
domain::{DomainName, ROOT_DOMAIN},
opt::{
//dau_dhu_n3u::{EdnsKeyTag, DAU, DHU, N3U},
Expand All @@ -21,6 +20,8 @@ use crate::dns::rfc::{
resource_record::OPT,
};

use crate::args::CliOptions;

// DNSSEC OK
const DNSSEC_FLAG: u16 = 0x8000;

Expand Down
40 changes: 40 additions & 0 deletions src/display.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
// titles when displaying headers: build a map giving for each title its colored version
use colored::*;
use std::collections::HashMap;
use std::sync::LazyLock;

type ColoredTitles = HashMap<String, ColoredString>;

pub static TITLES: LazyLock<ColoredTitles> = LazyLock::new(|| {
const COLOR: Color = Color::BrightCyan;

// local helper
fn insert_title(h: &mut ColoredTitles, title: &str, color: Color) {
h.insert(title.to_string(), title.color(color));
}

// init new hmap
let mut h = HashMap::new();

// add all titles
insert_title(&mut h, "qname", COLOR);
insert_title(&mut h, "qtype", COLOR);
insert_title(&mut h, "qclass", COLOR);
insert_title(&mut h, "name", COLOR);
insert_title(&mut h, "type", COLOR);
insert_title(&mut h, "payload", COLOR);
insert_title(&mut h, "rcode", COLOR);
insert_title(&mut h, "version", COLOR);
insert_title(&mut h, "flags", COLOR);

h
});

pub fn header_section(text: &str, length: Option<usize>) -> ColoredString {
let s = if let Some(l) = length {
format!("{:<l$}", text)
} else {
text.to_string()
};
s.black().on_bright_cyan()
}
75 changes: 1 addition & 74 deletions src/dns/message.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use super::rfc::{query::Query, response::Response, response_code::ResponseCode};
use log::{error, trace};
use serde::Serialize;

use crate::show::{header_section, DisplayOptions, QueryInfo, Show, ShowAll};
// use crate::show::{header_section, DisplayOptions, QueryInfo, Show, ShowAll};

#[derive(Debug, Serialize)]
pub struct Message {
Expand Down Expand Up @@ -74,17 +74,6 @@ impl fmt::Display for Message {
}
}

impl Show for Message {
fn show(&self, display_options: &DisplayOptions, length: Option<usize>) {
// print out Query if requested
if display_options.show_question {
self.query.show(display_options, length);
}

self.response.show(display_options, length);
}
}

//───────────────────────────────────────────────────────────────────────────────────
// convenient struct for holding all messages
//───────────────────────────────────────────────────────────────────────────────────
Expand Down Expand Up @@ -118,65 +107,3 @@ impl fmt::Display for MessageList {
Ok(())
}
}

impl ShowAll for MessageList {
fn show_all(&self, display_options: &mut DisplayOptions, info: QueryInfo) {
//───────────────────────────────────────────────────────────────────────────────────
// JSON
//───────────────────────────────────────────────────────────────────────────────────
if display_options.json_pretty {
let j = serde_json::json!({
"messages": self,
"info": info
});
println!("{}", serde_json::to_string_pretty(&j).unwrap());
return;
}

//───────────────────────────────────────────────────────────────────────────────────
// JSON pretty
//───────────────────────────────────────────────────────────────────────────────────
if display_options.json {
let j = serde_json::json!({
"messages": self,
"info": info
});
println!("{}", serde_json::to_string(&j).unwrap());
return;
}

//───────────────────────────────────────────────────────────────────────────────────
// fancy print out when only one message
//───────────────────────────────────────────────────────────────────────────────────
if self.len() == 1 {
// we only have 1 message
let msg = &self[0];
let resp = msg.response();

// when we only have one message, we print out a dig-like info
display_options.sho_resp_header = true;
display_options.show_headers = true;
display_options.show_all = true;

resp.show(display_options, None);

// print out stats
println!("{}", header_section("STATS", None));
println!("{}", info);
}
//───────────────────────────────────────────────────────────────────────────────────
// when several messages, just print out the ANSWER
//───────────────────────────────────────────────────────────────────────────────────
else {
let max_length = self.max_length();

for msg in self.iter() {
msg.show(display_options, max_length);
}

if display_options.stats {
println!("{}", info);
}
}
}
}
2 changes: 1 addition & 1 deletion src/dns/rfc/a.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ use serde::Serialize;
// A resource record
#[allow(clippy::upper_case_acronyms)]
#[derive(Debug, PartialEq, FromNetwork, Serialize)]
pub(super) struct A(pub Ipv4Addr);
pub struct A(pub Ipv4Addr);

impl Default for A {
fn default() -> Self {
Expand Down
2 changes: 1 addition & 1 deletion src/dns/rfc/afsdb.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ use super::domain::DomainName;

#[allow(clippy::upper_case_acronyms)]
#[derive(Debug, Default, FromNetwork, Serialize)]
pub(super) struct AFSDB {
pub struct AFSDB {
subtype: u16,
hostname: DomainName,
}
Expand Down
2 changes: 1 addition & 1 deletion src/dns/rfc/apl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ impl Serialize for InnerAPL {
//───────────────────────────────────────────────────────────────────────────────────
#[allow(clippy::upper_case_acronyms)]
#[derive(Debug, Default, Serialize)]
pub(super) struct APL {
pub struct APL {
#[serde(skip_serializing)]
rd_length: u16,
apl: Vec<InnerAPL>,
Expand Down
2 changes: 1 addition & 1 deletion src/dns/rfc/caa.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ use crate::{dns::buffer::Buffer, new_rd_length};
// +----------------+----------------+.....+----------------+
#[allow(clippy::upper_case_acronyms)]
#[derive(Debug, Default, FromNetwork, Serialize)]
pub(super) struct CAA {
pub struct CAA {
// transmistted through RR deserialization
#[serde(skip_serializing)]
#[from_network(ignore)]
Expand Down
5 changes: 5 additions & 0 deletions src/dns/rfc/char_string.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,11 @@ impl CharacterString {
pub fn len(&self) -> u8 {
self.length
}

#[inline]
pub fn is_empty(&self) -> bool {
self.length == 0
}
}

impl DataLength for CharacterString {
Expand Down
2 changes: 1 addition & 1 deletion src/dns/rfc/dnskey.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ use super::algorithm::DNSSECAlgorithmTypes;
#[allow(clippy::upper_case_acronyms)]
#[derive(Debug, Default, FromNetwork)]
#[from_network(TryFrom)]
pub(super) struct DNSKEY {
pub struct DNSKEY {
#[from_network(ignore)]
rd_length: u16,

Expand Down
11 changes: 1 addition & 10 deletions src/dns/rfc/domain.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,12 @@ use std::io::{Cursor, Result};
use std::ops::Deref;
use std::slice::Iter;

use colored::Colorize;
use log::trace;
use serde::{Serialize, Serializer};
use type2network::{FromNetworkOrder, ToNetworkOrder};
use type2network_derive::ToNetwork;

use crate::error::{self, Dns, Error};
use crate::show::ToColor;

pub const ROOT_DOMAIN: DomainName = DomainName { labels: vec![] };
pub const ROOT: &str = ".";
Expand All @@ -29,7 +27,7 @@ impl Label {
self.0.len()
}

pub fn size(&self) -> usize {
pub fn _size(&self) -> usize {
self.0.len() + 1
}

Expand Down Expand Up @@ -292,13 +290,6 @@ impl fmt::Debug for DomainName {
}
}

impl ToColor for DomainName {
fn to_color(&self) -> colored::ColoredString {
self.to_string().bright_green()
// self.to_string().truecolor(NAME_COLOR.0, NAME_COLOR.1, NAME_COLOR.2)
}
}

// Convert from a ref
impl<'a> TryFrom<&'a DomainName> for DomainName {
type Error = Error;
Expand Down
2 changes: 1 addition & 1 deletion src/dns/rfc/eui48.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ use type2network_derive::FromNetwork;
// | |
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
#[derive(Debug, Default, FromNetwork)]
pub(super) struct EUI48([u8; 6]);
pub struct EUI48([u8; 6]);

impl fmt::Display for EUI48 {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
Expand Down
2 changes: 1 addition & 1 deletion src/dns/rfc/eui64.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ use type2network_derive::FromNetwork;
// | |
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
#[derive(Debug, Default, FromNetwork)]
pub(super) struct EUI64(u64);
pub struct EUI64(u64);

impl fmt::Display for EUI64 {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
Expand Down
8 changes: 7 additions & 1 deletion src/dns/rfc/flags.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ use crate::error::{Dns, Error};
// +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
// |QR| Opcode |AA|TC|RD|RA|Z |AD|CD| RCODE |
// +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
#[derive(Debug, Default, PartialEq, Serialize)]
#[derive(Debug, Default, Clone, PartialEq, Serialize)]
pub struct Flags {
pub(super) qr: PacketType, // A one bit field that specifies whether this message is a query (0), or a response (1).
pub(super) op_code: OpCode, // A four bit field that specifies kind of query in this
Expand Down Expand Up @@ -48,6 +48,12 @@ pub struct Flags {
//6-15 Reserved for future use.
}

impl Flags {
pub fn set_response_code(&mut self, rc: ResponseCode) {
self.response_code = rc;
}
}

#[derive(Debug, PartialEq, Clone, Serialize)]
pub struct BitFlags {
pub authorative_answer: bool, // Authoritative Answer - this bit is valid in responses,
Expand Down
Loading

0 comments on commit 861e568

Please sign in to comment.