Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Impl FromStr for Question and use it in Stelline. #317

Merged
merged 3 commits into from
Jun 3, 2024
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
2 changes: 1 addition & 1 deletion src/base/name/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@

pub use self::absolute::{Name, NameError};
pub use self::builder::{
FromStrError, NameBuilder, PushError, PushNameError,
FromStrError, NameBuilder, PresentationError, PushError, PushNameError,
};
pub use self::chain::{Chain, ChainIter, LongChainError, UncertainChainIter};
pub use self::label::{
Expand Down
172 changes: 171 additions & 1 deletion src/base/question.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,13 @@

use super::cmp::CanonicalOrd;
use super::iana::{Class, Rtype};
use super::name;
use super::name::{ParsedName, ToName};
use super::wire::{Composer, ParseError};
use core::cmp::Ordering;
use core::str::FromStr;
use core::{fmt, hash};
use octseq::builder::ShortBuf;
use octseq::octets::{Octets, OctetsFrom};
use octseq::parse::Parser;

Expand Down Expand Up @@ -111,7 +114,7 @@ impl<N: ToName> Question<N> {
}
}

//--- From
//--- From and FromStr

impl<N: ToName> From<(N, Rtype, Class)> for Question<N> {
fn from((name, rtype, class): (N, Rtype, Class)) -> Self {
Expand All @@ -125,6 +128,71 @@ impl<N: ToName> From<(N, Rtype)> for Question<N> {
}
}

impl<N: FromStr<Err = name::FromStrError>> FromStr for Question<N> {
type Err = FromStrError;

/// Parses a question from a string.
///
/// The string should contain a question as the query name, class, and
/// query type separated by white space. The query name should be first
/// and in the same form as `Name::from_str` requires. The class and
/// query type follow the name in either order. If the class is left out,
/// it is assumed to be IN.
fn from_str(s: &str) -> Result<Self, Self::Err> {
let mut s = s.split_whitespace();

let qname = match s.next() {
Some(qname) => qname,
None => return Err(PresentationErrorEnum::MissingQname.into()),
};
let qname = N::from_str(qname)?;
let class_or_qtype = match s.next() {
Some(value) => value,
None => {
return Err(PresentationErrorEnum::MissingClassAndQtype.into())
}
};
let res = match Class::from_str(class_or_qtype) {
Ok(class) => {
let qtype = match s.next() {
Some(qtype) => qtype,
None => {
return Err(PresentationErrorEnum::MissingQtype.into())
}
};
match Rtype::from_str(qtype) {
Ok(qtype) => Self::new(qname, qtype, class),
Err(_) => {
return Err(PresentationErrorEnum::BadQtype.into())
}
}
}
Err(_) => {
let qtype = match Rtype::from_str(class_or_qtype) {
Ok(qtype) => qtype,
Err(_) => {
return Err(PresentationErrorEnum::BadQtype.into())
}
};
let class = match s.next() {
Some(class) => class,
None => return Ok(Self::new(qname, qtype, Class::IN)),
};
match Class::from_str(class) {
Ok(class) => Self::new(qname, qtype, class),
Err(_) => {
return Err(PresentationErrorEnum::BadClass.into())
}
}
}
};
if s.next().is_some() {
return Err(PresentationErrorEnum::TrailingData.into());
}
Ok(res)
}
}

//--- OctetsFrom

impl<Name, SrcName> OctetsFrom<Question<SrcName>> for Question<Name>
Expand Down Expand Up @@ -298,3 +366,105 @@ impl<Name: ToName> ComposeQuestion for (Name, Rtype) {
Question::new(&self.0, self.1, Class::IN).compose(target)
}
}

//------------ FromStrError --------------------------------------------------

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum FromStrError {
/// The string content was wrongly formatted.
Presentation(PresentationError),

/// The buffer is too short to contain the name.
ShortBuf,
}

//--- From

impl From<name::FromStrError> for FromStrError {
fn from(err: name::FromStrError) -> FromStrError {
match err {
name::FromStrError::Presentation(err) => {
Self::Presentation(err.into())
}
name::FromStrError::ShortBuf => Self::ShortBuf,
}
}
}

