dnstracer 1.1.7

A DNS traceroute tool
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
use clap::Parser;
use eyre::{Result, WrapErr as _, bail};
use hickory_proto::rr::RecordType;
use std::{net::IpAddr, str::FromStr as _, time::Duration};

// Original arguments
// -c: disable local caching, default enabled
// -C: enable negative caching, default disabled
// -e: disable EDNS0, default enabled
// TODO: -E <size>: set EDNS0 size, default 1500
// -o: enable overview of received answers, default disabled
// -q <querytype>: query-type to use for the DNS requests, default A
// -r <retries>: amount of retries for DNS requests, default 3
// -s <server>: use this server for the initial request, default localhost
//             If . is specified, A.ROOT-SERVERS.NET will be used.
// -t <maximum timeout>: Limit time to wait per try
// TODO: -v: verbose
// -S <ip address>: use this source address.
// -4: don't query IPv6 servers

/// Our command line arguments
#[expect(clippy::struct_excessive_bools, reason = "Those are flags, not states")]
#[derive(Parser, Debug, Clone, PartialEq, Eq)]
#[command(version, about)]
pub struct Args {
    /// The domain to query
    pub domain: String,

    /// disable positive response caching, default enabled
    #[arg(short = 'c', long)]
    pub no_positive_cache: bool,

    /// enable negative response caching, default disabled
    #[arg(short = 'C', long)]
    pub negative_cache: bool,

    /// disable EDNS0, default enabled
    #[arg(short = 'e', long)]
    pub no_edns0: bool,

    /// enable overview of received answers, default disabled
    #[arg(short = 'o', long)]
    pub overview: bool,

    /// The type of record (A, AAAA, NS ...)
    #[arg(short = 'q', long, default_value = "A", value_parser = RecordType::from_str)]
    pub query_type: RecordType,

    /// amount of retries for DNS requests, default 3
    #[arg(short = 'r', long, default_value = "3")]
    pub retries: usize,

    /// Start the query at the given DNS server
    /// If an ip is given, it will be used
    /// If a hostname is given, all its ip will be used
    /// If "." is specified, all root servers will be used
    #[arg(short, long, default_value = "a.root-servers.net")]
    pub server: String,

    /// Limit time to wait per try
    #[arg(short = 't', long, default_value = "5", value_parser = parse_duration)]
    pub timeout: Duration,

    /// use this source address.
    #[arg(short = 'S', long)]
    pub source_address: Option<IpAddr>,

    /// Force using IPv6 for DNS queries (no IPv4)
    #[arg(short = '6', long)]
    pub ipv6: bool,

    /// Force using IPv4 for DNS queries (no IPv6)
    #[arg(short = '4', long)]
    pub ipv4: bool,

    /// Force using TCP for DNS queries
    #[arg(short = 'T', long)]
    pub tcp: bool,
}

impl Args {
    /// Perform some validation on arguments
    pub fn validate(&mut self) -> Result<()> {
        match self.source_address {
            Some(IpAddr::V4(ip)) => {
                if self.ipv6 {
                    bail!("Cannot use IPv6 only queries with an ipv4 source address ({ip})");
                }
                // Also, force IPv4 queries everywhere, otherwise we'd get protocol errors
                self.ipv4 = true;
            }
            Some(IpAddr::V6(ip)) => {
                if self.ipv4 {
                    bail!("Cannot use IPv4 only queries with an ipv6 source address ({ip})");
                }
                // Also, force IPv6 queries everywhere, otherwise we'd get protocol errors
                self.ipv6 = true;
            }
            None => (),
        }

        Ok(())
    }
}

/// Duration parser for args
fn parse_duration(src: &str) -> Result<Duration> {
    src.parse::<u64>()
        .map(Duration::from_secs)
        .wrap_err_with(|| format!("Invalid duration: {src}"))
}

#[cfg(test)]
mod tests {
    #![allow(clippy::expect_used, clippy::unwrap_used, reason = "test")]

    use super::*;
    use insta::assert_debug_snapshot;

