utils.rs 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  1. #![allow(dead_code)]
  2. #[cfg(feature = "log")]
  3. use env_logger::Builder;
  4. use getopts::{Matches, Options};
  5. #[cfg(feature = "log")]
  6. use log::{trace, Level, LevelFilter};
  7. use std::env;
  8. use std::fs::File;
  9. use std::io::{self, Write};
  10. use std::process;
  11. use std::str::{self, FromStr};
  12. use std::time::{SystemTime, UNIX_EPOCH};
  13. #[cfg(feature = "phy-tuntap_interface")]
  14. use smoltcp::phy::TunTapInterface;
  15. use smoltcp::phy::{Device, FaultInjector, Medium, Tracer};
  16. use smoltcp::phy::{PcapMode, PcapWriter};
  17. use smoltcp::time::{Duration, Instant};
  18. #[cfg(feature = "log")]
  19. pub fn setup_logging_with_clock<F>(filter: &str, since_startup: F)
  20. where
  21. F: Fn() -> Instant + Send + Sync + 'static,
  22. {
  23. Builder::new()
  24. .format(move |buf, record| {
  25. let elapsed = since_startup();
  26. let timestamp = format!("[{elapsed}]");
  27. if record.target().starts_with("smoltcp::") {
  28. writeln!(
  29. buf,
  30. "\x1b[0m{} ({}): {}\x1b[0m",
  31. timestamp,
  32. record.target().replace("smoltcp::", ""),
  33. record.args()
  34. )
  35. } else if record.level() == Level::Trace {
  36. let message = format!("{}", record.args());
  37. writeln!(
  38. buf,
  39. "\x1b[37m{} {}\x1b[0m",
  40. timestamp,
  41. message.replace('\n', "\n ")
  42. )
  43. } else {
  44. writeln!(
  45. buf,
  46. "\x1b[32m{} ({}): {}\x1b[0m",
  47. timestamp,
  48. record.target(),
  49. record.args()
  50. )
  51. }
  52. })
  53. .filter(None, LevelFilter::Trace)
  54. .parse_filters(filter)
  55. .parse_env("RUST_LOG")
  56. .init();
  57. }
  58. #[cfg(feature = "log")]
  59. pub fn setup_logging(filter: &str) {
  60. setup_logging_with_clock(filter, Instant::now)
  61. }
  62. pub fn create_options() -> (Options, Vec<&'static str>) {
  63. let mut opts = Options::new();
  64. opts.optflag("h", "help", "print this help menu");
  65. (opts, Vec::new())
  66. }
  67. pub fn parse_options(options: &Options, free: Vec<&str>) -> Matches {
  68. match options.parse(env::args().skip(1)) {
  69. Err(err) => {
  70. println!("{err}");
  71. process::exit(1)
  72. }
  73. Ok(matches) => {
  74. if matches.opt_present("h") || matches.free.len() != free.len() {
  75. let brief = format!(
  76. "Usage: {} [OPTION]... {}",
  77. env::args().next().unwrap(),
  78. free.join(" ")
  79. );
  80. print!("{}", options.usage(&brief));
  81. process::exit((matches.free.len() != free.len()) as _);
  82. }
  83. matches
  84. }
  85. }
  86. }
  87. pub fn add_tuntap_options(opts: &mut Options, _free: &mut [&str]) {
  88. opts.optopt("", "tun", "TUN interface to use", "tun0");
  89. opts.optopt("", "tap", "TAP interface to use", "tap0");
  90. }
  91. #[cfg(feature = "phy-tuntap_interface")]
  92. pub fn parse_tuntap_options(matches: &mut Matches) -> TunTapInterface {
  93. let tun = matches.opt_str("tun");
  94. let tap = matches.opt_str("tap");
  95. match (tun, tap) {
  96. (Some(tun), None) => TunTapInterface::new(&tun, Medium::Ip).unwrap(),
  97. (None, Some(tap)) => TunTapInterface::new(&tap, Medium::Ethernet).unwrap(),
  98. _ => panic!("You must specify exactly one of --tun or --tap"),
  99. }
  100. }
  101. pub fn add_middleware_options(opts: &mut Options, _free: &mut [&str]) {
  102. opts.optopt("", "pcap", "Write a packet capture file", "FILE");
  103. opts.optopt(
  104. "",
  105. "drop-chance",
  106. "Chance of dropping a packet (%)",
  107. "CHANCE",
  108. );
  109. opts.optopt(
  110. "",
  111. "corrupt-chance",
  112. "Chance of corrupting a packet (%)",
  113. "CHANCE",
  114. );
  115. opts.optopt(
  116. "",
  117. "size-limit",
  118. "Drop packets larger than given size (octets)",
  119. "SIZE",
  120. );
  121. opts.optopt(
  122. "",
  123. "tx-rate-limit",
  124. "Drop packets after transmit rate exceeds given limit \
  125. (packets per interval)",
  126. "RATE",
  127. );
  128. opts.optopt(
  129. "",
  130. "rx-rate-limit",
  131. "Drop packets after transmit rate exceeds given limit \
  132. (packets per interval)",
  133. "RATE",
  134. );
  135. opts.optopt(
  136. "",
  137. "shaping-interval",
  138. "Sets the interval for rate limiting (ms)",
  139. "RATE",
  140. );
  141. }
  142. pub fn parse_middleware_options<D>(
  143. matches: &mut Matches,
  144. device: D,
  145. loopback: bool,
  146. ) -> FaultInjector<Tracer<PcapWriter<D, Box<dyn io::Write>>>>
  147. where
  148. D: Device,
  149. {
  150. let drop_chance = matches
  151. .opt_str("drop-chance")
  152. .map(|s| u8::from_str(&s).unwrap())
  153. .unwrap_or(0);
  154. let corrupt_chance = matches
  155. .opt_str("corrupt-chance")
  156. .map(|s| u8::from_str(&s).unwrap())
  157. .unwrap_or(0);
  158. let size_limit = matches
  159. .opt_str("size-limit")
  160. .map(|s| usize::from_str(&s).unwrap())
  161. .unwrap_or(0);
  162. let tx_rate_limit = matches
  163. .opt_str("tx-rate-limit")
  164. .map(|s| u64::from_str(&s).unwrap())
  165. .unwrap_or(0);
  166. let rx_rate_limit = matches
  167. .opt_str("rx-rate-limit")
  168. .map(|s| u64::from_str(&s).unwrap())
  169. .unwrap_or(0);
  170. let shaping_interval = matches
  171. .opt_str("shaping-interval")
  172. .map(|s| u64::from_str(&s).unwrap())
  173. .unwrap_or(0);
  174. let pcap_writer: Box<dyn io::Write> = match matches.opt_str("pcap") {
  175. Some(pcap_filename) => Box::new(File::create(pcap_filename).expect("cannot open file")),
  176. None => Box::new(io::sink()),
  177. };
  178. let seed = SystemTime::now()
  179. .duration_since(UNIX_EPOCH)
  180. .unwrap()
  181. .subsec_nanos();
  182. let device = PcapWriter::new(
  183. device,
  184. pcap_writer,
  185. if loopback {
  186. PcapMode::TxOnly
  187. } else {
  188. PcapMode::Both
  189. },
  190. );
  191. let device = Tracer::new(device, |_timestamp, _printer| {
  192. #[cfg(feature = "log")]
  193. trace!("{}", _printer);
  194. });
  195. let mut device = FaultInjector::new(device, seed);
  196. device.set_drop_chance(drop_chance);
  197. device.set_corrupt_chance(corrupt_chance);
  198. device.set_max_packet_size(size_limit);
  199. device.set_max_tx_rate(tx_rate_limit);
  200. device.set_max_rx_rate(rx_rate_limit);
  201. device.set_bucket_interval(Duration::from_millis(shaping_interval));
  202. device
  203. }