impl From<PresentationErrorEnum> for FromStrError {
fn from(err: PresentationErrorEnum) -> Self {
Self::Presentation(err.into())
}
}

//--- Display and Error

impl fmt::Display for FromStrError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
FromStrError::Presentation(err) => err.fmt(f),
FromStrError::ShortBuf => ShortBuf.fmt(f),
}
}
}

#[cfg(feature = "std")]
impl std::error::Error for FromStrError {}

//------------ PresentationError ---------------------------------------------

/// An illegal presentation format was encountered.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct PresentationError(PresentationErrorEnum);

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum PresentationErrorEnum {
BadName(name::PresentationError),
MissingQname,
MissingClassAndQtype,
MissingQtype,
BadClass,
BadQtype,
TrailingData,
}

//--- From

impl From<PresentationErrorEnum> for PresentationError {
fn from(err: PresentationErrorEnum) -> Self {
Self(err)
}
}

impl From<name::PresentationError> for PresentationError {
fn from(err: name::PresentationError) -> Self {
Self(PresentationErrorEnum::BadName(err))
}
}

//--- Display and Error

impl fmt::Display for PresentationError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self.0 {
PresentationErrorEnum::BadName(err) => err.fmt(f),
PresentationErrorEnum::MissingQname => {
f.write_str("missing qname")
}
PresentationErrorEnum::MissingClassAndQtype => {
f.write_str("missing class and qtype")
}
PresentationErrorEnum::MissingQtype => {
f.write_str("missing qtype")
}
PresentationErrorEnum::BadClass => f.write_str("invalid class"),
PresentationErrorEnum::BadQtype => f.write_str("invalid qtype"),
PresentationErrorEnum::TrailingData => {
f.write_str("trailing data")
}
}
}
}

#[cfg(feature = "std")]
impl std::error::Error for PresentationError {}
7 changes: 1 addition & 6 deletions src/stelline/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@ use crate::net::client::request::{
};

use super::matches::match_msg;
use super::parse_query;
use super::parse_stelline::{Entry, Reply, Stelline, StepType};

use super::channel::DEF_CLIENT_ADDR;
Expand Down Expand Up @@ -493,11 +492,7 @@ fn entry2reqmsg(entry: &Entry) -> RequestMessage<Vec<u8>> {
let sections = entry.sections.as_ref().unwrap();
let mut msg = MessageBuilder::new_vec().question();
for q in &sections.question {
let question = match q {
parse_query::Entry::QueryRecord(question) => question,
_ => todo!(),
};
msg.push(question).unwrap();
msg.push(q).unwrap();
}
let msg = msg.answer();
for _a in &sections.answer {
Expand Down
13 changes: 3 additions & 10 deletions src/stelline/matches.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
use super::parse_query;
use super::parse_stelline::{Entry, Matches, Reply};
use super::parse_stelline::{Entry, Matches, Question, Reply};
use crate::base::iana::{Opcode, OptRcode, Rtype};
use crate::base::opt::{Opt, OptRecord};
use crate::base::{Message, ParsedName, QuestionSection, RecordSection};
Expand Down Expand Up @@ -443,7 +442,7 @@ fn match_section<
}

fn match_question<Octs: Octets>(
match_section: Vec<parse_query::Entry>,
match_section: Vec<Question>,
msg_section: QuestionSection<'_, Octs>,
match_qname: bool,
match_qtype: bool,
Expand All @@ -454,13 +453,7 @@ fn match_question<Octs: Octets>(
}
for msg_rr in msg_section {
let msg_rr = msg_rr.unwrap();
let mat_rr = if let parse_query::Entry::QueryRecord(record) =
&match_section[0]
{
record
} else {
panic!("include not expected");
};
let mat_rr = &match_section[0];
if match_qname && msg_rr.qname() != mat_rr.qname() {
return false;
}
Expand Down
1 change: 0 additions & 1 deletion src/stelline/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,5 @@ pub mod connect;
pub mod connection;
pub mod dgram;
mod matches;
mod parse_query;
pub mod parse_stelline;
pub mod server;
Loading
Loading