Skip to main content

hickory_proto/rr/
dns_class.rs

1// Copyright 2015-2017 Benjamin Fry <benjaminfry@me.com>
2//
3// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
4// https://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
5// https://opensource.org/licenses/MIT>, at your option. This file may not be
6// copied, modified, or distributed except according to those terms.
7
8//! class of DNS operations, in general always IN for internet
9#![allow(clippy::use_self)]
10
11use alloc::borrow::ToOwned;
12use core::{
13    cmp::Ordering,
14    fmt::{self, Display, Formatter},
15    str::FromStr,
16};
17
18#[cfg(feature = "serde")]
19use serde::{Deserialize, Serialize};
20
21use crate::error::*;
22use crate::serialize::binary::*;
23
24/// The DNS Record class
25#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
26#[derive(Debug, PartialEq, Eq, Hash, Copy, Clone)]
27#[allow(dead_code)]
28pub enum DNSClass {
29    /// Internet
30    IN,
31    /// Chaos
32    CH,
33    /// Hesiod
34    HS,
35    /// QCLASS NONE
36    NONE,
37    /// QCLASS * (ANY)
38    ANY,
39    /// Special class for OPT Version, it was overloaded for EDNS - RFC 6891
40    /// From the RFC: `Values lower than 512 MUST be treated as equal to 512`
41    OPT(u16),
42    /// Unknown DNSClass was parsed
43    Unknown(u16),
44}
45
46impl FromStr for DNSClass {
47    type Err = DecodeError;
48
49    /// Convert from `&str` to `DNSClass`
50    ///
51    /// ```
52    /// use std::str::FromStr;
53    /// use hickory_proto::rr::DNSClass;
54    ///
55    /// let var: DNSClass = DNSClass::from_str("IN").unwrap();
56    /// assert_eq!(DNSClass::IN, var);
57    /// ```
58    fn from_str(str: &str) -> Result<Self, Self::Err> {
59        match str {
60            "IN" => Ok(Self::IN),
61            "CH" => Ok(Self::CH),
62            "HS" => Ok(Self::HS),
63            "NONE" => Ok(Self::NONE),
64            "ANY" | "*" => Ok(Self::ANY),
65            _ => Err(DecodeError::UnknownDnsClassStr(str.to_owned())),
66        }
67    }
68}
69
70impl DNSClass {
71    /// Return the OPT version from value
72    pub fn for_opt(value: u16) -> Self {
73        // From RFC 6891: `Values lower than 512 MUST be treated as equal to 512`
74        let value = value.max(512);
75        Self::OPT(value)
76    }
77}
78
79impl BinEncodable for DNSClass {
80    fn emit(&self, encoder: &mut BinEncoder<'_>) -> ProtoResult<()> {
81        encoder.emit_u16((*self).into())
82    }
83}
84
85impl BinDecodable<'_> for DNSClass {
86    fn read(decoder: &mut BinDecoder<'_>) -> Result<Self, DecodeError> {
87        let this = Self::from(
88            decoder.read_u16()?.unverified(/*DNSClass is verified as safe in processing this*/),
89        );
90
91        Ok(this)
92    }
93}
94
95// TODO make these a macro or annotation
96
97/// Convert from `DNSClass` to `&str`
98///
99/// ```
100/// use hickory_proto::rr::DNSClass;
101///
102/// let var: &'static str = DNSClass::IN.into();
103/// assert_eq!("IN", var);
104/// ```
105impl From<DNSClass> for &'static str {
106    fn from(rt: DNSClass) -> &'static str {
107        match rt {
108            DNSClass::IN => "IN",
109            DNSClass::CH => "CH",
110            DNSClass::HS => "HS",
111            DNSClass::NONE => "NONE",
112            DNSClass::ANY => "ANY",
113            DNSClass::OPT(_) => "OPT",
114            DNSClass::Unknown(_) => "UNKNOWN",
115        }
116    }
117}
118
119/// Convert from `u16` to `DNSClass`
120///
121/// ```
122/// use hickory_proto::rr::DNSClass;
123///
124/// let var: DNSClass = 1u16.into();
125/// assert_eq!(DNSClass::IN, var);
126/// ```
127impl From<u16> for DNSClass {
128    fn from(value: u16) -> Self {
129        match value {
130            1 => Self::IN,
131            3 => Self::CH,
132            4 => Self::HS,
133            254 => Self::NONE,
134            255 => Self::ANY,
135            _ => Self::Unknown(value),
136        }
137    }
138}
139
140/// Convert from `DNSClass` to `u16`
141///
142/// ```
143/// use hickory_proto::rr::DNSClass;
144///
145/// let var: u16 = DNSClass::IN.into();
146/// assert_eq!(1, var);
147/// ```
148impl From<DNSClass> for u16 {
149    fn from(rt: DNSClass) -> Self {
150        match rt {
151            DNSClass::IN => 1,
152            DNSClass::CH => 3,
153            DNSClass::HS => 4,
154            DNSClass::NONE => 254,
155            DNSClass::ANY => 255,
156            // see https://tools.ietf.org/html/rfc6891#section-6.1.2
157            DNSClass::OPT(max_payload_len) => max_payload_len.max(512),
158            DNSClass::Unknown(unknown) => unknown,
159        }
160    }
161}
162
163impl PartialOrd<Self> for DNSClass {
164    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
165        Some(self.cmp(other))
166    }
167}
168
169impl Ord for DNSClass {
170    fn cmp(&self, other: &Self) -> Ordering {
171        u16::from(*self).cmp(&u16::from(*other))
172    }
173}
174
175impl Display for DNSClass {
176    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), fmt::Error> {
177        f.write_str(Into::<&str>::into(*self))
178    }
179}
180
181#[cfg(test)]
182mod tests {
183    use super::*;
184    #[test]
185    fn test_order() {
186        let ordered = vec![
187            DNSClass::IN,
188            DNSClass::CH,
189            DNSClass::HS,
190            DNSClass::NONE,
191            DNSClass::ANY,
192        ];
193        let mut unordered = vec![
194            DNSClass::NONE,
195            DNSClass::HS,
196            DNSClass::CH,
197            DNSClass::IN,
198            DNSClass::ANY,
199        ];
200
201        unordered.sort();
202
203        assert_eq!(unordered, ordered);
204    }
205
206    #[test]
207    fn check_dns_class_parse_wont_panic_with_symbols() {
208        let dns_class = "a-b-c".to_ascii_uppercase().parse::<DNSClass>();
209        assert!(matches!(
210            &dns_class,
211            Err(DecodeError::UnknownDnsClassStr(_))
212        ));
213    }
214}