    #[test]
    fn default_values() {
        let args = Args::try_parse_from(["test", "example.com"]).unwrap();

        assert_debug_snapshot!(args, @r#"
        Args {
            domain: "example.com",
            no_positive_cache: false,
            negative_cache: false,
            no_edns0: false,
            overview: false,
            query_type: A,
            retries: 3,
            server: "a.root-servers.net",
            timeout: 5s,
            source_address: None,
            ipv6: false,
            ipv4: false,
            tcp: false,
        }
        "#);
    }

    #[test]
    fn all_flags() {
        let args = Args::try_parse_from([
            "test",
            "-c", // no_positive_cache
            "-C", // negative_cache
            "-e", // edns0 disabled
            "-o", // overview enabled
            "-q",
            "NS", // query_type: NS
            "-r",
            "5", // retries: 5
            "-s",
            "8.8.8.8", // server: 8.8.8.8
            "-t",
            "10", // timeout: 10 seconds
            "-S",
            "192.168.0.1", // source_address: 192.168.0.1
            "-6",          // force IPv6
            "-T",          // use TCP
            "example.com",
        ])
        .unwrap();

        assert_debug_snapshot!(args, @r#"
        Args {
            domain: "example.com",
            no_positive_cache: true,
            negative_cache: true,
            no_edns0: true,
            overview: true,
            query_type: NS,
            retries: 5,
            server: "8.8.8.8",
            timeout: 10s,
            source_address: Some(
                192.168.0.1,
            ),
            ipv6: true,
            ipv4: false,
            tcp: true,
        }
        "#);
    }

    #[test]
    fn ipv4_flag() {
        let args = Args::try_parse_from(["test", "example.com", "-4"]).unwrap();

        assert_debug_snapshot!(args, @r#"
        Args {
            domain: "example.com",
            no_positive_cache: false,
            negative_cache: false,
            no_edns0: false,
            overview: false,
            query_type: A,
            retries: 3,
            server: "a.root-servers.net",
            timeout: 5s,
            source_address: None,
            ipv6: false,
            ipv4: true,
            tcp: false,
        }
        "#);
    }

    #[test]
    fn with_server_override() {
        let args = Args::try_parse_from(["test", "-s", "1.1.1.1", "example.com"]).unwrap();

        assert_debug_snapshot!(args, @r#"
        Args {
            domain: "example.com",
            no_positive_cache: false,
            negative_cache: false,
            no_edns0: false,
            overview: false,
            query_type: A,
            retries: 3,
            server: "1.1.1.1",
            timeout: 5s,
            source_address: None,
            ipv6: false,
            ipv4: false,
            tcp: false,
        }
        "#);
    }

    #[test]
    fn with_query_type() {
        let args = Args::try_parse_from(["test", "example.com", "-q", "AAAA"]).unwrap();

        assert_debug_snapshot!(args, @r#"
        Args {
            domain: "example.com",
            no_positive_cache: false,
            negative_cache: false,
            no_edns0: false,
            overview: false,
            query_type: AAAA,
            retries: 3,
            server: "a.root-servers.net",
            timeout: 5s,
            source_address: None,
            ipv6: false,
            ipv4: false,
            tcp: false,
        }
        "#);
    }

    #[test]
    fn invalid_query_type() {
        let result = Args::try_parse_from(["test", "example.com", "-q", "INVALID"]);
        assert_debug_snapshot!(result, @r#"
        Err(
            ErrorInner {
                kind: ValueValidation,
                context: FlatMap {
                    keys: [
                        InvalidArg,
                        InvalidValue,
                    ],
                    values: [
                        String(
                            "--query-type <QUERY_TYPE>",
                        ),
                        String(
                            "INVALID",
                        ),
                    ],
                },
                message: None,
                source: Some(
                    ProtoError {
                        kind: UnknownRecordTypeStr(
                            "INVALID",
                        ),
                    },
                ),
                help_flag: Some(
                    "--help",
                ),
                styles: Styles {
                    header: Style {
                        fg: None,
                        bg: None,
                        underline: None,
                        effects: Effects(BOLD | UNDERLINE),
                    },
                    error: Style {
                        fg: Some(
                            Ansi(
                                Red,
                            ),
                        ),
                        bg: None,
                        underline: None,
                        effects: Effects(BOLD),
                    },
                    usage: Style {
                        fg: None,
                        bg: None,
                        underline: None,
                        effects: Effects(BOLD | UNDERLINE),
                    },
                    literal: Style {
                        fg: None,
                        bg: None,
                        underline: None,
                        effects: Effects(BOLD),
                    },
                    placeholder: Style {
                        fg: None,
                        bg: None,
                        underline: None,
                        effects: Effects(),
                    },
                    valid: Style {
                        fg: Some(
                            Ansi(
                                Green,
                            ),
                        ),
                        bg: None,
                        underline: None,
                        effects: Effects(),
                    },
                    invalid: Style {
                        fg: Some(
                            Ansi(
                                Yellow,
                            ),
                        ),
                        bg: None,
                        underline: None,
                        effects: Effects(),
                    },
                    context: Style {
                        fg: None,
                        bg: None,
                        underline: None,
                        effects: Effects(),
                    },
                    context_value: None,
                },
                color_when: Auto,
                color_help_when: Auto,
                backtrace: None,
            },
        )
        "#);
    }

    #[test]
    fn with_source_address_v4() {
        let mut args = Args::try_parse_from(["test", "example.com", "-S", "1.1.1.1"]).unwrap();
        let validated = args.validate();

        assert!(validated.is_ok());
        assert_debug_snapshot!(args, @r#"
        Args {
            domain: "example.com",
            no_positive_cache: false,
            negative_cache: false,
            no_edns0: false,
            overview: false,
            query_type: A,
            retries: 3,
            server: "a.root-servers.net",
            timeout: 5s,
            source_address: Some(
                1.1.1.1,
            ),
            ipv6: false,
            ipv4: true,
            tcp: false,
        }
        "#);
    }

    #[test]
    fn with_source_address_v6() {
        let mut args = Args::try_parse_from(["test", "example.com", "-S", "2001:db8::1"]).unwrap();
        let validated = args.validate();

        assert!(validated.is_ok());
        assert_debug_snapshot!(args, @r#"
        Args {
            domain: "example.com",
            no_positive_cache: false,
            negative_cache: false,
            no_edns0: false,
            overview: false,
            query_type: A,
            retries: 3,
            server: "a.root-servers.net",
            timeout: 5s,
            source_address: Some(
                2001:db8::1,
            ),
            ipv6: true,
            ipv4: false,
            tcp: false,
        }
        "#);
    }

    #[test]
    fn with_source_address_v4_and_ipv6() {
        let mut args =
            Args::try_parse_from(["test", "example.com", "-6", "-S", "1.1.1.1"]).unwrap();
        let validated = args.validate();

        assert_debug_snapshot!(validated, @r#"
        Err(
            "Cannot use IPv6 only queries with an ipv4 source address (1.1.1.1)",
        )
        "#);
    }

    #[test]
    fn with_source_address_v6_and_ipv4() {
        let mut args =
            Args::try_parse_from(["test", "example.com", "-4", "-S", "2001:db8::1"]).unwrap();
        let validated = args.validate();

        assert_debug_snapshot!(validated, @r#"
        Err(
            "Cannot use IPv4 only queries with an ipv6 source address (2001:db8::1)",
        )
        "#);
    }
}