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
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
use crate::error::Result;
use crate::{
Error, IcmpExtensionParseMode, MaxInflight, MaxRounds, MultipathStrategy, PacketSize,
PayloadPattern, PortDirection, PrivilegeMode, Protocol, Round, Sequence, State, TimeToLive,
TraceId, TypeOfService,
};
use std::fmt::Debug;
use std::net::IpAddr;
use std::sync::Arc;
use std::thread;
use std::thread::JoinHandle;
use std::time::Duration;
/// A traceroute implementation.
///
/// See the [`crate`] documentation for more information.
///
/// Note that this is type cheaply cloneable.
#[derive(Debug, Clone)]
pub struct Tracer {
inner: Arc<inner::TracerInner>,
}
impl Tracer {
/// Create a `Tracer`.
///
/// Use the [`crate::Builder`] type to create a [`Tracer`].
#[allow(clippy::too_many_arguments)]
#[must_use]
pub(crate) fn new(
interface: Option<String>,
source_addr: Option<IpAddr>,
target_addr: IpAddr,
privilege_mode: PrivilegeMode,
protocol: Protocol,
packet_size: PacketSize,
payload_pattern: PayloadPattern,
tos: TypeOfService,
icmp_extension_parse_mode: IcmpExtensionParseMode,
read_timeout: Duration,
tcp_connect_timeout: Duration,
trace_identifier: TraceId,
max_rounds: Option<MaxRounds>,
first_ttl: TimeToLive,
max_ttl: TimeToLive,
grace_duration: Duration,
max_inflight: MaxInflight,
initial_sequence: Sequence,
multipath_strategy: MultipathStrategy,
port_direction: PortDirection,
min_round_duration: Duration,
max_round_duration: Duration,
max_samples: usize,
max_flows: usize,
drop_privileges: bool,
) -> Self {
Self {
inner: Arc::new(inner::TracerInner::new(
interface,
source_addr,
target_addr,
privilege_mode,
protocol,
packet_size,
payload_pattern,
tos,
icmp_extension_parse_mode,
read_timeout,
tcp_connect_timeout,
trace_identifier,
max_rounds,
first_ttl,
max_ttl,
grace_duration,
max_inflight,
initial_sequence,
multipath_strategy,
port_direction,
min_round_duration,
max_round_duration,
max_samples,
max_flows,
drop_privileges,
)),
}
}
/// Run the [`Tracer`].
///
/// This method will block until either the trace completes all rounds (if
/// [`crate::Builder::max_rounds`] has been called to set to a non-zero
/// value) or until the trace fails.
///
/// At the completion of the trace, the state of the tracer can be
/// retrieved using the [`Tracer::snapshot`] method.
///
/// If you want to run the tracer indefinitely (by not setting
/// [`crate::Builder::max_rounds`]), you can either clone and run the
/// tracer on a separate thread by using the [`Tracer::spawn`] method or
/// by use the [`Tracer::run_with`] method in the current thread to gather
/// pee round state manually.
///
/// # Example
///
/// The following will run the tracer for a fixed number (3) of rounds and
/// then retrieve the final state snapshot:
///
/// ```no_run
/// # fn main() -> anyhow::Result<()> {
/// # use std::net::IpAddr;
/// # use std::str::FromStr;
/// use trippy_core::Builder;
///
/// let addr = IpAddr::from_str("1.1.1.1")?;
/// let tracer = Builder::new(addr).max_rounds(Some(3)).build()?;
/// tracer.run()?;
/// let _state = tracer.snapshot();
/// # Ok(())
/// # }
/// ```
///
/// # See Also
///
/// - [`Tracer::run_with`] - Run the tracer with a custom round handler.
/// - [`Tracer::spawn`] - Spawn the tracer on a new thread without a custom round handler.
pub fn run(&self) -> Result<()> {
self.inner.run()
}
/// Run the [`Tracer`] with a custom round handler.
///
/// This method will block until either the trace completes all rounds (if
/// [`crate::Builder::max_rounds`] has been called to set to a non-zero
/// value) or until the trace fails.
///
/// At the completion of the trace, the state of the tracer can be
/// retrieved using the [`Tracer::snapshot`] method.
///
/// This method will additionally call the provided function for each round
/// that is completed. This can be useful if you want to gather round state
/// manually if the tracer is run indefinitely (by not setting
/// [`crate::Builder::max_rounds`])
///
/// # Example
///
/// The following will run the tracer indefinitely and print the data from
/// each round of tracing:
///
/// ```no_run
/// # fn main() -> anyhow::Result<()> {
/// # use std::net::IpAddr;
/// # use std::str::FromStr;
/// use trippy_core::Builder;
///
/// let addr = IpAddr::from_str("1.1.1.1")?;
/// let tracer = Builder::new(addr).build()?;
/// tracer.run_with(|round| println!("{:?}", round))?;
/// # Ok(())
/// # }
/// ```
///
/// # See Also
///
/// - [`Tracer::run`] - Run the tracer without a custom round handler.
pub fn run_with<F: Fn(&Round<'_>)>(&self, func: F) -> Result<()> {
self.inner.run_with(func)
}
/// Spawn the tracer on a new thread.
///
/// This method will spawn a new thread to run the tracer and immediately
/// return the [`Tracer`] and a handle to the thread, so it may be joined
/// with [`JoinHandle::join`].
///
/// If you want to run the tracer indefinitely (by not setting
/// [`crate::Builder::max_rounds`]) you can use this method to spawn the
/// tracer on a new thread and return the [`Tracer`] such that a
/// [`Tracer::snapshot`] of the state can be taken at any time.
///
/// # Example
///
/// The following will spawn a tracer on a new thread and take a snapshot
/// of the state every 5 seconds:
///
/// ```no_run
/// # fn main() -> anyhow::Result<()> {
/// # use std::net::IpAddr;
/// # use std::str::FromStr;
/// # use std::thread;
/// # use std::time::Duration;
/// use trippy_core::Builder;
///
/// let addr = IpAddr::from_str("1.1.1.1")?;
/// let (tracer, _) = Builder::new(addr).build()?.spawn()?;
/// loop {
/// thread::sleep(Duration::from_secs(5));
/// // get the latest state.
/// let _state = tracer.snapshot();
/// }
/// # Ok(())
/// # }
/// ```
///
/// # See Also
///
/// - [`Tracer::run`] - Run the tracer on the current thread.
pub fn spawn(self) -> Result<(Self, JoinHandle<Result<()>>)> {
let tracer = self.clone();
let handle = thread::Builder::new()
.name(format!("tracer-{}", self.trace_identifier().0))
.spawn(move || tracer.run())
.map_err(|err| Error::Other(err.to_string()))?;
Ok((self, handle))
}
/// Spawn the tracer with a custom round handler on a new thread.
///
/// This method will spawn a new thread to run the tracer with a custom
/// round handler and immediately return the [`Tracer`] and a handle to the
/// thread, so it may be joined with [`JoinHandle::join`].
///
/// # Example
///
/// The following will spawn a tracer on a new thread with a custom round
/// handler to print the data from each round of tracing and also take a
/// snapshot of the state every 5 seconds until the tracer completes all
/// rounds:
///
/// ```no_run
/// # fn main() -> anyhow::Result<()> {
/// # use std::net::IpAddr;
/// # use std::str::FromStr;
/// # use std::thread;
/// # use std::time::Duration;
/// use trippy_core::Builder;
///
/// let addr = IpAddr::from_str("1.1.1.1")?;
/// let (tracer, handle) = Builder::new(addr)
/// .max_rounds(Some(3))
/// .build()?
/// .spawn_with(|round| println!("{:?}", round))?;
/// for i in 0..3 {
/// thread::sleep(Duration::from_secs(5));
/// // get the latest state.
/// let _state = tracer.snapshot();
/// }
/// handle.join().unwrap()?;
/// # Ok(())
/// # }
/// ```
///
/// # See Also
///
/// - [`Tracer::spawn`] - Spawn the tracer on a new thread without a custom round handler.
pub fn spawn_with<F: Fn(&Round<'_>) + Send + 'static>(
self,
func: F,
) -> Result<(Self, JoinHandle<Result<()>>)> {
let tracer = self.clone();
let handle = thread::Builder::new()
.name(format!("tracer-{}", self.trace_identifier().0))
.spawn(move || tracer.run_with(func))
.map_err(|err| Error::Other(err.to_string()))?;
Ok((self, handle))
}
/// Take a snapshot of the tracer state.
#[must_use]
pub fn snapshot(&self) -> State {
self.inner.snapshot()
}
/// Clear the tracer state.
pub fn clear(&self) {
self.inner.clear();
}
/// The maximum number of flows to record.
#[must_use]
pub fn max_flows(&self) -> usize {
self.inner.max_flows()
}
/// The maximum number of samples to record.
#[must_use]
pub fn max_samples(&self) -> usize {
self.inner.max_samples()
}
/// The privilege mode of the tracer.
#[must_use]
pub fn privilege_mode(&self) -> PrivilegeMode {
self.inner.privilege_mode()
}
/// The protocol of the tracer.
#[must_use]
pub fn protocol(&self) -> Protocol {
self.inner.protocol()
}
/// The interface to use for the tracer.
#[must_use]
pub fn interface(&self) -> Option<&str> {
self.inner.interface()
}
/// The source address of the tracer.
#[must_use]
pub fn source_addr(&self) -> Option<IpAddr> {
self.inner.source_addr()
}
/// The target address of the tracer.
#[must_use]
pub fn target_addr(&self) -> IpAddr {
self.inner.target_addr()
}
/// The packet size of the tracer.
#[must_use]
pub fn packet_size(&self) -> PacketSize {
self.inner.packet_size()
}
/// The payload pattern of the tracer.
#[must_use]
pub fn payload_pattern(&self) -> PayloadPattern {
self.inner.payload_pattern()
}
/// The initial sequence number of the tracer.
#[must_use]
pub fn initial_sequence(&self) -> Sequence {
self.inner.initial_sequence()
}
/// The type of service of the tracer.
#[must_use]
pub fn tos(&self) -> TypeOfService {
self.inner.tos()
}
/// The ICMP extension parse mode of the tracer.
#[must_use]
pub fn icmp_extension_parse_mode(&self) -> IcmpExtensionParseMode {
self.inner.icmp_extension_parse_mode()
}
/// The read timeout of the tracer.
#[must_use]
pub fn read_timeout(&self) -> Duration {
self.inner.read_timeout()
}
/// The TCP connect timeout of the tracer.
#[must_use]
pub fn tcp_connect_timeout(&self) -> Duration {
self.inner.tcp_connect_timeout()
}
/// The trace identifier of the tracer.
#[must_use]
pub fn trace_identifier(&self) -> TraceId {
self.inner.trace_identifier()
}
/// The maximum number of rounds of the tracer.
#[must_use]
pub fn max_rounds(&self) -> Option<MaxRounds> {
self.inner.max_rounds()
}
/// The first time-to-live value of the tracer.
#[must_use]
pub fn first_ttl(&self) -> TimeToLive {
self.inner.first_ttl()
}
/// The maximum time-to-live value of the tracer.
#[must_use]
pub fn max_ttl(&self) -> TimeToLive {
self.inner.max_ttl()
}
/// The grace duration of the tracer.
#[must_use]
pub fn grace_duration(&self) -> Duration {
self.inner.grace_duration()
}
/// The maximum number of in-flight probes of the tracer.
#[must_use]
pub fn max_inflight(&self) -> MaxInflight {
self.inner.max_inflight()
}
/// The multipath strategy of the tracer.
#[must_use]
pub fn multipath_strategy(&self) -> MultipathStrategy {
self.inner.multipath_strategy()
}
/// The port direction of the tracer.
#[must_use]
pub fn port_direction(&self) -> PortDirection {
self.inner.port_direction()
}
/// The minimum round duration of the tracer.
#[must_use]
pub fn min_round_duration(&self) -> Duration {
self.inner.min_round_duration()
}
/// The maximum round duration of the tracer.
#[must_use]
pub fn max_round_duration(&self) -> Duration {
self.inner.max_round_duration()
}
}
mod inner {
use crate::config::{ChannelConfig, StateConfig, StrategyConfig};
use crate::error::Result;
use crate::net::{PlatformImpl, SocketImpl};
use crate::{
Channel, Error, IcmpExtensionParseMode, MaxInflight, MaxRounds, MultipathStrategy,
PacketSize, PayloadPattern, PortDirection, PrivilegeMode, Protocol, Round, Sequence,
SourceAddr, State, Strategy, TimeToLive, TraceId, TypeOfService,
};
use parking_lot::RwLock;
use std::fmt::Debug;
use std::net::IpAddr;
use std::sync::OnceLock;
use std::time::Duration;
use tracing::instrument;
use trippy_privilege::Privilege;
#[derive(Debug)]
pub(super) struct TracerInner {
source_addr: Option<IpAddr>,
interface: Option<String>,
target_addr: IpAddr,
privilege_mode: PrivilegeMode,
protocol: Protocol,
packet_size: PacketSize,
payload_pattern: PayloadPattern,
tos: TypeOfService,
icmp_extension_parse_mode: IcmpExtensionParseMode,
read_timeout: Duration,
tcp_connect_timeout: Duration,
trace_identifier: TraceId,
max_rounds: Option<MaxRounds>,
first_ttl: TimeToLive,
max_ttl: TimeToLive,
grace_duration: Duration,
max_inflight: MaxInflight,
initial_sequence: Sequence,
multipath_strategy: MultipathStrategy,
port_direction: PortDirection,
min_round_duration: Duration,
max_round_duration: Duration,
max_samples: usize,
max_flows: usize,
drop_privileges: bool,
state: RwLock<State>,
src: OnceLock<IpAddr>,
}
impl TracerInner {
#[allow(clippy::too_many_arguments)]
pub(super) fn new(
interface: Option<String>,
source_addr: Option<IpAddr>,
target_addr: IpAddr,
privilege_mode: PrivilegeMode,
protocol: Protocol,
packet_size: PacketSize,
payload_pattern: PayloadPattern,
tos: TypeOfService,
icmp_extension_parse_mode: IcmpExtensionParseMode,
read_timeout: Duration,
tcp_connect_timeout: Duration,
trace_identifier: TraceId,
max_rounds: Option<MaxRounds>,
first_ttl: TimeToLive,
max_ttl: TimeToLive,
grace_duration: Duration,
max_inflight: MaxInflight,
initial_sequence: Sequence,
multipath_strategy: MultipathStrategy,
port_direction: PortDirection,
min_round_duration: Duration,
max_round_duration: Duration,
max_samples: usize,
max_flows: usize,
drop_privileges: bool,
) -> Self {
Self {
source_addr,
interface,
target_addr,
privilege_mode,
protocol,
packet_size,
payload_pattern,
tos,
icmp_extension_parse_mode,
read_timeout,
tcp_connect_timeout,
trace_identifier,
max_rounds,
first_ttl,
max_ttl,
grace_duration,
max_inflight,
initial_sequence,
multipath_strategy,
port_direction,
min_round_duration,
max_round_duration,
max_samples,
max_flows,
drop_privileges,
state: RwLock::new(State::new(Self::make_state_config(max_flows, max_samples))),
src: OnceLock::new(),
}
}
#[instrument(skip_all, level = "trace")]
pub(super) fn run(&self) -> Result<()> {
self.run_internal(|_| ())
.map_err(|err| self.handle_error(err))
}
#[instrument(skip_all, level = "trace")]
pub(super) fn run_with<F: Fn(&Round<'_>)>(&self, func: F) -> Result<()> {
self.run_internal(func)
.map_err(|err| self.handle_error(err))
}
pub(super) fn snapshot(&self) -> State {
self.state.read().clone()
}
pub(super) fn clear(&self) {
*self.state.write() =
State::new(Self::make_state_config(self.max_flows, self.max_samples));
}
pub(super) const fn max_flows(&self) -> usize {
self.max_flows
}
pub(super) const fn max_samples(&self) -> usize {
self.max_samples
}
pub(super) const fn privilege_mode(&self) -> PrivilegeMode {
self.privilege_mode
}
pub(super) const fn protocol(&self) -> Protocol {
self.protocol
}
pub(super) fn interface(&self) -> Option<&str> {
self.interface.as_deref()
}
pub(super) fn source_addr(&self) -> Option<IpAddr> {
self.src.get().copied()
}
pub(super) const fn target_addr(&self) -> IpAddr {
self.target_addr
}
pub(super) const fn packet_size(&self) -> PacketSize {
self.packet_size
}
pub(super) const fn payload_pattern(&self) -> PayloadPattern {
self.payload_pattern
}
pub(super) const fn initial_sequence(&self) -> Sequence {
self.initial_sequence
}
pub(super) const fn tos(&self) -> TypeOfService {
self.tos
}
pub(super) const fn icmp_extension_parse_mode(&self) -> IcmpExtensionParseMode {
self.icmp_extension_parse_mode
}
pub(super) const fn read_timeout(&self) -> Duration {
self.read_timeout
}
pub(super) const fn tcp_connect_timeout(&self) -> Duration {
self.tcp_connect_timeout
}
pub(super) const fn trace_identifier(&self) -> TraceId {
self.trace_identifier
}
pub(super) const fn max_rounds(&self) -> Option<MaxRounds> {
self.max_rounds
}
pub(super) const fn first_ttl(&self) -> TimeToLive {
self.first_ttl
}
pub(super) const fn max_ttl(&self) -> TimeToLive {
self.max_ttl
}
pub(super) const fn grace_duration(&self) -> Duration {
self.grace_duration
}
pub(super) const fn max_inflight(&self) -> MaxInflight {
self.max_inflight
}
pub(super) const fn multipath_strategy(&self) -> MultipathStrategy {
self.multipath_strategy
}
pub(super) const fn port_direction(&self) -> PortDirection {
self.port_direction
}
pub(super) const fn min_round_duration(&self) -> Duration {
self.min_round_duration
}
pub(super) const fn max_round_duration(&self) -> Duration {
self.max_round_duration
}
#[instrument(skip_all, level = "trace")]
fn run_internal<F: Fn(&Round<'_>)>(&self, func: F) -> Result<()> {
// if we are given a source address, validate it otherwise
// discover it based on the target address and interface.
let source_addr = match self.source_addr {
None => SourceAddr::discover::<SocketImpl, PlatformImpl>(
self.target_addr,
self.port_direction,
self.interface.as_deref(),
)?,
Some(addr) => SourceAddr::validate::<SocketImpl>(addr)?,
};
self.src
.set(source_addr)
.map_err(|_| Error::Other(String::from("failed to set source_addr")))?;
let channel_config = self.make_channel_config(source_addr);
let channel = Channel::<SocketImpl>::connect(&channel_config)?;
if self.drop_privileges {
Privilege::drop_privileges()?;
}
let strategy_config = self.make_strategy_config();
let strategy = Strategy::new(&strategy_config, |round| {
self.handler(round);
func(round);
});
strategy.run(channel)?;
Ok(())
}
fn handler(&self, round: &Round<'_>) {
self.state.write().update_from_round(round);
}
fn handle_error(&self, err: Error) -> Error {
self.state.write().set_error(Some(err.to_string()));
err
}
const fn make_state_config(max_flows: usize, max_samples: usize) -> StateConfig {
StateConfig {
max_samples,
max_flows,
}
}
const fn make_channel_config(&self, source_addr: IpAddr) -> ChannelConfig {
ChannelConfig {
privilege_mode: self.privilege_mode,
protocol: self.protocol,
source_addr,
target_addr: self.target_addr,
packet_size: self.packet_size,
payload_pattern: self.payload_pattern,
initial_sequence: self.initial_sequence,
tos: self.tos,
icmp_extension_parse_mode: self.icmp_extension_parse_mode,
read_timeout: self.read_timeout,
tcp_connect_timeout: self.tcp_connect_timeout,
}
}
const fn make_strategy_config(&self) -> StrategyConfig {
StrategyConfig {
target_addr: self.target_addr,
protocol: self.protocol,
trace_identifier: self.trace_identifier,
max_rounds: self.max_rounds,
first_ttl: self.first_ttl,
max_ttl: self.max_ttl,
grace_duration: self.grace_duration,
max_inflight: self.max_inflight,
initial_sequence: self.initial_sequence,
multipath_strategy: self.multipath_strategy,
port_direction: self.port_direction,
min_round_duration: self.min_round_duration,
max_round_duration: self.max_round_duration,
}
}
}
}