Skip to main content

cmtraceopen_parser/parser/
dns_types.rs

1use crate::models::log_entry::Severity;
2
3/// Map a numeric DNS QTYPE code to its canonical name.
4pub fn qtype_name(code: u32) -> String {
5    let name = match code {
6        1 => "A",
7        2 => "NS",
8        5 => "CNAME",
9        6 => "SOA",
10        12 => "PTR",
11        13 => "HINFO",
12        15 => "MX",
13        16 => "TXT",
14        17 => "RP",
15        18 => "AFSDB",
16        24 => "SIG",
17        25 => "KEY",
18        28 => "AAAA",
19        29 => "LOC",
20        33 => "SRV",
21        35 => "NAPTR",
22        36 => "KX",
23        37 => "CERT",
24        39 => "DNAME",
25        41 => "OPT",
26        43 => "DS",
27        44 => "SSHFP",
28        45 => "IPSECKEY",
29        46 => "RRSIG",
30        47 => "NSEC",
31        48 => "DNSKEY",
32        49 => "DHCID",
33        50 => "NSEC3",
34        51 => "NSEC3PARAM",
35        52 => "TLSA",
36        53 => "SMIMEA",
37        55 => "HIP",
38        59 => "CDS",
39        60 => "CDNSKEY",
40        61 => "OPENPGPKEY",
41        64 => "SVCB",
42        65 => "HTTPS",
43        99 => "SPF",
44        249 => "TKEY",
45        250 => "TSIG",
46        251 => "IXFR",
47        252 => "AXFR",
48        255 => "ANY",
49        256 => "URI",
50        257 => "CAA",
51        65281 => "WINS",
52        65282 => "WINSR",
53        _ => return format!("UNKNOWN({})", code),
54    };
55    name.to_string()
56}
57
58/// Map a numeric DNS RCODE to its canonical name.
59pub fn rcode_name(code: u32) -> String {
60    let name = match code {
61        0 => "NOERROR",
62        1 => "FORMERR",
63        2 => "SERVFAIL",
64        3 => "NXDOMAIN",
65        4 => "NOTIMP",
66        5 => "REFUSED",
67        6 => "YXDOMAIN",
68        7 => "YXRRSET",
69        8 => "NXRRSET",
70        9 => "NOTAUTH",
71        10 => "NOTZONE",
72        16 => "BADSIG",
73        17 => "BADKEY",
74        18 => "BADTIME",
75        19 => "BADMODE",
76        20 => "BADNAME",
77        21 => "BADALG",
78        22 => "BADTRUNC",
79        23 => "BADCOOKIE",
80        _ => return format!("RCODE({})", code),
81    };
82    name.to_string()
83}
84
85/// Map an RCODE name to a log severity.
86pub fn rcode_to_severity(rcode: &str) -> Severity {
87    match rcode {
88        "NOERROR" => Severity::Info,
89        "NXDOMAIN" => Severity::Warning,
90        "SERVFAIL" | "REFUSED" | "FORMERR" => Severity::Error,
91        _ => Severity::Warning,
92    }
93}
94
95/// Decode a DNS query name from wire-format or dotted notation.
96///
97/// Formats handled:
98/// - Wire-format labels: `(3)www(6)google(3)com(0)` → `www.google.com`
99/// - Compression pointers: `[C00C](4)home(4)gell(3)one(0)` → `home.gell.one`
100/// - Multiple pointers: `[C02B](4)dns3[C00C](4)home(4)gell(3)one(0)` → `dns3.home.gell.one`
101/// - Root: `(0)` → `.`
102/// - Dotted notation: `.ns1.example.com.` → `ns1.example.com`
103/// - Empty: `""` → `""`
104pub fn decode_query_name(raw: &str) -> String {
105    if raw.is_empty() {
106        return String::new();
107    }
108
109    // If the string contains wire-format labels like `(N)label`, decode them.
110    if raw.contains('(') {
111        return decode_wire_format(raw);
112    }
113
114    // Dotted notation: strip leading/trailing dots.
115    let trimmed = raw.trim_matches('.');
116    trimmed.to_string()
117}
118
119/// Decode wire-format DNS name, handling compression pointers `[XXXX]`.
120///
121/// Compression pointers are stripped; only the following labels are used.
122fn decode_wire_format(raw: &str) -> String {
123    let mut labels: Vec<String> = Vec::new();
124
125    // We process the string left to right, consuming tokens.
126    let mut remaining = raw;
127
128    while !remaining.is_empty() {
129        if remaining.starts_with('[') {
130            // Compression pointer: skip to the closing `]`
131            if let Some(end) = remaining.find(']') {
132                remaining = &remaining[end + 1..];
133                continue;
134            } else {
135                // Malformed — consume the rest.
136                break;
137            }
138        }
139
140        if remaining.starts_with('(') {
141            // Wire-format label: `(N)label`
142            if let Some(close_paren) = remaining.find(')') {
143                let len_str = &remaining[1..close_paren];
144                if let Ok(len) = len_str.parse::<usize>() {
145                    let after_paren = &remaining[close_paren + 1..];
146                    if len == 0 {
147                        // Root label — signals end of name.
148                        break;
149                    }
150                    // Extract exactly `len` bytes for the label.
151                    let label_end = len.min(after_paren.len());
152                    let label = &after_paren[..label_end];
153                    if !label.is_empty() {
154                        labels.push(label.to_string());
155                    }
156                    remaining = &after_paren[label_end..];
157                    continue;
158                }
159            }
160            // Malformed — stop.
161            break;
162        }
163
164        // Unexpected character — advance by one to avoid an infinite loop.
165        remaining = &remaining[1..];
166    }
167
168    if labels.is_empty() {
169        // `(0)` alone is the root zone.
170        if raw.trim() == "(0)" {
171            return ".".to_string();
172        }
173        return String::new();
174    }
175
176    labels.join(".")
177}
178
179#[cfg(test)]
180mod tests {
181    use super::*;
182
183    #[test]
184    fn test_qtype_known() {
185        assert_eq!(qtype_name(1), "A");
186        assert_eq!(qtype_name(28), "AAAA");
187        assert_eq!(qtype_name(6), "SOA");
188        assert_eq!(qtype_name(33), "SRV");
189        assert_eq!(qtype_name(12), "PTR");
190        assert_eq!(qtype_name(5), "CNAME");
191        assert_eq!(qtype_name(15), "MX");
192        assert_eq!(qtype_name(65281), "WINS");
193        assert_eq!(qtype_name(65282), "WINSR");
194    }
195
196    #[test]
197    fn test_qtype_unknown() {
198        assert_eq!(qtype_name(9999), "UNKNOWN(9999)");
199    }
200
201    #[test]
202    fn test_rcode_known() {
203        assert_eq!(rcode_name(0), "NOERROR");
204        assert_eq!(rcode_name(3), "NXDOMAIN");
205        assert_eq!(rcode_name(2), "SERVFAIL");
206        assert_eq!(rcode_name(5), "REFUSED");
207    }
208
209    #[test]
210    fn test_rcode_unknown() {
211        assert_eq!(rcode_name(99), "RCODE(99)");
212    }
213
214    #[test]
215    fn test_rcode_severity() {
216        assert_eq!(rcode_to_severity("NOERROR"), Severity::Info);
217        assert_eq!(rcode_to_severity("NXDOMAIN"), Severity::Warning);
218        assert_eq!(rcode_to_severity("SERVFAIL"), Severity::Error);
219        assert_eq!(rcode_to_severity("REFUSED"), Severity::Error);
220        assert_eq!(rcode_to_severity("FORMERR"), Severity::Error);
221        assert_eq!(rcode_to_severity("NOTAUTH"), Severity::Warning);
222    }
223
224    #[test]
225    fn test_decode_wire_format() {
226        assert_eq!(
227            decode_query_name("(4)home(4)gell(3)one(0)"),
228            "home.gell.one"
229        );
230    }
231
232    #[test]
233    fn test_decode_wire_format_www() {
234        assert_eq!(
235            decode_query_name("(3)www(6)google(3)com(0)"),
236            "www.google.com"
237        );
238    }
239
240    #[test]
241    fn test_decode_wire_format_root() {
242        assert_eq!(decode_query_name("(0)"), ".");
243    }
244
245    #[test]
246    fn test_decode_dotted() {
247        assert_eq!(decode_query_name(".ns1.example.com."), "ns1.example.com");
248    }
249
250    #[test]
251    fn test_decode_compression_pointer() {
252        assert_eq!(
253            decode_query_name("[C00C](4)home(4)gell(3)one(0)"),
254            "home.gell.one"
255        );
256    }
257
258    #[test]
259    fn test_decode_multiple_compression_pointers() {
260        assert_eq!(
261            decode_query_name("[C02B](4)dns3[C00C](4)home(4)gell(3)one(0)"),
262            "dns3.home.gell.one"
263        );
264    }
265
266    #[test]
267    fn test_decode_empty() {
268        assert_eq!(decode_query_name(""), "");
269    }
270}