1 // TODO: this is literally a copy of examples/utils.rs, but without an allow dead code attribute.
2 // The include logic does not allow having attributes in included files.
3 
4 use getopts::{Matches, Options};
5 use std::env;
6 use std::fs::File;
7 use std::io;
8 use std::io::Write;
9 use std::process;
10 use std::str::{self, FromStr};
11 use std::time::{SystemTime, UNIX_EPOCH};
12 
13 use smoltcp::phy::{Device, FaultInjector, Tracer};
14 use smoltcp::phy::{PcapMode, PcapWriter};
15 use smoltcp::time::Duration;
16 
create_options() -> (Options, Vec<&'static str>)17 pub fn create_options() -> (Options, Vec<&'static str>) {
18     let mut opts = Options::new();
19     opts.optflag("h", "help", "print this help menu");
20     (opts, Vec::new())
21 }
22 
parse_options(options: &Options, free: Vec<&str>) -> Matches23 pub fn parse_options(options: &Options, free: Vec<&str>) -> Matches {
24     match options.parse(env::args().skip(1)) {
25         Err(err) => {
26             println!("{}", err);
27             process::exit(1)
28         }
29         Ok(matches) => {
30             if matches.opt_present("h") || matches.free.len() != free.len() {
31                 let brief = format!(
32                     "Usage: {} [OPTION]... {}",
33                     env::args().nth(0).unwrap(),
34                     free.join(" ")
35                 );
36                 print!("{}", options.usage(&brief));
37                 process::exit(if matches.free.len() != free.len() {
38                     1
39                 } else {
40                     0
41                 })
42             }
43             matches
44         }
45     }
46 }
47 
add_middleware_options(opts: &mut Options, _free: &mut Vec<&str>)48 pub fn add_middleware_options(opts: &mut Options, _free: &mut Vec<&str>) {
49     opts.optopt("", "pcap", "Write a packet capture file", "FILE");
50     opts.optopt(
51         "",
52         "drop-chance",
53         "Chance of dropping a packet (%)",
54         "CHANCE",
55     );
56     opts.optopt(
57         "",
58         "corrupt-chance",
59         "Chance of corrupting a packet (%)",
60         "CHANCE",
61     );
62     opts.optopt(
63         "",
64         "size-limit",
65         "Drop packets larger than given size (octets)",
66         "SIZE",
67     );
68     opts.optopt(
69         "",
70         "tx-rate-limit",
71         "Drop packets after transmit rate exceeds given limit \
72                                       (packets per interval)",
73         "RATE",
74     );
75     opts.optopt(
76         "",
77         "rx-rate-limit",
78         "Drop packets after transmit rate exceeds given limit \
79                                       (packets per interval)",
80         "RATE",
81     );
82     opts.optopt(
83         "",
84         "shaping-interval",
85         "Sets the interval for rate limiting (ms)",
86         "RATE",
87     );
88 }
89 
parse_middleware_options<D>( matches: &mut Matches, device: D, loopback: bool, ) -> FaultInjector<Tracer<PcapWriter<D, Box<dyn Write>>>> where D: Device,90 pub fn parse_middleware_options<D>(
91     matches: &mut Matches,
92     device: D,
93     loopback: bool,
94 ) -> FaultInjector<Tracer<PcapWriter<D, Box<dyn Write>>>>
95 where
96     D: Device,
97 {
98     let drop_chance = matches
99         .opt_str("drop-chance")
100         .map(|s| u8::from_str(&s).unwrap())
101         .unwrap_or(0);
102     let corrupt_chance = matches
103         .opt_str("corrupt-chance")
104         .map(|s| u8::from_str(&s).unwrap())
105         .unwrap_or(0);
106     let size_limit = matches
107         .opt_str("size-limit")
108         .map(|s| usize::from_str(&s).unwrap())
109         .unwrap_or(0);
110     let tx_rate_limit = matches
111         .opt_str("tx-rate-limit")
112         .map(|s| u64::from_str(&s).unwrap())
113         .unwrap_or(0);
114     let rx_rate_limit = matches
115         .opt_str("rx-rate-limit")
116         .map(|s| u64::from_str(&s).unwrap())
117         .unwrap_or(0);
118     let shaping_interval = matches
119         .opt_str("shaping-interval")
120         .map(|s| u64::from_str(&s).unwrap())
121         .unwrap_or(0);
122 
123     let pcap_writer: Box<dyn io::Write>;
124     if let Some(pcap_filename) = matches.opt_str("pcap") {
125         pcap_writer = Box::new(File::create(pcap_filename).expect("cannot open file"))
126     } else {
127         pcap_writer = Box::new(io::sink())
128     }
129 
130     let seed = SystemTime::now()
131         .duration_since(UNIX_EPOCH)
132         .unwrap()
133         .subsec_nanos();
134 
135     let device = PcapWriter::new(
136         device,
137         pcap_writer,
138         if loopback {
139             PcapMode::TxOnly
140         } else {
141             PcapMode::Both
142         },
143     );
144 
145     let device = Tracer::new(device, |_timestamp, _printer| {
146         #[cfg(feature = "log")]
147         trace!("{}", _printer);
148     });
149     let mut device = FaultInjector::new(device, seed);
150     device.set_drop_chance(drop_chance);
151     device.set_corrupt_chance(corrupt_chance);
152     device.set_max_packet_size(size_limit);
153     device.set_max_tx_rate(tx_rate_limit);
154     device.set_max_rx_rate(rx_rate_limit);
155     device.set_bucket_interval(Duration::from_millis(shaping_interval));
156     device
157 }
158